Programs & Examples On #Xslt tools

add onclick function to a submit button

if you need to do something before submitting data, you could use form's onsubmit.

<form method=post onsubmit="return doSomething()">
  <input type=text name=text1>
  <input type=submit>
</form>

Is it possible to listen to a "style change" event?

Since jQuery is open-source, I would guess that you could tweak the css function to call a function of your choice every time it is invoked (passing the jQuery object). Of course, you'll want to scour the jQuery code to make sure there is nothing else it uses internally to set CSS properties. Ideally, you'd want to write a separate plugin for jQuery so that it does not interfere with the jQuery library itself, but you'll have to decide whether or not that is feasible for your project.

How to auto-generate a C# class file from a JSON string

Five options:

Pros and Cons:

  • jsonclassgenerator converts to PascalCase but the others do not.

  • app.quicktype.io has some logic to recognize dictionaries and handle JSON properties whose names are invalid c# identifiers.

Convert string to Date in java

String str_date="13-09-2011";
DateFormat formatter ; 
Date date ; 
formatter = new SimpleDateFormat("dd-MM-yyyy");
date = (Date)formatter.parse(str_date); 
System.out.println("Today is " +date.getTime());

Try this

Getting permission denied (public key) on gitlab

In our case, it wasn't a problem on the user/client side, but on the Gitlab server side.

We are running a local Gitlab CE 12.9 instance on CentOS 7.1.

We found out that on the server, the .ssh/authorized_keys file was not updating properly. Users create their SSH keys (following the Gitlab guide) and add it to the Gitlab server, but the server does not update the authorized_keys, so it will always result to permission denied errors.

A workaround was to rebuild the authorized_keys file by running:

$ sudo gitlab-rake gitlab:shell:setup

That would work for anyone who added their keys before running the rake task. For the next users who would add their keys, someone has to manually run the rake tasks again.

A more permanent solution was to not use the authorized_keys file and use instead an indexed lookup on the Gitlab database:

GitLab Shell provides a way to authorize SSH users via a fast, indexed lookup to the GitLab database. GitLab Shell uses the fingerprint of the SSH key to check whether the user is authorized to access GitLab.

Add the following to your sshd_config file. This is usually located at /etc/ssh/sshd_config, but it will be /assets/sshd_config if you're using Omnibus Docker:

Match User git    # Apply the AuthorizedKeysCommands to the git user only   
  AuthorizedKeysCommand /opt/gitlab/embedded/service/gitlab-shell/bin/gitlab-shell-authorized-keys-check git %u %k   
  AuthorizedKeysCommandUser git 
Match all    # End match, settings apply to all users again 

Reload OpenSSH:

# Debian or Ubuntu installations   
sudo service ssh reload

# CentOS installations   
sudo service sshd reload 

Confirm that SSH is working by removing your user's SSH key in the UI, adding a new one, and attempting to pull a repo.

By default (well the default on our installation), the Write to authorized_keys file was checked in the Admin Area > Performance Optimization settings. So we unchecked that and used the Gitlab database instead.

enter image description here

After setting up indexed lookup and unchecking the Write to authorized_keys file, SSH access became OK.

How to add data validation to a cell using VBA

Use this one:

Dim ws As Worksheet
Dim range1 As Range, rng As Range
'change Sheet1 to suit
Set ws = ThisWorkbook.Worksheets("Sheet1")

Set range1 = ws.Range("A1:A5")
Set rng = ws.Range("B1")

With rng.Validation
    .Delete 'delete previous validation
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
        Formula1:="='" & ws.Name & "'!" & range1.Address
End With

Note that when you're using Dim range1, rng As range, only rng has type of Range, but range1 is Variant. That's why I'm using Dim range1 As Range, rng As Range.
About meaning of parameters you can read is MSDN, but in short:

  • Type:=xlValidateList means validation type, in that case you should select value from list
  • AlertStyle:=xlValidAlertStop specifies the icon used in message boxes displayed during validation. If user enters any value out of list, he/she would get error message.
  • in your original code, Operator:= xlBetween is odd. It can be used only if two formulas are provided for validation.
  • Formula1:="='" & ws.Name & "'!" & range1.Address for list data validation provides address of list with values (in format =Sheet!A1:A5)

How to use Jquery how to change the aria-expanded="false" part of a dom element (Bootstrap)?

You can use .attr() as a part of however you plan to toggle it:

$("button").attr("aria-expanded","true");

Property 'value' does not exist on type 'Readonly<{}>'

The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'

Here is a good reference

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

class App extends React.Component<AppProps, AppState> {
  // ...
}

Xcode 6 iPhone Simulator Application Support location

Here is the sh for last used simulator and application. Just run sh and copy printed text and paste and run command for show in finder.

#!/bin/zsh

lastUsedSimulatorAndApplication=`ls -td -- ~/Library/Developer/CoreSimulator/Devices/*/data/Containers/Data/Application/*/ | head -n1`

echo $lastUsedSimulatorAndApplication

ssh "permissions are too open" error

For Windows 10 this is what I've found works for me:

  1. Move your key to the Linux file system: mv ~/.ssh /home/{username}
  2. Set the permission on that key: chmod 700 /home/{username}/.ssh/id_rsa
  3. Create a symbolic link to the key: ln -s /home/{username}/.ssh ~/.ssh

This happens if you have set your home directory (~) to be stored in Windows instead of Linux (under /mnt/ vs /home/).

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

You can convert a string to a date easily by:

CAST(YourDate AS DATE)

Mockito: InvalidUseOfMatchersException

The error message outlines the solution. The line

doNothing().when(cmd).dnsCheck(HOST, any(InetAddressFactory.class))

uses one raw value and one matcher, when it's required to use either all raw values or all matchers. A correct version might read

doNothing().when(cmd).dnsCheck(eq(HOST), any(InetAddressFactory.class))

How do I protect Python code?

"Is there a good way to handle this problem?" No. Nothing can be protected against reverse engineering. Even the firmware on DVD machines has been reverse engineered and the AACS Encryption key exposed. And that's in spite of the DMCA making that a criminal offense.

Since no technical method can stop your customers from reading your code, you have to apply ordinary commercial methods.

  1. Licenses. Contracts. Terms and Conditions. This still works even when people can read the code. Note that some of your Python-based components may require that you pay fees before you sell software using those components. Also, some open-source licenses prohibit you from concealing the source or origins of that component.

  2. Offer significant value. If your stuff is so good -- at a price that is hard to refuse -- there's no incentive to waste time and money reverse engineering anything. Reverse engineering is expensive. Make your product slightly less expensive.

  3. Offer upgrades and enhancements that make any reverse engineering a bad idea. When the next release breaks their reverse engineering, there's no point. This can be carried to absurd extremes, but you should offer new features that make the next release more valuable than reverse engineering.

  4. Offer customization at rates so attractive that they'd rather pay you to build and support the enhancements.

  5. Use a license key which expires. This is cruel, and will give you a bad reputation, but it certainly makes your software stop working.

  6. Offer it as a web service. SaaS involves no downloads to customers.

How to POST a FORM from HTML to ASPX page

This is very possible. I mocked up 3 pages which should give you a proof of concept:

.aspx page:

<form id="form1" runat="server">
    <div>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <asp:TextBox TextMode="password" ID="TextBox2" runat="server"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" Text="Button" />
    </div>
</form>

code behind:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    For Each s As String In Request.Form.AllKeys
        Response.Write(s & ": " & Request.Form(s) & "<br />")
    Next
End Sub

Separate HTML page:

<form action="http://localhost/MyTestApp/Default.aspx" method="post">
    <input name="TextBox1" type="text" value="" id="TextBox1" />
    <input name="TextBox2" type="password" id="TextBox2" />
    <input type="submit" name="Button1" value="Button" id="Button1" />
</form>

...and it regurgitates the form values as expected. If this isn't working, as others suggested, use a traffic analysis tool (fiddler, ethereal), because something probably isn't going where you're expecting.

Single Line Nested For Loops

The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.

Look at this longer list comprehension from the tutorial (the if part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)):

>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).

>>> combs = []
>>> for x in [1,2,3]:
...     for y in [3,1,4]:
...         if x != y:
...             combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.

On to your questions:

What type must object be in order to use this for loop structure?

An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.

What is the order in which i and j are assigned to elements in object?

They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)

Can it be simulated by a different for loop structure?

Yes, already shown above.

Can this for loop be nested with a similar or different structure for loop? And how would it look?

Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:

[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]

How to add a button dynamically in Android?

public void add_btn() {

    lin_btn.setWeightSum(3f);
    for (int j = 0; j < 3; j++) {
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        params1.setMargins(10, 0, 0, 10);
        params1.weight = 1.0f;

        LinearLayout ll;
        ll = new LinearLayout(this);
        ll.setGravity(Gravity.CENTER_VERTICAL);
        ll.setOrientation(LinearLayout.HORIZONTAL);
        ll.setLayoutParams(params1);

        final Button btn;
        btn = new Button(DynamicActivity.this);

        btn.setText("A"+(j+1));
        btn.setTextSize(15);
        btn.setId(j);
        btn.setPadding(10, 8, 10, 10);

        ll.addView(btn);

        lin_btn.addView(ll);


        btn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                if(v.getId()==0)
                {
                    txt_text.setText("Hii");
                }else if(v.getId()==1)
                {
                    txt_text.setText("hello");
                }else if(v.getId()==2)
                {
                    txt_text.setText("how r u");
                }



            }
        });
    }

}

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

Is it fine to have foreign key as primary key?

Yes, a foreign key can be a primary key in the case of one to one relationship between those tables

Extracting a parameter from a URL in WordPress

In the call back function, use the $request parameter

$parameters = $request->get_params();
echo $parameters['ppc'];

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

Plot a legend outside of the plotting area in base graphics?

I can offer only an example of the layout solution already pointed out.

layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
par(mar = c(5, 4, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2))
lines(1:3, rnorm(3), pch = 2, lty = 2, type="o")
par(mar = c(5, 0, 4, 2) + 0.1)
plot(1:3, rnorm(3), pch = 1, lty = 1, ylim=c(-2,2), type = "n", axes = FALSE, ann = FALSE)
legend(1, 1, c("group A", "group B"), pch = c(1,2), lty = c(1,2))

an ugly picture :S

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';

The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.

Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.

Resolving instances with ASP.NET Core DI from within ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddDbContext<ConfigurationRepository>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString")));

    services.AddScoped<IConfigurationBL, ConfigurationBL>();
    services.AddScoped<IConfigurationRepository, ConfigurationRepository>();
}

Why am I getting "void value not ignored as it ought to be"?

  int a = srand(time(NULL));

The prototype for srand is void srand(unsigned int) (provided you included <stdlib.h>).
This means it returns nothing ... but you're using the value it returns (???) to assign, by initialization, to a.


Edit: this is what you need to do:

#include <stdlib.h> /* srand(), rand() */
#include <time.h>   /* time() */

#define ARRAY_SIZE 1024

void getdata(int arr[], int n)
{
    for (int i = 0; i < n; i++)
    {
        arr[i] = rand();
    }
}

int main(void)
{
    int arr[ARRAY_SIZE];
    srand(time(0));
    getdata(arr, ARRAY_SIZE);
    /* ... */
}

Explanation of 'String args[]' and static in 'public static void main(String[] args)'

If I were explaining this to someone I'd say we'll get to it later for now you need to know that the way to run your program is to use :

public static void main(String[] args) {
        ...
    }

Assuming he/she knows what an array is, I'd say the args is an argument array and you can show some cool examples.

Then after you've gone a bit about Java/JVM and that stuff, you'd get to modifiers eventually to static and public as well.

Then you can spend some time talking about meaning of these IMHO.

You could mention other "cool" stuff such as varargs that you can use this in later versions of Java.

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

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

Android Studio: Default project directory

  • This worked for me :- -> Go to settings -> Type system setting in search bar -> Select your location -> Press Apply

Order of execution of tests in TestNG

Use this:

public class TestNG
{
        @BeforeTest
        public void setUp() 
        {
                   /*--Initialize broowsers--*/

        }

        @Test(priority=0)
        public void Login() 
        {

        }

        @Test(priority=2)
        public void Logout() 
        {

        }

        @AfterTest
        public void tearDown() 
        {
                //--Close driver--//

        }

}

Usually TestNG provides number of annotations, We can use @BeforeSuite, @BeforeTest, @BeforeClass for initializing browsers/setup.

We can assign priority if you have written number of test cases in your script and want to execute as per assigned priority then use: @Test(priority=0) starting from 0,1,2,3....

Meanwhile we can group number of test cases and execute it by grouping. for that we will use @Test(Groups='Regression')

At the end like closing the browsers we can use @AfterTest, @AfterSuite, @AfterClass annotations.

Gridview with two columns and auto resized images

another simple approach with modern built-in stuff like PercentRelativeLayout is now available for new users who hit this problem. thanks to android team for release this item.

<android.support.percent.PercentRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
app:layout_widthPercent="50%">

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:background="#55000000"
        android:paddingBottom="15dp"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:textColor="@android:color/white" />

</FrameLayout>

and for better performance you can use some stuff like picasso image loader which help you to fill whole width of every image parents. for example in your adapter you should use this:

int width= context.getResources().getDisplayMetrics().widthPixels;
    com.squareup.picasso.Picasso
            .with(context)
            .load("some url")
            .centerCrop().resize(width/2,width/2)
            .error(R.drawable.placeholder)
            .placeholder(R.drawable.placeholder)
            .into(item.drawableId);

now you dont need CustomImageView Class anymore.

P.S i recommend to use ImageView in place of Type Int in class Item.

hope this help..

Compiling Java 7 code via Maven

Try to change Java compiler settings in Properties in Eclipse-

Goto: Preferences->Java->Compiler->Compiler Compliance Level-> 1.7 Apply Ok

Restart IDE.

Confirm Compiler setting for project- Goto: Project Properties->Java Compiler-> Uncheck(Use Compliance from execution environment 'JavaSE-1.6' on the java Build path.) and select 1.7 from the dropdown. (Ignore if already 1.7)

Restart IDE.

If still the problem persist- Run individual test cases using command in terminal-

mvn -Dtest=<test class name> test

performSelector may cause a leak because its selector is unknown

To make Scott Thompson's macro more generic:

// String expander
#define MY_STRX(X) #X
#define MY_STR(X) MY_STRX(X)

#define MYSilenceWarning(FLAG, MACRO) \
_Pragma("clang diagnostic push") \
_Pragma(MY_STR(clang diagnostic ignored MY_STR(FLAG))) \
MACRO \
_Pragma("clang diagnostic pop")

Then use it like this:

MYSilenceWarning(-Warc-performSelector-leaks,
[_target performSelector:_action withObject:self];
                )

Pointers in Python?

There's no way you can do that changing only that line. You can do:

a = [1]
b = a
a[0] = 2
b[0]

That creates a list, assigns the reference to a, then b also, uses the a reference to set the first element to 2, then accesses using the b reference variable.

permission denied - php unlink

// Path relative to where the php file is or absolute server path
chdir($FilePath); // Comment this out if you are on the same folder
chown($FileName,465); //Insert an Invalid UserId to set to Nobody Owner; for instance 465
$do = unlink($FileName);

if($do=="1"){ 
    echo "The file was deleted successfully."; 
} else { echo "There was an error trying to delete the file."; } 

Try this. Hope it helps.

Unfamiliar symbol in algorithm: what does ? mean?

In math, ? means FOR ALL.

Unicode character (\u2200, ?).

Keep SSH session alive

putty settings

FYI Putty Users can set the options here

Java synchronized block vs. Collections.synchronizedMap

If you are using JDK 6 then you might want to check out ConcurrentHashMap

Note the putIfAbsent method in that class.

Resize UIImage and change the size of UIImageView

This is the Swift equivalent for Rajneesh071's answer, using extensions

UIImage {
  func scaleToSize(aSize :CGSize) -> UIImage {
    if (CGSizeEqualToSize(self.size, aSize)) {
      return self
    }

    UIGraphicsBeginImageContextWithOptions(aSize, false, 0.0)
    self.drawInRect(CGRectMake(0.0, 0.0, aSize.width, aSize.height))
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
  }
}

Usage:

let image = UIImage(named: "Icon")
item.icon = image?.scaleToSize(CGSize(width: 30.0, height: 30.0))

Tools to search for strings inside files without indexing

I'm a fan of the Find-In-Files dialog in Notepad++. Bonus: It's free.

enter image description here

Validating with an XML schema in Python

As for "pure python" solutions: the package index lists:

  • pyxsd, the description says it uses xml.etree.cElementTree, which is not "pure python" (but included in stdlib), but source code indicates that it falls back to xml.etree.ElementTree, so this would count as pure python. Haven't used it, but according to the docs, it does do schema validation.
  • minixsv: 'a lightweight XML schema validator written in "pure" Python'. However, the description says "currently a subset of the XML schema standard is supported", so this may not be enough.
  • XSV, which I think is used for the W3C's online xsd validator (it still seems to use the old pyxml package, which I think is no longer maintained)

node.js string.replace doesn't work?

Strings are always modelled as immutable (atleast in heigher level languages python/java/javascript/Scala/Objective-C).

So any string operations like concatenation, replacements always returns a new string which contains intended value, whereas the original string will still be same.

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

Facebook Callback appends '#_=_' to Return URL

Using Angular 2 (RC5) and hash-based routes, I do this:

const appRoutes: Routes = [
  ...
  {path: '_', redirectTo: '/facebookLoginSuccess'},
  ...
]

and

export const routing = RouterModule.forRoot(appRoutes, { useHash: true });

As far as I understand, the = character in the route is interpreted as part of optional route parameters definition (see https://angular.io/docs/ts/latest/guide/router.html#!#optional-route-parameters), so not involved in the route matching.

How to handle configuration in Go

Just use standard go flags with iniflags.

Standard go flags have the following benefits:

  • Idiomatic.
  • Easy to use. Flags can be easily added and scattered across arbitrary packages your project uses.
  • Flags have out-of-the-box support for default values and description.
  • Flags provide standard 'help' output with default values and description.

The only drawback standard go flags have - is management problems when the number of flags used in your app becomes too large.

Iniflags elegantly solves this problem: just modify two lines in your main package and it magically gains support for reading flag values from ini file. Flags from ini files can be overriden by passing new values in command-line.

See also https://groups.google.com/forum/#!topic/golang-nuts/TByzyPgoAQE for details.

Git Bash: Could not open a connection to your authentication agent

above solution doesn't work for me for unknown reason. below is my workaround which was worked successfully.

1) DO NOT generate a new ssh key by using command ssh-keygen -t rsa -C"[email protected]", you can delete existing SSH keys.

2) but use Git GUI, -> "Help" -> "Show ssh key" -> "Generate key", the key will saved to ssh automatically and no need to use ssh-add anymore.

How to convert a normal Git repository to a bare one?

Please also consider to use

git clone --mirror path_to_source_repository

From the documentation:

Set up a mirror of the source repository. This implies --bare. Compared to --bare, --mirror not only maps local branches of the source to local branches of the target, it maps all refs (including remote-tracking branches, notes etc.) and sets up a refspec configuration such that all these refs are overwritten by a git remote update in the target repository.

Difference between int and double

int is a binary representation of a whole number, double is a double-precision floating point number.

PowerShell - Start-Process and Cmdline Switches

I've found using cmd works well as an alternative, especially when you need to pipe the output from the called application (espeically when it doesn't have built in logging, unlike msbuild)

cmd /C "$msbuild $args" >> $outputfile

How to split a string between letters and digits (or between digits and letters)?

You can try this:

Pattern p = Pattern.compile("[a-z]+|\\d+");
Matcher m = p.matcher("123abc345def");
ArrayList<String> allMatches = new ArrayList<>();
while (m.find()) {
    allMatches.add(m.group());
}

The result (allMatches) will be:

["123", "abc", "345", "def"]

How to access SVG elements with Javascript

If you are using an <img> tag for the SVG, then you cannot manipulate its contents (as far as I know).

As the accepted answer shows, using <object> is an option.

I needed this recently and used gulp-inject during my gulp build to inject the contents of an SVG file directly into the HTML document as an <svg> element, which is then very easy to work with using CSS selectors and querySelector/getElementBy*.

How do I get the Back Button to work with an AngularJS ui-router state machine?

app.run(['$window', '$rootScope', 
function ($window ,  $rootScope) {
  $rootScope.goBack = function(){
    $window.history.back();
  }
}]);

<a href="#" ng-click="goBack()">Back</a>

What does "O(1) access time" mean?

It means that the access takes constant time i.e. does not depend on the size of the dataset. O(n) means that the access will depend on the size of the dataset linearly.

The O is also known as big-O.

Suppress output of a function

you can use 'capture.output' like below. This allows you to use the data later:

log <- capture.output({
  test <- CensReg.SMN(cc=cc,x=x,y=y, nu=NULL, type="Normal")
})

test$betas

How to use Apple's new San Francisco font on a webpage

Apple's new system font is not publicly exposed. Apple has started abstracting system font names:

The motivation for this abstraction is so the operating system can make better choices on which face to use at a given weight. Apple is also working on font features, such as selectable “6" and “9" glyphs or non-monospaced numbers. It’s my guess that they’d like to bring these features to the web, as well.

Safari and Firefox use SF for -apple-system; Chrome recognizes BlinkMacSystemFont:

body {
    font-family: -apple-system, BlinkMacSystemFont, sans-serif;
}

There are also other variations:

font-family: -apple-system-body
font-family: -apple-system-headline
font-family: -apple-system-subheadline
font-family: -apple-system-caption1
font-family: -apple-system-caption2
font-family: -apple-system-footnote
font-family: -apple-system-short-body
font-family: -apple-system-short-headline
font-family: -apple-system-short-subheadline
font-family: -apple-system-short-caption1
font-family: -apple-system-short-footnote
font-family: -apple-system-tall-body

You can demo these at the following fiddle; most are not supported yet: http://jsfiddle.net/v94gw9nx/

I got my info from Craig Hockenberry's article which has a lot of great info about using the font: http://furbo.org/2015/07/09/i-left-my-system-fonts-in-san-francisco/

Also, some great info on the Surfin' Safari blog about using abstracted system fonts: https://www.webkit.org/blog/3709/using-the-system-font-in-web-content/

And apparently Apple is working with the W3C to standardize using a generic "system" font name in CSS. https://lists.w3.org/Archives/Public/www-style/2015Jul/0169.html

Download the SF font .otf files for your own personal use: https://developer.apple.com/fonts/

How to save a plot as image on the disk?

There are two closely-related questions, and an answer for each.


1. An image will be generated in future in my script, how do I save it to disk?

To save a plot, you need to do the following:

  1. Open a device, using png(), bmp(), pdf() or similar
  2. Plot your model
  3. Close the device using dev.off()

Some example code for saving the plot to a png file:

fit <- lm(some ~ model)

png(filename="your/file/location/name.png")
plot(fit)
dev.off()

This is described in the (combined) help page for the graphical formats ?png, ?bmp, ?jpeg and ?tiff as well as in the separate help page for ?pdf.

Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.


Note that if your plot is made by either lattice or ggplot2 you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing


2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.

dev.print(pdf, 'filename.pdf')

This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace pdf with other filetypes such as png.

Remove numbers from string sql server

Quoting part of @Jatin answer with some modifications,

use this in your where statement:

    SELECT * FROM .... etc.
        Where 
         REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE
        (REPLACE (Name, '0', ''),
        '1', ''),
        '2', ''),
        '3', ''),
        '4', ''),
        '5', ''),
        '6', ''),
        '7', ''),
        '8', ''),
        '9', '') = P_SEARCH_KEY

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I imagine everyone knows what cors is and what it is for. In a simple way and for example if you use nodejs and express for the management, enable it is like this

Dependency:

https://www.npmjs.com/package/cors

app.use (
   cors ({
     origin: "*",
    ... more
   })
);

And for the problem of browser requests locally, it is only to install this extension of google chrome.

Name: Allow CORS: Access-Control-Allow-Origin

https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=es

This allows you to enable and disable cros in local, and problem solved.

Converting Numpy Array to OpenCV Array

Your code can be fixed as follows:

import numpy as np, cv
vis = np.zeros((384, 836), np.float32)
h,w = vis.shape
vis2 = cv.CreateMat(h, w, cv.CV_32FC3)
vis0 = cv.fromarray(vis)
cv.CvtColor(vis0, vis2, cv.CV_GRAY2BGR)

Short explanation:

  1. np.uint32 data type is not supported by OpenCV (it supports uint8, int8, uint16, int16, int32, float32, float64)
  2. cv.CvtColor can't handle numpy arrays so both arguments has to be converted to OpenCV type. cv.fromarray do this conversion.
  3. Both arguments of cv.CvtColor must have the same depth. So I've changed source type to 32bit float to match the ddestination.

Also I recommend you use newer version of OpenCV python API because it uses numpy arrays as primary data type:

import numpy as np, cv2
vis = np.zeros((384, 836), np.float32)
vis2 = cv2.cvtColor(vis, cv2.COLOR_GRAY2BGR)

AWS S3: how do I see how much disk space is using

s3admin is an opensource app (UI) that lets you browse buckets, calculate total size, show largest/smallest files. It's tailored for having a quick overview of your Buckets and their usage.

Using Gradle to build a jar with dependencies

The answer by @felix almost brought me there. I had two issues:

  1. With Gradle 1.5, the manifest tag was not recognised inside the fatJar task, so the Main-Class attribute could not directly be set
  2. the jar had conflicting external META-INF files.

The following setup resolves this

jar {
  manifest {
    attributes(
      'Main-Class': 'my.project.main',
    )
  }
}

task fatJar(type: Jar) {
  manifest.from jar.manifest
  classifier = 'all'
  from {
    configurations.runtimeClasspath.collect { it.isDirectory() ? it : zipTree(it) }
  } {
    exclude "META-INF/*.SF"
    exclude "META-INF/*.DSA"
    exclude "META-INF/*.RSA"
  }
  with jar
}

To add this to the standard assemble or build task, add:

artifacts {
    archives fatJar
}

Edit: thanks to @mjaggard: in recent versions of Gradle, change configurations.runtime to configurations.runtimeClasspath

Event binding on dynamically created elements?

Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  //Particular Parent chield click_x000D_
  $(".buttons").on("click","button",function(){_x000D_
    alert("Clicked");_x000D_
  });  _x000D_
  _x000D_
  //Dynamic event bind on button class  _x000D_
  $(document).on("click",".button",function(){_x000D_
    alert("Dymamic Clicked");_x000D_
  });_x000D_
  $("input").addClass("button");  _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="buttons">_x000D_
  <input type="button" value="1">_x000D_
  <button>2</button>_x000D_
  <input type="text">_x000D_
  <button>3</button>  _x000D_
  <input type="button" value="5">  _x000D_
  </div>_x000D_
<button>6</button>
_x000D_
_x000D_
_x000D_

How do you check if a JavaScript Object is a DOM Object?

In Firefox, you can use the instanceof Node. That Node is defined in DOM1.

But that is not that easy in IE.

  1. "instanceof ActiveXObject" only can tell that it is a native object.
  2. "typeof document.body.appendChild=='object'" tell that it may be DOM object, but also can be something else have same function.

You can only ensure it is DOM element by using DOM function and catch if any exception. However, it may have side effect (e.g. change object internal state/performance/memory leak)

MySQL select one column DISTINCT, with corresponding other columns

Keep in mind when using the group by and order by that MySQL is the ONLY database that allows for columns to be used in the group by and/or order by piece that are not part of the select statement.

So for example: select column1 from table group by column2 order by column3

That will not fly in other databases like Postgres, Oracle, MSSQL, etc. You would have to do the following in those databases

select column1, column2, column3 from table group by column2 order by column3

Just some info in case you ever migrate your current code to another database or start working in another database and try to reuse code.

Git Checkout warning: unable to unlink files, permission denied

I ran into this problem whenever running "git repack" or "git gc" on my OS X machines, even when running git with admin privileges, and I finally solved it after coming across this page: http://hints.macworld.com/comment.php?mode=view&cid=1734

The fix is to open a terminal, go to your git repo, cd into the .git folder, and then do:

chflags -R nouchg *

If that was the issue, then after that, your git commands will work as normal.

Is there a standardized method to swap two variables in Python?

Does not work for multidimensional arrays, because references are used here.

import numpy as np

# swaps
data = np.random.random(2)
print(data)
data[0], data[1] = data[1], data[0]
print(data)

# does not swap
data = np.random.random((2, 2))
print(data)
data[0], data[1] = data[1], data[0]
print(data)

See also Swap slices of Numpy arrays

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

You can't remove hidden without also removing system.

You want:

cd mydir
attrib -H -S /D /S

That will remove the hidden and system attributes from all the files/folders inside of your current directory.

jQuery Ajax Request inside Ajax Request

Call second ajax from 'complete'

Here is the example

   var dt='';
   $.ajax({
    type: "post",
    url: "ajax/example.php",
    data: 'page='+btn_page,
    success: function(data){
        dt=data;
        /*Do something*/
    },
    complete:function(){
        $.ajax({
           var a=dt; // This line shows error.
           type: "post",
           url: "example.php",
           data: 'page='+a,
           success: function(data){
              /*do some thing in second function*/
           },
       });
    }
});

How to automatically convert strongly typed enum into int?

#include <cstdlib>
#include <cstdio>
#include <cstdint>

#include <type_traits>

namespace utils
{

namespace details
{

template< typename E >
using enable_enum_t = typename std::enable_if< std::is_enum<E>::value, 
                                               typename std::underlying_type<E>::type 
                                             >::type;

}   // namespace details


template< typename E >
constexpr inline details::enable_enum_t<E> underlying_value( E e )noexcept
{
    return static_cast< typename std::underlying_type<E>::type >( e );
}   


template< typename E , typename T>
constexpr inline typename std::enable_if< std::is_enum<E>::value &&
                                          std::is_integral<T>::value, E
                                         >::type 
 to_enum( T value ) noexcept 
 {
     return static_cast<E>( value );
 }

} // namespace utils




int main()
{
    enum class E{ a = 1, b = 3, c = 5 };

    constexpr auto a = utils::underlying_value(E::a);
    constexpr E    b = utils::to_enum<E>(5);
    constexpr auto bv = utils::underlying_value(b);

    printf("a = %d, b = %d", a,bv);
    return 0;
}

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

Index of duplicates items in a python list

I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...

my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
    if elem in my_dict:
        my_dict[elem].append(ind)
    else:
        my_dict.update({elem:[ind]})

for key,value in my_dict.iteritems():
    if len(value) > 1:
        print "key(%s) has indices (%s)" %(key,value)

which prints the following:

key(1) has indices ([0, 1])
key(5) has indices ([5, 6])

A Simple AJAX with JSP example

loadXMLDoc JS function should return false, otherwise it will result in postback.

How to connect to a secure website using SSL in Java with a pkcs12 file?

For anyone encountering a similar situation I was able to solve the issue above as follows:

  1. Regenerate your pkcs12 file as follows:

    openssl pkcs12 -in oldpkcs.p12 -out keys -passout pass:tmp
    openssl pkcs12 -in keys -export -out new.p12 -passin pass:tmp -passout pass:newpasswd
    
  2. Import the CA certificate from server into a TrustStore ( either your own, or the java keystore in $JAVA_HOME/jre/lib/security/cacerts, password: changeit).

  3. Set the following system properties:

    System.setProperty("javax.net.ssl.trustStore", "myTrustStore");
    System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
    System.setProperty("javax.net.ssl.keyStoreType", "pkcs12");
    System.setProperty("javax.net.ssl.keyStore", "new.p12");
    System.setProperty("javax.net.ssl.keyStorePassword", "newpasswd");
    
  4. Test ur url.

Courtesy@ http://forums.sun.com/thread.jspa?threadID=5296333

Case insensitive string compare in LINQ-to-SQL

Remember that there is a difference between whether the query works and whether it works efficiently! A LINQ statement gets converted to T-SQL when the target of the statement is SQL Server, so you need to think about the T-SQL that would be produced.

Using String.Equals will most likely (I am guessing) bring back all of the rows from SQL Server and then do the comparison in .NET, because it is a .NET expression that cannot be translated into T-SQL.

In other words using an expression will increase your data access and remove your ability to make use of indexes. It will work on small tables and you won't notice the difference. On a large table it could perform very badly.

That's one of the problems that exists with LINQ; people no longer think about how the statements they write will be fulfilled.

In this case there isn't a way to do what you want without using an expression - not even in T-SQL. Therefore you may not be able to do this more efficiently. Even the T-SQL answer given above (using variables with collation) will most likely result in indexes being ignored, but if it is a big table then it is worth running the statement and looking at the execution plan to see if an index was used.

How to auto-size an iFrame?

My workaround is to set the iframe the height/width well over any anticipated source page size in CSS & the background property to transparent.

In the iframe set allow-transparency to true and scrolling to no.

The only thing visible will be whatever source file you use. It works in IE8, Firefox 3, & Safari.

How do I get my page title to have an icon?

If using in ruby rails use the below code.

For calculating the path of the file, asset_path function is used to find the image that we are using inside of the rails code embedded in <%= code %>

<link rel="icon" type="image/png" href="<%= asset_path('icon_name.jpg')%>">

Regarding C++ Include another class

What is the basic problem in your code?

Your code needs to be separated out in to interfaces(.h) and Implementations(.cpp).
The compiler needs to see the composition of a type when you write something like

ClassTwo obj;

This is because the compiler needs to reserve enough memory for object of type ClassTwo to do so it needs to see the definition of ClassTwo. The most common way to do this in C++ is to split your code in to header files and source files.
The class definitions go in the header file while the implementation of the class goes in to source files. This way one can easily include header files in to other source files which need to see the definition of class who's object they create.

Why can't I simply put all code in cpp files and include them in other files?

You cannot simple put all the code in source file and then include that source file in other files.C++ standard mandates that you can declare a entity as many times as you need but you can define it only once(One Definition Rule(ODR)). Including the source file would violate the ODR because a copy of the entity is created in every translation unit where the file is included.

How to solve this particular problem?

Your code should be organized as follows:

//File1.h

Define ClassOne 

//File2.h

#include <iostream>
#include <string>


class ClassTwo
{
private:
   string myType;
public:
   void setType(string);
   std::string getType();
}; 

//File1.cpp

#include"File1.h"

Implementation of ClassOne 

//File2.cpp

#include"File2.h"

void ClassTwo::setType(std::string sType)
{
    myType = sType;
}

void ClassTwo::getType(float fVal)
{
    return myType;
} 

//main.cpp

#include <iostream>
#include <string>
#include "file1.h"
#include "file2.h"
using namespace std;

int main()
{

    ClassOne cone;
    ClassTwo ctwo;

    //some codes
}

Is there any alternative means rather than including header files?

If your code only needs to create pointers and not actual objects you might as well use Forward Declarations but note that using forward declarations adds some restrictions on how that type can be used because compiler sees that type as an Incomplete type.

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

How to dynamically change the color of the selected menu item of a web page?

It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

/* CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* JQuery Example */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>

How to change the color of text in javafx TextField?

The CSS styles for text input controls such as TextField for JavaFX 8 are defined in the modena.css stylesheet as below. Create a custom CSS stylesheet and modify the colors as you wish. Use the CSS reference guide if you need help understanding the syntax and available attributes and values.

.text-input {
    -fx-text-fill: -fx-text-inner-color;
    -fx-highlight-fill: derive(-fx-control-inner-background,-20%);
    -fx-highlight-text-fill: -fx-text-inner-color;
    -fx-prompt-text-fill: derive(-fx-control-inner-background,-30%);
    -fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border),
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: 0, 1;
    -fx-background-radius: 3, 2;
    -fx-cursor: text;
    -fx-padding: 0.333333em 0.583em 0.333333em 0.583em; /* 4 7 4 7 */
}
.text-input:focused {
    -fx-highlight-fill: -fx-accent;
    -fx-highlight-text-fill: white;
    -fx-background-color: 
        -fx-focus-color,
        -fx-control-inner-background,
        -fx-faint-focus-color,
        linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);
    -fx-background-insets: -0.2, 1, -1.4, 3;
    -fx-background-radius: 3, 2, 4, 0;
    -fx-prompt-text-fill: transparent;
}

Although using an external stylesheet is a preferred way to do the styling, you can style inline, using something like below:

textField.setStyle("-fx-text-inner-color: red;");

Difference between static memory allocation and dynamic memory allocation

Static memory allocation. Memory allocated will be in stack.

int a[10];

Dynamic memory allocation. Memory allocated will be in heap.

int *a = malloc(sizeof(int) * 10);

and the latter should be freed since there is no Garbage Collector(GC) in C.

free(a);

Java, how to compare Strings with String Arrays

import java.util.Scanner;
import java.util.*;
public class Main
{
  public static void main (String[]args) throws Exception
  {
    Scanner in = new Scanner (System.in);
    /*Prints out the welcome message at the top of the screen */
      System.out.printf ("%55s", "**WELCOME TO IDIOCY CENTRAL**\n");
      System.out.printf ("%55s", "=================================\n");

      String[] codes =
    {
    "G22", "K13", "I30", "S20"};

      System.out.printf ("%5s%5s%5s%5s\n", codes[0], codes[1], codes[2],
             codes[3]);
      System.out.printf ("Enter one of the above!\n");

    String usercode = in.nextLine ();
    for (int i = 0; i < codes.length; i++)
      {
    if (codes[i].equals (usercode))
      {
        System.out.printf ("What's the matter with you?\n");
      }
    else
      {
        System.out.printf ("Youda man!");
      }
      }

  }
}

How to set image name in Dockerfile?

Tagging of the image isn't supported inside the Dockerfile. This needs to be done in your build command. As a workaround, you can do the build with a docker-compose.yml that identifies the target image name and then run a docker-compose build. A sample docker-compose.yml would look like

version: '2'

services:
  man:
    build: .
    image: dude/man:v2

That said, there's a push against doing the build with compose since that doesn't work with swarm mode deploys. So you're back to running the command as you've given in your question:

docker build -t dude/man:v2 .

Personally, I tend to build with a small shell script in my folder (build.sh) which passes any args and includes the name of the image there to save typing. And for production, the build is handled by a ci/cd server that has the image name inside the pipeline script.

How to convert float to int with Java

Actually, there are different ways to downcast float to int, depending on the result you want to achieve: (for int i, float f)

  • round (the closest integer to given float)

    i = Math.round(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -3
    

    note: this is, by contract, equal to (int) Math.floor(f + 0.5f)

  • truncate (i.e. drop everything after the decimal dot)

    i = (int) f;
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
  • ceil/floor (an integer always bigger/smaller than a given value if it has any fractional part)

    i = (int) Math.ceil(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  3 ; f =  2.68 -> i =  3
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -2 ; f = -2.68 -> i = -2
    
    i = (int) Math.floor(f);
      f =  2.0 -> i =  2 ; f =  2.22 -> i =  2 ; f =  2.68 -> i =  2
      f = -2.0 -> i = -2 ; f = -2.22 -> i = -3 ; f = -2.68 -> i = -3
    

For rounding positive values, you can also just use (int)(f + 0.5), which works exactly as Math.Round in those cases (as per doc).

You can also use Math.rint(f) to do the rounding to the nearest even integer; it's arguably useful if you expect to deal with a lot of floats with fractional part strictly equal to .5 (note the possible IEEE rounding issues), and want to keep the average of the set in place; you'll introduce another bias, where even numbers will be more common than odd, though.

See

http://mindprod.com/jgloss/round.html

http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html

for more information and some examples.

How to use a ViewBag to create a dropdownlist?

Use Viewbag is wrong for sending list to view.You should using Viewmodel in this case. like this:

Send Country list and City list and Other list you need to show in View:

HomeController Code:

[HttpGet]
        public ActionResult NewAgahi() // New Advertising
        {
            //--------------------------------------------------------
            // ??????? ?? ?????? ???? ????? ??? ??? ?? ???
            Country_Repository blCountry = new Country_Repository();
            Ostan_Repository blOstan = new Ostan_Repository();
            City_Repository blCity = new City_Repository();
            Mahale_Repository blMahale = new Mahale_Repository();
            Agahi_Repository blAgahi = new Agahi_Repository();

            var vm = new NewAgahi_ViewModel();
            vm.Country = blCountry.Select();
            vm.Ostan = blOstan.Select();
            vm.City = blCity.Select();
            vm.Mahale = blMahale.Select();
            //vm.Agahi = blAgahi.Select();

            return View(vm);
        }

        [ValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult NewAgahi(Agahi agahi)
        {

            if (ModelState.IsValid == true)
            {
                Agahi_Repository blAgahi = new Agahi_Repository();

                agahi.Date = DateTime.Now.Date;
                agahi.UserId = 1048;
                agahi.GroupId = 1;


                if (blAgahi.Add(agahi) == true)
                {
                    //Success
                    return JavaScript("alert('??? ??')");

                }
                else
                {
                    //Fail
                    return JavaScript("alert('????? ?? ???')");

            }

Viewmodel Code:

using ProjectName.Models.DomainModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace ProjectName.ViewModels
{
    public class NewAgahi_ViewModel // ???? ??????? ???? ?? ??? ??? ?? ?? ???
    { 

        public IEnumerable<Country> Country { get; set; }

        public IEnumerable<Ostan> Ostan { get; set; }

        public IEnumerable<City> City { get; set; }

        public IQueryable<Mahale> Mahale { get; set; }

        public ProjectName.Models.DomainModels.Agahi Agahi { get; set; }

    }
}

View Code:

@model ProjectName.ViewModels.NewAgahi_ViewModel

..... .....

@Html.DropDownList("CountryList", new SelectList(Model.Country, "id", "Name"))

 @Html.DropDownList("CityList", new SelectList(Model.City, "id", "Name"))

Country_Repository Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ProjectName.Models.DomainModels;

namespace ProjectName.Models.Repositories
{
    public class Country_Repository : IDisposable
    {
        private MyWebSiteDBEntities db = null;


        public Country_Repository()
        {
            db = new DomainModels.MyWebSiteDBEntities();
        }

        public Boolean Add(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Add(entity);
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges()); 
                                                                //return "True";
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message;
                //return e.Message;
                return false;
            }
        }


        public bool Update(Country entity, bool autoSave = true)
        {
            try
            {
                db.Country.Attach(entity);
                db.Entry(entity).State = System.Data.Entity.EntityState.Modified;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch (Exception e)
            {
                string ss = e.Message; // ?? ?????????? ??? ???? ?????? ?????? ??? ?? ?????

                return false;
            }
        }

        public bool Delete(Country entity, bool autoSave = true)
        {
            try
            {
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public bool Delete(int id, bool autoSave = true)
        {
            try
            {
                var entity = db.Country.Find(id);
                db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                if (autoSave)
                    return Convert.ToBoolean(db.SaveChanges());
                else
                    return false;
            }
            catch
            {
                return false;
            }
        }

        public Country Find(int id)
        {
            try
            {
                return db.Country.Find(id);
            }
            catch
            {
                return null;
            }
        }


        public IQueryable<Country> Where(System.Linq.Expressions.Expression<Func<Country, bool>> predicate)
        {
            try
            {
                return db.Country.Where(predicate);
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<Country> Select()
        {
            try
            {
                return db.Country.AsQueryable();
            }
            catch
            {
                return null;
            }
        }

        public IQueryable<TResult> Select<TResult>(System.Linq.Expressions.Expression<Func<Country, TResult>> selector)
        {
            try
            {
                return db.Country.Select(selector);
            }
            catch
            {
                return null;
            }
        }

        public int GetLastIdentity()
        {
            try
            {
                if (db.Country.Any())
                    return db.Country.OrderByDescending(p => p.id).First().id;
                else
                    return 0;
            }
            catch
            {
                return -1;
            }
        }

        public int Save()
        {
            try
            {
                return db.SaveChanges();
            }
            catch
            {
                return -1;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.db != null)
                {
                    this.db.Dispose();
                    this.db = null;
                }
            }
        }

        ~Country_Repository()
        {
            Dispose(false);
        }
    }
}

Simple Android RecyclerView example

Android RecyclerView

Start by adding recyclerview library.

implementation 'androidx.recyclerview:recyclerview:1.1.0'

Create model class.

     public class UserModel implements Serializable {

    private String userName;


    public UserModel(String userName) {
        this.userName = userName;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
   }

create adapter class.

public class UsersAdapter extends RecyclerView.Adapter<UsersAdapter.UsersAdapterVh> implements Filterable {

    private List<UserModel> userModelList;
    private List<UserModel> getUserModelListFiltered;
    private Context context;
    private SelectedUser selectedUser;

    public UsersAdapter(List<UserModel> userModelList,SelectedUser selectedUser) {
        this.userModelList = userModelList;
        this.getUserModelListFiltered = userModelList;
        this.selectedUser = selectedUser;
    }

    @NonNull
    @Override
    public UsersAdapter.UsersAdapterVh onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        context = parent.getContext();

        return new UsersAdapterVh(LayoutInflater.from(context).inflate(R.layout.row_users,null));
    }

    @Override
    public void onBindViewHolder(@NonNull UsersAdapter.UsersAdapterVh holder, int position) {

        UserModel userModel = userModelList.get(position);

        String username = userModel.getUserName();
        String prefix = userModel.getUserName().substring(0,1);

        holder.tvUsername.setText(username);
        holder.tvPrefix.setText(prefix);

    }

    @Override
    public int getItemCount() {
        return userModelList.size();
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {
            @Override
            protected FilterResults performFiltering(CharSequence charSequence) {
                FilterResults filterResults = new FilterResults();

                if(charSequence == null | charSequence.length() == 0){
                    filterResults.count = getUserModelListFiltered.size();
                    filterResults.values = getUserModelListFiltered;

                }else{
                    String searchChr = charSequence.toString().toLowerCase();

                    List<UserModel> resultData = new ArrayList<>();

                    for(UserModel userModel: getUserModelListFiltered){
                        if(userModel.getUserName().toLowerCase().contains(searchChr)){
                            resultData.add(userModel);
                        }
                    }
                    filterResults.count = resultData.size();
                    filterResults.values = resultData;

                }

                return filterResults;
            }

            @Override
            protected void publishResults(CharSequence charSequence, FilterResults filterResults) {

                userModelList = (List<UserModel>) filterResults.values;
                notifyDataSetChanged();

            }
        };
        return filter;
    }


    public interface SelectedUser{

        void selectedUser(UserModel userModel);

    }

    public class UsersAdapterVh extends RecyclerView.ViewHolder {

        TextView tvPrefix;
        TextView tvUsername;
        ImageView imIcon;
        public UsersAdapterVh(@NonNull View itemView) {
            super(itemView);
            tvPrefix = itemView.findViewById(R.id.prefix);
            tvUsername = itemView.findViewById(R.id.username);
            imIcon = itemView.findViewById(R.id.imageView);

            itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    selectedUser.selectedUser(userModelList.get(getAdapterPosition()));
                }
            });


        }
    }
}

create layout row_uses.xml

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:padding="10dp"
        android:layout_height="wrap_content">

        <RelativeLayout
            android:layout_width="50dp"
            android:background="@drawable/users_bg"
            android:layout_height="50dp">
            <TextView
                android:id="@+id/prefix"
                android:layout_width="wrap_content"
                android:textSize="16sp"
                android:textColor="@color/headerColor"
                android:text="T"
                android:layout_centerInParent="true"
                android:layout_height="wrap_content"/>

        </RelativeLayout>
        <TextView
            android:id="@+id/username"
            android:layout_width="wrap_content"
            android:textSize="16sp"
            android:textColor="@color/headerColor"
            android:text="username"
            android:layout_marginStart="90dp"
            android:layout_centerVertical="true"
            android:layout_height="wrap_content"/>
        <ImageView
            android:layout_width="wrap_content"
            android:id="@+id/imageView"
            android:layout_margin="10dp"
            android:layout_alignParentEnd="true"
            android:src="@drawable/ic_navigate_next_black_24dp"
            android:layout_height="wrap_content"/>
    </RelativeLayout>

</LinearLayout>

Find recyclerview and populate data.

Toolbar toolbar;
RecyclerView recyclerView;

List<UserModel> userModelList = new ArrayList<>();

String[] names = {"Richard","Alice","Hannah","David"};

UsersAdapter usersAdapter;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    recyclerView = findViewById(R.id.recyclerview);
    toolbar = findViewById(R.id.toolbar);

    this.setSupportActionBar(toolbar);
    this.getSupportActionBar().setTitle("");

    recyclerView.setLayoutManager(new LinearLayoutManager(this));
    recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));

    for(String s:names){
        UserModel userModel = new UserModel(s);

        userModelList.add(userModel);
    }

    usersAdapter = new UsersAdapter(userModelList,this);

    recyclerView.setAdapter(usersAdapter);

}

find full tutorial and source code here:

Android RecyclerView

How to validate phone numbers using regex

This is a simple Regular Expression pattern for Philippine Mobile Phone Numbers:

((\+[0-9]{2})|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

or

((\+63)|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

will match these:

+63.917.123.4567  
+63-917-123-4567  
+63 917 123 4567  
+639171234567  
09171234567  

The first one will match ANY two digit country code, while the second one will match the Philippine country code exclusively.

Test it here: http://refiddle.com/1ox

phpMyAdmin on MySQL 8.0

As @kgr mentioned, MySQL 8.0.11 made some changes to the authentication method.

I've opened a phpMyAdmin bug report about this: https://github.com/phpmyadmin/phpmyadmin/issues/14220.

MySQL 8.0.4-rc was working fine for me, and I kind of think it's ridiculous for MySQL to make such a change in a patch level release.

What is the easiest way to get current GMT time in Unix timestamp format?

I would use time.time() to get a timestamp in seconds since the epoch.

import time

time.time()

Output:

1369550494.884832

For the standard CPython implementation on most platforms this will return a UTC value.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

You may convert latitude-longitude to UTM format which is metric format that may help you to calculate distances. Then you can easily decide if point falls into specific location.

How do I get the current username in Windows PowerShell?

$username=( ( Get-WMIObject -class Win32_ComputerSystem | Select-Object -ExpandProperty username ) -split '\\' )[1]

$username

The second username is for display only purposes only if you copy and paste it.

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

Writing a list to a file with Python

Using numpy.savetxt is also an option:

import numpy as np

np.savetxt('list.txt', list, delimiter="\n", fmt="%s")

printf, wprintf, %s, %S, %ls, char* and wchar*: Errors not announced by a compiler warning?

At least in Visual C++: printf (and other ACSII functions): %s represents an ASCII string %S is a Unicode string wprintf (and other Unicode functions): %s is a Unicode string %S is an ASCII string

As far as no compiler warnings, printf uses a variable argument list, with only the first argument able to be type checked. The compiler is not designed to parse the format string and type check the parameters that match. In cases of functions like printf, that is up to the programmer

Converting std::__cxx11::string to std::string

For me -D_GLIBCXX_USE_CXX11_ABI=0 didn't help.

It works after I linked to C++ libs version instead of gnustl.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

In You MainActivity.java import android .support.v7.widget.Toolbar insert of java program

How can I create an MSI setup?

If you don't understand Windows Installer then I highly recommend The Definitive Guide to Windows Installer. You can't really use WiX without understanding MSI. Also worth downloading is the Windows Installer 4.5 SDK.

If you don't want to learn the Windows Installer fundamentals, then you'll need some wizard type package to hide all the nitty gritty details and hold your hand. There are plenty of options, some more expensive than others.

  • InstallShield
  • Advanced Installer
  • MSI Factory
  • etc..

However still I'd suggest picking up the above book and taking some time to understand what's going on "under the hood", it'll really help you figure out what's going wrong when customers start complaining that something is broken with the setup :)

HTTPS using Jersey Client

If you are using Java 8, a shorter version for Jersey2 than the answer provided by Aleksandr.

SSLContext sslContext = null;
try {
  sslContext = SSLContext.getInstance("SSL");
  // Create a new X509TrustManager
  sslContext.init(null, getTrustManager(), null);
} catch (NoSuchAlgorithmException | KeyManagementException e) {
  throw e;
}
final Client client = ClientBuilder.newBuilder().hostnameVerifier((s, session) -> true)
  .sslContext(sslContext).build();
return client;

private TrustManager[] getTrustManager() {
  return new TrustManager[] {
    new X509TrustManager() {
      @Override
      public X509Certificate[] getAcceptedIssuers() {
        return null;
      }
      @Override
      public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
      @Override
      public void checkClientTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
      }
    }
  };
}

Deep copy vs Shallow Copy

The quintessential example of this is an array of pointers to structs or objects (that are mutable).

A shallow copy copies the array and maintains references to the original objects.

A deep copy will copy (clone) the objects too so they bear no relation to the original. Implicit in this is that the object themselves are deep copied. This is where it gets hard because there's no real way to know if something was deep copied or not.

The copy constructor is used to initilize the new object with the previously created object of the same class. By default compiler wrote a shallow copy. Shallow copy works fine when dynamic memory allocation is not involved because when dynamic memory allocation is involved then both objects will points towards the same memory location in a heap, Therefore to remove this problem we wrote deep copy so both objects have their own copy of attributes in a memory.

In order to read the details with complete examples and explanations you could see the article Constructors and destructors.

The default copy constructor is shallow. You can make your own copy constructors deep or shallow, as appropriate. See C++ Notes: OOP: Copy Constructors.

How to echo or print an array in PHP?

To see the contents of array you can use.

1) print_r($array); or if you want nicely formatted array then:

echo '<pre>'; print_r($array); echo '</pre>';

2) use var_dump($array) to get more information of the content in the array like datatype and length.

3) you can loop the array using php's foreach(); and get the desired output. more info on foreach in php's documentation website:
http://in3.php.net/manual/en/control-structures.foreach.php

Accessing bash command line args $@ vs $*

$@ is same as $*, but each parameter is a quoted string, that is, the parameters are passed on intact, without interpretation or expansion. This means, among other things, that each parameter in the argument list is seen as a separate word.

Of course, "$@" should be quoted.

http://tldp.org/LDP/abs/html/internalvariables.html#ARGLIST

How to change the Spyder editor background to dark?

If you're using Spyder 3, please go to

Tools > Preferences > Syntax Coloring

and select there the dark theme you want to use.

In Spyder 4, a dark theme is used by default. But if you want to select a different theme you can go to

Tools > Preferences > Appearance > Syntax highlighting theme

How can I get the active screen dimensions?

You can use this to get desktop workspace bounds of the primary screen:

System.Windows.SystemParameters.WorkArea

This is also useful for getting just the size of the primary screen:

System.Windows.SystemParameters.PrimaryScreenWidth System.Windows.SystemParameters.PrimaryScreenHeight

best way to get folder and file list in Javascript

fs/promises and fs.Dirent

Here's an efficient, non-blocking ls program using Node's fast fs.Dirent objects and fs/promises module. This approach allows you to skip wasteful fs.exist or fs.stat calls on every path -

// main.js
import { readdir } from "fs/promises"
import { join } from "path"

async function* ls (path = ".")
{ yield path
  for (const dirent of await readdir(path, { withFileTypes: true }))
    if (dirent.isDirectory())
      yield* ls(join(path, dirent.name))
    else
      yield join(path, dirent.name)
}

async function* empty () {}

async function toArray (iter = empty())
{ let r = []
  for await (const x of iter)
    r.push(x)
  return r
}

toArray(ls(".")).then(console.log, console.error)

Let's get some sample files so we can see ls working -

$ yarn add immutable     # (just some example package)
$ node main.js
[
  '.',
  'main.js',
  'node_modules',
  'node_modules/.yarn-integrity',
  'node_modules/immutable',
  'node_modules/immutable/LICENSE',
  'node_modules/immutable/README.md',
  'node_modules/immutable/contrib',
  'node_modules/immutable/contrib/cursor',
  'node_modules/immutable/contrib/cursor/README.md',
  'node_modules/immutable/contrib/cursor/__tests__',
  'node_modules/immutable/contrib/cursor/__tests__/Cursor.ts.skip',
  'node_modules/immutable/contrib/cursor/index.d.ts',
  'node_modules/immutable/contrib/cursor/index.js',
  'node_modules/immutable/dist',
  'node_modules/immutable/dist/immutable-nonambient.d.ts',
  'node_modules/immutable/dist/immutable.d.ts',
  'node_modules/immutable/dist/immutable.es.js',
  'node_modules/immutable/dist/immutable.js',
  'node_modules/immutable/dist/immutable.js.flow',
  'node_modules/immutable/dist/immutable.min.js',
  'node_modules/immutable/package.json',
  'package.json',
  'yarn.lock'
]

For added explanation and other ways to leverage async generators, see this Q&A.

SQL Server check case-sensitivity?

Collation can be set at various levels:

  1. Server
  2. Database
  3. Column

So you could have a Case Sensitive Column in a Case Insensitive database. I have not yet come across a situation where a business case could be made for case sensitivity of a single column of data, but I suppose there could be.

Check Server Collation

SELECT SERVERPROPERTY('COLLATION')

Check Database Collation

SELECT DATABASEPROPERTYEX('AdventureWorks', 'Collation') SQLCollation;

Check Column Collation

select table_name, column_name, collation_name
from INFORMATION_SCHEMA.COLUMNS
where table_name = @table_name

What is the purpose of the single underscore "_" variable in Python?

Underscore _ is considered as "I don't Care" or "Throwaway" variable in Python

  • The python interpreter stores the last expression value to the special variable called _.

    >>> 10 
    10
    
    >>> _ 
    10
    
    >>> _ * 3 
    30
    
  • The underscore _ is also used for ignoring the specific values. If you don’t need the specific values or the values are not used, just assign the values to underscore.

    Ignore a value when unpacking

    x, _, y = (1, 2, 3)
    
    >>> x
    1
    
    >>> y 
    3
    

    Ignore the index

    for _ in range(10):     
        do_something()
    

Can I redirect the stdout in python into some sort of string buffer?

Starting with Python 2.6 you can use anything implementing the TextIOBase API from the io module as a replacement. This solution also enables you to use sys.stdout.buffer.write() in Python 3 to write (already) encoded byte strings to stdout (see stdout in Python 3). Using StringIO wouldn't work then, because neither sys.stdout.encoding nor sys.stdout.buffer would be available.

A solution using TextIOWrapper:

import sys
from io import TextIOWrapper, BytesIO

# setup the environment
old_stdout = sys.stdout
sys.stdout = TextIOWrapper(BytesIO(), sys.stdout.encoding)

# do something that writes to stdout or stdout.buffer

# get output
sys.stdout.seek(0)      # jump to the start
out = sys.stdout.read() # read output

# restore stdout
sys.stdout.close()
sys.stdout = old_stdout

This solution works for Python 2 >= 2.6 and Python 3.

Please note that our new sys.stdout.write() only accepts unicode strings and sys.stdout.buffer.write() only accepts byte strings. This might not be the case for old code, but is often the case for code that is built to run on Python 2 and 3 without changes, which again often makes use of sys.stdout.buffer.

You can build a slight variation that accepts unicode and byte strings for write():

class StdoutBuffer(TextIOWrapper):
    def write(self, string):
        try:
            return super(StdoutBuffer, self).write(string)
        except TypeError:
            # redirect encoded byte strings directly to buffer
            return super(StdoutBuffer, self).buffer.write(string)

You don't have to set the encoding of the buffer the sys.stdout.encoding, but this helps when using this method for testing/comparing script output.

How to make a Bootstrap accordion collapse when clicking the header div?

All you need to do is to to use...

  • data-toggle="collapse"
  • data-target="#ElementToExpandOnClick"

...on the element you want to click to trigger the collapse/expand effect.

The element with data-toggle="collapse" will be the element to trigger the effect. The data-target attribute indicates the element that will expand when the effect is triggered.

Optionally you can set the data-parent if you want to create an accordion effect instead of independent collapsible, e.g.:

  • data-parent="#accordion"

I would also add the following CSS to the elements with data-toggle="collapse" if they aren't <a> tags, e.g.:

.panel-heading {
    cursor: pointer;
}

Here's a jsfiddle with the modified html from the Bootstrap 3 documentation.

Write to rails console

I think you should use the Rails debug options:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"
logger.info "Processing the request..."
logger.fatal "Terminating application, raised unrecoverable error!!!"

https://guides.rubyonrails.org/debugging_rails_applications.html

How can I add an item to a ListBox in C# and WinForms?

ListBoxItem is a WPF class, NOT a WinForms class.

For WPF, use ListBoxItem.

For WinForms, the item is a Object type, so use one of these:
1. Provide your own ToString() method for the Object type.
2. Use databinding with DisplayMemeber and ValueMember (see Kelsey's answer)

Accessing JSON elements

import json

# some JSON:
json_str =  '{ "name":"Sarah", "age":25, "city":"Chicago"}'

# parse json_str:
json = json.loads(json_str)

# get tags from json   
tags = []
for tag in json:
    tags.append(tag)
  

# print each tag name e your content
for i in range(len(tags)):
    print(tags[i] + ': ' + str(json[tags[i]]))

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Inspired by @aaronpenne and @Soumyaansh

f = open("file.txt", "rb")
text = f.read().decode(errors='replace')

Getting URL hash location, and using it in jQuery

I would suggest better cek first if the current page has a hash. Otherwise it will be undefined.

$(window).on('load', function(){        
    if( location.hash && location.hash.length ) {
       var hash = decodeURIComponent(location.hash.substr(1));
       $('ul'+hash+':first').show();;
    }       
});

hexadecimal string to byte array in python

There is a built-in function in bytearray that does what you intend.

bytearray.fromhex("de ad be ef 00")

It returns a bytearray and it reads hex strings with or without space separator.

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

How to include a font .ttf using CSS?

You can use font face like this:

@font-face {
  font-family:"Name-Of-Font";
  src: url("yourfont.ttf") format("truetype");
}

How to kill a thread instantly in C#?

The reason it's hard to just kill a thread is because the language designers want to avoid the following problem: your thread takes a lock, and then you kill it before it can release it. Now anyone who needs that lock will get stuck.

What you have to do is use some global variable to tell the thread to stop. You have to manually, in your thread code, check that global variable and return if you see it indicates you should stop.

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

How to get a Char from an ASCII Character Code in c#

You can simply write:

char c = (char) 2;

or

char c = Convert.ToChar(2);

or more complex option for ASCII encoding only

char[] characters = System.Text.Encoding.ASCII.GetChars(new byte[]{2});
char c = characters[0];

The identity used to sign the executable is no longer valid

I fixed this issue by selecting the correct team within Xcode (I'm part of multiple teams). Also, I revoked my certificate, requested a new one, uploaded that, and then re-downloaded it.

How do you install Boost on MacOS?

Download MacPorts, and run the following command:

sudo port install boost 

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

Compress images on client side before uploading

If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.

SQL QUERY replace NULL value in a row with a value from the previous known value

The best solution is the one offered by Bill Karwin. I recently had to solve this in a relatively large resultset (1000 rows with 12 columns each needing this type of "show me last non-null value if this value is null on the current row") and using the update method with a top 1 select for the previous known value (or subquery with a top 1 ) ran super slow.

I am using SQL 2005 and the syntax for a variable replacement is slightly different than mysql:

UPDATE mytable 
SET 
    @n = COALESCE(number, @n),
    number = COALESCE(number, @n)
ORDER BY date

The first set statement updates the value of the variable @n to the current row's value of 'number' if the 'number' is not null (COALESCE returns the first non-null argument you pass into it) The second set statement updates the actual column value for 'number' to itself (if not null) or the variable @n (which always contains the last non NULL value encountered).

The beauty of this approach is that there are no additional resources expended on scanning the temporary table over and over again... The in-row update of @n takes care of tracking the last non-null value.

I don't have enough rep to vote his answer up, but someone should. It's the most elegant and best performant.

Is there a query language for JSON?

You could use linq.js.

This allows to use aggregations and selectings from a data set of objects, as other structures data.

_x000D_
_x000D_
var data = [{ x: 2, y: 0 }, { x: 3, y: 1 }, { x: 4, y: 1 }];_x000D_
_x000D_
// SUM(X) WHERE Y > 0     -> 7_x000D_
console.log(Enumerable.From(data).Where("$.y > 0").Sum("$.x"));_x000D_
_x000D_
// LIST(X) WHERE Y > 0    -> [3, 4]_x000D_
console.log(Enumerable.From(data).Where("$.y > 0").Select("$.x").ToArray());
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>
_x000D_
_x000D_
_x000D_

Iterate over a Javascript associative array in sorted order

_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
  document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
_x000D_
_x000D_

How to log as much information as possible for a Java Exception?

The java.util.logging package is standard in Java SE. Its Logger includes an overloaded log method that accepts Throwable objects. It will log stacktraces of exceptions and their cause for you.

For example:

import java.util.logging.Level;
import java.util.logging.Logger;

[...]

Logger logger = Logger.getAnonymousLogger();
Exception e1 = new Exception();
Exception e2 = new Exception(e1);
logger.log(Level.SEVERE, "an exception was thrown", e2);

Will log:

SEVERE: an exception was thrown
java.lang.Exception: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:21)
Caused by: java.lang.Exception
    at LogStacktrace.main(LogStacktrace.java:20)

Internally, this does exactly what @philipp-wendler suggests, by the way. See the source code for SimpleFormatter.java. This is just a higher level interface.

How can I get table names from an MS Access Database?

To build on Ilya's answer try the following query:

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6)))
order by MSysObjects.Name 

(this one works without modification with an MDB)

ACCDB users may need to do something like this

SELECT MSysObjects.Name AS table_name
FROM MSysObjects
WHERE (((Left([Name],1))<>"~") 
        AND ((Left([Name],4))<>"MSys") 
        AND ((MSysObjects.Type) In (1,4,6))
        AND ((MSysObjects.Flags)=0))
order by MSysObjects.Name 

As there is an extra table is included that appears to be a system table of some sort.

Rails: How can I rename a database column in a Ruby on Rails migration?

$:  rails g migration RenameHashedPasswordColumn
invoke  active_record
      create    db/migrate/20160323054656_rename_hashed_password_column.rb

Open that migration file and modify that file as below(Do enter your original table_name)

class  RenameHashedPasswordColumn < ActiveRecord::Migration
  def change
    rename_column :table_name, :hased_password, :hashed_password
  end
end

How do browser cookie domains work?

The previous answers are a little outdated.

RFC 6265 was published in 2011, based on the browser consensus at that time. Since then, there has been some complication with public suffix domains. I've written an article explaining the current situation - http://bayou.io/draft/cookie.domain.html

To summarize, rules to follow regarding cookie domain:

  • The origin domain of a cookie is the domain of the originating request.

  • If the origin domain is an IP, the cookie's domain attribute must not be set.

  • If a cookie's domain attribute is not set, the cookie is only applicable to its origin domain.

  • If a cookie's domain attribute is set,

    • the cookie is applicable to that domain and all its subdomains;
    • the cookie's domain must be the same as, or a parent of, the origin domain
    • the cookie's domain must not be a TLD, a public suffix, or a parent of a public suffix.

It can be derived that a cookie is always applicable to its origin domain.

The cookie domain should not have a leading dot, as in .foo.com - simply use foo.com

As an example,

  • x.y.z.com can set a cookie domain to itself or parents - x.y.z.com, y.z.com, z.com. But not com, which is a public suffix.
  • a cookie with domain=y.z.com is applicable to y.z.com, x.y.z.com, a.x.y.z.com etc.

Examples of public suffixes - com, edu, uk, co.uk, blogspot.com, compute.amazonaws.com

Intellij reformat on file save

This solution worked better for me:

  1. Make a macro (I used Organize Imports, Format Code, Save All)
  2. Assign it a keystroke (I overrode Ctrl+S)

Note: You will have to check the box "Do not show this message again" the first time for the organized imports, but it works as expected after that.

Step-by-step for IntelliJ 10.0:

  1. Code -> "Optimize Imports...", if a dialogue box appears, check the box that says "Do not show this message again.", then click "Run".
  2. Tools -> "Start Macro Recording"
  3. Code -> "Optimize Imports..."
  4. Code -> "Reformat Code..."
  5. File -> "Save all"
  6. Tools -> "Stop Macro Recording"
  7. Name the macro (something like "formatted save")
  8. In File -> Settings -> Keymap, select your macro located at "Main Menu -> Tools -> "formatted save"
  9. Click "Add Keyboard Shortcut", then perform the keystroke you want. If you choose Ctrl+S like me, it will ask you what to do with the previous Ctrl+S shortcut. Remove it. You can always reassign it later if you want.
  10. Enjoy!

For IntelliJ 11, replace

step 2. with: Edit -> Macros -> "Start Macro Recording"
step 6. with: Edit -> Macros -> "Stop Macro Recording"

Everything else remains the same.

IntelliJ 12

8. The Preferences contain the Keymap settings. Use the input field to filter the content, as shown in the screenshot.

Intellij / Preferences / Keymap / Macros

Drop rows containing empty cells from a pandas DataFrame

If you don't care about the columns where the missing files are, considering that the dataframe has the name New and one wants to assign the new dataframe to the same variable, simply run

New = New.drop_duplicates()

If you specifically want to remove the rows for the empty values in the column Tenant this will do the work

New = New[New.Tenant != '']

This may also be used for removing rows with a specific value - just change the string to the value that one wants.

Note: If instead of an empty string one has NaN, then

New = New.dropna(subset=['Tenant'])

How to Extract Year from DATE in POSTGRESQL

you can also use just like this in newer version of sql,

select year('2001-02-16 20:38:40') as year,
month('2001-02-16 20:38:40') as month,
day('2001-02-16 20:38:40') as day,
hour('2001-02-16 20:38:40') as hour,
minute('2001-02-16 20:38:40') as minute

How can I change the default Django date template format?

Within your template, you can use Django's date filter. E.g.:

<p>Birthday: {{ birthday|date:"M d, Y" }}</p>

Gives:

Birthday: Jan 29, 1983

More formatting examples in the date filter docs.

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

How can I pop-up a print dialog box using Javascript?

I know the answer has already been provided. But I just wanted to elaborate with regards to doing this in a Blazor app (razor)...

You will need to inject IJSRuntime, in order to perform JSInterop (running javascript functions from C#)

IN YOUR RAZOR PAGE:

@inject IJSRuntime JSRuntime

Once you have that injected, create a button with a click event that calls a C# method:

<MatFAB Icon="@MatIconNames.Print" OnClick="@(async () => await print())"></MatFAB>

(or something more simple if you don't use MatBlazor)

<button @onclick="@(async () => await print())">PRINT</button>

For the C# method:

public async Task print()
{
    await JSRuntime.InvokeVoidAsync("printDocument");
}

NOW IN YOUR index.html:

<script>
    function printDocument() {
        window.print();
    }
</script>

Something to note, the reason the onclick events are asynchronous is because IJSRuntime awaits it's calls such as InvokeVoidAsync

PS: If you wanted to message box in asp net core for instance:

await JSRuntime.InvokeAsync<string>("alert", "Hello user, this is the message box");

To have a confirm message box:

bool question = await JSRuntime.InvokeAsync<bool>("confirm", "Are you sure you want to do this?");
    if(question == true)
    {
        //user clicked yes
    }
    else
    {
        //user clicked no
    }

Hope this helps :)

Find unused code

I would also mention that using IOC aka Unity may make these assessments misleading. I may have erred but several very important classes that are instantiated via Unity appear to have no instantiation as far as ReSharper can tell. If I followed the ReSharper recommendations I would get hosed!

How to install sklearn?

I would recommend you look at getting the anaconda package, it will install and configure Sklearn and its dependencies.

https://www.continuum.io

How do you programmatically set an attribute?

let x be an object then you can do it two ways

x.attr_name = s 
setattr(x, 'attr_name', s)

How can I convert byte size into a human-readable format in Java?


private static final String[] Q = new String[]{"", "K", "M", "G", "T", "P", "E"};

public String getAsString(long bytes)
{
    for (int i = 6; i > 0; i--)
    {
        double step = Math.pow(1024, i);
        if (bytes > step) return String.format("%3.1f %s", bytes / step, Q[i]);
    }
    return Long.toString(bytes);
}

Ternary operator (?:) in Bash

if [ "$b" -eq 5 ]; then a="$c"; else a="$d"; fi

The cond && op1 || op2 expression suggested in other answers has an inherent bug: if op1 has a nonzero exit status, op2 silently becomes the result; the error will also not be caught in -e mode. So, that expression is only safe to use if op1 can never fail (e.g., :, true if a builtin, or variable assignment without any operations that can fail (like division and OS calls)).

Note the "" quotes. The first pair will prevent a syntax error if $b is blank or has whitespace. Others will prevent translation of all whitespace into single spaces.

Remove a git commit which has not been pushed

There are two branches to this question (Rolling back a commit does not mean I want to lose all my local changes):

1. To revert the latest commit and discard changes in the committed file do:

git reset --hard HEAD~1

2. To revert the latest commit but retain the local changes (on disk) do:

git reset --soft HEAD~1

This (the later command) will take you to the state you would have been if you did git add.

If you want to unstage the files after that, do

git reset

Now you can make more changes before adding and then committing again.

ERROR:'keytool' is not recognized as an internal or external command, operable program or batch file

Found it.

GO TO:

my computer->rightClick->properties->Advanced system settings->environment variables->find path in system variables->dbl click-> paste the "C:\Program Files\Java\jdk1.6.0_16\bin"->OK

GO TO:

cmd -> keytool -list -alias androiddebugkey -keystore "C:\Users\meee\.android\debug.keystore" -storepass android -keypass android

UTF-8 encoded html pages show ? (questions marks) instead of characters

Tell PDO your charset initially.... something like

PDO("mysql:host=$host;dbname=$DB_name;charset=utf8;", $username, $password);

Notice the: charset=utf8; part.

hope it helps!

How to code a BAT file to always run as admin mode?

You can use nircmd.exe's elevate command

NirCmd Command Reference - elevate

elevate [Program] {Command-Line Parameters}

For Windows Vista/7/2008 only: Run a program with administrator rights. When the [Program] contains one or more space characters, you must put it in quotes.

Examples:

elevate notepad.exe 
elevate notepad.exe C:\Windows\System32\Drivers\etc\HOSTS 
elevate "c:\program files\my software\abc.exe"

PS: I use it on win 10 and it works

Android: How to Programmatically set the size of a Layout

LinearLayout YOUR_LinearLayout =(LinearLayout)findViewById(R.id.YOUR_LinearLayout)
    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                       /*width*/ ViewGroup.LayoutParams.MATCH_PARENT,
               /*height*/ 100,
               /*weight*/ 1.0f
                );
                YOUR_LinearLayout.setLayoutParams(param);

Setting Action Bar title and subtitle

    <activity android:name=".yourActivity" android:label="@string/yourText" />

Put this code into your android manifest file and it should set the title of the action bar to what ever you want!

Loop through a date range with JavaScript

var start = new Date("2014-05-01"); //yyyy-mm-dd
var end = new Date("2014-05-05"); //yyyy-mm-dd

while(start <= end){

    var mm = ((start.getMonth()+1)>=10)?(start.getMonth()+1):'0'+(start.getMonth()+1);
    var dd = ((start.getDate())>=10)? (start.getDate()) : '0' + (start.getDate());
    var yyyy = start.getFullYear();
    var date = dd+"/"+mm+"/"+yyyy; //yyyy-mm-dd

    alert(date); 

    start = new Date(start.setDate(start.getDate() + 1)); //date increase by 1
}

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

If your class extends Serializable, you can write and read objects through a ByteArrayOutputStream, that's what I usually do.

Rename master branch for both local and remote Git repositories

git update-ref newref oldref
git update-ref -d oldref newref

Disable output buffering

The following works in Python 2.6, 2.7, and 3.2:

import os
import sys
buf_arg = 0
if sys.version_info[0] == 3:
    os.environ['PYTHONUNBUFFERED'] = '1'
    buf_arg = 1
sys.stdout = os.fdopen(sys.stdout.fileno(), 'a+', buf_arg)
sys.stderr = os.fdopen(sys.stderr.fileno(), 'a+', buf_arg)

Javascript extends class

Douglas Crockford has some very good explanations of inheritance in JavaScript:

  1. prototypal inheritance: the 'natural' way to do things in JavaScript
  2. classical inheritance: closer to what you find in most OO languages, but kind of runs against the grain of JavaScript

How to draw interactive Polyline on route google maps v2 android

You can use this method to draw polyline on googleMap

// Draw polyline on map
public void drawPolyLineOnMap(List<LatLng> list) {
    PolylineOptions polyOptions = new PolylineOptions();
    polyOptions.color(Color.RED);
    polyOptions.width(5);
    polyOptions.addAll(list);

    googleMap.clear();
    googleMap.addPolyline(polyOptions);

    LatLngBounds.Builder builder = new LatLngBounds.Builder();
    for (LatLng latLng : list) {
        builder.include(latLng);
    }

    final LatLngBounds bounds = builder.build();

    //BOUND_PADDING is an int to specify padding of bound.. try 100.
    CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, BOUND_PADDING);
    googleMap.animateCamera(cu);
}

You need to add this line in your gradle in case you haven't.

compile 'com.google.android.gms:play-services-maps:8.4.0'

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

Query to select data between two dates with the format m/d/yyyy

use this

select * from xxx where dates between '10/oct/2012' and '10/dec/2012'

you are entering string, So give the name of month as according to format...

Making heatmap from pandas DataFrame

For people looking at this today, I would recommend the Seaborn heatmap() as documented here.

The example above would be done as follows:

import numpy as np 
from pandas import DataFrame
import seaborn as sns
%matplotlib inline

Index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
Cols = ['A', 'B', 'C', 'D']
df = DataFrame(abs(np.random.randn(5, 4)), index=Index, columns=Cols)

sns.heatmap(df, annot=True)

Where %matplotlib is an IPython magic function for those unfamiliar.

PHP Fatal error: Cannot access empty property

First, don't declare variables using var, but

public $my_value;

Then you can access it using

$this->my_value;

and not

$this->$my_value;

How to change bower's default components folder?

Try putting the components.json file in the public directory of your application, rather than the root directory, then re-run bower install ...try this in your app home directory:

cp components.json public
cd public
bower install

Export to CSV via PHP

Works with over 100 lines, if you specify the size of the file in the headers simple call the get() method in your own class

function setHeader($filename, $filesize)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 01 Jan 2001 00:00:01 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Type: text/x-csv');

    // disposition / encoding on response body
    if (isset($filename) && strlen($filename) > 0)
        header("Content-Disposition: attachment;filename={$filename}");
    if (isset($filesize))
        header("Content-Length: ".$filesize);
    header("Content-Transfer-Encoding: binary");
    header("Connection: close");
}

function getSql()
{
    // return you own sql
    $sql = "SELECT id, date, params, value FROM sometable ORDER BY date;";
    return $sql;
}

function getExportData()
{
    $values = array();

    $sql = $this->getSql();
    if (strlen($sql) > 0)
    {
        $result = dbquery($sql); // opens the database and executes the sql ... make your own ;-) 
        $fromDb = mysql_fetch_assoc($result);
        if ($fromDb !== false)
        {
            while ($fromDb)
            {
                $values[] = $fromDb;
                $fromDb = mysql_fetch_assoc($result);
            }
        }
    }
    return $values;
}

function get()
{
    $values = $this->getExportData(); // values as array 
    $csv = tmpfile();

    $bFirstRowHeader = true;
    foreach ($values as $row) 
    {
        if ($bFirstRowHeader)
        {
            fputcsv($csv, array_keys($row));
            $bFirstRowHeader = false;
        }

        fputcsv($csv, array_values($row));
    }

    rewind($csv);

    $filename = "export_".date("Y-m-d").".csv";

    $fstat = fstat($csv);
    $this->setHeader($filename, $fstat['size']);

    fpassthru($csv);
    fclose($csv);
}

How can I access Oracle from Python?

Ensure these two and it should work:-

  1. Python, Oracle instantclient and cx_Oracle are 32 bit.
  2. Set the environment variables.

Fixes this issue on windows like a charm.

Reading an integer from user input

Use this simple line:

int x = int.Parse(Console.ReadLine());

What is the bit size of long on 64-bit Windows?

In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.

Type           ILP64   LP64   LLP64
char              8      8       8
short            16     16      16
int              64     32      32
long             64     64      32
long long        64     64      64
pointer          64     64      64

The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.

Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.

If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h> header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):

  • int8_t - 8-bit integers
  • int16_t - 16-bit integers
  • int32_t - 32-bit integers
  • int64_t - 64-bit integers
  • uintptr_t - unsigned integers big enough to hold pointers
  • intmax_t - biggest size of integer on the platform (might be larger than int64_t)

You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t values (ptrdiff_t).

But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.

What is a "web service" in plain English?

A web service, as used by software developers, generally refers to an operation that is performed on a remote server and invoked using the XML/SOAP specification. As with all definitions, there are nuances to it, but that's the most common use of the term.

How to use table variable in a dynamic sql statement?

Here is an example of using a dynamic T-SQL query and then extracting the results should you have more than one column of returned values (notice the dynamic table name):

DECLARE 
@strSQLMain nvarchar(1000),
@recAPD_number_key char(10),    
@Census_sub_code varchar(1),
@recAPD_field_name char(100),
@recAPD_table_name char(100),
@NUMBER_KEY varchar(10),

if object_id('[Permits].[dbo].[myTempAPD_Txt]') is not null 

    DROP TABLE [Permits].[dbo].[myTempAPD_Txt]

CREATE TABLE [Permits].[dbo].[myTempAPD_Txt]
(
    [MyCol1] char(10) NULL,
    [MyCol2] char(1) NULL,

)   
-- an example of what @strSQLMain is : @strSQLMain = SELECT @recAPD_number_key = [NUMBER_KEY], @Census_sub_code=TEXT_029 FROM APD_TXT0 WHERE Number_Key = '01-7212' 
SET @strSQLMain = ('INSERT INTO myTempAPD_Txt SELECT [NUMBER_KEY], '+ rtrim(@recAPD_field_name) +' FROM '+ rtrim(@recAPD_table_name) + ' WHERE Number_Key = '''+ rtrim(@Number_Key) +'''')      
EXEC (@strSQLMain)  
SELECT @recAPD_number_key = MyCol1, @Census_sub_code = MyCol2 from [Permits].[dbo].[myTempAPD_Txt]

DROP TABLE [Permits].[dbo].[myTempAPD_Txt]  

How to search text using php if ($text contains "World")

  /* https://ideone.com/saBPIe */

  function search($search, $string) {

    $pos = strpos($string, $search);  

    if ($pos === false) {

      return "not found";     

    } else {

      return "found in " . $pos;

    }    

  }

  echo search("world", "hello world");

Embed PHP online:

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/saBPIe" ></iframe>
_x000D_
_x000D_
_x000D_

Convert a char to upper case using regular expressions (EditPad Pro)

You can do this in jEdit, by using the "Return value of a BeanShell snippet" option in jEdit's find and replace dialog. Just search for " [a-z]" and replace it by " _0.toUpperCase()" (without quotes)

Function in JavaScript that can be called only once

It helps to prevent sticky execution

var done = false;

function doItOnce(func){
  if(!done){
    done = true;
    func()
  }
  setTimeout(function(){
    done = false;
  },1000)
}

json_encode function: special characters

The manual for json_encode specifies this:

All string data must be UTF-8 encoded.

Thus, try array_mapping utf8_encode() to your array before you encode it:

$arr = array_map('utf8_encode', $arr);
$json = json_encode($arr);

// {"funds":"ComStage STOXX\u00c2\u00aeEurope 600 Techn NR ETF"}

For reference, take a look at the differences between the three examples on this fiddle. The first doesn't use character encoding, the second uses htmlentities and the third uses utf8_encode - they all return different results.

For consistency, you should use utf8_encode().

Docs

How do you test to see if a double is equal to NaN?

Try Double.isNaN():

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

For those who need to use the output in subsequent shell commands, rather than groovy, something like this example could be done:

    stage('Show Files') {
        environment {
          MY_FILES = sh(script: 'cd mydir && ls -l', returnStdout: true)
        }
        steps {
          sh '''
            echo "$MY_FILES"
          '''
        }
    }

I found the examples on code maven to be quite useful.

Sort dataGridView columns in C# ? (Windows Form)

There's a method on the DataGridView called "Sort":

this.dataGridView1.Sort(this.dataGridView1.Columns["Name"], ListSortDirection.Ascending);

This will programmatically sort your datagridview.

How to get current time and date in C++?

#include <Windows.h>

void main()
{
     //Following is a structure to store date / time

SYSTEMTIME SystemTime, LocalTime;

    //To get the local time

int loctime = GetLocalTime(&LocalTime);

    //To get the system time

int systime = GetSystemTime(&SystemTime)

}

Subtracting 1 day from a timestamp date

Use the INTERVAL type to it. E.g:

--yesterday
SELECT NOW() - INTERVAL '1 DAY';

--Unrelated to the question, but PostgreSQL also supports some shortcuts:
SELECT 'yesterday'::TIMESTAMP, 'tomorrow'::TIMESTAMP, 'allballs'::TIME;

Then you can do the following on your query:

SELECT 
    org_id,
    count(accounts) AS COUNT,
    ((date_at) - INTERVAL '1 DAY') AS dateat
FROM 
    sourcetable
WHERE 
    date_at <= now() - INTERVAL '130 DAYS'
GROUP BY 
    org_id,
    dateat;


TIPS

Tip 1

You can append multiple operands. E.g.: how to get last day of current month?

SELECT date_trunc('MONTH', CURRENT_DATE) + INTERVAL '1 MONTH - 1 DAY';

Tip 2

You can also create an interval using make_interval function, useful when you need to create it at runtime (not using literals):

SELECT make_interval(days => 10 + 2);
SELECT make_interval(days => 1, hours => 2);
SELECT make_interval(0, 1, 0, 5, 0, 0, 0.0);


More info:

Date/Time Functions and Operators

datatype-datetime (Especial values).

click or change event on radio using jquery

You can specify the name attribute as below:

$( 'input[name="testGroup"]:radio' ).change(

Change SVN repository URL

If U want commit to a new empty Repo ,You can checkout the new empty Repo and commit to new remote repo.
chekout a new empty Repo won't delete your local files.
try this: for example, remote repo url : https://example.com/SVNTest cd [YOUR PROJECT PATH] rm -rf .svn svn co https://example.com/SVNTest ../[YOUR PROJECT DIR NAME] svn add ./* svn ci -m"changed repo url"

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

In C#, what is the difference between public, private, protected, and having no access modifier?

Access modifiers

From docs.microsoft.com:

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can only be accessed by code in the same class or struct.

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class.

private protected (added in C# 7.2)

The type or member can only be accessed by code in the same class or struct, or in a derived class from the same assembly, but not from another assembly.

internal

The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal

The type or member can be accessed by any code in the same assembly, or by any derived class in another assembly.

When no access modifier is set, a default access modifier is used. So there is always some form of access modifier even if it's not set.

static modifier

The static modifier on a class means that the class cannot be instantiated, and that all of its members are static. A static member has one version regardless of how many instances of its enclosing type are created.

A static class is basically the same as a non-static class, but there is one difference: a static class cannot be externally instantiated. In other words, you cannot use the new keyword to create a variable of the class type. Because there is no instance variable, you access the members of a static class by using the class name itself.

However, there is a such thing as a static constructor. Any class can have one of these, including static classes. They cannot be called directly & cannot have parameters (other than any type parameters on the class itself). A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced. Looks like this:

static class Foo()
{
    static Foo()
    {
        Bar = "fubar";
    }
    
    public static string Bar { get; set; }
}

Static classes are often used as services, you can use them like so:

MyStaticClass.ServiceMethod(...);

How can I delete a file from a Git repository?

If you have the GitHub for Windows application, you can delete a file in 5 easy steps:

  • Click Sync.
  • Click on the directory where the file is located and select your latest version of the file.
  • Click on tools and select "Open a shell here."
  • In the shell, type: "rm {filename}" and hit enter.
  • Commit the change and resync.

How to safely open/close files in python 2.4

No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

Open Source HTML to PDF Renderer with Full CSS Support

It's not open source, but you can at least get a free personal use license to Prince, which really does a lovely job.

Why plt.imshow() doesn't display the image?

If you want to print the picture using imshow() you also execute plt.show()

jQuery/JavaScript: accessing contents of an iframe

Have you tried the classic, waiting for the load to complete using jQuery's builtin ready function?

$(document).ready(function() {
    $('some selector', frames['nameOfMyIframe'].document).doStuff()
} );

K

How do I Merge two Arrays in VBA?

To join Array1 and Array2, create a new array say JointArray

Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
    If i <= UBound(Array1) Then
    JointArray(i) = Array1(i)
    Else
    JointArray(i) = Array2(i - UBound(Array1) - 1)
    End If
Next

Get values from an object in JavaScript

I am sorry that your concluding question is not that clear but you are wrong from the very first line. The variable data is an Object not an Array

To access the attributes of an object is pretty easy:

alert(data.second);

But, if this does not completely answer your question, please clarify it and post back.

Thanks !

OR is not supported with CASE Statement in SQL Server

Try

CASE WHEN ebv.db_no IN (22978,23218,23219) THEN 'WECS 9500' ELSE 'WECS 9520' END

Remove last characters from a string in C#. An elegant way?

This will return to you a string excluding everything after the comma

str = str.Substring(0, str.IndexOf(','));

Of course, this assumes your string actually has a comma with decimals. The above code will fail if it doesn't. You'd want to do more checks:

commaPos = str.IndexOf(',');
if(commaPos != -1)
    str = str.Substring(0, commaPos)

I'm assuming you're working with a string to begin with. Ideally, if you're working with a number to begin with, like a float or double, you could just cast it to an int, then do myInt.ToString() like:

myInt = (int)double.Parse(myString)

This parses the double using the current culture (here in the US, we use . for decimal points). However, this again assumes that your input string is can be parsed.

Deleting a SQL row ignoring all foreign keys and constraints

You can disable all of the constaints on your database by the following line of code:

EXEC sp_MSforeachtable "ALTER TABLE ? NOCHECK CONSTRAINT all"

and after the runing your update/delete command, you can enable it again as the following:

EXEC sp_MSforeachtable "ALTER TABLE ? WITH CHECK CHECK CONSTRAINT all"

Mean Squared Error in Numpy?

Just for kicks

mse = (np.linalg.norm(A-B)**2)/len(A)

Auto-fit TextView for Android

Ok I have used the last week to massively rewrite my code to precisely fit your test. You can now copy this 1:1 and it will immediately work - including setSingleLine(). Please remember to adjust MIN_TEXT_SIZE and MAX_TEXT_SIZE if you're going for extreme values.

Converging algorithm looks like this:

for (float testSize; (upperTextSize - lowerTextSize) > mThreshold;) {

    // Go to the mean value...
    testSize = (upperTextSize + lowerTextSize) / 2;

    // ... inflate the dummy TextView by setting a scaled textSize and the text...
    mTestView.setTextSize(TypedValue.COMPLEX_UNIT_SP, testSize / mScaledDensityFactor);
    mTestView.setText(text);

    // ... call measure to find the current values that the text WANTS to occupy
    mTestView.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
    int tempHeight = mTestView.getMeasuredHeight();

    // ... decide whether those values are appropriate.
    if (tempHeight >= targetFieldHeight) {
        upperTextSize = testSize; // Font is too big, decrease upperSize
    }
    else {
        lowerTextSize = testSize; // Font is too small, increase lowerSize
    }
}

And the whole class can be found here.

The result is very flexible now. This works the same declared in xml like so:

<com.example.myProject.AutoFitText
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="4"
    android:text="@string/LoremIpsum" />

... as well as built programmatically like in your test.

I really hope you can use this now. You can call setText(CharSequence text) now to use it by the way. The class takes care of stupendously rare exceptions and should be rock-solid. The only thing that the algorithm does not support yet is:

  • Calls to setMaxLines(x) where x >= 2

But I have added extensive comments to help you build this if you wish to!


Please note:

If you just use this normally without limiting it to a single line then there might be word-breaking as you mentioned before. This is an Android feature, not the fault of the AutoFitText. Android will always break words that are too long for a TextView and it's actually quite a convenience. If you want to intervene here than please see my comments and code starting at line 203. I have already written an adequate split and the recognition for you, all you'd need to do henceforth is to devide the words and then modify as you wish.

In conclusion: You should highly consider rewriting your test to also support space chars, like so:

final Random _random = new Random();
final String ALLOWED_CHARACTERS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890";
final int textLength = _random.nextInt(80) + 20;
final StringBuilder builder = new StringBuilder();
for (int i = 0; i < textLength; ++i) {
    if (i % 7 == 0 && i != 0) {
        builder.append(" ");
    }
    builder.append(ALLOWED_CHARACTERS.charAt(_random.nextInt(ALLOWED_CHARACTERS.length())));
}
((AutoFitText) findViewById(R.id.textViewMessage)).setText(builder.toString());

This will produce very beutiful (and more realistic) results.
You will find commenting to get you started in this matter as well.

Good luck and best regards

VBA Object doesn't support this property or method

Object doesn't support this property or method.

Think of it like if anything after the dot is called on an object. It's like a chain.

An object is a class instance. A class instance supports some properties defined in that class type definition. It exposes whatever intelli-sense in VBE tells you (there are some hidden members but it's not related to this). So after each dot . you get intelli-sense (that white dropdown) trying to help you pick the correct action.

(you can start either way - front to back or back to front, once you understand how this works you'll be able to identify where the problem occurs)

Type this much anywhere in your code area

Dim a As Worksheets
a.

you get help from VBE, it's a little dropdown called Intelli-sense

enter image description here

It lists all available actions that particular object exposes to any user. You can't see the .Selection member of the Worksheets() class. That's what the error tells you exactly.

Object doesn't support this property or method.

If you look at the example on MSDN

Worksheets("GRA").Activate
iAreaCount = Selection.Areas.Count

It activates the sheet first then calls the Selection... it's not connected together because Selection is not a member of Worksheets() class. Simply, you can't prefix the Selection

What about

Sub DisplayColumnCount()
    Dim iAreaCount As Integer
    Dim i As Integer

    Worksheets("GRA").Activate
    iAreaCount = Selection.Areas.Count

    If iAreaCount <= 1 Then
        MsgBox "The selection contains " & Selection.Columns.Count & " columns."
    Else
        For i = 1 To iAreaCount
        MsgBox "Area " & i & " of the selection contains " & _
        Selection.Areas(i).Columns.Count & " columns."
        Next i
    End If
End Sub

from HERE

org.hibernate.MappingException: Unknown entity

check that entity is defined in hibernate.cfg.xml or not.

CMake does not find Visual C++ compiler

In my case there was an environment variable set which was the reason for this error. The problem was solved after deleting cxx_flags from the environment variables.

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

input = InputBox("Text:")

If input <> "" Then
   ' Normal
Else
   ' Cancelled, or empty
End If

From MSDN:

If the user clicks Cancel, the function returns a zero-length string ("").

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

Update in July 2020:

During the last 16 months, maybe the most notable change in the React community is React hooks.

According to what I observe, in order to gain better compatibility with functional components and hooks, projects (even those large ones) would tend to use:

  1. hook + async thunk (hook makes everything very flexible so you could actually place async thunk in where you want and use it as normal functions, for example, still write thunk in action.ts and then useDispatch() to trigger the thunk: https://stackoverflow.com/a/59991104/5256695),
  2. useRequest,
  3. GraphQL/Apollo useQuery useMutation
  4. react-fetching-library
  5. other popular choices of data fetching/API call libraries, tools, design patterns, etc

In comparison, redux-saga doesn't really provide significant benefit in most normal cases of API calls comparing to the above approaches for now, while increasing project complexity by introducing many saga files/generators (also because the last release v1.1.1 of redux-saga was on 18 Sep 2019, which was a long time ago).

But still, redux-saga provides some unique features such as racing effect and parallel requests. Therefore, if you need these special functionalities, redux-saga is still a good choice.


Original post in March 2019:

Just some personal experience:

  1. For coding style and readability, one of the most significant advantages of using redux-saga in the past is to avoid callback hell in redux-thunk — one does not need to use many nesting then/catch anymore. But now with the popularity of async/await thunk, one could also write async code in sync style when using redux-thunk, which may be regarded as an improvement in redux-thunk.

  2. One may need to write much more boilerplate codes when using redux-saga, especially in Typescript. For example, if one wants to implement a fetch async function, the data and error handling could be directly performed in one thunk unit in action.js with one single FETCH action. But in redux-saga, one may need to define FETCH_START, FETCH_SUCCESS and FETCH_FAILURE actions and all their related type-checks, because one of the features in redux-saga is to use this kind of rich “token” mechanism to create effects and instruct redux store for easy testing. Of course one could write a saga without using these actions, but that would make it similar to a thunk.

  3. In terms of the file structure, redux-saga seems to be more explicit in many cases. One could easily find an async related code in every sagas.ts, but in redux-thunk, one would need to see it in actions.

  4. Easy testing may be another weighted feature in redux-saga. This is truly convenient. But one thing that needs to be clarified is that redux-saga “call” test would not perform actual API call in testing, thus one would need to specify the sample result for the steps which may be used after the API call. Therefore before writing in redux-saga, it would be better to plan a saga and its corresponding sagas.spec.ts in detail.

  5. Redux-saga also provides many advanced features such as running tasks in parallel, concurrency helpers like takeLatest/takeEvery, fork/spawn, which are far more powerful than thunks.

In conclusion, personally, I would like to say: in many normal cases and small to medium size apps, go with async/await style redux-thunk. It would save you many boilerplate codes/actions/typedefs, and you would not need to switch around many different sagas.ts and maintain a specific sagas tree. But if you are developing a large app with much complex async logic and the need for features like concurrency/parallel pattern, or have a high demand for testing and maintenance (especially in test-driven development), redux-sagas would possibly save your life.

Anyway, redux-saga is not more difficult and complex than redux itself, and it does not have a so-called steep learning curve because it has well-limited core concepts and APIs. Spending a small amount of time learning redux-saga may benefit yourself one day in the future.

Map enum in JPA with fixed values?

For versions earlier than JPA 2.1, JPA provides only two ways to deal with enums, by their name or by their ordinal. And the standard JPA doesn't support custom types. So:

  • If you want to do custom type conversions, you'll have to use a provider extension (with Hibernate UserType, EclipseLink Converter, etc). (the second solution). ~or~
  • You'll have to use the @PrePersist and @PostLoad trick (the first solution). ~or~
  • Annotate getter and setter taking and returning the int value ~or~
  • Use an integer attribute at the entity level and perform a translation in getters and setters.

I'll illustrate the latest option (this is a basic implementation, tweak it as required):

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {

    public enum Right {
        READ(100), WRITE(200), EDITOR (300);

        private int value;

        Right(int value) { this.value = value; }    

        public int getValue() { return value; }

        public static Right parse(int id) {
            Right right = null; // Default
            for (Right item : Right.values()) {
                if (item.getValue()==id) {
                    right = item;
                    break;
                }
            }
            return right;
        }

    };

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "AUTHORITY_ID")
    private Long id;

    @Column(name = "RIGHT_ID")
    private int rightId;

    public Right getRight () {
        return Right.parse(this.rightId);
    }

    public void setRight(Right right) {
        this.rightId = right.getValue();
    }

}

Git: See my last commit

After you do several commits or clone/pull a repository, you might want to see what commits have been made. Just check these simple solutions to see your commit history (from last/recent commit to the first one).

For the last commit, just fire this command: git log -1. For more interesting things see below -

  1. To see the commit ID (SHA-1 checksum), Author name <mail ID>, Date along with time, and commit message -

    git log
    
  2. To see some more stats, such as the names of all the files changed during that commit and number of insertions/deletions. This comes in very handy while reviewing the code -

    git log --stat
    
  3. To see commit histories in some pretty formats :) (This is followed by some prebuild options)-

    • If you have too many commits to review, this command will show them in a neat single line:

      git log --pretty=oneline
      
    • To see short, medium, full, or even more details of your commit, use following, respectively -

      git log --pretty=short
      git log --pretty=medium
      git log --pretty=full
      git log --pretty=fuller
      
  4. You can even use your own output format using the format option -

    git log --pretty=format:"%an, %ae - %s"
    

    where %an - author name, %ae - author email, %s - subject of commit, etc.

This can help you with your commit histories. For more information, click here.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Install windows service without InstallUtil.exe

This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.