Programs & Examples On #Marquee

A non-standard HTML element that causes text to scroll automatically

Is it possible to change the speed of HTML's <marquee> tag?

To increase scroll speed of text use attribute

scrollamount
OR
scrolldelay

in the 'marquee' tag. place any integer value which represent how fast you need your text to move

Very Simple, Very Smooth, JavaScript Marquee

My text marquee for more text, and position absolute enabled

http://jsfiddle.net/zrW5q/2075/

(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
  position: 'absolute',
  visibility: 'hidden',
  height: 'auto',
  width: 'auto',
  'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};

$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
    offset = that.width(),
    width = offset,
    css = {
        'text-indent': that.css('text-indent'),
        'overflow': that.css('overflow'),
        'white-space': that.css('white-space')
    },
    marqueeCss = {
        'text-indent': width,
        'overflow': 'hidden',
        'white-space': 'nowrap'
    },
    args = $.extend(true, {
        count: -1,
        speed: 1e1,
        leftToRight: false
    }, args),
    i = 0,
    stop = textWidth * -1,
    dfd = $.Deferred();

function go() {
    if (that.css('overflow') != "hidden") {
        that.css('text-indent', width + 'px');
        return false;
    }
    if (!that.length) return dfd.reject();

    if (width <= stop) {
        i++;
        if (i == args.count) {
            that.css(css);
            return dfd.resolve();
        }
        if (args.leftToRight) {
            width = textWidth * -1;
        } else {
            width = offset;
        }
    }
    that.css('text-indent', width + 'px');
    if (args.leftToRight) {
        width++;
    } else {
        width--;
    }
    setTimeout(go, args.speed);
};

if (args.leftToRight) {
    width = textWidth * -1;
    width++;
    stop = offset;
} else {
    width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {     
    $(this).removeAttr("style");
}).mouseout(function () {
    $(this).marquee();
});
})(jQuery);

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

No Exception while type casting with a null in java

Print:

Print an object. The string produced by the String.valueOf(Object) method is translated into bytes

ValueOf:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

It wil simply return a string with value "null" when the object is null.

Which port(s) does XMPP use?

The ports required will be different for your XMPP Server and any XMPP Clients. Most "modern" XMPP Servers follow the defined IANA Ports for Server-to-Server 5269 and for Client-to-Server 5222. Any additional ports depends on what features you enable on the Server, i.e. if you offer BOSH then you may need to open port 80.

File Transfer is highly dependent on both the Clients you use and the Server as to what port it will use, but most of them also negotiate the connect via your existing XMPP Client-to-Server link so the required port opening will be client side (or proxied via port 80.)

open read and close a file in 1 line of code

No need to import any special libraries to do this.

Use normal syntax and it will open the file for reading then close it.

with open("/etc/hostname","r") as f: print f.read() 

or

with open("/etc/hosts","r") as f: x = f.read().splitlines()

which gives you an array x containing the lines, and can be printed like so:

for line in x: print line

These one-liners are very helpful for maintenance - basically self-documenting.

Escaping a forward slash in a regular expression

What context/language? Some languages use / as the pattern delimiter, so yes, you need to escape it, depending on which language/context. You escape it by putting a backward slash in front of it: \/ For some languages (like PHP) you can use other characters as the delimiter and therefore you don't need to escape it. But AFAIK in all languages, the only special significance the / has is it may be the designated pattern delimiter.

In LaTeX, how can one add a header/footer in the document class Letter?

Just before your "Content of the letter" line, add \thispagestyle{fancy} and it should show the headers you defined. (It worked for me.)

Here's the full document that I used to test:

\documentclass[12pt]{letter}

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

% page counting, header/footer
\usepackage{fancyhdr}
\usepackage{lastpage}

\pagestyle{fancy}
\lhead{\footnotesize \parbox{11cm}{Draft 1} }
\lfoot{\footnotesize \parbox{11cm}{\textit{2}}}
\cfoot{}
\rhead{\footnotesize 3}
\rfoot{\footnotesize Page \thepage\ of \pageref{LastPage}}
\renewcommand{\headheight}{24pt}
\renewcommand{\footrulewidth}{0.4pt}

\usepackage{lipsum}% provides filler text

\begin{document}
\name{ Joe Laroo }
\signature{ Joe Laroo }
\begin{letter}{ To-Address }
\renewcommand{\today}{ February 16, 2009 }
\opening{ Opening }

\thispagestyle{fancy}% sets the current page style to 'fancy' -- must occur *after* \opening
\lipsum[1-10]% just dumps ten paragraphs of filler text

\closing{ Yours truly, }
\end{letter}
\end{document}

The \opening command sets the page style to firstpage or empty, so you have to use \thispagestyle after that command.

How do you configure HttpOnly cookies in tomcat / java webapps?

also it should be noted that turning on HttpOnly will break applets that require stateful access back to the jvm.

the Applet http requests will not use the jsessionid cookie and may get assigned to a different tomcat.

Vim autocomplete for Python

I tried pydiction (didn't work for me) and the normal omnicompletion (too limited). I looked into Jedi as suggested but found it too complex to set up. I found python-mode, which in the end satisfied my needs. Thanks @klen.

Swipe ListView item From right to left show delete button

I had created a demo on my github which includes on swiping from right to left a delete button will appear and you can then delete your item from the ListView and update your ListView.

How to change the JDK for a Jenkins job?

There is a JDK dropdown in "job name" -> Configure in Jenkins web ui. It will list all JDKs available in Jenkins configuration.

Difference between shared objects (.so), static libraries (.a), and DLL's (.so)?

You are correct in that static files are copied to the application at link-time, and that shared files are just verified at link time and loaded at runtime.

The dlopen call is not only for shared objects, if the application wishes to do so at runtime on its behalf, otherwise the shared objects are loaded automatically when the application starts. DLLS and .so are the same thing. the dlopen exists to add even more fine-grained dynamic loading abilities for processes. You dont have to use dlopen yourself to open/use the DLLs, that happens too at application startup.

Can I use conditional statements with EJS templates (in JMVC)?

For others that stumble on this, you can also use ejs params/props in conditional statements:

recipes.js File:

app.get("/recipes", function(req, res) {
    res.render("recipes.ejs", {
        recipes: recipes
    });
});

recipes.ejs File:

<%if (recipes.length > 0) { %>
// Do something with more than 1 recipe
<% } %>

How to send an object from one Android Activity to another using Intents?

The simplest would be to just use the following where the item is a string:

intent.putextra("selected_item",item)

For receiving:

String name = data.getStringExtra("selected_item");

How to list all users in a Linux group?

Use Python to list groupmembers:

python -c "import grp; print grp.getgrnam('GROUP_NAME')[3]"

See https://docs.python.org/2/library/grp.html

iOS start Background Thread

Swift 2.x answer:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
        self.getResultSetFromDB(docids)
    }

Get value from SimpleXMLElement Object

You have to cast simpleXML Object to a string.

$value = (string) $xml->code[0]->lat;

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How do I check if the user is pressing a key?

Try this:

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JFrame;
import javax.swing.JTextField;

public class Main {

    public static void main(String[] argv) throws Exception {

    JTextField textField = new JTextField();

    textField.addKeyListener(new Keychecker());

    JFrame jframe = new JFrame();

    jframe.add(textField);

    jframe.setSize(400, 350);

    jframe.setVisible(true);

}

class Keychecker extends KeyAdapter {

    @Override
    public void keyPressed(KeyEvent event) {

        char ch = event.getKeyChar();

        System.out.println(event.getKeyChar());

    }

}

Installing PDO driver on MySQL Linux server

  1. PDO stands for PHP Data Object.
  2. PDO_MYSQL is the driver that will implement the interface between the dataobject(database) and the user input (a layer under the user interface called "code behind") accessing your data object, the MySQL database.

The purpose of using this is to implement an additional layer of security between the user interface and the database. By using this layer, data can be normalized before being inserted into your data structure. (Capitals are Capitals, no leading or trailing spaces, all dates at properly formed.)

But there are a few nuances to this which you might not be aware of.

First of all, up until now, you've probably written all your queries in something similar to the URL, and you pass the parameters using the URL itself. Using the PDO, all of this is done under the user interface level. User interface hands off the ball to the PDO which carries it down field and plants it into the database for a 7-point TOUCHDOWN.. he gets seven points, because he got it there and did so much more securely than passing information through the URL.

You can also harden your site to SQL injection by using a data-layer. By using this intermediary layer that is the ONLY 'player' who talks to the database itself, I'm sure you can see how this could be much more secure. Interface to datalayer to database, datalayer to database to datalayer to interface.

And:

By implementing best practices while writing your code you will be much happier with the outcome.

Additional sources:

Re: MySQL Functions in the url php dot net/manual/en/ref dot pdo-mysql dot php

Re: three-tier architecture - adding security to your applications https://blog.42.nl/articles/introducing-a-security-layer-in-your-application-architecture/

Re: Object Oriented Design using UML If you really want to learn more about this, this is the best book on the market, Grady Booch was the father of UML http://dl.acm.org/citation.cfm?id=291167&CFID=241218549&CFTOKEN=82813028

Or check with bitmonkey. There's a group there I'm sure you could learn a lot with.

>

If we knew what the terminology really meant we wouldn't need to learn anything.

>

How to replicate vector in c?

https://github.com/jakubgorny47/baku-code/tree/master/c_vector

Here's my implementation. It's basicaly a struct containing pointer to the data, size (in elements), overall allocated space and a size of the type that's being stored in vector to allow use of void pointer.

Convert a PHP script into a stand-alone windows executable

Peachpie

http://www.peachpie.io

https://github.com/iolevel/peachpie

Peachpie is PHP 7 compiler based on Roslyn by Microsoft and drawing from popular Phalanger. It allows PHP to be executed within the .NET/.NETCore by compiling the PHP code to pure MSIL.

Phalanger

http://v4.php-compiler.net/

http://wiki.php-compiler.net/Phalanger_Wiki

https://github.com/devsense/phalanger

Phalanger is a project which was started at Charles University in Prague and was supported by Microsoft. It compiles source code written in the PHP scripting language into CIL (Common Intermediate Language) byte-code. It handles the beginning of a compiling process which is completed by the JIT compiler component of the .NET Framework. It does not address native code generation nor optimization. Its purpose is to compile PHP scripts into .NET assemblies, logical units containing CIL code and meta-data.

Bambalam

https://github.com/xZero707/Bamcompile/

Bambalam PHP EXE Compiler/Embedder is a free command line tool to convert PHP applications to standalone Windows .exe applications. The exe files produced are totally standalone, no need for php dlls etc. The php code is encoded using the Turck MMCache Encode library so it's a perfect solution if you want to distribute your application while protecting your source code. The converter is also suitable for producing .exe files for windowed PHP applications (created using for example the WinBinder library). It's also good for making stand-alone PHP Socket servers/clients (using the php_sockets.dll extension). It's NOT really a compiler in the sense that it doesn't produce native machine code from PHP sources, but it works!

ZZEE PHPExe

http://www.zzee.com/phpexe/

ZZEE PHPExe compiles PHP, HTML, Javascript, Flash and other web files into Windows GUI exes. You can rapidly develop Windows GUI applications by employing the familiar PHP web paradigm. You can use the same code for online and Windows applications with little or no modification. It is a Commercial product.

phc-win

http://wiki.swiftlytilting.com/Phc-win

The PHP extension bcompiler is used to compile PHP script code into PHP bytecode. This bytecode can be included just like any php file as long as the bcompiler extension is loaded. Once all the bytecode files have been created, a modified Embeder is used to pack all of the project files into the program exe.

Requires

  • php5ts.dll
  • php_win32std.dll
  • php_bcompiler.dll
  • php-embed.ini

ExeOutput

http://www.exeoutput.com/

Commercial

WinBinder

http://winbinder.org/

WinBinder is an open source extension to PHP, the script programming language. It allows PHP programmers to easily build native Windows applications, producing quick and rewarding results with minimum effort. Even short scripts with a few dozen lines can generate a useful program, thanks to the power and flexibility of PHP.

PHPDesktop

https://github.com/cztomczak/phpdesktop

PHP Desktop is an open source project founded by Czarek Tomczak in 2012 to provide a way for developing native desktop applications using web technologies such as PHP, HTML5, JavaScript & SQLite. This project is more than just a PHP to EXE compiler, it embeds a web-browser (Internet Explorer or Chrome embedded), a Mongoose web-server and a PHP interpreter. The development workflow you are used to remains the same, the step of turning an existing website into a desktop application is basically a matter of copying it to "www/" directory. Using SQLite database is optional, you could embed mysql/postgresql database in application's installer.

PHP Nightrain

https://github.com/kjellberg/nightrain

Using PHP Nightrain you will be able to deploy and run HTML, CSS, JavaScript and PHP web applications as a native desktop application on Windows, Mac and the Linux operating systems. Popular PHP Frameworks (e.g. CakePHP, Laravel, Drupal, etc…) are well supported!

phc-win "fork"

https://github.com/RDashINC/phc-win

A more-or-less forked version of phc-win, it uses the same techniques as phc-win but supports almost all modern PHP versions. (5.3, 5.4, 5.5, 5.6, etc) It also can use Enigma VB to combine the php5ts.dll with your exe, aswell as UPX compress it. Lastly, it has win32std and winbinder compilied statically into PHP.

EDIT

Another option is to use

http://www.appcelerator.com/products/titanium-cross-platform-application-development/

an online compiler that can build executables for a number of different platforms, from a number of different languages including PHP

TideSDK

http://www.tidesdk.org/

TideSDK is actually the renamed Titanium Desktop project. Titanium remained focused on mobile, and abandoned the desktop version, which was taken over by some people who have open sourced it and dubbed it TideSDK.

Generally, TideSDK uses HTML, CSS and JS to render applications, but it supports scripted languages like PHP, as a plug-in module, as well as other scripting languages like Python and Ruby.

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

Why doesn't file_get_contents work?

The error may be that you need to change the permission of folder and file which you are going to access. If like GoDaddy service you can access the file and change the permission or by ssh use the command like:

sudo chmod 777 file.jpeg

and then you can access if the above mentioned problems are not your case.

Setting the Textbox read only property to true using JavaScript

You can try

document.getElementById("textboxid").readOnly = true;

Failed to load resource: the server responded with a status of 404 (Not Found)

I have added app.UseStaticFiles(); this code in my startup.cs than it is fixed

Get selected element's outer HTML

If the scenario is appending a new row dynamically, you can use this:

var row = $(".myRow").last().clone();
$(".myRow").last().after(row);

.myrow is the classname of the <tr>. It makes a copy of the last row and inserts that as a new last row. This also works in IE7, while the [0].outerHTML method does not allow assignments in ie7

Best approach to remove time part of datetime in SQL Server

In SQL Server 2008, you can use:

CONVERT(DATE, getdate(), 101)

How can I open a URL in Android's web browser from my application?

Simple Answer

You can see the official sample from Android Developer.

/**
 * Open a web page of a specified URL
 *
 * @param url URL to open
 */
public void openWebPage(String url) {
    Uri webpage = Uri.parse(url);
    Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
    if (intent.resolveActivity(getPackageManager()) != null) {
        startActivity(intent);
    }
}

How it works

Please have a look at the constructor of Intent:

public Intent (String action, Uri uri)

You can pass android.net.Uri instance to the 2nd parameter, and a new Intent is created based on the given data url.

And then, simply call startActivity(Intent intent) to start a new Activity, which is bundled with the Intent with the given URL.

Do I need the if check statement?

Yes. The docs says:

If there are no apps on the device that can receive the implicit intent, your app will crash when it calls startActivity(). To first verify that an app exists to receive the intent, call resolveActivity() on your Intent object. If the result is non-null, there is at least one app that can handle the intent and it's safe to call startActivity(). If the result is null, you should not use the intent and, if possible, you should disable the feature that invokes the intent.

Bonus

You can write in one line when creating the Intent instance like below:

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));

Get records with max value for each group of grouped SQL results

with CTE as 
(select Person, 
[Group], Age, RN= Row_Number() 
over(partition by [Group] 
order by Age desc) 
from yourtable)`


`select Person, Age from CTE where RN = 1`

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

Ok, finally got it.

Change this line in %windir%\System32\inetsrv\Config\ApplicationHost.config

<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />

To

<add name="ServiceModel" type="System.ServiceModel.Activation.HttpModule, System.ServiceModel, Version=3.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler,runtimeVersionv2.0" />

If this is not enough

Add this following line to the Web.config

<system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Just follow these steps:

1) Install eclipse
2) Import Apache to eclipse
3) Install mysql
4) Download mysqlconnector/J
5) Unzip the zipped file navigate through it until you get the bin file in it. Then place all files that are present in the folder containing bin to C:\Program Files\mysql\mysql server5.1/ then give the same path as the address while defining the driver in eclipse.

That's all very easy guys.

ASP.NET MVC Dropdown List From SelectList

Just try this in razor

@{
    var selectList = new SelectList(
        new List<SelectListItem>
        {
            new SelectListItem {Text = "Google", Value = "Google"},
            new SelectListItem {Text = "Other", Value = "Other"},
        }, "Value", "Text");
}

and then

@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })

or

@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })

SQL Server - In clause with a declared variable

Try this:

CREATE PROCEDURE MyProc @excludedlist integer_list_tbltype READONLY AS
  SELECT * FROM A WHERE ID NOT IN (@excludedlist)

And then call it like this:

DECLARE @ExcludedList integer_list_tbltype
INSERT @ExcludedList(n) VALUES(3, 4, 22)
exec MyProc @ExcludedList

How to create virtual column using MySQL SELECT?

Your syntax would create an alias for a as b, but it wouldn't have scope beyond the results of the statement. It sounds like you may want to create a VIEW

creating a random number using MYSQL

As RAND produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)

So to produce the range you need:

SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

Maven: How to rename the war file for the project?

You can follow the below step to modify the .war file name if you are using maven project.

Open pom.xml file of your maven project and go to the tag <build></build>,

  1. In that give your desired name between this tag : <finalName></finalName>.

    ex. : <finalName>krutik</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/

  2. If you want to access the url with slash '/' then you will have to specify then name as below:

    e.x. : <finalName>krutik#maheta</finalName>

    After deploying this .war you will be able to access url with:
    http://localhost:8080/krutik/maheta

How do I convert from int to String?

The other way I am aware of is from the Integer class:

Integer.toString(int n);
Integer.toString(int n, int radix);

A concrete example (though I wouldn't think you need any):

String five = Integer.toString(5); // returns "5"

It also works for other primitive types, for instance Double.toString.

See here for more details.

Set colspan dynamically with jquery

Setting colspan="0" is support only in firefox.

In other browsers we can get around it with:

// Auto calculate table colspan if set to 0
var colCount = 0;
$("td[colspan='0']").each(function(){
    colCount = 0;
    $(this).parents("table").find('tr').eq(0).children().each(function(){
        if ($(this).attr('colspan')){
            colCount += +$(this).attr('colspan');
        } else {
            colCount++;
        }
    });
$(this).attr("colspan", colCount);
});

http://tinker.io/3d642/4

How to make a floated div 100% height of its parent?

A similar case when you need several child elements have the same height can be solved with flexbox:

https://css-tricks.com/using-flexbox/

Set display: flex; for parent and flex: 1; for child elements, they all will have the same height.

How do I vertically center an H1 in a div?

I've had success putting text within span tags and then setting vertical-align: middle on that span. Don't know how cross-browser compliant this is though, I've only tested it in webkit browsers.

How to retrieve records for last 30 minutes in MS SQL?

Have a look at using DATEADD

something like

SELECT DATEADD(minute, -30, GETDATE())

How to check if string input is a number?

Here is the simplest solution:

a= input("Choose the option\n")

if(int(a)):
    print (a);
else:
    print("Try Again")

Why not inherit from List<T>?

Does allowing people to say

myTeam.subList(3, 5);

make any sense at all? If not then it shouldn't be a List.

get unique machine id

Maybe the easiest way is. Get the DeviceId Nuget package

And use it like

string deviceId = new DeviceIdBuilder()
.AddMachineName()
.AddMacAddress()
.AddProcessorId()
.AddMotherboardSerialNumber()
.ToString();

You can personalize the info used to generate the ID

Github Project

How to populate HTML dropdown list with values from database

I'd suggest following a few debugging steps.

First run the query directly against the DB. Confirm it is bringing results back. Even with something as simple as this you can find you've made a mistake, or the table is empty, or somesuch oddity.

If the above is ok, then try looping and echoing out the contents of $row just directly into the HTML to see what you've getting back in the mysql_query - see if it matches what you got directly in the DB.

If your data is output onto the page, then look at what's going wrong in your HTML formatting.

However, if nothing is output from $row, then figure out why the mysql_query isn't working e.g. does the user have permission to query that DB, do you have an open DB connection, can the webserver connect to the DB etc [something on these lines can often be a gotcha]

Changing your query slightly to

$sql = mysql_query("SELECT username FROM users") or die(mysql_error());  

may help to highlight any errors: php manual

How to enable Logger.debug() in Log4j

Here's a quick one-line hack that I occasionally use to temporarily turn on log4j debug logging in a JUnit test:

Logger.getRootLogger().setLevel(Level.DEBUG);

or if you want to avoid adding imports:

org.apache.log4j.Logger.getRootLogger().setLevel(
      org.apache.log4j.Level.DEBUG);

Note: this hack doesn't work in log4j2 because setLevel has been removed from the API, and there doesn't appear to be equivalent functionality.

Converting between java.time.LocalDateTime and java.util.Date

I think below approach will solve the conversion without taking time-zone into consideration. Please comment if it has any pitfalls.

    LocalDateTime datetime //input
    public static final DateTimeFormatter yyyyMMddHHmmss_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    String formatDateTime = datetime.format(yyyyMMddHHmmss_DATE_FORMAT);
    Date outputDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(formatDateTime); //output

How to determine the version of android SDK installed in computer?

In the case of Linux, You get the version of Android SDK using sdkmanager.

your_path/android-sdk/tools/bin/sdkmanager --version

in my case

/var/lib/jenkins/android-sdk/tools/bin/sdkmanager --versionenter image description here

How can I convert an HTML element to a canvas element?

The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.

What is the significance of #pragma marks? Why do we need #pragma marks?

When we have a big/lengthy class say more than couple 100 lines of code we can't see everything on Monitor screen, hence we can't see overview (also called document items) of our class. Sometime we want to see overview of our class; its all methods, constants, properties etc at a glance. You can press Ctrl+6 in XCode to see overview of your class. You'll get a pop-up kind of Window aka Jump Bar.

By default, this jump bar doesn't have any buckets/sections. It's just one long list. (Though we can just start typing when jump Bar appears and it will search among jump bar items). Here comes the need of pragma mark

If you want to create sections in your Jump Bar then you can use pragma marks with relevant description. Now refer snapshot attached in question. There 'View lifeCycle' and 'A section dedicated ..' are sections created by pragma marks

When to use EntityManager.find() vs EntityManager.getReference() with JPA

I disagree with the selected answer, and as davidxxx correctly pointed out, getReference does not provide such behaviour of dynamic updations without select. I asked a question concerning the validity of this answer, see here - cannot update without issuing select on using setter after getReference() of hibernate JPA.

I quite honestly haven't seen anybody who's actually used that functionality. ANYWHERE. And i don't understand why it's so upvoted.

Now first of all, no matter what you call on a hibernate proxy object, a setter or a getter, an SQL is fired and the object is loaded.

But then i thought, so what if JPA getReference() proxy doesn't provide that functionality. I can just write my own proxy.

Now, we can all argue that selects on primary keys are as fast as a query can get and it's not really something to go to great lengths to avoid. But for those of us who can't handle it due to one reason or another, below is an implementation of such a proxy. But before i you see the implementation, see it's usage and how simple it is to use.

USAGE

Order example = ProxyHandler.getReference(Order.class, 3);
example.setType("ABCD");
example.setCost(10);
PersistenceService.save(example);

And this would fire the following query -

UPDATE Order SET type = 'ABCD' and cost = 10 WHERE id = 3;

and even if you want to insert, you can still do PersistenceService.save(new Order("a", 2)); and it would fire an insert as it should.

IMPLEMENTATION

Add this to your pom.xml -

<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>3.2.10</version>
</dependency>

Make this class to create dynamic proxy -

@SuppressWarnings("unchecked")
public class ProxyHandler {

public static <T> T getReference(Class<T> classType, Object id) {
    if (!classType.isAnnotationPresent(Entity.class)) {
        throw new ProxyInstantiationException("This is not an entity!");
    }

    try {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(classType);
        enhancer.setCallback(new ProxyMethodInterceptor(classType, id));
        enhancer.setInterfaces((new Class<?>[]{EnhancedProxy.class}));
        return (T) enhancer.create();
    } catch (Exception e) {
        throw new ProxyInstantiationException("Error creating proxy, cause :" + e.getCause());
    }
}

Make an interface with all the methods -

public interface EnhancedProxy {
    public String getJPQLUpdate();
    public HashMap<String, Object> getModifiedFields();
}

Now, make an interceptor which will allow you to implement these methods on your proxy -

import com.anil.app.exception.ProxyInstantiationException;
import javafx.util.Pair;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import javax.persistence.Id;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
/**
* @author Anil Kumar
*/
public class ProxyMethodInterceptor implements MethodInterceptor, EnhancedProxy {

private Object target;
private Object proxy;
private Class classType;
private Pair<String, Object> primaryKey;
private static HashSet<String> enhancedMethods;

ProxyMethodInterceptor(Class classType, Object id) throws IllegalAccessException, InstantiationException {
    this.classType = classType;
    this.target = classType.newInstance();
    this.primaryKey = new Pair<>(getPrimaryKeyField().getName(), id);
}

static {
    enhancedMethods = new HashSet<>();
    for (Method method : EnhancedProxy.class.getDeclaredMethods()) {
        enhancedMethods.add(method.getName());
    }
}

@Override
public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
    //intercept enhanced methods
    if (enhancedMethods.contains(method.getName())) {
        this.proxy = obj;
        return method.invoke(this, args);
    }
    //else invoke super class method
    else
        return proxy.invokeSuper(obj, args);
}

@Override
public HashMap<String, Object> getModifiedFields() {
    HashMap<String, Object> modifiedFields = new HashMap<>();
    try {
        for (Field field : classType.getDeclaredFields()) {

            field.setAccessible(true);

            Object initialValue = field.get(target);
            Object finalValue = field.get(proxy);

            //put if modified
            if (!Objects.equals(initialValue, finalValue)) {
                modifiedFields.put(field.getName(), finalValue);
            }
        }
    } catch (Exception e) {
        return null;
    }
    return modifiedFields;
}

@Override
public String getJPQLUpdate() {
    HashMap<String, Object> modifiedFields = getModifiedFields();
    if (modifiedFields == null || modifiedFields.isEmpty()) {
        return null;
    }
    StringBuilder fieldsToSet = new StringBuilder();
    for (String field : modifiedFields.keySet()) {
        fieldsToSet.append(field).append(" = :").append(field).append(" and ");
    }
    fieldsToSet.setLength(fieldsToSet.length() - 4);
    return "UPDATE "
            + classType.getSimpleName()
            + " SET "
            + fieldsToSet
            + "WHERE "
            + primaryKey.getKey() + " = " + primaryKey.getValue();
}

private Field getPrimaryKeyField() throws ProxyInstantiationException {
    for (Field field : classType.getDeclaredFields()) {
        field.setAccessible(true);
        if (field.isAnnotationPresent(Id.class))
            return field;
    }
    throw new ProxyInstantiationException("Entity class doesn't have a primary key!");
}
}

And the exception class -

public class ProxyInstantiationException extends RuntimeException {
public ProxyInstantiationException(String message) {
    super(message);
}

A service to save using this proxy -

@Service
public class PersistenceService {

@PersistenceContext
private EntityManager em;

@Transactional
private void save(Object entity) {
    // update entity for proxies
    if (entity instanceof EnhancedProxy) {
        EnhancedProxy proxy = (EnhancedProxy) entity;
        Query updateQuery = em.createQuery(proxy.getJPQLUpdate());
        for (Entry<String, Object> entry : proxy.getModifiedFields().entrySet()) {
            updateQuery.setParameter(entry.getKey(), entry.getValue());
        }
        updateQuery.executeUpdate();
    // insert otherwise
    } else {
        em.persist(entity);
    }

}
}

What's wrong with using == to compare floats in Java?

As mentioned in other answers, doubles can have small deviations. And you could write your own method to compare them using an "acceptable" deviation. However ...

There is an apache class for comparing doubles: org.apache.commons.math3.util.Precision

It contains some interesting constants: SAFE_MIN and EPSILON, which are the maximum possible deviations of simple arithmetic operations.

It also provides the necessary methods to compare, equal or round doubles. (using ulps or absolute deviation)

How to call a function in shell Scripting?

The functions need to be defined before being used. There is no mechanism is sh to pre-declare functions, but a common technique is to do something like:

main() {
  case "$choice" in
    true)  process_install;;
    false) process_exit;;
  esac
}

process_install()
{
  commands...
  commands...
}

process_exit()
{
  commands...
  commands...
}

main()

Best way to implement keyboard shortcuts in a Windows Forms application?

From the main Form, you have to:

  • Be sure you set KeyPreview to true( TRUE by default)
  • Add MainForm_KeyDown(..) - by which you can set here any shortcuts you want.

Additionally,I have found this on google and I wanted to share this to those who are still searching for answers. (for global)

I think you have to be using user32.dll

protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    if (m.Msg == 0x0312)
    {
        /* Note that the three lines below are not needed if you only want to register one hotkey.
         * The below lines are useful in case you want to register multiple keys, which you can use a switch with the id as argument, or if you want to know which key/modifier was pressed for some particular reason. */

        Keys key = (Keys)(((int)m.LParam >> 16) & 0xFFFF);                  // The key of the hotkey that was pressed.
        KeyModifier modifier = (KeyModifier)((int)m.LParam & 0xFFFF);       // The modifier of the hotkey that was pressed.
        int id = m.WParam.ToInt32();                                        // The id of the hotkey that was pressed.


        MessageBox.Show("Hotkey has been pressed!");
        // do something
    }
}

Further read this http://www.fluxbytes.com/csharp/how-to-register-a-global-hotkey-for-your-application-in-c/

How do I find the PublicKeyToken for a particular dll?

As @CRice said you can use the below method to get a list of dependent assembly with publicKeyToken

public static int DependencyInfo(string args) 
{
    Console.WriteLine(Assembly.LoadFile(args).FullName);
    Console.WriteLine(Assembly.LoadFile(args).GetCustomAttributes(typeof(System.Runtime.Versioning.TargetFrameworkAttribute), false).SingleOrDefault());
    try {
        var assemblies = Assembly.LoadFile(args).GetReferencedAssemblies(); 

        if (assemblies.GetLength(0) > 0)
        {
            foreach (var assembly in assemblies)
            {
                Console.WriteLine(" - " + assembly.FullName + ", ProcessorArchitecture=" + assembly.ProcessorArchitecture);             
            }
            return 0;
        }
    }
    catch(Exception e) {
        Console.WriteLine("An exception occurred: {0}", e.Message);
        return 1;
    } 
    finally{}

    return 1;
}

i generally use it as a LinqPad script you can call it as

DependencyInfo("@c:\MyAssembly.dll"); from the code

How to enable loglevel debug on Apache2 server

Edit: note that this answer is 3+ years old. For newer versions of apache, please see the answer by sp00n. Leaving this answer for users of older versions of apache.

For older version apache:

For debugging mod_rewrite issues, you'll want to use RewriteLogLevel and RewriteLog:

RewriteLogLevel 3
RewriteLog "/usr/local/var/apache/logs/rewrite.log"

What is EOF in the C programming language?

#include <stdio.h>

int main() {
    int c;
    while((c = getchar()) != EOF) { //precedence of != is greater than =, so use braces
        printf("%d\n", c);
    }
    printf("%d - at EOF\n", c);
}

I think this is right way to check value of EOF. And I checked the output.

For INPUT: abc and Enter I got OUTPUT: 97 98 99 10. ( the ASCII values)

For INPUT Ctrl-D I got OUTPUT: -1 - at EOF. So I think -1 is the value for EOF.

Try other inputs instead of Ctrl-D, like Ctrl-Z. I think it varies from compiler to compiler.

How can I create a simple message box in Python?

In Windows, you can use ctypes with user32 library:

from ctypes import c_int, WINFUNCTYPE, windll
from ctypes.wintypes import HWND, LPCSTR, UINT
prototype = WINFUNCTYPE(c_int, HWND, LPCSTR, LPCSTR, UINT)
paramflags = (1, "hwnd", 0), (1, "text", "Hi"), (1, "caption", None), (1, "flags", 0)
MessageBox = prototype(("MessageBoxA", windll.user32), paramflags)

MessageBox()
MessageBox(text="Spam, spam, spam")
MessageBox(flags=2, text="foo bar")

HTTP Error 500.22 - Internal Server Error (An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode.)

Set Application pool to classic .NET appool and make sure that Classic .Net apppool working on Classic managed piple line .

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

I'm sure the original poster's issue has long since been resolved. However, I had this same issue, so I thought I'd explain what was causing this problem for me.

I was doing a union query with two tables -- 'foo' and 'foo_bar'. However, in my SQL statement, I had a typo: 'foo.bar'

So, instead of telling me that the 'foo.bar' table doesn't exist, the error message indicates that the command was denied -- as though I don't have permissions.

Hope this helps someone.

Open Cygwin at a specific folder

@echo off
C:
SET mypath=%~dp0
c:\cygwin\bin\bash -c "cd '%mypath%'; export CHERE_INVOKING=1; exec /bin/bash --login -i"

Copy above commands in a text file and save it as .bat in any of "your folder of interest". It should open cygwin in "your folder of interest".

CodeIgniter htaccess and URL rewrite issues

Open the application/config/config.php file and make the changes given below,

  1. set your base url by replacing the value of $config['base_url'], as $config['base_url'] = 'http://localhost/YOUR_PROJECT_DIR_NAME';

  2. make the $config['index_page'] configuration to empty as $config['index_page'] = '';

Create new .htaccess file in project root folder and use the given settings, RewriteEngine on RewriteCond $1 !^(index\.php|resources|assets|images|js|css|uploads|favicon.png|favicon.ico|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php/$1 [L,QSA]

Restart the server, open the project and you'll be good to go.

invalid multibyte char (US-ASCII) with Rails and Ruby 1.9

That worked for me:

$ export LC_ALL=en_US.UTF-8
$ export LANG=en_US.UTF-8

Oracle SQL query for Date format

to_date() returns a date at 00:00:00, so you need to "remove" the minutes from the date you are comparing to:

select * 
from table
where trunc(es_date) = TO_DATE('27-APR-12','dd-MON-yy')

You probably want to create an index on trunc(es_date) if that is something you are doing on a regular basis.

The literal '27-APR-12' can fail very easily if the default date format is changed to anything different. So make sure you you always use to_date() with a proper format mask (or an ANSI literal: date '2012-04-27')

Although you did right in using to_date() and not relying on implict data type conversion, your usage of to_date() still has a subtle pitfall because of the format 'dd-MON-yy'.

With a different language setting this might easily fail e.g. TO_DATE('27-MAY-12','dd-MON-yy') when NLS_LANG is set to german. Avoid anything in the format that might be different in a different language. Using a four digit year and only numbers e.g. 'dd-mm-yyyy' or 'yyyy-mm-dd'

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.

Edit:

Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/

Get attribute name value of <input>

Give your input an ID and use the attr method:

var name = $("#id").attr("name");

What is the difference between IQueryable<T> and IEnumerable<T>?

First of all, IQueryable<T> extends the IEnumerable<T> interface, so anything you can do with a "plain" IEnumerable<T>, you can also do with an IQueryable<T>.

IEnumerable<T> just has a GetEnumerator() method that returns an Enumerator<T> for which you can call its MoveNext() method to iterate through a sequence of T.

What IQueryable<T> has that IEnumerable<T> doesn't are two properties in particular—one that points to a query provider (e.g., a LINQ to SQL provider) and another one pointing to a query expression representing the IQueryable<T> object as a runtime-traversable abstract syntax tree that can be understood by the given query provider (for the most part, you can't give a LINQ to SQL expression to a LINQ to Entities provider without an exception being thrown).

The expression can simply be a constant expression of the object itself or a more complex tree of a composed set of query operators and operands. The query provider's IQueryProvider.Execute() or IQueryProvider.CreateQuery() methods are called with an Expression passed to it, and then either a query result or another IQueryable is returned, respectively.

Extension mysqli is missing, phpmyadmin doesn't work

Checking the extension_dir is one of the thing you like to check from phpinfo().In my case it was extension_dir = "./" by default which was wrong. Change it to extension_dir = './ext/' or where all your extension dlls are currently residing.

remove inner shadow of text input

here is a small snippet that might be cool to try out:

input {
border-radius: 10px;
border-color: violet;
border-style: solid;
}

note that: border-style removes the inner shadow.

_x000D_
_x000D_
input {_x000D_
    border-radius: 10px;_x000D_
    border-color: violet;_x000D_
    border-style: solid;_x000D_
  }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Convert Enumeration to a Set/List

When using guava (See doc) there is Iterators.forEnumeration. Given an Enumeration x you can do the following:

to get a immutable Set:

ImmutableSet.copyOf(Iterators.forEnumeration(x));

to get a immutable List:

ImmutableList.copyOf(Iterators.forEnumeration(x));

to get a hashSet:

Sets.newHashSet(Iterators.forEnumeration(x));

"echo -n" prints "-n"

I believe right now your output printing as below

~ echo -e "String1\nString2"
String1
String2

You can use xargs to get multiline stdout into same line.

 ~ echo -e "String1\nString2" | xargs
String1 String2

 ~

C library function to perform sort

try qsort in stdlib.h.

How to access your website through LAN in ASP.NET

I'm not sure how stuck you are:

You must have a web server (Windows comes with one called IIS, but it may not be installed)

  1. Make sure you actually have IIS installed! Try typing http://localhost/ in your browser and see what happens. If nothing happens it means that you may not have IIS installed. See Installing IIS
  2. Set up IIS How to set up your first IIS Web site
  3. You may even need to Install the .NET Framework (or your server will only serve static html pages, and not asp.net pages)

Installing your application

Once you have done that, you can more or less just copy your application to c:\wwwroot\inetpub\. Read Installing ASP.NET Applications (IIS 6.0) for more information

Accessing the web site from another machine

In theory, once you have a web server running, and the application installed, you only need the IP address of your web server to access the application.

To find your IP address try: Start -> Run -> type cmd (hit ENTER) -> type ipconfig (hit ENTER)

Once

  • you have the IP address AND
  • IIS running AND
  • the application is installed

you can access your website from another machine in your LAN by just typing in the IP Address of you web server and the correct path to your application.

If you put your application in a directory called NewApp, you will need to type something like http://your_ip_address/NewApp/default.aspx

Turn off your firewall

If you do have a firewall turn it off while you try connecting for the first time, you can sort that out later.

Simple way to transpose columns and rows in SQL?

There are several ways that you can transform this data. In your original post, you stated that PIVOT seems too complex for this scenario, but it can be applied very easily using both the UNPIVOT and PIVOT functions in SQL Server.

However, if you do not have access to those functions this can be replicated using UNION ALL to UNPIVOT and then an aggregate function with a CASE statement to PIVOT:

Create Table:

CREATE TABLE yourTable([color] varchar(5), [Paul] int, [John] int, [Tim] int, [Eric] int);

INSERT INTO yourTable
    ([color], [Paul], [John], [Tim], [Eric])
VALUES
    ('Red', 1, 5, 1, 3),
    ('Green', 8, 4, 3, 5),
    ('Blue', 2, 2, 9, 1);

Union All, Aggregate and CASE Version:

select name,
  sum(case when color = 'Red' then value else 0 end) Red,
  sum(case when color = 'Green' then value else 0 end) Green,
  sum(case when color = 'Blue' then value else 0 end) Blue
from
(
  select color, Paul value, 'Paul' name
  from yourTable
  union all
  select color, John value, 'John' name
  from yourTable
  union all
  select color, Tim value, 'Tim' name
  from yourTable
  union all
  select color, Eric value, 'Eric' name
  from yourTable
) src
group by name

See SQL Fiddle with Demo

The UNION ALL performs the UNPIVOT of the data by transforming the columns Paul, John, Tim, Eric into separate rows. Then you apply the aggregate function sum() with the case statement to get the new columns for each color.

Unpivot and Pivot Static Version:

Both the UNPIVOT and PIVOT functions in SQL server make this transformation much easier. If you know all of the values that you want to transform, you can hard-code them into a static version to get the result:

select name, [Red], [Green], [Blue]
from
(
  select color, name, value
  from yourtable
  unpivot
  (
    value for name in (Paul, John, Tim, Eric)
  ) unpiv
) src
pivot
(
  sum(value)
  for color in ([Red], [Green], [Blue])
) piv

See SQL Fiddle with Demo

The inner query with the UNPIVOT performs the same function as the UNION ALL. It takes the list of columns and turns it into rows, the PIVOT then performs the final transformation into columns.

Dynamic Pivot Version:

If you have an unknown number of columns (Paul, John, Tim, Eric in your example) and then an unknown number of colors to transform you can use dynamic sql to generate the list to UNPIVOT and then PIVOT:

DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
               C.name <> 'color'
         for xml path('')), 1, 1, '')

select @colsPivot = STUFF((SELECT  ',' 
                      + quotename(color)
                    from yourtable t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select name, '+@colsPivot+'
      from
      (
        select color, name, value
        from yourtable
        unpivot
        (
          value for name in ('+@colsUnpivot+')
        ) unpiv
      ) src
      pivot
      (
        sum(value)
        for color in ('+@colsPivot+')
      ) piv'

exec(@query)

See SQL Fiddle with Demo

The dynamic version queries both yourtable and then the sys.columns table to generate the list of items to UNPIVOT and PIVOT. This is then added to a query string to be executed. The plus of the dynamic version is if you have a changing list of colors and/or names this will generate the list at run-time.

All three queries will produce the same result:

| NAME | RED | GREEN | BLUE |
-----------------------------
| Eric |   3 |     5 |    1 |
| John |   5 |     4 |    2 |
| Paul |   1 |     8 |    2 |
|  Tim |   1 |     3 |    9 |

How to install iPhone application in iPhone Simulator

Enter the following in the terminal:

$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path/to/your/file/projectname.app/projectname

Code to loop through all records in MS Access

In "References", import DAO 3.6 object reference.

private sub showTableData

dim db as dao.database
dim rs as dao.recordset

set db = currentDb
set rs = db.OpenRecordSet("myTable") 'myTable is a MS-Access table created previously

'populate the table
rs.movelast
rs.movefirst

do while not rs.EOF
   debug.print(rs!myField) 'myField is a field name in table myTable
   rs.movenext             'press Ctrl+G to see debuG window beneath
loop

msgbox("End of Table")

end sub

You can interate data objects like queries and filtered tables in different ways:

Trhough query:

private sub showQueryData

dim db as dao.database
dim rs as dao.recordset
dim sqlStr as string

sqlStr = "SELECT * FROM customers as c WHERE c.country='Brazil'"

set db = currentDb
set rs = db.openRecordset(sqlStr)

rs.movefirst

do while not rs.EOF
  debug.print("cust ID: " & rs!id & " cust name: " & rs!name)
  rs.movenext
loop

msgbox("End of customers from Brazil")

end sub

You should also look for "Filter" property of the recordset object to filter only the desired records and then interact with them in the same way (see VB6 Help in MS-Access code window), or create a "QueryDef" object to run a query and use it as a recordset too (a little bit more tricky). Tell me if you want another aproach.

I hope I've helped.

CSS text-transform capitalize on all caps

I know this is a late response but if you want to compare the performance of various solutions I have a jsPerf that I created.

Regex solutions are the fastest for sure.

Here is the jsPerf: https://jsperf.com/capitalize-jwaz

There are 2 regex solutions.

The first one uses/\b[a-z]/g. Word boundary will capital words such as non-disclosure to Non-Disclosure.

If you only want to capitalize letters that are preceded by a space then use the second regex

/(^[a-z]|\s[a-z])/g

Convert Mongoose docs to json

I found out I made a mistake. There's no need to call toObject() or toJSON() at all. The __proto__ in the question came from jquery, not mongoose. Here's my test:

UserModel.find({}, function (err, users) {
    console.log(users.save);    // { [Function] numAsyncPres: 0 }
    var json = JSON.stringify(users);
    users = users.map(function (user) {
        return user.toObject();
    }
    console.log(user.save);    // undefined
    console.log(json == JSON.stringify(users));    // true
}

doc.toObject() removes doc.prototype from a doc. But it makes no difference in JSON.stringify(doc). And it's not needed in this case.

If Else in LINQ

 var result = _context.Employees
                .Where(x => !x.IsDeleted)
                .Where(x => x.ClientId > (clientId > 0 ? clientId - 1 : -1))
                .Where(x => x.ClientId < (clientId > 0 ? clientId + 1 : 1000))
                .Where(x => x.ContractorFlag == employeeFlag);
            return result;

If clientId = 0 we want ALL employees,. but for any clientId between 1 and 999 we want only clients with that ID. I was having issues with seperate LINQ statements not being the same (Deleted/Clients filters need to be on all queries), so by add these two lines it works (all be it until we have 999+ clients - which would be a happy re-factor day!!

how to set active class to nav menu from twitter bootstrap

I had the same problem... solved it by adding the code shown below to the Into "$(document).ready" part of my "functions.js" file which is included in every page footer. It's pretty simple. It gets the full current URL of the displayed page and compares it to the full anchor href URL. If they are the same, set anchor (li) parent as active. And do this only if anchor href value is not "#", then the bootstrap will solve it.

$(document).ready(function () {         
    $(function(){
        var current_page_URL = location.href;

        $( "a" ).each(function() {

            if ($(this).attr("href") !== "#") {

                var target_URL = $(this).prop("href");

                    if (target_URL == current_page_URL) {
                        $('nav a').parents('li, ul').removeClass('active');
                        $(this).parent('li').addClass('active');

                        return false;
                    }
            }
        }); }); });

How to clear the entire array?

[your Array name] = Empty

Then the array will be without content and can be filled again.

'this' is undefined in JavaScript class methods

This question has been answered, but maybe this might someone else coming here.

I also had an issue where this is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:

import MyClass from "./myClass"

// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined

// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK

How to get the real and total length of char * (char array)?

You can make a back-tracker character, ex, you could append any special character say "%" to the end of your string and then check the occurrence of that character.
But this is a very risky way as that character can be in other places also in the char*

char* stringVar = new char[4] ; 
stringVar[0] = 'H' ; 
stringVar[1] = 'E' ; 
stringVar[2] = '$' ; // back-tracker character.
int i = 0 ;
while(1)
{
   if (stringVar[i] == '$')
     break ; 
   i++ ; 
}
//  i is the length of the string.
// you need to make sure, that there is no other $ in the char* 

Otherwise define a custom structure to keep track of length and allocate memory.

Intellij idea subversion checkout error: `Cannot run program "svn"`

Check my solution, It will work.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) Download link ( https://www.visualsvn.com/downloads/ )

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the pic:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

Passing Objects By Reference or Value in C#

In Pass By Reference You only add "ref" in the function parameters and one more thing you should be declaring function "static" because of main is static(#public void main(String[] args))!

namespace preparation
{
  public  class Program
    {
      public static void swap(ref int lhs,ref int rhs)
      {
          int temp = lhs;
          lhs = rhs;
          rhs = temp;
      }
          static void Main(string[] args)
        {
            int a = 10;
            int b = 80;

  Console.WriteLine("a is before sort " + a);
            Console.WriteLine("b is before sort " + b);
            swap(ref a, ref b);
            Console.WriteLine("");
            Console.WriteLine("a is after sort " + a);
            Console.WriteLine("b is after sort " + b);  
        }
    }
}

Sql Server string to date conversion

Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:

Declare @d datetime
select @d = getdate()

select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,12),12,'yymmdd'
union all
select @d,convert(varchar,@d,112),112,'yyyymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'

How can I convert a string to boolean in JavaScript?

another solution. jsFiddle

var toBoolean = function(value) {
    var strValue = String(value).toLowerCase();
    strValue = ((!isNaN(strValue) && strValue !== '0') &&
        strValue !== '' &&
        strValue !== 'null' &&
        strValue !== 'undefined') ? '1' : strValue;
    return strValue === 'true' || strValue === '1' ? true : false
};

test cases run in node

> toBoolean(true)
true
> toBoolean(false)
false
> toBoolean(undefined)
false
> toBoolean(null)
false
> toBoolean('true')
true
> toBoolean('True')
true
> toBoolean('False')
false
> toBoolean('false')
false
> toBoolean('0')
false
> toBoolean('1')
true
> toBoolean('100')
true
> 

Bash command to sum a column of numbers

If you have ruby installed

cat FileWithColumnOfNumbers.txt | xargs ruby -e "puts ARGV.map(&:to_i).inject(&:+)"

How to use stringstream to separate comma separated strings

#include <iostream>
#include <sstream>

std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;

while(std::getline(ss, token, ',')) {
    std::cout << token << '\n';
}

abc
def
ghi

How do I convert between ISO-8859-1 and UTF-8 in Java?

Here is an easy way with String output (I created a method to do this):

public static String (String input){
    String output = "";
    try {
        /* From ISO-8859-1 to UTF-8 */
        output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
        /* From UTF-8 to ISO-8859-1 */
        output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return output;
}
// Example
input = "Música";
output = "Música";

Validating file types by regular expression

Your regexp seems to validate both the file name and the extension. Is that what you need? I'll assume it's just the extension and would use a regexp like this:

\.(jpg|gif|doc|pdf)$

And set the matching to be case insensitive.

What does `ValueError: cannot reindex from a duplicate axis` mean?

I wasted couple of hours on the same issue. In my case, I had to reset_index() of a dataframe before using apply function. Before merging, or looking up from another indexed dataset, you need to reset the index as 1 dataset can have only 1 Index.

Looping through a hash, or using an array in PowerShell

You can also do this without a variable

@{
  'foo' = 222
  'bar' = 333
  'baz' = 444
  'qux' = 555
} | % getEnumerator | % {
  $_.key
  $_.value
}

Filtering Table rows using Jquery

I chose @nrodic's answer (thanks, by the way), but it has several drawbacks:

1) If you have rows containing "cat", "dog", "mouse", "cat dog", "cat dog mouse" (each on separate row), then when you search explicitly for "cat dog mouse", you'll be displayed "cat", "dog", "mouse", "cat dog", "cat dog mouse" rows.

2) .toLowerCase() was not implemented, that is, when you enter lower case string, rows with matching upper case text will not be showed.

So I came up with a fork of @nrodic's code, where

var data = this.value; //plain text, not an array

and

jo.filter(function (i, v) {
    var $t = $(this);
    var stringsFromRowNodes = $t.children("td:nth-child(n)")
    .text().toLowerCase();
    var searchText = data.toLowerCase();
    if (stringsFromRowNodes.contains(searchText)) {
        return true;
        }
    return false;
})
//show the rows that match.
.show();

Here goes the full code: http://jsfiddle.net/jumasheff/081qyf3s/

React: how to update state.item[1] in state using setState?

As none of the above options was ideal to me I ended up using map:

this.setState({items: this.state.items.map((item,idx)=> idx!==1 ?item :{...item,name:'new_name'}) })

'ls' is not recognized as an internal or external command, operable program or batch file

We can use ls and many other Linux commands in Windows cmd. Just follow these steps.

Steps:

1) Install Git in your computer - https://git-scm.com/downloads.

2) After installing Git, go to the folder in which Git is installed. Mostly it will be in C drive and then Program Files Folder.

3) In Program Files folder, you will find the folder named Git, find the bin folder which is inside usr folder in the Git folder.

In my case, the location for bin folder was - C:\Program Files\Git\usr\bin

4) Add this location (C:\Program Files\Git\usr\bin) in path variable, in system environment variables.

5) You are done. Restart cmd and try to run ls and other Linux commands.

Create a new cmd.exe window from within another cmd.exe prompt

Here is the code you need:

start cmd.exe @cmd /k "Command"

R memory management / cannot allocate vector of size n Mb

I followed to the help page of memory.limit and found out that on my computer R by default can use up to ~ 1.5 GB of RAM and that the user can increase this limit. Using the following code,

>memory.limit()
[1] 1535.875
> memory.limit(size=1800)

helped me to solve my problem.

How to change the docker image installation directory?

On an AWS Ubuntu 16.04 Server I put the Docker images on a separate EBS, mounted on /home/ubuntu/kaggle/, under the docker dir

This snippet of my initialization script worked correctly

# where are the images initially stored?
sudo docker info | grep "Root Dir"
# ... not where I want them

# modify the configuration files to change to image location
# NOTE this generates an error
# WARNING: Usage of loopback devices is strongly discouraged for production use.
#          Use `--storage-opt dm.thinpooldev` to specify a custom block storage device.
# see https://stackoverflow.com/questions/31620825/
#     warning-of-usage-of-loopback-devices-is-strongly-discouraged-for-production-use

sudo sed -i   ' s@#DOCKER_OPTS=.*@DOCKER_OPTS="-g /home/ubuntu/kaggle/docker"@ '  /etc/default/docker

sudo chmod -R ugo+rw /lib/systemd/system/docker.service
sudo cp  /lib/systemd/system/docker.service /etc/systemd/system/
sudo chmod -R ugo+rw /etc/systemd/system/

sudo sed -i ' s@ExecStart.*@ExecStart=/usr/bin/dockerd $DOCKER_OPTS -H fd://@ '  /etc/systemd/system/docker.service
sudo sed -i '/ExecStart/a EnvironmentFile=-/etc/default/docker' /etc/systemd/system/docker.service
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo docker info | grep "Root Dir"
# now they're where I want them

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

Package name does not correspond to the file path - IntelliJ

I was just fighting with similar problem. My way to solve it was to set the root source file for Intellij module to match the original project root folder. Then i needed to mark some folders as Excluded in project navigation panel (the one that should not be used in new one project, for me it was part used under Android). That's all.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

The answer to many CSS formatting problems seems to be "add another <div>!"

So, in that spirit, have you tried adding a wrapper div to which the border/padding are applied and then putting the 100% width textarea inside of that? Something like (untested):

_x000D_
_x000D_
textarea_x000D_
{_x000D_
  width:100%;_x000D_
}_x000D_
.textwrapper_x000D_
{_x000D_
  border:1px solid #999999;_x000D_
  margin:5px 0;_x000D_
  padding:3px;_x000D_
}
_x000D_
<div style="display: block;" id="rulesformitem" class="formitem">_x000D_
  <label for="rules" id="ruleslabel">Rules:</label>_x000D_
  <div class="textwrapper"><textarea cols="2" rows="10" id="rules"/></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Correct file permissions for WordPress

Correct permissions for the file is 644 Correct permissions for the folder is 755

To change the permissions , use terminal and following commands.

find foldername -type d -exec chmod 755 {} \;
find foldername -type f -exec chmod 644 {} \;

755 for folders and 644 for files.

Getting the class name of an instance?

Have you tried the __name__ attribute of the class? ie type(x).__name__ will give you the name of the class, which I think is what you want.

>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'

If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:

x.__class__.__name__

How to center an unordered list?

From your post, I understand that you cannot set the width to your li.

How about this?

_x000D_
_x000D_
ul {
  border:2px solid red;
  display:inline-block;
}

li {
  display:inline;
  padding:0 30%; /* try adjusting the side % to give a feel of center aligned.*/
}
_x000D_
<ul>
    <li>Hello</li>
    <li>Hezkdhkfskdhfkllo</li>
    <li>Hello</li>
</ul>
_x000D_
_x000D_
_x000D_

Here's a demo. http://codepen.io/anon/pen/HhBwx

REST API error return good practices

I know this is extremely late to the party, but now, in year 2013, we have a few media types to cover error handling in a common distributed (RESTful) fashion. See "vnd.error", application/vnd.error+json (https://github.com/blongden/vnd.error) and "Problem Details for HTTP APIs", application/problem+json (https://tools.ietf.org/html/draft-nottingham-http-problem-05).

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

org.glassfish.jersey.servlet.ServletContainer.class

here remove .class

org.glassfish.jersey.servlet.ServletContainer now you wont get

convert streamed buffers to utf8-string

Single Buffer

If you have a single Buffer you can use its toString method that will convert all or part of the binary contents to a string using a specific encoding. It defaults to utf8 if you don't provide a parameter, but I've explicitly set the encoding in this example.

var req = http.request(reqOptions, function(res) {
    ...

    res.on('data', function(chunk) {
        var textChunk = chunk.toString('utf8');
        // process utf8 text chunk
    });
});

Streamed Buffers

If you have streamed buffers like in the question above where the first byte of a multi-byte UTF8-character may be contained in the first Buffer (chunk) and the second byte in the second Buffer then you should use a StringDecoder. :

var StringDecoder = require('string_decoder').StringDecoder;

var req = http.request(reqOptions, function(res) {
    ...
    var decoder = new StringDecoder('utf8');

    res.on('data', function(chunk) {
        var textChunk = decoder.write(chunk);
        // process utf8 text chunk
    });
});

This way bytes of incomplete characters are buffered by the StringDecoder until all required bytes were written to the decoder.

Default SQL Server Port

The default port 1433 is used when there is only one SQL Server named instance running on the computer.

When multiple SQL Server named instances are running, they run by default under a dynamic port (49152–65535). In this scenario, an application will connect to the SQL Server Browser service port (UDP 1434) to get the dynamic port and then connect to the dynamic port directly.

https://docs.microsoft.com/en-us/sql/sql-server/install/configure-the-windows-firewall-to-allow-sql-server-access

Changing every value in a hash in Ruby

After testing it with RSpec like this:

describe Hash do
  describe :map_values do
    it 'should map the values' do
      expect({:a => 2, :b => 3}.map_values { |x| x ** 2 }).to eq({:a => 4, :b => 9})
    end
  end
end

You could implement Hash#map_values as follows:

class Hash
  def map_values
    Hash[map { |k, v| [k, yield(v)] }]
  end
end

The function then can be used like this:

{:a=>'a' , :b=>'b'}.map_values { |v| "%#{v}%" }
# {:a=>"%a%", :b=>"%b%"}

How to find substring from string?

Example using std::string find method:

#include <iostream>
#include <string>

int main (){
    std::string str ("There are two needles in this haystack with needles.");
    std::string str2 ("needle");

    size_t found = str.find(str2);
    if(found!=std::string::npos){ 
        std::cout << "first 'needle' found at: " << found << '\n';
    }

    return 0;
}

Result:

first 'needle' found at: 14.

Reset select2 value and show placeholder

In order to reset the values and the placeholder I just reinitiate the select2 element:

$( "#select2element" ).select2({
    placeholder: '---placeholder---',
    allowClear: true,
    minimumResultsForSearch: 5,
    width:'100%'
});

How do I change the figure size with subplots?

Alternatively, create a figure() object using the figsize argument and then use add_subplot to add your subplots. E.g.

import matplotlib.pyplot as plt
import numpy as np

f = plt.figure(figsize=(10,3))
ax = f.add_subplot(121)
ax2 = f.add_subplot(122)
x = np.linspace(0,4,1000)
ax.plot(x, np.sin(x))
ax2.plot(x, np.cos(x), 'r:')

Simple Example

Benefits of this method are that the syntax is closer to calls of subplot() instead of subplots(). E.g. subplots doesn't seem to support using a GridSpec for controlling the spacing of the subplots, but both subplot() and add_subplot() do.

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

Encode html entities in javascript

You can use this.

var escapeChars = {
  '¢' : 'cent',
  '£' : 'pound',
  '¥' : 'yen',
  '€': 'euro',
  '©' :'copy',
  '®' : 'reg',
  '<' : 'lt',
  '>' : 'gt',
  '"' : 'quot',
  '&' : 'amp',
  '\'' : '#39'
};

var regexString = '[';
for(var key in escapeChars) {
  regexString += key;
}
regexString += ']';

var regex = new RegExp( regexString, 'g');

function escapeHTML(str) {
  return str.replace(regex, function(m) {
    return '&' + escapeChars[m] + ';';
  });
};

https://github.com/epeli/underscore.string/blob/master/escapeHTML.js

var htmlEntities = {
    nbsp: ' ',
    cent: '¢',
    pound: '£',
    yen: '¥',
    euro: '€',
    copy: '©',
    reg: '®',
    lt: '<',
    gt: '>',
    quot: '"',
    amp: '&',
    apos: '\''
};

function unescapeHTML(str) {
    return str.replace(/\&([^;]+);/g, function (entity, entityCode) {
        var match;

        if (entityCode in htmlEntities) {
            return htmlEntities[entityCode];
            /*eslint no-cond-assign: 0*/
        } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
            return String.fromCharCode(parseInt(match[1], 16));
            /*eslint no-cond-assign: 0*/
        } else if (match = entityCode.match(/^#(\d+)$/)) {
            return String.fromCharCode(~~match[1]);
        } else {
            return entity;
        }
    });
};

JQuery Redirect to URL after specified time

just use:

setTimeout("window.location.href='yoururl';",4000);

..where the '4000' is m.second

In Linux, how to tell how much memory processes are using?

First get the pid:

ps ax | grep [process name]

And then:

top -p PID

You can watch various processes in the same time:

top -p PID1 -p PID2 

pip install: Please check the permissions and owner of that directory

basic info

  • system: mac os 18.0.0
  • current user: yutou

the key

  1. add the current account to wheel group
sudo dscl . -append /Groups/wheel wheel $(whoami)
  1. modify python package mode to 775.
chmod -R 775 ${this_is_your_python_package_path}

the whole thing

  • when python3 compiled well, the infomation is just like the question said.
  • I try to use pip3 install requests and got:
File "/usr/local/python3/lib/python3.6/os.py", line 220, in makedirs
    mkdir(name, mode)
PermissionError: [Errno 13] Permission denied: 
'/usr/local/python3/lib/python3.6/site-packages/requests'
  • so i cd /usr/local/python3/lib/python3.6/site-packages, then ls -al and got:
drwxr-xr-x    6 root   wheel   192B  2 27 18:06 requests/

when i saw this, i understood, makedirs is an action of write, but the requests mode drwxrwxr-x displaied only user root can write the requests file. If add yutou(whoami) to the group wheel, and modify the package to the group wheel can write, then i can write, and the problem solved.

How to add yutou to group wheel? + detect group wheel, sudo dscl . -list /groups GroupMembership, you will find:

wheel                    root

the group wheel only one member root. + add yutou to group wheel, sudo dscl . -append /Groups/wheel wheel yutou. + check, sudo dscl . -list /groups GroupMembership:

wheel                    root yutou

modify the python package mode

chmod -R 775 /usr/local/python3/lib/python3.6

'too many values to unpack', iterating over a dict. key=>string, value=>list

You want to use iteritems. This returns an iterator over the dictionary, which gives you a tuple(key, value)

>>> for field, values in fields.iteritems():
...     print field, values
... 
first_names ['foo', 'bar']
last_name ['gravy', 'snowman']

Your problem was that you were looping over fields, which returns the keys of the dictionary.

>>> for field in fields:
...     print field
... 
first_names
last_name

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

You're not reading the file content:

my_file_contents = f.read()

See the docs for further infos

You could, without calling read() or readlines() loop over your file object:

f = open('goodlines.txt')
for line in f:
    print(line)

If you want a list out of it (without \n as you asked)

my_list = [line.rstrip('\n') for line in f]

How to get an element's top position relative to the browser's viewport?

Thanks for all the answers. It seems Prototype already has a function that does this (the page() function). By viewing the source code of the function, I found that it first calculates the element offset position relative to the page (i.e. the document top), then subtracts the scrollTop from that. See the source code of prototype for more details.

How to delete an SVN project from SVN repository

this answer can be confusing

do read the comments attached to this post and make sure this is what you are after

'svn delete' works against repository content, not against the repository itself. for doing repository maintenance (like completely deleting one) you should use svnadmin. However, there's a reason why svnadmin doesn't have a 'delete' subcommand. You can just

rm -rf $REPOS_PATH

on the svn server,

where $REPOS_PATH is the path you used to create your repository with

svnadmin create $REPOS_PATH

Ruby replace string with captured regex pattern

 "foobar".gsub(/(o+)/){|s|s+'ball'}
 #=> "fooballbar"

How to debug Apache mod_rewrite

There's the htaccess tester.

It shows which conditions were tested for a certain URL, which ones met the criteria and which rules got executed.

It seems to have some glitches, though.

Squaring all elements in a list

Use a list comprehension (this is the way to go in pure Python):

>>> l = [1, 2, 3, 4]
>>> [i**2 for i in l]
[1, 4, 9, 16]

Or numpy (a well-established module):

>>> numpy.array([1, 2, 3, 4])**2
array([ 1,  4,  9, 16])

In numpy, math operations on arrays are, by default, executed element-wise. That's why you can **2 an entire array there.

Other possible solutions would be map-based, but in this case I'd really go for the list comprehension. It's Pythonic :) and a map-based solution that requires lambdas is slower than LC.

Center text output from Graphics.DrawString()

Here's some code. This assumes you are doing this on a form, or a UserControl.

Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");

int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));

From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.

Settings to Windows Firewall to allow Docker for Windows to share drive

Only this solution helps me:

  • Go to Hyper-V Manager -> Virtual Switch Manager -> DockerNAT -> Connection Type: change from internal to private, apply, change back to internal, apply
  • Restart MobyLinuxVM
  • Restart Docker
  • Set Docker network profile to 'Private'. Run command in PowerShell as admin
    Set-NetConnectionProfile -interfacealias "vEthernet (DockerNAT)" -NetworkCategory Private
  • Reset File and Printer Sharing for Microsoft Networks on DockerNAT connection
  • Go to Docker -> Settings -> Shared Drives and share C:

Bash: Echoing a echo command with a variable in bash

The immediate problem is you have is with quoting: by using double quotes ("..."), your variable references are instantly expanded, which is probably not what you want.

Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.

(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $ of references you do not want expanded with \; e.g., \$var).

However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<, and the closing one on a line by itself - starting at the very first column; search for Here Documents in man bash or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.

If you quote the here-doc delimiter (EOF in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \:

echo "creating new script file."

cat <<'EOF'  > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}` 
if [ $servicetest > /dev/null ]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi
EOF

As @BruceK notes, you can prefix your here-doc delimiter with - (applied to this example: <<-"EOF") in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern. Note, however, that this only works with actual tab characters, not leading spaces.

Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):

cat <<-'EOF' > "$servfile"
    #!/bin/bash
    read -p "Please enter a service name: " ser
    if [[ -n $(getsebool -a | grep "${ser}") ]]; then 
      echo "We are now going to work with ${ser}."
    else
      exit 1
    fi
EOF

Finally, note that in bash even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.

Thus, note how in the following #!/bin/bash has to follow the opening ' immediately in order to become the first line of output:

echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then 
  echo "we are now going to work with ${ser}"
else
  exit 1
fi' > "$servfile"

Afterthoughts regarding the contents of your script:

  • The syntax $(...) is preferred over `...` for command substitution nowadays.
  • You should double-quote ${ser} in the grep command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).
  • Use [[ -n $servicetest ]] to test whether $servicetest is empty (or perform the command substitution directly inside the conditional) - [[ ... ]] - the preferred form in bash - protects you from breaking the conditional if the $servicetest happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ] or [[ ... ]], as no stdout output is passed through; thus, the > /dev/null is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).

Create a day-of-week column in a Pandas dataframe using Python

Using dt.weekday_name is deprecated since pandas 0.23.0, instead, use dt.day_name():

df = pd.DataFrame({'my_dates':['2015-01-01','2015-01-02','2015-01-03'],'myvals':[1,2,3]})
df['my_dates'] = pd.to_datetime(df['my_dates'])

df['my_dates'].dt.day_name()

0    Thursday
1      Friday
2    Saturday
Name: my_dates, dtype: object

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

jQuery - Detect value change on hidden input field

So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

function setUserID(myValue) {
     $('#userid').val(myValue)
                 .trigger('change');
}

Once that's the case,

$('#userid').change(function(){
      //fire your ajax call  
})

should work as expected.

Check a collection size with JSTL

You can use like this

${fn:length(numList)}

Delete a row from a SQL Server table

Try with paramter

.....................
.....................

    using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = " + @IDNumber, con))
             {
                   command.Paramter.Add("@IDNumber",IDNumber)
                   command.ExecuteNonQuery();
             }

.....................
.....................

No need to close connection in using statement

What is the equivalent to getLastInsertId() in Cakephp?

this is best way to find out last inserted id.

$this->ModelName->getInsertID();

other way is using

$this->ModelName->find('first',array('order'=>'id DESC')) 

react-router go back a page how do you configure history?

import { withRouter } from 'react-router-dom'

this.props.history.goBack();

I am using these versions

"react": "^15.6.1",
"react-dom": "^15.6.1",
"react-router": "^4.2.0",
"react-router-dom": "^4.2.2",

How do I modify fields inside the new PostgreSQL JSON datatype?

For those who use mybatis, here is an example update statement:

<update id="saveAnswer">
    update quiz_execution set answer_data = jsonb_set(answer_data, concat('{', #{qid}, '}')::text[], #{value}::jsonb), updated_at = #{updatedAt}
    where id = #{id}
</update>


Params:

  • qid, the key for field.
  • value, is a valid json string, for field value,
    e.g converted from object to json string via jackson,

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

React-Router External link

It doesn't need to request react router. This action can be done natively and it is provided by the browser.

just use window.location

class RedirectPage extends React.Component {
  componentDidMount(){
    window.location.replace('https://www.google.com')
  }
}

also, if you want to open it in a new tab:

window.open('https://www.google.com', '_blank');

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

When is layoutSubviews called?

https://developer.apple.com/library/prerelease/tvos/documentation/WindowsViews/Conceptual/ViewPG_iPhoneOS/CreatingViews/CreatingViews.html#//apple_ref/doc/uid/TP40009503-CH5-SW1

Layout changes can occur whenever any of the following events happens in a view:

a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling the setNeedsLayout or layoutIfNeeded method of a view.
e. Your application forces layout by calling the setNeedsLayout method of the view’s underlying layer object.

Skip first entry in for loop in python?

An alternative method:

for idx, car in enumerate(cars):
    # Skip first line.
    if not idx:
        continue
    # Skip last line.
    if idx + 1 == len(cars):
        continue
    # Real code here.
    print car

How to set the Android progressbar's height?

This is the progress bar I have used.

<ProgressBar
     android:padding="@dimen/dimen_5"
     android:layout_below="@+id/txt_chklist_progress"
     android:id="@+id/pb_media_progress"
     style="@style/MyProgressBar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:progress="70"
     android:scaleY="5"
     android:max="100"
     android:progressBackgroundTint="@color/white"
     android:progressTint="@color/green_above_avg" />

And this is my style tag

 <style name="MyProgressBar" parent="@style/Widget.AppCompat.ProgressBar.Horizontal">
    <item name="android:progressBackgroundTint">@color/white</item>
    <item name="android:progressTint">@color/green_above_avg</item>
</style>

How to build a 'release' APK in Android Studio?

Click \Build\Select Build Variant... in Android Studio. And choose release.

ASP.NET document.getElementById('<%=Control.ClientID%>'); returns null

Gotcha!

You have to use RegisterStartupScript instead of RegisterClientScriptBlock

Here My Example.

MasterPage:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="MasterPage.master.cs"
    Inherits="prueba.MasterPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script type="text/javascript">

        function confirmCallBack() {
            var a = document.getElementById('<%= Page.Master.FindControl("ContentPlaceHolder1").FindControl("Button1").ClientID %>');

            alert(a.value);

        }

    </script>

    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html>

WebForm1.aspx

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.Master" AutoEventWireup="true"
    CodeBehind="WebForm1.aspx.cs" Inherits="prueba.WebForm1" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
<asp:Button ID="Button1" runat="server" Text="Button" />
</asp:Content>

WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace prueba
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ClientScript.RegisterStartupScript(this.GetType(), "js", "confirmCallBack();", true);

        }
    }
}

Iterate through every file in one directory

The find library is designed for this task specifically: https://ruby-doc.org/stdlib-2.5.1/libdoc/find/rdoc/Find.html

require 'find'
Find.find(path) do |file|
  # process
end

This is a standard ruby library, so it should be available

Extracting text from a PDF file using PDFMiner in python?

Here is a working example of extracting text from a PDF file using the current version of PDFMiner(September 2016)

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage
from io import StringIO

def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos=set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages, password=password,caching=caching, check_extractable=True):
        interpreter.process_page(page)

    text = retstr.getvalue()

    fp.close()
    device.close()
    retstr.close()
    return text

PDFMiner's structure changed recently, so this should work for extracting text from the PDF files.

Edit : Still working as of the June 7th of 2018. Verified in Python Version 3.x

Edit: The solution works with Python 3.7 at October 3, 2019. I used the Python library pdfminer.six, released on November 2018.

Soft hyphen in HTML (<wbr> vs. &shy;)

The zero-width space entity can be used in place of <wbr> tag reliably on virtually every platform.

&#8203;

Also useful is the word joiner entity, that can be used to prohibit a break. (Insert between each character of a word, except where you want the break.)

&#8288;

With the two of these, you can do anything.

How do you run `apt-get` in a dockerfile behind a proxy?

As suggested by other answers, --build-arg may be the solution. In my case, I had to add --network=host in addition to the --build-arg options.

docker build -t <TARGET> --build-arg http_proxy=http://<IP:PORT> --build-arg https_proxy=http://<IP:PORT> --network=host .

Powershell: How can I stop errors from being displayed in a script?

Windows PowerShell provides two mechanisms for reporting errors: one mechanism for terminating errors and another mechanism for non-terminating errors.

Internal CmdLets code can call a ThrowTerminatingError method when an error occurs that does not or should not allow the cmdlet to continue to process its input objects. The script writter can them use exception to catch these error.

EX :

try
{
  Your database code
}
catch
{
  Error reporting/logging
}

Internal CmdLets code can call a WriteError method to report non-terminating errors when the cmdlet can continue processing the input objects. The script writer can then use -ErrorAction option to hide the messages, or use the $ErrorActionPreference to setup the entire script behaviour.

How to highlight text using javascript

Simply pass your word into the following function:

function highlight_words(word) {
    const page = document.body.innerHTML;
    document.body.innerHTML = page.replace(new RegExp(word, "gi"), (match) => `<mark>${match}</mark>`);
}

Usage:

highlight_words("hello")

This will highlight all instances of the word on the page.

Add items to comboBox in WPF

Use this

string[] str = new string[] {"Foo", "Bar"};

myComboBox.ItemsSource = str;
myComboBox.SelectedIndex = 0;

OR

foreach (string s in str)
    myComboBox.Items.Add(s);

myComboBox.SelectedIndex = 0;      

How to force reloading a page when using browser back button?

An alternative that solved the problem to me is to disable cache for the page. That make the browser to get the page from the server instead of using a cached version:

Response.AppendHeader("Cache-Control","no-cache, no-store, must-revalidate");
Response.AppendHeader("Pragma", "no-cache");
Response.AppendHeader("Expires", "0");

How to specify names of columns for x and y when joining in dplyr?

This feature has been added in dplyr v0.3. You can now pass a named character vector to the by argument in left_join (and other joining functions) to specify which columns to join on in each data frame. With the example given in the original question, the code would be:

left_join(test_data, kantrowitz, by = c("first_name" = "name"))

How to add chmod permissions to file in Git?

According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index sub-command.

To set the flag, use following command:

git update-index --chmod=+x path/to/file

To remove it, use:

git update-index --chmod=-x path/to/file

Under the hood

While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:

  • 100644 for regular files
  • 100755 for executable ones

You can visualize it using ls-file subcommand, with --stage option:

$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0       .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0       my_executable_script.sh

By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode option to false:

git config core.fileMode false

Troubleshooting

If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:

git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file

Bonus

Starting with Git 2.9, you can stage a file AND set the flag in one command:

git add --chmod=+x path/to/file

Convert java.util.Date to String

Why don't you use Joda (org.joda.time.DateTime)? It's basically a one-liner.

Date currentDate = GregorianCalendar.getInstance().getTime();
String output = new DateTime( currentDate ).toString("yyyy-MM-dd HH:mm:ss");

// output: 2014-11-14 14:05:09

Where does Hive store files in HDFS?

Hive database is nothing but directories within HDFS with .db extensions.

So, from a Unix or Linux host which is connected to HDFS, search by following based on type of HDFS distribution:

hdfs dfs -ls -R / 2>/dev/null|grep db or hadoop fs -ls -R / 2>/dev/null|grep db

You will see full path of .db database directories. All tables will be residing under respective .db database directories.

How can I get the client's IP address in ASP.NET MVC?

I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:

System.Web.HttpContext.Current.Request.UserHostAddress

Pretty print in MongoDB shell as default

Check this out:

db.collection.find().pretty()

Switch statement: must default be the last case?

It's valid and very useful in some cases.

Consider the following code:

switch(poll(fds, 1, 1000000)){
   default:
    // here goes the normal case : some events occured
   break;
   case 0:
    // here goes the timeout case
   break;
   case -1:
     // some error occurred, you have to check errno
}

The point is that the above code is more readable and efficient than cascaded if. You could put default at the end, but it is pointless as it will focus your attention on error cases instead of normal cases (which here is the default case).

Actually, it's not such a good example, in poll you know how many events may occur at most. My real point is that there are cases with a defined set of input values where there are 'exceptions' and normal cases. If it's better to put exceptions or normal cases at front is a matter of choice.

In software field I think of another very usual case: recursions with some terminal values. If you can express it using a switch, default will be the usual value that contains recursive call and distinguished elements (individual cases) the terminal values. There is usually no need to focus on terminal values.

Another reason is that the order of the cases may change the compiled code behavior, and that matters for performances. Most compilers will generate compiled assembly code in the same order as the code appears in the switch. That makes the first case very different from the others: all cases except the first one will involve a jump and that will empty processor pipelines. You may understand it like branch predictor defaulting to running the first appearing case in the switch. If a case if much more common that the others then you have very good reasons to put it as the first case.

Reading comments it's the specific reason why the original poster asked that question after reading Intel compiler Branch Loop reorganisation about code optimisation.

Then it will become some arbitration between code readability and code performance. Probably better to put a comment to explain to future reader why a case appears first.

Remove gutter space for a specific div only

Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter row, you could copy-paste-merge most answers into the following snippet:

.row.no-gutter [class*='col-']:first-child:not(:only-child) {
    padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
    padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
    padding-right: 0;
    padding-left: 0;
}

If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).

Strange PostgreSQL "value too long for type character varying(500)"

Character varying is different than text. Try running

ALTER TABLE product_product ALTER COLUMN code TYPE text;

That will change the column type to text, which is limited to some very large amount of data (you would probably never actually hit it.)

Apache: The requested URL / was not found on this server. Apache

Try changing Deny from all to Allow from all in your conf and see if that helps.

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

You would expect that this is easily possible but that seems not be the case. The only way I see at the moment is to create a user defined JQL function. I never tried this but here is a plug-in:

http://confluence.atlassian.com/display/DEVNET/Plugin+Tutorial+-+Adding+a+JQL+Function+to+JIRA

Java synchronized method lock on object, or method?

You can do something like the following. In this case you are using the lock on a and b to synchronized instead of the lock on "this". We cannot use int because primitive values don't have locks, so we use Integer.

class x{
   private Integer a;
   private Integer b;
   public void addA(){
      synchronized(a) {
         a++;
      }
   }
   public synchronized void addB(){
      synchronized(b) {
         b++;
      }
   }
}

JavaScript OOP in NodeJS: how?

This is the best video about Object-Oriented JavaScript on the internet:

The Definitive Guide to Object-Oriented JavaScript

Watch from beginning to end!!

Basically, Javascript is a Prototype-based language which is quite different than the classes in Java, C++, C#, and other popular friends. The video explains the core concepts far better than any answer here.

With ES6 (released 2015) we got a "class" keyword which allows us to use Javascript "classes" like we would with Java, C++, C#, Swift, etc.

Screenshot from the video showing how to write and instantiate a Javascript class/subclass: enter image description here

Convert NVARCHAR to DATETIME in SQL Server 2008

DECLARE @chr nvarchar(50) = (SELECT CONVERT(nvarchar(50), GETDATE(), 103))

SELECT @chr chars, CONVERT(date, @chr, 103) date_again

Controlling number of decimal digits in print output in R

One more solution able to control the how many decimal digits to print out based on needs (if you don't want to print redundant zero(s))

For example, if you have a vector as elements and would like to get sum of it

elements <- c(-1e-05, -2e-04, -3e-03, -4e-02, -5e-01, -6e+00, -7e+01, -8e+02)
sum(elements)
## -876.5432

Apparently, the last digital as 1 been truncated, the ideal result should be -876.54321, but if set as fixed printing decimal option, e.g sprintf("%.10f", sum(elements)), redundant zero(s) generate as -876.5432100000

Following the tutorial here: printing decimal numbers, if able to identify how many decimal digits in the certain numeric number, like here in -876.54321, there are 5 decimal digits need to print, then we can set up a parameter for format function as below:

decimal_length <- 5
formatC(sum(elements), format = "f", digits = decimal_length)
## -876.54321

We can change the decimal_length based on each time query, so it can satisfy different decimal printing requirement.

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission>

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Replace a newline in TSQL

In SQL Server 2017 & later, use Trim

Select Trim(char(10) + char(13) from @str)
  1. it trims on starting and ending, not in the middle
  2. the order of \r and \n does not matter

I use it to trim special characters for a file name

Select Trim(char(10) + char(13) + ' *<>' from @fileName)

jQuery: click function exclude children.

My solution:

jQuery('.foo').on('click',function(event){
    if ( !jQuery(event.target).is('.foo *') ) {
        // code goes here
    } 
});

How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure?

The linked list holds operations on the shared data structure.

For example, if I have a stack, it will be manipulated with pushes and pops. The linked list would be a set of pushes and pops on the pseudo-shared stack. Each thread sharing that stack will actually have a local copy, and to get to the current shared state, it'll walk the linked list of operations, and apply each operation in order to its local copy of the stack. When it reaches the end of the linked list, its local copy holds the current state (though, of course, it's subject to becoming stale at any time).

In the traditional model, you'd have some sort of locks around each push and pop. Each thread would wait to obtain a lock, then do a push or pop, then release the lock.

In this model, each thread has a local snapshot of the stack, which it keeps synchronized with other threads' view of the stack by applying the operations in the linked list. When it wants to manipulate the stack, it doesn't try to manipulate it directly at all. Instead, it simply adds its push or pop operation to the linked list, so all the other threads can/will see that operation and they can all stay in sync. Then, of course, it applies the operations in the linked list, and when (for example) there's a pop it checks which thread asked for the pop. It uses the popped item if and only if it's the thread that requested this particular pop.

Validate form field only on submit or user input

Erik Aigner,

Please use $dirty(The field has been modified) and $invalid (The field content is not valid).

Please check below examples for angular form validation

1)

Validation example HTML for user enter inputs:

<form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate>
  <p>Email:<br>
    <input type="email" name="email" ng-model="email" required>
    <span ng-show="myForm.email.$dirty && myForm.email.$invalid">
      <span ng-show="myForm.email.$error.required">Email is required.</span>
      <span ng-show="myForm.email.$error.email">Invalid email address.</span>
      </span>
  </p>
    </form>

2)

Validation example HTML/Js for user submits :

      <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate form-submit-validation="">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Custom Directive :

app.directive('formSubmitValidation', function () {

        return {
            require: 'form',
            compile: function (tElem, tAttr) {

                tElem.data('augmented', true);

                return function (scope, elem, attr, form) {
                    elem.on('submit', function ($event) {
                        scope.$broadcast('form:submit', form);

                        if (!form.$valid) {
                            $event.preventDefault();
                        }
                        scope.$apply(function () {
                            scope.submitted = true;
                        });


                    });
                }
            }
        };


  })

3)

you don't want use directive use ng-change function like below

  <form  ng-app="myApp"  ng-controller="validateCtrl" name="myForm" novalidate ng-change="submitFun()">
      <p>Email:<br>
        <input type="email" name="email" ng-model="email" required>
        <span ng-show="submitted || myForm.email.$dirty && myForm.email.$invalid">
          <span ng-show="myForm.email.$error.required">Email is required.</span>
          <span ng-show="myForm.email.$error.email">Invalid email address.</span>
          </span>
      </p>
<p>
  <input type="submit">
</p>
</form>

Controller SubmitFun() JS:

 var app = angular.module('example', []);
 app.controller('exampleCntl', function($scope) {
 $scope.submitFun = function($event) {
 $scope.submitted = true;
  if (!$scope.myForm.$valid) 
  {
        $event.preventDefault();
   }
  }

});

How to set the color of "placeholder" text?

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

Presenting modal in iOS 13 fullscreen

If you have a UITabController with Screens with Embeded Navigation Controllers, you have to set the UITabController Presentation to FullScreen as shown in pic below

enter image description here

Can someone explain the dollar sign in Javascript?

In your example the $ has no special significance other than being a character of the name.

However, in ECMAScript 6 (ES6) the $ may represent a Template Literal

var user = 'Bob'
console.log(`We love ${user}.`); //Note backticks
// We love Bob.

C++ Calling a function from another class

What you should do, is put CallFunction into *.cpp file, where you include B.h.

After edit, files will look like:

B.h:

#pragma once //or other specific to compiler...
using namespace std;

class A 
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
        {
            //stuff done here
        }
};

B.cpp

#include "B.h"
void A::CallFunction(){
//use B object here...
}

Referencing to your explanation, that you have tried to change B b; into pointer- it would be okay, if you wouldn't use it in that same place. You can use pointer of undefined class(but declared), because ALL pointers have fixed byte size(4), so compiler doesn't have problems with that. But it knows nothing about the object they are pointing to(simply: knows the size/boundary, not the content).

So as long as you are using the knowledge, that all pointers are same size, you can use them anywhere. But if you want to use the object, they are pointing to, the class of this object must be already defined and known by compiler.

And last clarification: objects may differ in size, unlike pointers. Pointer is a number/index, which indicates the place in RAM, where something is stored(for example index: 0xf6a7b1).

MySQL Cannot drop index needed in a foreign key constraint

A foreign key always requires an index. Without an index enforcing the constraint would require a full table scan on the referenced table for every inserted or updated key in the referencing table. And that would have an unacceptable performance impact. This has the following 2 consequences:

  • When creating a foreign key, the database checks if an index exists. If not an index will be created. By default, it will have the same name as the constraint.
  • When there is only one index that can be used for the foreign key, it can't be dropped. If you really wan't to drop it, you either have to drop the foreign key constraint or to create another index for it first.

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

jQuery scroll to ID from different page

function scroll_down(){
    $.noConflict();
    jQuery(document).ready(function($) {
        $('html, body').animate({
            scrollTop : $("#bottom").offset().top
        }, 1);
    });
    return false;
}

here "bottom" is the div tag id where you want to scroll to. For changing the animation effects, you can change the time from '1' to a different value

How can I render HTML from another file in a React component?

You can use the dangerouslySetInnerHTML property to inject arbitrary HTML:

_x000D_
_x000D_
// Assume from another require()'ed module:_x000D_
var html = '<h1>Hello, world!</h1>'_x000D_
_x000D_
var MyComponent = React.createClass({_x000D_
  render: function() {_x000D_
    return React.createElement("h1", {dangerouslySetInnerHTML: {__html: html}})_x000D_
  }_x000D_
})_x000D_
_x000D_
ReactDOM.render(React.createElement(MyComponent), document.getElementById('app'))
_x000D_
<script src="https://fb.me/react-0.14.3.min.js"></script>_x000D_
<script src="https://fb.me/react-dom-0.14.3.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

You could even componentize this template behavior (untested):

class TemplateComponent extends React.Component {
  constructor(props) {
    super(props)
    this.html = require(props.template)
  }

  render() {
    return <div dangerouslySetInnerHTML={{__html: this.html}}/>
  }

}

TemplateComponent.propTypes = {
  template: React.PropTypes.string.isRequired
}

// use like
<TemplateComponent template='./template.html'/>

And with this, template.html (in the same directory) looks something like (again, untested):

// ./template.html
module.exports = '<h1>Hello, world!</h1>'

MySQL load NULL values from CSV data

The behaviour is different depending upon the database configuration. In the strict mode this would throw an error else a warning. Following query may be used for identifying the database configuration.

mysql> show variables like 'sql_mode';

How to wrap text using CSS?

Try doing this. Works for IE8, FF3.6, Chrome

<body>
  <table>
    <tr>
      <td>
        <div style="word-wrap: break-word; width: 100px">gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div>
      </td>
    </tr>
  </table>
</body>

Detecting iOS orientation change instantly

@vimal answer did not provide solution for me. It seems the orientation is not the current orientation, but from previous orientation. To fix it, I use [[UIDevice currentDevice] orientation]

- (void)orientationChanged:(NSNotification *)notification{
    [self adjustViewsForOrientation:[[UIDevice currentDevice] orientation]];
}

Then

- (void) adjustViewsForOrientation:(UIDeviceOrientation) orientation { ... }

With this code I get the current orientation position.

How to check if command line tools is installed

I think the simplest way which worked for me to find Command line tools is installed or not and its version irrespective of what macOS version is

$brew config

macOS: 10.14.2-x86_64
CLT: 10.1.0.0.1.1539992718
Xcode: 10.1

This when you have Command Line tools properly installed and paths set properly.

Earlier i got output as below
macOS: 10.14.2-x86_64
CLT: N/A
Xcode: 10.1

CLT was shown as N/A in spite of having gcc and make working fine and below outputs

$xcode-select -p              
/Applications/Xcode.app/Contents/Developer
$pkgutil --pkg-info=com.apple.pkg.CLTools_Executables
No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'.
$brew doctor
Your system is ready to brew.

Finally doing xcode-select --install resolved my issue of brew unable to find CLT for installing packages as below.

Installing sphinx-doc dependency: python
Warning: Building python from source:
  The bottle needs the Apple Command Line Tools to be installed.
  You can install them, if desired, with:
    xcode-select --install

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

Is there an equivalent to background-size: cover and contain for image elements?

What you could do is use the 'style' attribute to add the background image to the element, that way you will still be calling the image in the HTML but you will still be able to use the background-size: cover css behaviour:

HTML:

    <div class="image-div" style="background-image:url(yourimage.jpg)">
    </div>

CSS:

    .image-div{
    background-size: cover;
    }

This is how I add the background-size: cover behaviour to elements that I need to dynamically load into HTML. You can then use awesome css classes like background-position: center. boom

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

PDO support for multiple queries (PDO_MYSQL, PDO_MYSQLND)

Like thousands of people, I'm looking for this question:
Can run multiple queries simultaneously, and if there was one error, none would run I went to this page everywhere
But although the friends here gave good answers, these answers were not good for my problem
So I wrote a function that works well and has almost no problem with sql Injection.
It might be helpful for those who are looking for similar questions so I put them here to use

function arrayOfQuerys($arrayQuery)
{
    $mx = true;
    $conn->beginTransaction();
    try {
        foreach ($arrayQuery AS $item) {
            $stmt = $conn->prepare($item["query"]);
            $stmt->execute($item["params"]);
            $result = $stmt->rowCount();
            if($result == 0)
                $mx = false;
         }
         if($mx == true)
             $conn->commit();
         else
             $conn->rollBack();
    } catch (Exception $e) {
        $conn->rollBack();
        echo "Failed: " . $e->getMessage();
    }
    return $mx;
}

for use(example):

 $arrayQuery = Array(
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("aa1", 1)
    ),
    Array(
        "query" => "UPDATE test SET title = ? WHERE test.id = ?",
        "params" => Array("bb1", 2)
    )
);
arrayOfQuerys($arrayQuery);

and my connection:

    try {
        $options = array(
            //For updates where newvalue = oldvalue PDOStatement::rowCount()   returns zero. You can use this:
            PDO::MYSQL_ATTR_FOUND_ROWS => true
        );
        $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password, $options);
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    } catch (PDOException $e) {
        echo "Error connecting to SQL Server: " . $e->getMessage();
    }

Note:
This solution helps you to run multiple statement together,
If an incorrect a statement occurs, it does not execute any other statement

The input is not a valid Base-64 string as it contains a non-base 64 character

Remove the unnecessary string through Regex

Regex regex=new Regex(@"^[\w/\:.-]+;base64,");
base64File=regex.Replace(base64File,string.Empty);

Java - How Can I Write My ArrayList to a file, and Read (load) that file to the original ArrayList?

This might work for you

public void save(String fileName) throws FileNotFoundException {
FileOutputStream fout= new FileOutputStream (fileName);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(clubs);
fout.close();
}

To read back you can have

public void read(String fileName) throws FileNotFoundException {
FileInputStream fin= new FileInputStream (fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
clubs= (ArrayList<Clubs>)ois.readObject();
fin.close();
}

PHP Curl UTF-8 Charset

First method (internal function)

The best way I have tried before is to use urlencode(). Keep in mind, don't use it for the whole url; instead, use it only for the needed parts. For example, a request that has two 'text-fa' and 'text-en' fields and they contain a Persian and an English text, respectively, you might only need to encode the Persian text, not the English one.

Second Method (using cURL function)

However, there are better ways if the range of characters have to be encoded is more limited. One of these ways is using CURLOPT_ENCODING, by passing it to curl_setopt():

curl_setopt($ch, CURLOPT_ENCODING, "");

On localhost, how do I pick a free port number?

You can listen on whatever port you want; generally, user applications should listen to ports 1024 and above (through 65535). The main thing if you have a variable number of listeners is to allocate a range to your app - say 20000-21000, and CATCH EXCEPTIONS. That is how you will know if a port is unusable (used by another process, in other words) on your computer.

However, in your case, you shouldn't have a problem using a single hard-coded port for your listener, as long as you print an error message if the bind fails.

Note also that most of your sockets (for the slaves) do not need to be explicitly bound to specific port numbers - only sockets that wait for incoming connections (like your master here) will need to be made a listener and bound to a port. If a port is not specified for a socket before it is used, the OS will assign a useable port to the socket. When the master wants to respond to a slave that sends it data, the address of the sender is accessible when the listener receives data.

I presume you will be using UDP for this?

How to check 'undefined' value in jQuery

I know I am late to answer the function but jquery have a in build function to do this

if(jQuery.type(val) === "undefined"){
    //Some code goes here
}

Refer jquery API document of jquery.type https://api.jquery.com/jQuery.type/ for the same.

Hash Table/Associative Array in VBA

I've used Francesco Balena's HashTable class several times in the past when a Collection or Dictionary wasn't a perfect fit and i just needed a HashTable.

Query Mongodb on month, day, year... of a datetime

You can find record by month, day, year etc of dates by Date Aggregation Operators, like $dayOfYear, $dayOfWeek, $month, $year etc.

As an example if you want all the orders which are created in April 2016 you can use below query.

db.getCollection('orders').aggregate(
   [
     {
       $project:
         {
           doc: "$$ROOT",
           year: { $year: "$created" },
           month: { $month: "$created" },
           day: { $dayOfMonth: "$created" }
         }
     },
     { $match : { "month" : 4, "year": 2016 } }
   ]
)

Here created is a date type field in documents, and $$ROOT we used to pass all other field to project in next stage, and give us all the detail of documents.

You can optimize above query as per your need, it is just to give an example. To know more about Date Aggregation Operators, visit the link.