Programs & Examples On #Opacitymask

Could not find server 'server name' in sys.servers. SQL Server 2014

At first check out that your linked server is in the list by this query

select name from sys.servers

If it not exists then try to add to the linked server

EXEC sp_addlinkedserver @server = 'SERVER_NAME' --or may be server ip address

After that login to that linked server by

EXEC sp_addlinkedsrvlogin 'SERVER_NAME'
                         ,'false'
                         ,NULL
                         ,'USER_NAME'
                         ,'PASSWORD'

Then you can do whatever you want ,treat it like your local server

exec [SERVER_NAME].[DATABASE_NAME].dbo.SP_NAME @sample_parameter

Finally you can drop that server from linked server list by

sp_dropserver 'SERVER_NAME', 'droplogins'

If it will help you then please upvote.

while EOF in JAVA?

The others told you enough about your issue with multiple calls of readLine().

I just wanted to leave sth about code style: While you see this line = assignement and != null check together in one while condition in most examples (like @gotomanners example here) I prefer using a for for it.

It is much more readable in my opinion ...

for (String line = in.readLine(); line != null; line = in.readLine()) {
    ...
}

Another nice way to write it you see in @TheCapn's example. But when you write it that way you easily see that's what a for-loop is made for.

I do not like assignments scrambled with conditions in one line. It is bad style in my opinion. But because it is so MUCH popular for that special case here to do it that way I would not consider it really bad style. (But cannot understand who established this bad style to become that popular.)

Why ModelState.IsValid always return false in mvc

"ModelState.IsValid" tells you that the model is consumed by the view (i.e. PaymentAdviceEntity) is satisfy all types of validation or not specified in the model properties by DataAnotation.

In this code the view does not bind any model properties. So if you put any DataAnotations or validation in model (i.e. PaymentAdviceEntity). then the validations are not satisfy. say if any properties in model is Name which makes required in model.Then the value of the property remains blank after post.So the model is not valid (i.e. ModelState.IsValid returns false). You need to remove the model level validations.

Remove all constraints affecting a UIView

Using a Reusable Sequence

I decided to approach this in a more 'reusable' way. Since finding all constraints affecting a view is the basis for all of the above, I decided to implement a custom sequence that returns them all for me, along with the owning views.

First thing to do is define an extension on Arrays of NSLayoutConstraint that returns all elements affecting a specific view.

public extension Array where Element == NSLayoutConstraint {

    func affectingView(_ targetView:UIView) -> [NSLayoutConstraint] {

        return self.filter{

            if let firstView = $0.firstItem as? UIView,
                firstView == targetView {
                return true
            }

            if let secondView = $0.secondItem as? UIView,
                secondView == targetView {
                return true
            }

            return false
        }
    }
}

We then use that extension in a custom sequence that returns all constraints affecting that view, along with the views that actually own them (which can be anywhere up the view hierarchy)

public struct AllConstraintsSequence : Sequence {

    public init(view:UIView){
        self.view = view
    }

    public let view:UIView

    public func makeIterator() -> Iterator {
        return Iterator(view:view)
    }

    public struct Iterator : IteratorProtocol {

        public typealias Element = (constraint:NSLayoutConstraint, owningView:UIView)

        init(view:UIView){
            targetView  = view
            currentView = view
            currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
        }

        private let targetView  : UIView
        private var currentView : UIView
        private var currentViewConstraintsAffectingTargetView:[NSLayoutConstraint] = []
        private var nextConstraintIndex = 0

        mutating public func next() -> Element? {

            while(true){

                if nextConstraintIndex < currentViewConstraintsAffectingTargetView.count {
                    defer{nextConstraintIndex += 1}
                    return (currentViewConstraintsAffectingTargetView[nextConstraintIndex], currentView)
                }

                nextConstraintIndex = 0

                guard let superview = currentView.superview else { return nil }

                self.currentView = superview
                self.currentViewConstraintsAffectingTargetView = currentView.constraints.affectingView(targetView)
            }
        }
    }
}

Finally we declare an extension on UIView to expose all the constraints affecting it in a simple property that you can access with a simple for-each syntax.

extension UIView {

    var constraintsAffectingView:AllConstraintsSequence {
        return AllConstraintsSequence(view:self)
    }
}

Now we can iterate all constraints affecting a view and do what we want with them...

List their identifiers...

for (constraint, _) in someView.constraintsAffectingView{
    print(constraint.identifier ?? "No identifier")
}

Deactivate them...

for (constraint, _) in someView.constraintsAffectingView{
    constraint.isActive = false
}

Or remove them entirely...

for (constraint, owningView) in someView.constraintsAffectingView{
    owningView.removeConstraints([constraint])
}

Enjoy!

How to add a Hint in spinner in XML

The trick is this line

((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));

use it in the onItemSelected. Here is my code with more context

List<String> list = getLabels(); // First item will be the placeholder
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_spinner_item, list);
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(dataAdapter);
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                // First item will be gray
                if (position == 0) {
                    ((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.login_input_hint_color));
                } else {
                    ((TextView) view).setTextColor(ContextCompat.getColor(mContext, R.color.primary_text));
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

Read and write a String from text file

I had to recode like this:

let path = NSBundle.mainBundle().pathForResource("Output_5", ofType: "xml")
let text = try? NSString(contentsOfFile: path! as String, encoding: NSUTF8StringEncoding)
print(text)

How to read all rows from huge table?

I did it like below. Not the best way i think, but it works :)

    Connection c = DriverManager.getConnection("jdbc:postgresql://....");
    PreparedStatement s = c.prepareStatement("select * from " + tabName + " where id > ? order by id");
    s.setMaxRows(100);
    int lastId = 0;
    for (;;) {
        s.setInt(1, lastId);
        ResultSet rs = s.executeQuery();

        int lastIdBefore = lastId;
        while (rs.next()) {
            lastId = Integer.parseInt(rs.getObject(1).toString());
            // ...
        }

        if (lastIdBefore == lastId) {
            break;
        }
    }

Will the IE9 WebBrowser Control Support all of IE9's features, including SVG?

The IE9 "version" of the WebBrowser control, like the IE8 version, is actually several browsers in one. Unlike the IE8 version, you do have a little more control over the rendering mode inside the page by changing the doctype. Of course, to change the browser mode you have to set your registry like the earlier answer. Here is a reg file fragment for FEATURE_BROWSER_EMULATION:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION]
"contoso.exe"=dword:00002328

Here is the complete set of codes:

  • 9999 (0x270F) - Internet Explorer 9. Webpages are displayed in IE9 Standards mode, regardless of the !DOCTYPE directive.
  • 9000 (0x2328) - Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode.
  • 8888 (0x22B8) -Webpages are displayed in IE8 Standards mode, regardless of the !DOCTYPE directive.
  • 8000 (0x1F40) - Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode.
  • 7000 (0x1B58) - Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode.

The full docs:

http://msdn.microsoft.com/en-us/library/ee330730%28VS.85%29.aspx#browser_emulation

How get total sum from input box values using Javascript?

I need to sum the span elements so I edited Akhil Sekharan's answer below.

var arr = document.querySelectorAll('span[id^="score"]');
var total=0;
    for(var i=0;i<arr.length;i++){
        if(parseInt(arr[i].innerHTML))
            total+= parseInt(arr[i].innerHTML);
    }
console.log(total)

You can change the elements with other elements link will guide you with editing.

https://www.w3.org/TR/css3-selectors/#attribute-substrings

Change UITableView height dynamically

This can be massively simplified with just 1 line of code in viewDidAppear:

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        tableViewHeightConstraint.constant = tableView.contentSize.height
    }

jQuery UI accordion that keeps multiple sections open?

Simple, create multiple accordian div each representating one anchor tag like:

<div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
<div class="accordion">
<a href = "#">First heading</a>
</div>
</div>

It adds up some markup. But works like a pro...

SQL select everything in an array

// array of $ids that you need to select
$ids = array('1', '2', '3', '4', '5', '6', '7', '8');

// create sql part for IN condition by imploding comma after each id
$in = '(' . implode(',', $ids) .')';

// create sql
$sql = 'SELECT * FROM products WHERE catid IN ' . $in;

// see what you get
var_dump($sql);

Update: (a short version and update missing comma)

$ids = array('1','2','3','4');
$sql = 'SELECT * FROM products WHERE catid IN (' . implode(',', $ids) . ')';

Windows batch: echo without new line

Using set and the /p parameter you can echo without newline:

C:\> echo Hello World
Hello World

C:\> echo|set /p="Hello World"
Hello World
C:\>

Source

What's the best way to check if a String represents an integer in Java?

Integer.valueOf(string); 

works for me most of the time!

How do I check the difference, in seconds, between two dates?

Here's the one that is working for me.

from datetime import datetime

date_format = "%H:%M:%S"

# You could also pass datetime.time object in this part and convert it to string.
time_start = str('09:00:00') 
time_end = str('18:00:00')

# Then get the difference here.    
diff = datetime.strptime(time_end, date_format) - datetime.strptime(time_start, date_format)

# Get the time in hours i.e. 9.60, 8.5
result = diff.seconds / 3600;

Hope this helps!

Setting table column width

Try this instead.

<table style="width: 100%">
    <tr>
        <th style="width: 20%">
           column 1
        </th>
        <th style="width: 40%">
           column 2
        </th>
        <th style="width: 40%">
           column 3
        </th>
    </tr>
    <tr>
        <td style="width: 20%">
           value 1
        </td>
        <td style="width: 40%">
           value 2
        </td>
        <td style="width: 40%">
           value 3
        </td>
    </tr>
</table>

How to fix ReferenceError: primordials is not defined in node

We encountered the same issue when updating a legacy project depending on [email protected] to Node.js 12+.

These fixes enable you to use Node.js 12+ with [email protected] by overriding graceful-fs to version ^4.2.4.

If you are using yarn v1

Yarn v1 supports resolving a package to a defined version. You need to add a resolutions section to your package.json:

{
  // Your current package.json contents
  "resolutions": {
    "graceful-fs": "^4.2.4"
  }
}

Thanks @jazd for this way to solve the issue.

If you are using npm

Using npm-force-resolutions as a preinstall script, you can obtain a similar result as with yarn v1. You need to modify your package.json this way:

{
  // Your current package.json
  "scripts": {
    // Your current package.json scripts
    "preinstall": "npx npm-force-resolutions"
  },
  "resolutions": {
    "graceful-fs": "^4.2.4"
  }
}

npm-force-resolutions will alter the package-lock.json file to set graceful-fsto the wanted version before the install is done.

If you are using a custom .npmrc file in your project and it contains either a proxy or custom registry, you might need to change npx npm-force-resolutions to npx --userconfig .npmrc npm-force-resolutions because as of now, npx doesn't use the current folder .npmrc file by default.

Origin of the problem

This issue stems from the fact that [email protected] depends on graceful-fs@^3.0.0 which monkeypatches Node.js fs module.

This used to work with Node.js until version 11.15 (which is a version from a development branch and shouldn't be used in production).

graceful-fs@^4.0.0 does not monkeypatch Node.js fs module anymore, which makes it compatible with Node.js > 11.15 (tested and working with versions 12 and 14).

Note that this is not a perennial solution but it helps when you don't have the time to update to gulp@^4.0.0.

What does %5B and %5D in POST requests stand for?

The data would probably have been posted originally from a web form looking a bit like this (but probably much more complicated):

<form action="http://example.com" method="post">

  User login    <input name="user[login]"    /><br />
  User password <input name="user[password]" /><br />

  <input type="submit" />
</form>

If the method were "get" instead of "post", clicking the submit button would take you to a URL looking a bit like this:

http://example.com/?user%5Blogin%5D=username&user%5Bpassword%5D=123456

or:

http://example.com/?user[login]=username&user[password]=123456

The web server on the other end will likely take the user[login] and user[password] parameters, and make them into a user object with login and password fields containing those values.

SQL Server 2008: How to query all databases sizes?

Simplified & Improved version:

SELECT
    D.name,
    CAST(SUM(F.size) AS bigint) * 8*1024 AS SizeInBytes,
    CAST(SUM(F.size*8.0)/1024/1024 AS decimal(18,3)) AS SizeInGB
FROM 
    sys.master_files F
    INNER JOIN sys.databases D ON D.database_id = F.database_id
GROUP BY D.name
ORDER BY SizeInBytes desc

What is the difference between .NET Core and .NET Standard Class Library project types?

Another way of explaining the difference could be with real world examples, as most of us mere mortals will use existing tools and frameworks (Xamarin, Unity, etc.) to do the job.

So, with .NET Framework you have all the .NET tools to work with, but you can only target Windows applications (UWP, Windows Forms, ASP.NET, etc.). Since .NET Framework is closed source there isn't much to do about it.

With .NET Core you have fewer tools, but you can target the main desktop platforms (Windows, Linux, and Mac). This is specially useful in ASP.NET Core applications, since you can now host ASP.NET on Linux (cheaper hosting prices). Now, since .NET Core was open sourced, it's technically possible to develop libraries for other platforms. But since there aren't frameworks that support it, I don't think that's a good idea.

With .NET Standard you have even fewer tools, but you can target all/most platforms. You can target mobile thanks to Xamarin, and you can even target game consoles thanks to Mono/Unity. It's also possible to target web clients with the UNO platform and Blazor (although both are kind of experimental right now).

In a real-world application you may need to use all of them. For example, I developed a point of sale application that had the following architecture:

Shared both server and slient:

  • A .NET Standard library that handles the models of my application.
  • A .NET Standard library that handles the validation of data sent by the clients.

Since it's a .NET Standard library, it can be used in any other project (client and server).

Also a nice advantage of having the validation on a .NET standard library since I can be sure the same validation is applied on the server and the client. Server is mandatory, while client is optional and useful to reduce traffic.

Server side (Web API):

  • A .NET Standard (could be .NET Core as well) library that handles all the database connections.

  • A .NET Core project that handles the Rest API and makes use of the database library.

As this is developed in .NET Core, I can host the application on a Linux server.

Client side (MVVM with WPF + Xamarin.Forms Android/iOS):

  • A .NET Standard library that handles the client API connection.

  • A .NET Standard library that handles the ViewModels logic. It is used in all the views.

  • A .NET Framework WPF application that handles the WPF views for a windows application. WPF applications can be .NET core now, although they only work on Windows currently. AvaloniaUI is a good alternative for making desktop GUI applications for other desktop platforms.

  • A .NET Standard library that handles Xamarin forms views.

  • A Xamarin Android and Xamarin iOS project.

So you can see that there's a big advantage here on the client side of the application, since I can reuse both .NET Standard libraries (client API and ViewModels) and just make views with no logic for the WPF, Xamarin and iOS applications.

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

As mentioned in comments, this is a scoping issue. Specifically, $con is not in scope within your getPosts function.

You should pass your connection object in as a dependency, eg

function getPosts(mysqli $con) {
    // etc

I would also highly recommend halting execution if your connection fails or if errors occur. Something like this should suffice

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); // throw exceptions
$con=mysqli_connect("localhost","xxxx","xxxx","xxxxx");

getPosts($con);

Submitting HTML form using Jquery AJAX

If you add:

jquery.form.min.js

You can simply do this:

<script>
$('#myform').ajaxForm(function(response) {
  alert(response);
});

// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>

NOTE:

You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.

How to decompile an APK or DEX file on Android platform?

http://www.decompileandroid.com/

This website will decompile the code embedded in APK files and extract all the other assets in the file.

Get the latest record with filter in Django

latest is really designed to work with date fields (it probably does work with other total-ordered types too, but not sure). And the only way you can use it without specifying the field name is by setting the get_latest_by meta attribute, as mentioned here.

detect back button click in browser

So as far as AJAX is concerned...

Pressing back while using most web-apps that use AJAX to navigate specific parts of a page is a HUGE issue. I don't accept that 'having to disable the button means you're doing something wrong' and in fact developers in different facets have long run into this problem. Here's my solution:

window.onload = function () {
    if (typeof history.pushState === "function") {
        history.pushState("jibberish", null, null);
        window.onpopstate = function () {
            history.pushState('newjibberish', null, null);
            // Handle the back (or forward) buttons here
            // Will NOT handle refresh, use onbeforeunload for this.
        };
    }
    else {
        var ignoreHashChange = true;
        window.onhashchange = function () {
            if (!ignoreHashChange) {
                ignoreHashChange = true;
                window.location.hash = Math.random();
                // Detect and redirect change here
                // Works in older FF and IE9
                // * it does mess with your hash symbol (anchor?) pound sign
                // delimiter on the end of the URL
            }
            else {
                ignoreHashChange = false;   
            }
        };
    }
}

As far as Ive been able to tell this works across chrome, firefox, haven't tested IE yet.

What are XAND and XOR

To add to this, since I was just dealing with it, if you are looking for an "equivalence gate" or a "coincedence gate" as your XAND, what you really have is just "equals".

If you think about it, given XOR from above:

F XOR F = F
F XOR T = T
T XOR F = T
T XOR T = F

And we expect XAND should be:

F XAND F = T
F XAND T = F
T XAND F = F
T XAND T = T

And isn't this exactly the same?

F == F = T
F == T = F
T == F = F
T == T = T

Get the position of a spinner in Android

    final int[] positions=new int[2]; 
    Spinner sp=findViewByID(R.id.spinner);

    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {
            // TODO Auto-generated method stub
            Toast.makeText( arg2....);
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });

How to change the sender's name or e-mail address in mutt?

before you send the email you can press <ESC> f (Escape followed by f) to change the From: Address.

Constraint: This only works if you use mutt in curses mode and do not wan't to script it or if you want to change the address permanent. Then the other solutions are way better!

Use SELECT inside an UPDATE query

Does this work? Untested but should get the point across.

UPDATE FUNCTIONS
SET Func_TaxRef = 
(
  SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
  FROM TAX, FUNCTIONS F1
  WHERE F1.Func_Pure <= [Tax_ToPrice]
    AND F1.Func_Year=[Tax_Year]
    AND F1.Func_ID = FUNCTIONS.Func_ID
  GROUP BY F1.Func_ID;
)

Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.

Size of character ('a') in C/C++

In C the type of character literals are int and char in C++. This is in C++ required to support function overloading. See this example:

void foo(char c)
{
    puts("char");
}
void foo(int i)
{
    puts("int");
}
int main()
{
    foo('i');
    return 0;
}

Output:

char

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

C compiler for Windows?

GCC is ubiquitous. It is trusted and well understood by thousands of folks across dozens of communities.

Visual Studio is perhaps the best IDE ever developed. It has a great compiler underneath it. But it is strictly Windows-only.

If you're just playing, get GCC --it's free. If you're concerned about multiple platfroms, it's GCC. If you're talking serious Windows development, get Visual Studio.

Java split string to array

This behavior is explicitly documented in String.split(String regex) (emphasis mine):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

If you want those trailing empty strings included, you need to use String.split(String regex, int limit) with a negative value for the second parameter (limit):

String[] array = values.split("\\|", -1);

Running stages in parallel with Jenkins workflow / pipeline

As @Quartz mentioned, you can do something like

stage('Tests') {
    parallel(
        'Unit Tests': {
            container('node') {
                sh("npm test --cat=unit")
            }
        },
        'API Tests': {
            container('node') {
                sh("npm test --cat=acceptance")
            }
        }
    )
}

Reverse Y-Axis in PyPlot

using ylim() might be the best approach for your purpose:

xValues = list(range(10))
quads = [x** 2 for x in xValues]
plt.ylim(max(quads), 0)
plt.plot(xValues, quads)

will result:enter image description here

Inline list initialization in VB.NET

Use this syntax for VB.NET 2005/2008 compatibility:

Dim theVar As New List(Of String)(New String() {"one", "two", "three"})

Although the VB.NET 2010 syntax is prettier.

How to convert a hex string to hex number

Use format string

intNum = 123
print "0x%x"%(intNum)

or hex function.

intNum = 123
print hex(intNum)

How to set breakpoints in inline Javascript in Google Chrome?

Use the sources tab, you can set breakpoints in JavaScript there. In the directory tree underneath it (with the up and down arrow in it), you can select the file you want to debug. You can get out of an error by pressing resume on the right-hand side of the same tab.

Binding to static property

If you are using local resources you can refer to them as below:

<TextBlock Text="{Binding Source={x:Static prop:Resources.PerUnitOfMeasure}}" TextWrapping="Wrap" TextAlignment="Center"/>

github: server certificate verification failed

To me a simple

sudo apt-get update

solved the issue. It was a clock issue and with this command it resets to the current date/time and everything worked

Can angularjs routes have optional parameter values?

Please see @jlareau answer here: https://stackoverflow.com/questions/11534710/angularjs-how-to-use-routeparams-in-generating-the-templateurl

You can use a function to generate the template string:

var app = angular.module('app',[]);

app.config(
    function($routeProvider) {
        $routeProvider.
            when('/', {templateUrl:'/home'}).
            when('/users/:user_id', 
                {   
                    controller:UserView, 
                    templateUrl: function(params){ return '/users/view/' + params.user_id;   }
                }
            ).
            otherwise({redirectTo:'/'});
    }
);

How do I find the index of a character in a string in Ruby?

You can use this

"abcdefg".index('c')   #=> 2

What is Java Servlet?

As this article describes, a Servlet is a standardized way of extending a Java server, and accessing its capabilities.

Each Servlet can be seen as a tiny server (hence the name), that gets access to the request and response modelled in Java code, along with other context data, like the Session.

With these in hand, the Java code of the servlet can interface with whatever it needs to to render a response, including handing off to a JSP page for generating a HTML view.

SystemError: Parent module '' not loaded, cannot perform relative import

If you go one level up in running the script in the command line of your bash shell, the issue will be resolved. To do this, use cd .. command to change the working directory in which your script will be running. The result should look like this:

[username@localhost myProgram]$

rather than this:

[username@localhost app]$

Once you are there, instead of running the script in the following format:

python3 mymodule.py

Change it to this:

python3 app/mymodule.py

This process can be repeated once again one level up depending on the structure of your Tree diagram. Please also include the compilation command line that is giving you that mentioned error message.

CSS: Creating textured backgrounds

with latest CSS3 technology, it is possible to create textured background. Check this out: http://lea.verou.me/css3patterns/#

but it still limited on so many aspect. And browser support is also not so ready.

your best bet is using small texture image and make repeat to that background. you could get some nice ready to use texture image here:

http://subtlepatterns.com

How to allow only one radio button to be checked?

Add "name" attribute and keep the name same for all the radio buttons in a form.

i.e.,

<input type="radio" name="test" value="value1"> Value 1
<input type="radio" name="test" value="value2"> Value 2
<input type="radio" name="test" value="value3"> Value 3

Hope that would help.

What is an efficient way to implement a singleton pattern in Java?

Depending on the usage, there are several "correct" answers.

Since Java 5, the best way to do it is to use an enum:

public enum Foo {
   INSTANCE;
}

Pre Java 5, the most simple case is:

public final class Foo {

    private static final Foo INSTANCE = new Foo();

    private Foo() {
        if (INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return INSTANCE;
    }

    public Object clone() throws CloneNotSupportedException{
        throw new CloneNotSupportedException("Cannot clone instance of this class");
    }
}

Let's go over the code. First, you want the class to be final. In this case, I've used the final keyword to let the users know it is final. Then you need to make the constructor private to prevent users to create their own Foo. Throwing an exception from the constructor prevents users to use reflection to create a second Foo. Then you create a private static final Foo field to hold the only instance, and a public static Foo getInstance() method to return it. The Java specification makes sure that the constructor is only called when the class is first used.

When you have a very large object or heavy construction code and also have other accessible static methods or fields that might be used before an instance is needed, then and only then you need to use lazy initialization.

You can use a private static class to load the instance. The code would then look like:

public final class Foo {

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }
}

Since the line private static final Foo INSTANCE = new Foo(); is only executed when the class FooLoader is actually used, this takes care of the lazy instantiation, and is it guaranteed to be thread safe.

When you also want to be able to serialize your object you need to make sure that deserialization won't create a copy.

public final class Foo implements Serializable {

    private static final long serialVersionUID = 1L;

    private static class FooLoader {
        private static final Foo INSTANCE = new Foo();
    }

    private Foo() {
        if (FooLoader.INSTANCE != null) {
            throw new IllegalStateException("Already instantiated");
        }
    }

    public static Foo getInstance() {
        return FooLoader.INSTANCE;
    }

    @SuppressWarnings("unused")
    private Foo readResolve() {
        return FooLoader.INSTANCE;
    }
}

The method readResolve() will make sure the only instance will be returned, even when the object was serialized in a previous run of your program.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Your problem is here:

2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode

There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?

Fix this and possibly everything else will fall into place.

Add object to ArrayList at specified index

Bit late but hopefully can still be useful to someone.

2 steps to adding items to a specific position in an ArrayList

  1. add null items to a specific index in an ArrayList
  2. Then set the positions as and when required.

        list = new ArrayList();//Initialise the ArrayList
    for (Integer i = 0; i < mItems.size(); i++) {
        list.add(i, null); //"Add" all positions to null
    }
       // "Set" Items
        list.set(position, SomeObject);
    

This way you don't have redundant items in the ArrayList i.e. if you were to add items such as,

list = new ArrayList(mItems.size());    
list.add(position, SomeObject);

This would not overwrite existing items in the position merely, shifting existing ones to the right by one - so you have an ArrayList with twice as many indicies.

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

How do I print my Java object without getting "SomeType@2f92e0f4"?

If you look at the Object class (Parent class of all classes in Java) the toString() method implementation is

    public String toString() {
       return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

whenever you print any object in Java then toString() will be call. Now it's up to you if you override toString() then your method will call other Object class method call.

How do I select an entire row which has the largest ID in the table?

SELECT * 
FROM table 
WHERE id = (SELECT MAX(id) FROM TABLE)

How do I dynamically assign properties to an object in TypeScript?

I tend to put any on the other side i.e. var foo:IFoo = <any>{}; So something like this is still typesafe:

interface IFoo{
    bar:string;
    baz:string;
    boo:string;     
}

// How I tend to intialize 
var foo:IFoo = <any>{};

foo.bar = "asdf";
foo.baz = "boo";
foo.boo = "boo";

// the following is an error, 
// so you haven't lost type safety
foo.bar = 123; 

Alternatively you can mark these properties as optional:

interface IFoo{
    bar?:string;
    baz?:string;
    boo?:string;    
}

// Now your simple initialization works
var foo:IFoo = {};

Try it online

How to access shared folder without giving username and password

I found one way to access the shared folder without giving the username and password.

We need to change the share folder protect settings in the machine where the folder has been shared.

Go to Control Panel > Network and sharing center > Change advanced sharing settings > Enable Turn Off password protect sharing option.

By doing the above settings we can access the shared folder without any username/password.

JPA & Criteria API - Select only specific columns

You can do something like this

Session session = app.factory.openSession();
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery query = builder.createQuery();
Root<Users> root = query.from(Users.class);
query.select(root.get("firstname"));
String name = session.createQuery(query).getSingleResult();

where you can change "firstname" with the name of the column you want.

Bridged networking not working in Virtualbox under Windows 10

Virtual Box gives a lot of issues when it comes to bridge adaptor. I had the same issue with Virtual Box for windows 10. I decided to create VirtualBox Host-Only Ethernet adapter. But I again got issues while creating the host-only ethernet adaptor. I decided to switch to vmware. Vmware did not give me any issues. After installing vmware (and after changing few settings in the BIOS) and installing ubuntu on it, it automatically connected to my host machine's internet. It was able to generate it's own IP address as well and could also ping the host machine (windows machine). Hence, for me virtual box created a lot of issues whereas, vmware worked smoothly for me.

How to split a delimited string in Ruby and convert it to an array?

For String Integer without space as String

arr = "12345"

arr.split('')

output: ["1","2","3","4","5"]

For String Integer with space as String

arr = "1 2 3 4 5"

arr.split(' ')

output: ["1","2","3","4","5"]

For String Integer without space as Integer

arr = "12345"

arr.split('').map(&:to_i)

output: [1,2,3,4,5]

For String

arr = "abc"

arr.split('')

output: ["a","b","c"]

Explanation:

  1. arr -> string which you're going to perform any action.
  2. split() -> is an method, which split the input and store it as array.
  3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.

What does LINQ return when the results are empty

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(Dump is from LinqPad)

Rails Object to hash

In most recent version of Rails (can't tell which one exactly though), you could use the as_json method :

@post = Post.first
hash = @post.as_json
puts hash.pretty_inspect

Will output :

{ 
  :name => "test",
  :post_number => 20,
  :active => true
}

To go a bit further, you could override that method in order to customize the way your attributes appear, by doing something like this :

class Post < ActiveRecord::Base
  def as_json(*args)
    {
      :name => "My name is '#{self.name}'",
      :post_number => "Post ##{self.post_number}",
    }
  end
end

Then, with the same instance as above, will output :

{ 
  :name => "My name is 'test'",
  :post_number => "Post #20"
}

This of course means you have to explicitly specify which attributes must appear.

Hope this helps.

EDIT :

Also you can check the Hashifiable gem.

Callback function for JSONP with jQuery AJAX

delete this line:

jsonp: 'jsonp_callback',

Or replace this line:

url: 'http://url.of.my.server/submit?callback=json_callback',

because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.

Showing all errors and warnings

You can see a detailed description here.

ini_set('display_errors', 1);

// Report simple running errors
error_reporting(E_ERROR | E_WARNING | E_PARSE);

// Reporting E_NOTICE can be good too (to report uninitialized
// variables or catch variable name misspellings ...)
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);

// Report all errors except E_NOTICE
error_reporting(E_ALL & ~E_NOTICE);

// Report all PHP errors (see changelog)
error_reporting(E_ALL);

// Report all PHP errors
error_reporting(-1);

// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);

Changelog

  • 5.4.0 E_STRICT became part of E_ALL

  • 5.3.0 E_DEPRECATED and E_USER_DEPRECATED introduced.

  • 5.2.0 E_RECOVERABLE_ERROR introduced.

  • 5.0.0 E_STRICT introduced (not part of E_ALL).

Evaluate list.contains string in JSTL

there is no built-in feature to check that - what you would do is write your own tld function which takes a list and an item, and calls the list's contains() method. e.g.

//in your own WEB-INF/custom-functions.tld file add this
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!DOCTYPE taglib
        PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
        "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib
        xmlns="http://java.sun.com/xml/ns/j2ee"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
        version="2.0"
        >
    <tlib-version>1.0</tlib-version>
    <function>
        <name>contains</name>
        <function-class>com.Yourclass</function-class>
        <function-signature>boolean contains(java.util.List,java.lang.Object)
        </function-signature>
    </function>
</taglib>

Then create a class called Yourclass, and add a static method called contains with the above signature. I m sure the implementation of that method is pretty self explanatory:

package com; // just to illustrate how to represent the package in the tld
public class Yourclass {
   public static boolean contains(List list, Object o) {
      return list.contains(o);
   }
}

Then you can use it in your jsp:

<%@ taglib uri="/WEB-INF/custom-functions.tld" prefix="fn" %>
<c:if test="${  fn:contains( mylist, myValue ) }">style='display:none;'</c:if>

The tag can be used from any JSP in the site.

edit: more info regarding the tld file - more info here

MySQL - Trigger for updating same table after insert

On the last entry; this is another trick:

SELECT AUTO_INCREMENT FROM information_schema.tables WHERE table_schema = ... and table_name = ...

How to define global variable in Google Apps Script

Global variables certainly do exist in GAS, but you must understand the client/server relationship of the environment in order to use them correctly - please see this question: Global variables in Google Script (spreadsheet)

However this is not the problem with your code; the documentation indicates that the function to be executed by the menu must be supplied to the method as a string, right now you are supplying the output of the function: https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet#addMenu%28String,Object%29

function MainMenu_Init() {
    Logger.log('init');  
};

function onOpen() {
    var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
    var menus = [{
        name: "Init",
        functionName: "MainMenu_Init"
    }];
    spreadsheet.addMenu("Test", menus);
};

How to launch jQuery Fancybox on page load?

I got this to work by calling this function in document ready:

$(document).ready(function () {
        $.fancybox({
            'width': '40%',
            'height': '40%',
            'autoScale': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'iframe',
            'href': 'http://www.example.com'
        });
});

Warning comparison between pointer and integer

It should be

if (*message == '\0')

In C, simple quotes delimit a single character whereas double quotes are for strings.

Commenting out a set of lines in a shell script

Depending of the editor that you're using there are some shortcuts to comment a block of lines.

Another workaround would be to put your code in an "if (0)" conditional block ;)

add an onclick event to a div

Is it possible to add onclick to a div and have it occur if any area of the div is clicked.

Yes … although it should be done with caution. Make sure there is some mechanism that allows keyboard access. Build on things that work

If yes then why is the onclick method not going through to my div.

You are assigning a string where a function is expected.

divTag.onclick = printWorking;

There are nicer ways to assign event handlers though, although older versions of Internet Explorer are sufficiently different that you should use a library to abstract it. There are plenty of very small event libraries and every major library jQuery) has event handling functionality.

That said, now it is 2019, older versions of Internet Explorer no longer exist in practice so you can go direct to addEventListener

Tools to selectively Copy HTML+CSS+JS From A Specific Element of DOM

Webkit browsers (not sure about FireBug) allow you to copy the HTML of an element easily, so that's one part of the process out of the way.

Running this (in the javascript console) prior to copying the HTML for an element will move all the computed styles for the parent element given, as well as all child elements, into the inline style attribute which will then be available as part of the HTML.

var el = document.querySelector("#someid");
var els = el.getElementsByTagName("*");

for(var i = -1, l = els.length; ++i < l;){

    els[i].setAttribute("style", window.getComputedStyle(els[i]).cssText);

}

It's a total hack and you'll have alot of "junk" css attributes to wade through, but should at least get your started.

bootstrap multiselect get selected values

the solution what I found to work in my case

$('#multiselect1').multiselect({
    selectAllValue: 'multiselect-all',
    enableCaseInsensitiveFiltering: true,
    enableFiltering: true,
    maxHeight: '300',
    buttonWidth: '235',
    onChange: function(element, checked) {
        var brands = $('#multiselect1 option:selected');
        var selected = [];
        $(brands).each(function(index, brand){
            selected.push([$(this).val()]);
        });

        console.log(selected);
    }
}); 

mysql query: SELECT DISTINCT column1, GROUP BY column2

Try the following:

SELECT DISTINCT(ip), name, COUNT(name) nameCnt, 
time, price, SUM(price) priceSum
FROM tablename 
WHERE time >= $yesterday AND time <$today 
GROUP BY ip, name

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

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

You can also access the principal using the User property on ApiController.

So the following two statements are basically the same:

string id;
id = User.Identity.GetUserId();
id = RequestContext.Principal.Identity.GetUserId();

Convert character to ASCII numeric value in java

The several answers that purport to show how to do this are all wrong because Java characters are not ASCII characters. Java uses a multibyte encoding of Unicode characters. The Unicode character set is a super set of ASCII. So there can be characters in a Java string that do not belong to ASCII. Such characters do not have an ASCII numeric value, so asking how to get the ASCII numeric value of a Java character is unanswerable.

But why do you want to do this anyway? What are you going to do with the value?

If you want the numeric value so you can convert the Java String to an ASCII string, the real question is "how do I encode a Java String as ASCII". For that, use the object StandardCharsets.US_ASCII.

Call Python function from JavaScript code

Typically you would accomplish this using an ajax request that looks like

var xhr = new XMLHttpRequest();
xhr.open("GET", "pythoncode.py?text=" + text, true);
xhr.responseType = "JSON";
xhr.onload = function(e) {
  var arrOfStrings = JSON.parse(xhr.response);
}
xhr.send();

Multiple INSERT statements vs. single INSERT with multiple VALUES

It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.

Amazon S3 direct file upload from client browser - private key disclosure

Adding more info to the accepted answer, you can refer to my blog to see a running version of the code, using AWS Signature version 4.

Will summarize here:

As soon as the user selects a file to be uploaded, do the followings: 1. Make a call to the web server to initiate a service to generate required params

  1. In this service, make a call to AWS IAM service to get temporary cred

  2. Once you have the cred, create a bucket policy (base 64 encoded string). Then sign the bucket policy with the temporary secret access key to generate final signature

  3. send the necessary parameters back to the UI

  4. Once this is received, create a html form object, set the required params and POST it.

For detailed info, please refer https://wordpress1763.wordpress.com/2016/10/03/browser-based-upload-aws-signature-version-4/

Javascript ES6 export const vs export let

I think that once you've imported it, the behaviour is the same (in the place your variable will be used outside source file).

The only difference would be if you try to reassign it before the end of this very file.

How can I extract all values from a dictionary in Python?

Call the values() method on the dict.

How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?

For me (in Angular project) this code helped:

In HTML you should add autoplay muted

In JS/TS

playVideo() {
    const media = this.videoplayer.nativeElement;
    media.muted = true; // without this line it's not working although I have "muted" in HTML
    media.play();
}

The type initializer for 'Oracle.DataAccess.Client.OracleConnection' threw an exception

Ok, when you know for sure other applications that used the same process worked; on your new application make sure you have the data access reference and the three dll files...

I downloaded ODAC1120320Xcopy_32bit this from the Oracle site:

http://www.oracle.com/technetwork/database/windows/downloads/utilsoft-087491.html

Reference: Oracle.DataAccess.dll (ODAC1120320Xcopy_32bit\odp.net4\odp.net\bin\4\Oracle.DataAccess.dll)

Include these 3 files within your project:

  • oci.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oci.dll)
  • oraociei11.dll (ODAC1120320Xcopy_32bit\instantclient_11_2\oraociei11.dll)
  • OraOps11w.dll (ODAC1120320Xcopy_32bit\odp.net4\bin\OraOps11w.dll)

When I tried to create another application with the correct reference and files I would receive that error message.

The fix: Highlighted all three of the files and selected "Copy To Output" = Copy if newer. I did copy if newer since one of the dll's is above 100MB and any updates I do will not copy those files again.

I also ran into a registry error, this fixed it.

public void updateRegistryForOracleNLS()
{
    RegistryKey oracle = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\ORACLE");
    oracle.SetValue("NLS_LANG", "AMERICAN_AMERICA.WE8MSWIN1252");
}

For the Oracle nls_lang list, see this site: https://docs.oracle.com/html/B13804_02/gblsupp.htm

After that, everything worked smooth.

I hope it helps.

How do you reset the stored credentials in 'git credential-osxkeychain'?

git-credential-osxkeychain stores passwords in the Apple Keychain, as noted above.

By default, gitcredentials only considers the domain name. If you want Git to consider the full path (e.g. if you have multiple GitHub accounts), set the useHttpPath variable to true, as described at http://git-scm.com/docs/gitcredentials.html. Note that changing this setting will ask your credentials again for each URL.

MySQL INSERT INTO table VALUES.. vs INSERT INTO table SET

I think the extension is intended to allow a similar syntax for inserts and updates. In Oracle, a similar syntactical trick is:

UPDATE table SET (col1, col2) = (SELECT val1, val2 FROM dual)

Angular2 RC6: '<component> is not a known element'

OnInit was automatically implemented on my class while using the ng new ... key phrase on angular CLI to generate the new component. So after I removed the implementation and removed the empty method that was generated, the problem is resolved.

Avoid browser popup blockers

In addition Swiss Mister post, in my case the window.open was launched inside a promise, which turned the popup blocker on, my solution was: in angular:

$scope.gotClick = function(){

  var myNewTab = browserService.openNewTab();
  someService.getUrl().then(
    function(res){
        browserService.updateTabLocation(res.url, myNewTab);

    }
  );
};

browserService:

this.openNewTab = function(){
     var newTabWindow = $window.open();
     return newTabWindow;
}

this.updateTabLocation = function(tabLocation, tab) {
     if(!tabLocation){
       tab.close();
     }
     tab.location.href = tabLocation;
}

this is how you can open a new tab using the promise response and not invoking the popup blocker.

Creating a constant Dictionary in C#

There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:

Use Enumerable.ToLookup() - the Lookup<,> class is immutable (but multi-valued on the rhs); you can do this from a Dictionary<,> quite easily:

    Dictionary<string, int> ids = new Dictionary<string, int> {
      {"abc",1}, {"def",2}, {"ghi",3}
    };
    ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);
    int i = lookup["def"].Single();

How to fix Subversion lock error

I get this too. I go to the directory (not in Eclipse) where the files are, go into the .svn dir and delete the file called lock.

Flip back to Eclipse and continue.

There is a similar question here Problems committing file to SVN repository

How to format html table with inline styles to look like a rendered Excel table?

This is quick-and-dirty (and not formally valid HTML5), but it seems to work -- and it is inline as per the question:

<table border='1' style='border-collapse:collapse'>

No further styling of <tr>/<td> tags is required (for a basic table grid).

How do I edit $PATH (.bash_profile) on OSX?

Set the path JAVA_HOME and ANDROID_HOME > You have to open terminal and enter the below cmd.

touch ~/.bash_profile; open ~/.bash_profile

After that paste below paths in base profile file and save it

export ANDROID_HOME=/Users/<username>/Library/Android/sdk 
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home

java.lang.NoClassDefFoundError: com/fasterxml/jackson/core/JsonFactory

I have had the same error. I added dependency on pom.xml (I am working with Maven)

<dependency> 
        <groupId>com.fasterxml.jackson.core</groupId> 
        <artifactId>jackson-core</artifactId> 
        <version>2.12.1</version> 
 </dependency> 

I started trying with version 2.9.0, then I found a different error (com/fasterxml/jackson/core/exc/InputCoercionException) then I try different versions until all errors were solved with version 2.12.1

BehaviorSubject vs Observable?

An observable allows you to subscribe only whereas a subject allows you to both publish and subscribe.

So a subject allows your services to be used as both a publisher and a subscriber.

As of now, I'm not so good at Observable so I'll share only an example of Subject.

Let's understand better with an Angular CLI example. Run the below commands:

npm install -g @angular/cli

ng new angular2-subject

cd angular2-subject

ng serve

Replace the content of app.component.html with:

<div *ngIf="message">
  {{message}}
</div>

<app-home>
</app-home>

Run the command ng g c components/home to generate the home component. Replace the content of home.component.html with:

<input type="text" placeholder="Enter message" #message>
<button type="button" (click)="setMessage(message)" >Send message</button>

#message is the local variable here. Add a property message: string; to the app.component.ts's class.

Run this command ng g s service/message. This will generate a service at src\app\service\message.service.ts. Provide this service to the app.

Import Subject into MessageService. Add a subject too. The final code shall look like this:

import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';

@Injectable()
export class MessageService {

  public message = new Subject<string>();

  setMessage(value: string) {
    this.message.next(value); //it is publishing this value to all the subscribers that have already subscribed to this message
  }
}

Now, inject this service in home.component.ts and pass an instance of it to the constructor. Do this for app.component.ts too. Use this service instance for passing the value of #message to the service function setMessage:

import { Component } from '@angular/core';
import { MessageService } from '../../service/message.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent {

  constructor(public messageService:MessageService) { }

  setMessage(event) {
    console.log(event.value);
    this.messageService.setMessage(event.value);
  }
}

Inside app.component.ts, subscribe and unsubscribe (to prevent memory leaks) to the Subject:

import { Component, OnDestroy } from '@angular/core';
import { MessageService } from './service/message.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {

  message: string;
  subscription: Subscription;

  constructor(public messageService: MessageService) { }

  ngOnInit() {
    this.subscription = this.messageService.message.subscribe(
      (message) => {
        this.message = message;
      }
    );
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

That's it.

Now, any value entered inside #message of home.component.html shall be printed to {{message}} inside app.component.html

How to run batch file from network share without "UNC path are not supported" message?

Editing Windows registries is not worth it and not safe, use Map network drive and load the network share as if it's loaded from one of your local drives.

enter image description here

Create Word Document using PHP in Linux

<?php
function fWriteFile($sFileName,$sFileContent="No Data",$ROOT)
    {
        $word = new COM("word.application") or die("Unable to instantiate Word");
        //bring it to front
        $word->Visible = 1;
        //open an empty document
        $word->Documents->Add();
        //do some weird stuff
        $word->Selection->TypeText($sFileContent);
        $word->Documents[1]->SaveAs($ROOT."/".$sFileName.".doc");
        //closing word
        $word->Quit();
        //free the object
        $word = null;
        return $sFileName;
    }
?>



<?php
$PATH_ROOT=dirname(__FILE__);
$Return ="<table>";
$Return .="<tr><td>Row[0]</td></tr>";
 $Return .="<tr><td>Row[1]</td></tr>";
$sReturn .="</table>";
fWriteFile("test",$Return,$PATH_ROOT);
?> 

The CSRF token is invalid. Please try to resubmit the form

This seems to be an issue when using bootstrap unless you are rendering the form by {{ form(form)}}. In addition, the issues seems to only occur on input type="hidden". If you inspect the page the with the form, you'll find that the hidden input is not part of the markup at all or it's being rendered but not submitted for some reason. As suggested above, adding {{form_rest(form)}} or wrapping the input like below should do the trick.

<div class="form-group">
    <input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</div>

codeigniter model error: Undefined property

You have to load the db library first. In autoload.php add :

$autoload['libraries'] = array('database');

Also, try renaming User model class for "User_model".

Using unset vs. setting a variable to empty

Based on the comments above, here is a simple test:

isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset()   { [ -z "$(isunset "$1")" ] && echo 1; }

Example:

$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set

Add a row number to result set of a SQL query

So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:

SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;

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

Follow these steps:

  1. Open CMD as administrator
  2. Enter this command : cd..
  3. cd..
  4. cd Program Files\Python38\Scripts
  5. Download the package you want and put it in Python38\Scripts folder.
  6. pip install packagename.whl
  7. Done

You can write your python version instead of "38"

jQuery UI " $("#datepicker").datepicker is not a function"

I could fix this problem removing the jquery bundle on the _Layout.cshtml

Header

    <script src="~/Scripts/jquery-1.10.2.js"></script>
    <script src="~/Scripts/kendo/2015.2.902/kendo.all.min.js"></script>
    ...

Footer

    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

Change footer to

    @Scripts.Render("~/bundles/bootstrap")
    @RenderSection("scripts", required: false)

List append() in for loop

No need to re-assign.

a=[]
for i in range(5):    
    a.append(i)
a

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

How can I read Chrome Cache files?

EDIT: The below answer no longer works see here


In Chrome or Opera, open a new tab and navigate to chrome://view-http-cache/

Click on whichever file you want to view. You should then see a page with a bunch of text and numbers. Copy all the text on that page. Paste it in the text box below.

Press "Go". The cached data will appear in the Results section below.

RESTful API methods; HEAD & OPTIONS

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

9.2 OPTIONS

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

Responses to this method are not cacheable.

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

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

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

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

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

9.4 HEAD

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

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

Expand Python Search Path to Other Source

You should also read about python packages here: http://docs.python.org/tutorial/modules.html.

From your example, I would guess that you really have a package at ~/codez/project. The file __init__.py in a python directory maps a directory into a namespace. If your subdirectories all have an __init__.py file, then you only need to add the base directory to your PYTHONPATH. For example:

PYTHONPATH=$PYTHONPATH:$HOME/adaifotis/project

In addition to testing your PYTHONPATH environment variable, as David explains, you can test it in python like this:

$ python
>>> import project                      # should work if PYTHONPATH set
>>> import sys
>>> for line in sys.path: print line    # print current python path

...

Python 3.4.0 with MySQL database

sudo apt-get install python3-dev
sudo apt-get install libmysqlclient-dev
sudo apt-get install zlib1g-dev
sudo pip3 install mysqlclient

that worked for me!

Java - Opposite of .contains (does not contain)

Maybe

if (inventory.contains("bread") && !inventory.contains("water"))

Or

if (inventory.contains("bread")) {
    if (!inventory.contains("water")) {
        // do something here
    } 
}

How can I parse a YAML file in Python

If you have YAML that conforms to the YAML 1.2 specification (released 2009) then you should use ruamel.yaml (disclaimer: I am the author of that package). It is essentially a superset of PyYAML, which supports most of YAML 1.1 (from 2005).

If you want to be able to preserve your comments when round-tripping, you certainly should use ruamel.yaml.

Upgrading @Jon's example is easy:

import ruamel.yaml as yaml

with open("example.yaml") as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

Use safe_load() unless you really have full control over the input, need it (seldom the case) and know what you are doing.

If you are using pathlib Path for manipulating files, you are better of using the new API ruamel.yaml provides:

from ruamel.yaml import YAML
from pathlib import Path

path = Path('example.yaml')
yaml = YAML(typ='safe')
data = yaml.load(path)

BASH Syntax error near unexpected token 'done'

In my case, what was causing the problem was an if else statement. After re-writing the conditions, the error 'near done' got away.

How to read until EOF from cin in C++

Using loops:

#include <iostream>
using namespace std;
...
// numbers
int n;
while (cin >> n)
{
   ...
}
// lines
string line;
while (getline(cin, line))
{
   ...
}
// characters
char c;
while (cin.get(c))
{
   ...
}

resource

Convert a Python int into a big-endian string of bytes

Very easy with pwntools , the tools created for software hacking

(Un-ironically, I stumbled across this thread and tried solutions here, until I realised there exists conversion functionality in pwntools)

import pwntools

x2 = p32(x1)

What is the difference between json.load() and json.loads() functions

Just going to add a simple example to what everyone has explained,

json.load()

json.load can deserialize a file itself i.e. it accepts a file object, for example,

# open a json file for reading and print content using json.load
with open("/xyz/json_data.json", "r") as content:
  print(json.load(content))

will output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I use json.loads to open a file instead,

# you cannot use json.loads on file object
with open("json_data.json", "r") as content:
  print(json.loads(content))

I would get this error:

TypeError: expected string or buffer

json.loads()

json.loads() deserialize string.

So in order to use json.loads I will have to pass the content of the file using read() function, for example,

using content.read() with json.loads() return content of the file,

with open("json_data.json", "r") as content:
  print(json.loads(content.read()))

Output,

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

That's because type of content.read() is string, i.e. <type 'str'>

If I use json.load() with content.read(), I will get error,

with open("json_data.json", "r") as content:
  print(json.load(content.read()))

Gives,

AttributeError: 'str' object has no attribute 'read'

So, now you know json.load deserialze file and json.loads deserialize a string.

Another example,

sys.stdin return file object, so if i do print(json.load(sys.stdin)), I will get actual json data,

cat json_data.json | ./test.py

{u'event': {u'id': u'5206c7e2-da67-42da-9341-6ea403c632c7', u'name': u'Sufiyan Ghori'}}

If I want to use json.loads(), I would do print(json.loads(sys.stdin.read())) instead.

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

No space left on device

To list processes holding deleted files a linux system which has no lsof, here's my trick:

    pushd /proc ; for i in [1-9]* ; do ls -l $i/fd | grep "(deleted)" && (echo -n "used by: " ; ps -p $i | grep -v PID ; echo ) ; done ; popd

Rails 2.3.4 Persisting Model on Validation Failure

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

How to find index position of an element in a list when contains returns true

int indexOf(Object o) This method returns the index in this list of the first occurrence of the specified element, or -1 if this list does not contain this element.

Assigning strings to arrays of characters

To expand on Sparr's answer

Initialization and assignment are two distinct operations that happen to use the same operator ("=") here.

Think of it like this:

Imagine that there are 2 functions, called InitializeObject, and AssignObject. When the compiler sees thing = value, it looks at the context and calls one InitializeObject if you're making a new thing. If you're not, it instead calls AssignObject.

Normally this is fine as InitializeObject and AssignObject usually behave the same way. Except when dealing with char arrays (and a few other edge cases) in which case they behave differently. Why do this? Well that's a whole other post involving the stack vs the heap and so on and so forth.

PS: As an aside, thinking of it in this way will also help you understand copy constructors and other such things if you ever venture into C++

Minimal web server using netcat

I had the same need/problem but nothing here worked for me (or I didn't understand everything), so this is my solution.

I post my minimal_http_server.sh (working with my /bin/bash (4.3.11) but not /bin/sh because of the redirection):

rm -f out
mkfifo out
trap "rm -f out" EXIT
while true
do
  cat out | nc -l 1500 > >( # parse the netcat output, to build the answer redirected to the pipe "out".
    export REQUEST=
    while read -r line
    do
      line=$(echo "$line" | tr -d '\r\n')

      if echo "$line" | grep -qE '^GET /' # if line starts with "GET /"
      then
        REQUEST=$(echo "$line" | cut -d ' ' -f2) # extract the request
      elif [ -z "$line" ] # empty line / end of request
      then
        # call a script here
        # Note: REQUEST is exported, so the script can parse it (to answer 200/403/404 status code + content)
        ./a_script.sh > out
      fi
    done
  )
done

And my a_script.sh (with your need):

#!/bin/bash

echo -e "HTTP/1.1 200 OK\r"
echo "Content-type: text/html"
echo

date

H2 in-memory database. Table not found

I have tried adding ;DATABASE_TO_UPPER=false parameter, which it did work a single test, but what did the trick for me was ;CASE_INSENSITIVE_IDENTIFIERS=TRUE.

At the I had: jdbc:h2:mem:testdb;CASE_INSENSITIVE_IDENTIFIERS=TRUE

Moreover, the problem for me was when I upgraded to Spring Boot 2.4.1.

Uncaught Error: SECURITY_ERR: DOM Exception 18 when I try to set a cookie

This error pops up, if you try to create a web worker with data URI scheme.

var w = new Worker('data:text/javascript;charset=utf-8,onmessage%20%3D%20function()%20%7B%20postMessage(%22pong%22)%3B%20%7D'); w.postMessage('ping');

It's not allowed according to the standard: http://www.whatwg.org/specs/web-apps/current-work/multipage/workers.html#dom-worker

internet explorer 10 - how to apply grayscale filter?

IE10 does not support DX filters as IE9 and earlier have done, nor does it support a prefixed version of the greyscale filter.

However, you can use an SVG overlay in IE10 to accomplish the greyscaling. Example:

img.grayscale:hover {
    filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'><filter id=\'grayscale\'><feColorMatrix type=\'matrix\' values=\'1 0 0 0 0, 0 1 0 0 0, 0 0 1 0 0, 0 0 0 1 0\'/></filter></svg>#grayscale");
}

svg {
    background:url(http://4.bp.blogspot.com/-IzPWLqY4gJ0/T01CPzNb1KI/AAAAAAAACgA/_8uyj68QhFE/s400/a2cf7051-5952-4b39-aca3-4481976cb242.jpg);
}

(from: http://www.karlhorky.com/2012/06/cross-browser-image-grayscale-with-css.html)

Simplified JSFiddle: http://jsfiddle.net/KatieK/qhU7d/2/

More about the IE10 SVG filter effects: http://blogs.msdn.com/b/ie/archive/2011/10/14/svg-filter-effects-in-ie10.aspx

Using (Ana)conda within PyCharm

Continuum Analytics now provides instructions on how to setup Anaconda with various IDEs including Pycharm here. However, with Pycharm 5.0.1 running on Unbuntu 15.10 Project Interpreter settings were found via the File | Settings and then under the Project branch of the treeview on the Settings dialog.

Using ExcelDataReader to read Excel data starting from a particular cell

You could use the .NET library to do the same thing which i believe is more straightforward.

string ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0; data source={path of your excel file}; Extended Properties=Excel 12.0;";

        OleDbConnection objConn = null;
        System.Data.DataTable dt = null;
        //Create connection object by using the preceding connection string.
        objConn = new OleDbConnection(connString);
        objConn.Open();
        //Get the data table containg the schema guid.
        dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        string sql = string.Format("select * from [{0}$]", sheetName);
        var adapter = new System.Data.OleDb.OleDbDataAdapter(sql, ConnectionString);
        var ds = new System.Data.DataSet();
        string tableName = sheetName;
        adapter.Fill(ds, tableName);
        System.Data.DataTable data = ds.Tables[tableName];

After you have your data in the datatable you can access them as you would normally do with a DataTable class.

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

var filteredFiles = Directory
    .GetFiles(path, "*.*")
    .Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
    .ToList();

Edit 2014-07-23

You can do this in .NET 4.5 for a faster enumeration:

var filteredFiles = Directory
    .EnumerateFiles(path) //<--- .NET 4.5
    .Where(file => file.ToLower().EndsWith("aspx") || file.ToLower().EndsWith("ascx"))
    .ToList();

Directory.EnumerateFiles in MSDN

Eclipse fonts and background color

... on a Mac, Preferences' is under the main 'Aptana Studio 3' menu rather than the 'Windows' menu as mentioned above.

Copy table from one database to another

SELECT ... INTO :

select * into <destination table> from <source table>

How to install pip3 on Windows?

There is another way to install the pip3: just reinstall 3.6.

Ordering issue with date values when creating pivot tables

Go into options. You most likely have 'Manual Sort" turned on. You need to go and change to radio button to "ascending > date". You can also right click the row/column, "more sorting options". It took me forever to find this solution...

Django - taking values from POST request

For django forms you can do this;

form = UserLoginForm(data=request.POST) #getting the whole data from the user.
user = form.save() #saving the details obtained from the user.
username = user.cleaned_data.get("username") #where "username" in parenthesis is the name of the Charfield (the variale name i.e, username = forms.Charfield(max_length=64))

How do I use the CONCAT function in SQL Server 2008 R2?

I suggest you cast all columns before you concat them

cast('data1' as varchar) + cast('data2' as varchar) + cast('data3' as varchar)

This should work for you.

Show hide fragment in android

Try this:

MapFragment mapFragment = (MapFragment)getFragmentManager().findFragmentById(R.id.mapview);
mapFragment.getView().setVisibility(View.GONE);

How do I detect IE 8 with jQuery?

Assuming...

  • ...that it's the crunky rendering engine of old versions of IE you're interested in detecting, to make a style look right in old IE (otherwise, use feature detection)
  • ...that you can't just add conditional comments to the HTML - e.g. for JS plugins that can be applied to any page (otherwise, just do the trick of conditional classes on <body> or <html>)

...then this is probably the best trick (based on this non-jQuery, slightly less flexible variant). It creates then tests for then removes an appropriate conditional comment.

(Conditional comments are ignored in IE10+ 'standards mode' - but that should be fine since IE10+ 'standards mode' doesn't have a crazy rendering engine!)

Drop in this function:

function isIE( version, comparison ){
    var $div = $('<div style="display:none;"/>');

    // Don't chain these, in IE8 chaining stops some versions of jQuery writing the conditional comment properly
    $div.appendTo($('body'));
    $div.html('<!--[if '+(comparison||'')+' IE '+(version||'')+']><a>&nbsp;</a><![endif]-->');

    var ieTest = $div.find('a').length;
    $div.remove();
    return ieTest;
}

Then use it like this:

if(isIE()){ /* runs in all versions of IE after 4 before standards-mode 10 */ }

if(isIE(8)){ /* runs in IE8 */ }

if(isIE(9)){ /* runs in IE9 */ }

if(isIE(8,'lte')){ /* runs in IE8 or below */ }

if(isIE(6,'lte')){ /* if you need this, I pity you... */ }

I'd also suggest caching the results of this function so you don't have to repeat it. For example, you could use the string (comparison||'')+' IE '+(version||'') as a key to store and check for the result of this test in an object somewhere.

SQL - Rounding off to 2 decimal places

Works in both with postgresql and Oracle

SELECT ename, sal, round(((sal * .15 + comm) /12),2) 
FROM emp where job = 'SALESMAN' 

Circular (or cyclic) imports in Python

Suppose you are running a test python file named request.py In request.py, you write

import request

so this also most likely a circular import.

Solution:

Just change your test file to another name such as aaa.py, other than request.py.

Do not use names that are already used by other libs.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

This means the remote vm is not listening to current port i solved this by adding the port in the vm server

Any shortcut to initialize all array elements to zero?

In java all elements(primitive integer types byte short, int, long) are initialised to 0 by default. You can save the loop.

Check if Cookie Exists

You can do something like this to find out the cookies's value:

Request.Cookies[SESSION_COOKIE_NAME].Value

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

JPA OneToMany not deleting child

You can try this:

@OneToOne(orphanRemoval=true) or @OneToMany(orphanRemoval=true).

Explaining Apache ZooKeeper

In a nutshell, ZooKeeper helps you build distributed applications.

How it works

You may describe ZooKeeper as a replicated synchronization service with eventual consistency. It is robust, since the persisted data is distributed between multiple nodes (this set of nodes is called an "ensemble") and one client connects to any of them (i.e., a specific "server"), migrating if one node fails; as long as a strict majority of nodes are working, the ensemble of ZooKeeper nodes is alive. In particular, a master node is dynamically chosen by consensus within the ensemble; if the master node fails, the role of master migrates to another node.

How writes are handled

The master is the authority for writes: in this way writes can be guaranteed to be persisted in-order, i.e., writes are linear. Each time a client writes to the ensemble, a majority of nodes persist the information: these nodes include the server for the client, and obviously the master. This means that each write makes the server up-to-date with the master. It also means, however, that you cannot have concurrent writes.

The guarantee of linear writes is the reason for the fact that ZooKeeper does not perform well for write-dominant workloads. In particular, it should not be used for interchange of large data, such as media. As long as your communication involves shared data, ZooKeeper helps you. When data could be written concurrently, ZooKeeper actually gets in the way, because it imposes a strict ordering of operations even if not strictly necessary from the perspective of the writers. Its ideal use is for coordination, where messages are exchanged between the clients.

How reads are handled

This is where ZooKeeper excels: reads are concurrent since they are served by the specific server that the client connects to. However, this is also the reason for the eventual consistency: the "view" of a client may be outdated, since the master updates the corresponding server with a bounded but undefined delay.

In detail

The replicated database of ZooKeeper comprises a tree of znodes, which are entities roughly representing file system nodes (think of them as directories). Each znode may be enriched by a byte array, which stores data. Also, each znode may have other znodes under it, practically forming an internal directory system.

Sequential znodes

Interestingly, the name of a znode can be sequential, meaning that the name the client provides when creating the znode is only a prefix: the full name is also given by a sequential number chosen by the ensemble. This is useful, for example, for synchronization purposes: if multiple clients want to get a lock on a resource, they can each concurrently create a sequential znode on a location: whoever gets the lowest number is entitled to the lock.

Ephemeral znodes

Also, a znode may be ephemeral: this means that it is destroyed as soon as the client that created it disconnects. This is mainly useful in order to know when a client fails, which may be relevant when the client itself has responsibilities that should be taken by a new client. Taking the example of the lock, as soon as the client having the lock disconnects, the other clients can check whether they are entitled to the lock.

Watches

The example related to client disconnection may be problematic if we needed to periodically poll the state of znodes. Fortunately, ZooKeeper offers an event system where a watch can be set on a znode. These watches may be set to trigger an event if the znode is specifically changed or removed or new children are created under it. This is clearly useful in combination with the sequential and ephemeral options for znodes.

Where and how to use it

A canonical example of Zookeeper usage is distributed-memory computation, where some data is shared between client nodes and must be accessed/updated in a very careful way to account for synchronization.

ZooKeeper offers the library to construct your synchronization primitives, while the ability to run a distributed server avoids the single-point-of-failure issue you have when using a centralized (broker-like) message repository.

ZooKeeper is feature-light, meaning that mechanisms such as leader election, locks, barriers, etc. are not already present, but can be written above the ZooKeeper primitives. If the C/Java API is too unwieldy for your purposes, you should rely on libraries built on ZooKeeper such as cages and especially curator.

Where to read more

Official documentation apart, which is pretty good, I suggest to read Chapter 14 of Hadoop: The Definitive Guide which has ~35 pages explaining essentially what ZooKeeper does, followed by an example of a configuration service.

MongoDB: Combine data from multiple collections into one..how?

You've to do that in your application layer. If you're using an ORM, it could use annotations (or something similar) to pull references that exist in other collections. I only have worked with Morphia, and the @Reference annotation fetches the referenced entity when queried, so I am able to avoid doing it myself in the code.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

You can use the Logical NOT ! operator:

if (!$(this).parent().next().is('ul')){

Or equivalently (see comments below):

if (! ($(this).parent().next().is('ul'))){

For more information, see the Logical Operators section of the MDN docs.

python encoding utf-8

You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode before it can encode it back to UTF-8. That is what is failing here:

>>> data = u'\u00c3'            # Unicode data
>>> data = data.encode('utf8')  # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8')         # Try to *re*-encode it
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

Just write your data directly to the file, there is no need to encode already-encoded data.

If you instead build up unicode values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open() instead, which returns a file object that will encode unicode values to UTF-8 for you.

You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).

For your MySQL insert problem, you need to do two things:

  • Add charset='utf8' to your MySQLdb.connect() call.

  • Use unicode objects, not str objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:

    artiste = artiste.decode('utf8')  # it is already UTF8, decode to unicode
    
    c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    
    # ...
    
    c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
    

It may actually work better if you used codecs.open() to decode the contents automatically instead:

import codecs

sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')

with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
    for line in findex:
        if u'#artiste' not in line:
            continue

        artiste=line.split(u'[:::]')[1].strip()

    cursor = sql.cursor()
    cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
    if not cursor.fetchone()[0]:
        cursor = sql.cursor()
        cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
        artists_inserted += 1

You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:

Codeigniter - no input file specified

Godaddy hosting it seems fixed on .htaccess, myself it is working

RewriteRule ^(.*)$ index.php/$1 [L]

to

RewriteRule ^(.*)$ index.php?/$1 [QSA,L]

Apache VirtualHost 403 Forbidden

For apache Ubuntu 2.4.7 , I finally found you need to white list your virtual host in apache2.conf

# access here, or in any related virtual host.
<Directory /home/gav/public_html/>
    Options FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

How to echo with different colors in the Windows command line

Windows 10 - TH2 and above:

(a.k.a. Version 1511, build 10586, release 2015-11-10)

At Command Prompt:

echo ^[[32m HI ^[[0m

Using the actual keys:   echo Ctrl+[[32m HI Ctrl+[[0mEnter

You should see a green "HI" below it.

Code numbers can be found here:

Notepad:

To save this into notepad, you can type ESC into it using: Alt+027 with the numpad, then the [32m part. Another trick when I was on a laptop, redirect the line above into a file to get started, then cut and paste:

echo echo ^[[32m HI ^[[0m >> batch_file.cmd

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

C# loop - break vs. continue

A really easy way to understand this is to place the word "loop" after each of the keywords. The terms now make sense if they are just read like everyday phrases.

break loop - looping is broken and stops.

continue loop - loop continues to execute with the next iteration.

How to center a <p> element inside a <div> container?

To get left/right centering, then applying text-align: center to the div and margin: auto to the p.

For vertical positioning you should make sure you understand the different ways of doing so, this is a commonly asked problem: Vertical alignment of elements in a div

How to remove an element slowly with jQuery?

You mean like

$target.hide('slow')

?

How do I list all cron jobs for all users?

getent passwd | cut -d: -f1 | perl -e'while(<>){chomp;$l = `crontab -u $_ -l 2>/dev/null`;print "$_\n$l\n" if $l}'

This avoids messing with passwd directly, skips users that have no cron entries and for those who have them it prints out the username as well as their crontab.

Mostly dropping this here though so i can find it later in case i ever need to search for it again.

Is it possible to pass a flag to Gulp to have it run tasks in different ways?

It has been some time since this question has been posted, but maybe it will help someone.

I am using GULP CLI 2.0.1 (installed globally) and GULP 4.0.0 (installed locally) here is how you do it without any additional plugin. I think the code is quite self-explanatory.

var cp = require('child_process'), 
{ src, dest, series, parallel, watch } = require('gulp');

// == availableTasks: log available tasks to console
function availableTasks(done) {
  var command = 'gulp --tasks-simple';
  if (process.argv.indexOf('--verbose') > -1) {
    command = 'gulp --tasks';
  }
  cp.exec(command, function(err, stdout, stderr) {
    done(console.log('Available tasks are:\n' + stdout));
  });
}
availableTasks.displayName = 'tasks';
availableTasks.description = 'Log available tasks to console as plain text list.';
availableTasks.flags = {
  '--verbose': 'Display tasks dependency tree instead of plain text list.'
};
exports.availableTasks = availableTasks;

And run from the console:

gulp availableTasks

Then run and see the differences:

gulp availableTasks --verbose

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

How to change navigation bar color in iOS 7 or 6?

I'm not sure about changing the tint vs the background color but this is how you change the tint color of the Navigation Bar:

Try this code..

[navigationController.navigationBar setTintColor:[UIColor redColor]; //Red as an example.

Passing data between different controller action methods

I prefer to use this instead of TempData

public class Home1Controller : Controller 
{
    [HttpPost]
    public ActionResult CheckBox(string date)
    {
        return RedirectToAction("ActionName", "Home2", new { Date =date });
    }
}

and another controller Action is

public class Home2Controller : Controller 
{
    [HttpPost]
    Public ActionResult ActionName(string Date)
    {
       // do whatever with Date
       return View();
    }
}

it is too late but i hope to be helpful for any one in the future

How to get values from IGrouping

var groups = list.GroupBy(x => x.ID);

Can anybody suggest how to get the values (List) from an IGrouping<int, smth> in such a context?

"IGrouping<int, smth> group" is actually an IEnumerable with a key, so you either:

  • iterate on the group or
  • use group.ToList() to convert it to a List
foreach (IGrouping<int, smth> group in groups)
{
   var thisIsYourGroupKey = group.Key; 
   List<smth> list = group.ToList();     // or use directly group.foreach
}

Getting year in moment.js

_x000D_
_x000D_
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

How to submit a form using PhantomJS

I figured it out. Basically it's an async issue. You can't just submit and expect to render the subsequent page immediately. You have to wait until the onLoad event for the next page is triggered. My code is below:

var page = new WebPage(), testindex = 0, loadInProgress = false;

page.onConsoleMessage = function(msg) {
  console.log(msg);
};

page.onLoadStarted = function() {
  loadInProgress = true;
  console.log("load started");
};

page.onLoadFinished = function() {
  loadInProgress = false;
  console.log("load finished");
};

var steps = [
  function() {
    //Load Login Page
    page.open("https://website.com/theformpage/");
  },
  function() {
    //Enter Credentials
    page.evaluate(function() {

      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) { 
        if (arr[i].getAttribute('method') == "POST") {

          arr[i].elements["email"].value="mylogin";
          arr[i].elements["password"].value="mypassword";
          return;
        }
      }
    });
  }, 
  function() {
    //Login
    page.evaluate(function() {
      var arr = document.getElementsByClassName("login-form");
      var i;

      for (i=0; i < arr.length; i++) {
        if (arr[i].getAttribute('method') == "POST") {
          arr[i].submit();
          return;
        }
      }

    });
  }, 
  function() {
    // Output content of page to stdout after form has been submitted
    page.evaluate(function() {
      console.log(document.querySelectorAll('html')[0].outerHTML);
    });
  }
];


interval = setInterval(function() {
  if (!loadInProgress && typeof steps[testindex] == "function") {
    console.log("step " + (testindex + 1));
    steps[testindex]();
    testindex++;
  }
  if (typeof steps[testindex] != "function") {
    console.log("test complete!");
    phantom.exit();
  }
}, 50);

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Adding javafx accessible permission in eclipse oxygen go to project> properties> java build path> libraries> then expand the libraries and double click on> Access rules there you set the permission Resolution : Accessible Rule Pattern : javafx/**

enter image description here

enter image description here

enter image description here

Android: TextView: Remove spacing and padding on top and bottom

I think this problem can be solved in this way:

 <TextView
        android:id="@+id/leftText"
        android:includeFontPadding="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="30dp"
        android:text="Hello World!\nhello world" />

 <TextView
        android:id="@+id/rightUpperText"
        android:includeFontPadding="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/leftText"
        android:layout_alignTop="@+id/leftText"
        android:textSize="30dp"
        android:text="Hello World!" />

 <TextView
        android:id="@+id/rightLowerText"
        android:includeFontPadding="false"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/leftText"
        android:layout_below="@+id/rightUpperText"
        android:textSize="30dp"
        android:text="hello world" />

Those are the results:

ScreenShot-1

ScreenShot-3

Though the line of special characters in rightLowerText looks a little bit higher than the second line of leftText, their baselines are stilled aligned.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

I'm all about ROOT for these needs. Pretty heavy if you don't need all the analysis support, though.

Java Scanner class reading strings

use sc.nextLine(); two time so that we can read the last line of string

sc.nextLine() sc.nextLine()

Sorting HTML table with JavaScript

Sorting html table column on page load

var table = $('table#all_items_table');
var rows = table.find('tr:gt(0)').toArray().sort(comparer(3));
for (var i = 0; i < rows.length; i++) {
    table.append(rows[i])
}
function comparer(index) {
    return function (a, b) {
        var v1= getCellValue(a, index),
        v2= getCellValue(b, index);
        return $.isNumeric(v2) && $.isNumeric(v1) ? v2 - v1: v2.localeCompare(v1)
    }
}


function getCellValue(row, index) {
    return parseFloat($(row).children('td').eq(index).html().replace(/,/g,'')); //1234234.45645->1234234
}

enter image description here

How to remove all .svn directories from my application directories

Try this:

find . -name .svn -exec rm -rf '{}' \;

Before running a command like that, I often like to run this first:

find . -name .svn -exec ls '{}' \;

How to add an auto-incrementing primary key to an existing table, in PostgreSQL?

To use an identity column in v10,

ALTER TABLE test 
ADD COLUMN id { int | bigint | smallint}
GENERATED { BY DEFAULT | ALWAYS } AS IDENTITY PRIMARY KEY;

For an explanation of identity columns, see https://blog.2ndquadrant.com/postgresql-10-identity-columns/.

For the difference between GENERATED BY DEFAULT and GENERATED ALWAYS, see https://www.cybertec-postgresql.com/en/sequences-gains-and-pitfalls/.

For altering the sequence, see https://popsql.io/learn-sql/postgresql/how-to-alter-sequence-in-postgresql/.

How to test my servlet using JUnit

Use Selenium for webbased unit tests. There's a Firefox plugin called Selenium IDE which can record actions on the webpage and export to JUnit testcases which uses Selenium RC to run the test server.

Java Enum Methods - return opposite direction enum

This works:

public enum Direction {
    NORTH, SOUTH, EAST, WEST;

    public Direction oppose() {
        switch(this) {
            case NORTH: return SOUTH;
            case SOUTH: return NORTH;
            case EAST:  return WEST;
            case WEST:  return EAST;
        }
        throw new RuntimeException("Case not implemented");
    }
}

Python loop counter in a for loop

You could also do:

 for option in options:
      if option == options[selected_index]:
           #print
      else:
           #print

Although you'd run into issues if there are duplicate options.

JQuery datepicker language

Maybe you don't have a language file:

Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n

A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:

http://api.jqueryui.com/datepicker/

Application_Start not firing?

I had this problem when trying to initialize log4net. I decided to just make a static constructor for the Global.asax

static Global(){
//Do your initialization here statically
}

Google Maps API Multiple Markers with Infowindows

Source Link

Demo Link

The following code will show Multiple Markers with InfoWindow. You can Uncomment code to show Info on Hover as well

enter image description here

            var map;
            var InforObj = [];
            var centerCords = {
                lat: -25.344,
                lng: 131.036
            };
            var markersOnMap = [{
                    placeName: "Australia (Uluru)",
                    LatLng: [{
                        lat: -25.344,
                        lng: 131.036
                    }]
                },
                {
                    placeName: "Australia (Melbourne)",
                    LatLng: [{
                        lat: -37.852086,
                        lng: 504.985963
                    }]
                },
                {
                    placeName: "Australia (Canberra)",
                    LatLng: [{
                        lat: -35.299085,
                        lng: 509.109615
                    }]
                },
                {
                    placeName: "Australia (Gold Coast)",
                    LatLng: [{
                        lat: -28.013044,
                        lng: 513.425586
                    }]
                },
                {
                    placeName: "Australia (Perth)",
                    LatLng: [{
                        lat: -31.951994,
                        lng: 475.858081
                    }]
                }
            ];

            window.onload = function () {
                initMap();
            };

            function addMarkerInfo() {
                for (var i = 0; i < markersOnMap.length; i++) {
                    var contentString = '<div id="content"><h1>' + markersOnMap[i].placeName +
                        '</h1><p>Lorem ipsum dolor sit amet, vix mutat posse suscipit id, vel ea tantas omittam detraxit.</p></div>';

                    const marker = new google.maps.Marker({
                        position: markersOnMap[i].LatLng[0],
                        map: map
                    });

                    const infowindow = new google.maps.InfoWindow({
                        content: contentString,
                        maxWidth: 200
                    });

                    marker.addListener('click', function () {
                        closeOtherInfo();
                        infowindow.open(marker.get('map'), marker);
                        InforObj[0] = infowindow;
                    });
                    // marker.addListener('mouseover', function () {
                    //     closeOtherInfo();
                    //     infowindow.open(marker.get('map'), marker);
                    //     InforObj[0] = infowindow;
                    // });
                    // marker.addListener('mouseout', function () {
                    //     closeOtherInfo();
                    //     infowindow.close();
                    //     InforObj[0] = infowindow;
                    // });
                }
            }

            function closeOtherInfo() {
                if (InforObj.length > 0) {
                    InforObj[0].set("marker", null);
                    InforObj[0].close();
                    InforObj.length = 0;
                }
            }

            function initMap() {
                map = new google.maps.Map(document.getElementById('map'), {
                    zoom: 4,
                    center: centerCords
                });
                addMarkerInfo();
            }

Is it safe to delete a NULL pointer?

I have experienced that it is not safe (VS2010) to delete[] NULL (i.e. array syntax). I'm not sure whether this is according to the C++ standard.

It is safe to delete NULL (scalar syntax).

Get list of certificates from the certificate store in C#

Yes -- the X509Store.Certificates property returns a snapshot of the X.509 certificate store.

Open new Terminal Tab from command line (Mac OS X)

The keyboard shortcut cmd-t opens a new tab, so you can pass this keystroke to OSA command as follows:

osascript -e 'tell application "System Events"' -e 'keystroke "t" using command down' -e 'end tell'

CSS: Hover one element, effect for multiple elements?

OR

.section:hover > div {
  background-color: #0CF;
}

NOTE Parent element state can only affect a child's element state so you can use:

.image:hover + .layer {
  background-color: #0CF;
}
.image:hover {
  background-color: #0CF;
}

but you can not use

.layer:hover + .image {
  background-color: #0CF;
}

How to compare binary files to check if they are the same?

You can use MD5 hash function to check if two files are the same, with this you can not see the differences in a low level, but is a quick way to compare two files.

md5 <filename1>
md5 <filename2>

If both MD5 hashes (the command output) are the same, then, the two files are not different.

Number of regex matches

For those moments when you really want to avoid building lists:

import re
import operator
from functools import reduce
count = reduce(operator.add, (1 for _ in re.finditer(my_pattern, my_string))) 

Sometimes you might need to operate on huge strings. This might help.

Controlling execution order of unit tests in Visual Studio

I see that this topic is almost 6 years old, and we now have new version of Visual studio but I will reply anyway. I had that order problem in Visual Studio 19 and I figured it out by adding capital letter (you can also add small letter) in front of your method name and in alphabetical order like this:

[TestMethod]
        public void AName1()
        {}
[TestMethod]
        public void BName2()
        {}

And so on. I know that this doesn't look appealing, but it looks like Visual is sorting your tests in test explorer in alphabetical order, doesn't matter how you write it in your code. Playlist didn't work for me in this case.

Hope that this will help.

How to fix Invalid byte 1 of 1-byte UTF-8 sequence

This error comes when you are trying to load jasper report file with the extension .jasper
For Example 
c://reports//EmployeeReport.jasper"

While you should load jasper report file with the extension .jrxml
For Example 
c://reports//EmployeeReport.jrxml"
[See Problem Screenshot ][1] [1]: https://i.stack.imgur.com/D5SzR.png
[See Solution Screenshot][2] [2]: https://i.stack.imgur.com/VeQb9.png

  
  

How to change text and background color?

There is no (standard) cross-platform way to do this. On windows, try using conio.h. It has the:

textcolor(); // and
textbackground();

functions.

For example:

textcolor(RED);
cprintf("H");
textcolor(BLUE);
cprintf("e");
// and so on.

How to output only captured groups with sed?

you can use grep

grep -Eow "[0-9]+" file

What is the difference between a cer, pvk, and pfx file?

I actually came across something like this not too long ago... check it out over on msdn (see the first answer)

in summary:

.cer - certificate stored in the X.509 standard format. This certificate contains information about the certificate's owner... along with public and private keys.

.pvk - files are used to store private keys for code signing. You can also create a certificate based on .pvk private key file.

.pfx - stands for personal exchange format. It is used to exchange public and private objects in a single file. A pfx file can be created from .cer file. Can also be used to create a Software Publisher Certificate.

I summarized the info from the page based on the suggestion from the comments.

How to input a path with a white space?

SOME_PATH=/mnt/someProject/some\ path

should work

java.net.SocketException: Software caused connection abort: recv failed

This also happens if your TLS client is unable to be authenticate by the server configured to require client authentication.

CSS Image size, how to fill, but not stretch?

Building off of @Dominic Green's answer using jQuery, here is a solution that should work for images that are either wider than they are high or higher than they are wide.

http://jsfiddle.net/grZLR/4/

There is probably a more elegant way of doing the JavaScript, but this does work.

function myTest() {
  var imgH = $("#my-img").height();
  var imgW = $("#my-img").width();
  if(imgW > imgH) {
    $(".container img").css("height", "100%");
    var conWidth = $(".container").width();
    var imgWidth = $(".container img").width();
    var gap = (imgWidth - conWidth)/2;
    $(".container img").css("margin-left", -gap);
  } else {
    $(".container img").css("width", "100%");
    var conHeight = $(".container").height();
    var imgHeight = $(".container img").height();
    var gap = (imgHeight - conHeight)/2;
    $(".container img").css("margin-top", -gap);
  }
}
myTest();

PHPDoc type hinting for array of objects?

In the PhpStorm IDE from JetBrains, you can use /** @var SomeObj[] */, e.g.:

/**
 * @return SomeObj[]
 */
function getSomeObjects() {...}

The phpdoc documentation recommends this method:

specified containing a single type, the Type definition informs the reader of the type of each array element. Only one Type is then expected as element for a given array.

Example: @return int[]

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

Cross Browser Flash Detection in Javascript

Have created a small .swf which redirects. If the browser is flash enabled it will redirect.

package com.play48.modules.standalone.util;

import flash.net.URLRequest;


class Redirect {


static function main() {

    flash.Lib.getURL(new URLRequest("http://play48.com/flash.html"), "_self");

}

}

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

How do I do logging in C# without using 3rd party libraries?

I would rather not use any outside frameworks like log4j.net.

Why? Log4net would probably address most of your requirements. For example check this class: RollingFileAppender.

Log4net is well documented and there are thousand of resources and use cases on the web.

Which are more performant, CTE or temporary tables?

I'd say they are different concepts but not too different to say "chalk and cheese".

  • A temp table is good for re-use or to perform multiple processing passes on a set of data.

  • A CTE can be used either to recurse or to simply improved readability.
    And, like a view or inline table valued function can also be treated like a macro to be expanded in the main query

  • A temp table is another table with some rules around scope

I have stored procs where I use both (and table variables too)

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

In case anyone in the future had this problem, I'm using a Mac and just had to install the Command Line Tools using 'xcode-select --install'

jQuery same click event for multiple elements

Add a comma separated list of classes like this :

jQuery(document).ready(function($) {

$('.class, .id').click(function() { 

//  Your code

    }

});