Programs & Examples On #Wli

Oracle WebLogic Integration (WLI) is a comprehensive and flexible java-based solution that allows integrating systems, data and people within and across companies to make the most of existing assets wherever they are.

Method Call Chaining; returning a pointer vs a reference?

Since nullptr is never going to be returned, I recommend the reference approach. It more accurately represents how the return value will be used.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Why powershell does not run Angular commands?

I solved my problem by running below command

Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser

Why do I keep getting Delete 'cr' [prettier/prettier]?

I upgraded to "prettier": "^2.2.0" and error went away

How to use log4net in Asp.net core 2.0

Following on Irfan's answer, I have the following XML configuration on OSX with .NET Core 2.1.300 which correctly logs and appends to a ./log folder and also to the console. Note the log4net.config must exist in the solution root (whereas in my case, my app root is a subfolder).

<?xml version="1.0" encoding="utf-8" ?>
<log4net>
  <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
      <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date %-5level %logger - %message%newline" />
      </layout>
  </appender>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock"/>
    <file value="logs/" />
    <datePattern value="yyyy-MM-dd.'txt'"/>
    <staticLogFileName value="false"/>
    <appendToFile value="true"/>
    <rollingStyle value="Date"/>
    <maxSizeRollBackups value="100"/>
    <maximumFileSize value="15MB"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level App  %newline %message %newline %newline"/>
    </layout>
  </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="RollingLogFileAppender"/>
      <appender-ref ref="ConsoleAppender"/>
    </root>
</log4net>

Another note, the traditional way of setting the XML up within app.config did not work:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>
  <log4net> ...

For some reason, the log4net node was not found when accessing the XMLDocument via log4netConfig["log4net"].

Unable to create migrations after upgrading to ASP.NET Core 2.0

I had this issue in a solution that has:

  • a .NET Core 2.2 MVC project
  • a .NET Core 3.0 Blazor project
  • The DB Context in a .NET Standard 2.0 class library project

I get the "unable to create an object..." message when the Blazor project is set as the start up project, but not if the MVC project is set as the startup project.

That puzzles me, because in the Package Manager Console (which is where I'm creating the migration) I have the Default project set to a the C# class library that actually contains the DB Context, and I'm also specifying the DB context in my call to add-migration add-migration MigrationName -context ContextName, so it seems strange that Visual Studio cares what startup project is currently set.

I'm guessing the reason is that when the Blazor project is the startup project the PMC is determining the version of .NET to be Core 3.0 from the startup project and then trying to use that to run the migrations on the .NET Standard 2.0 class library and hitting a conflict of some sort.

Whatever the cause, changing the startup project to the MVC project that targets Core 2.2, rather than the Blazor project, fixed the issue

Bootstrap 4: Multilevel Dropdown Inside Navigation

I found this multidrop-down menu which work great in all device.

Also, have hover style

It supports multi-level submenus with bootstrap 4.

_x000D_
_x000D_
$( document ).ready( function () {_x000D_
    $( '.navbar a.dropdown-toggle' ).on( 'click', function ( e ) {_x000D_
        var $el = $( this );_x000D_
        var $parent = $( this ).offsetParent( ".dropdown-menu" );_x000D_
        $( this ).parent( "li" ).toggleClass( 'show' );_x000D_
_x000D_
        if ( !$parent.parent().hasClass( 'navbar-nav' ) ) {_x000D_
            $el.next().css( { "top": $el[0].offsetTop, "left": $parent.outerWidth() - 4 } );_x000D_
        }_x000D_
        $( '.navbar-nav li.show' ).not( $( this ).parents( "li" ) ).removeClass( "show" );_x000D_
        return false;_x000D_
    } );_x000D_
} );
_x000D_
.navbar-light .navbar-nav .nav-link {_x000D_
    color: rgb(64, 64, 64);_x000D_
}_x000D_
.btco-menu li > a {_x000D_
    padding: 10px 15px;_x000D_
    color: #000;_x000D_
}_x000D_
_x000D_
.btco-menu .active a:focus,_x000D_
.btco-menu li a:focus ,_x000D_
.navbar > .show > a:focus{_x000D_
    background: transparent;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
.dropdown-menu .show > .dropdown-toggle::after{_x000D_
    transform: rotate(-90deg);_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded btco-menu">_x000D_
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
        <span class="navbar-toggler-icon"></span>_x000D_
    </button>_x000D_
    <a class="navbar-brand" href="#">Navbar</a>_x000D_
    <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
        <ul class="navbar-nav">_x000D_
            <li class="nav-item active">_x000D_
                <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Features</a>_x000D_
            </li>_x000D_
            <li class="nav-item">_x000D_
                <a class="nav-link" href="#">Pricing</a>_x000D_
            </li>_x000D_
            <li class="nav-item dropdown">_x000D_
                <a class="nav-link dropdown-toggle" href="https://bootstrapthemes.co" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Dropdown link</a>_x000D_
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
                    <li><a class="dropdown-item" href="#">Action</a></li>_x000D_
                    <li><a class="dropdown-item" href="#">Another action</a></li>_x000D_
                    <li><a class="dropdown-item dropdown-toggle" href="#">Submenu</a>_x000D_
                        <ul class="dropdown-menu">_x000D_
                            <li><a class="dropdown-item" href="#">Submenu action</a></li>_x000D_
                            <li><a class="dropdown-item" href="#">Another submenu action</a></li>_x000D_
_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                            <li><a class="dropdown-item dropdown-toggle" href="#">Second subsubmenu</a>_x000D_
                                <ul class="dropdown-menu">_x000D_
                                    <li><a class="dropdown-item" href="#">Subsubmenu action</a></li>_x000D_
                                    <li><a class="dropdown-item" href="#">Another subsubmenu action</a></li>_x000D_
                                </ul>_x000D_
                            </li>_x000D_
                        </ul>_x000D_
                    </li>_x000D_
                </ul>_x000D_
            </li>_x000D_
        </ul>_x000D_
    </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

`col-xs-*` not working in Bootstrap 4

They dropped XS because Bootstrap is considered a mobile-first development tool. It's default is considered xs and so doesn't need to be defined.

ps1 cannot be loaded because running scripts is disabled on this system

open windows powershell in administrator mode and run the following command and its work VOILA!!

Set-ExecutionPolicy RemoteSigned

How do I preserve line breaks when getting text from a textarea?

Here is an idea as you may have multiple newline in a textbox:

 var text=document.getElementById('post-text').value.split('\n');
 var html = text.join('<br />');

This HTML value will preserve newline. Hope this helps.

Build error, This project references NuGet

Why should you need manipulations with packages.config or .csproj files?
The error explicitly says: Use NuGet Package Restore to download them.
Use it accordingly this instruction: https://docs.microsoft.com/en-us/nuget/consume-packages/package-restore-troubleshooting:

Quick solution for Visual Studio users
1.Select the Tools > NuGet Package Manager > Package Manager Settings menu command.
2.Set both options under Package Restore.
3.Select OK.
4.Build your project again.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

SQL 2016 solution/workaround here (could also work in earlier versions). This may not work or be appropriate in every situation, but I resolved the error by granting my database user read/write schema ownership as follows in SSMS:

Database > Security > Users > User > Properties > Owned Schemas > check db_datareader and db_datawriter.

How to add new line in Markdown presentation?

The newline character (\n) can be used to add a newline into a markdown file programmatically. For example, it is possible to do like this in python:

with open("file_name.md", "w") as file:
   file.write("Some text")
   file.write("\n")
   file.write("Some other text")

NuGet Packages are missing

I had this issue as a failed build in Azure, when deployed from Git.

Turns out my .gitignore was excluding the build folder from ..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.2.0.0\build\net46\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props.

Once the build folder was (force) committed to Git, the issue was solved.

Print "\n" or newline characters as part of the output on terminal

Use repr

>>> string = "abcd\n"
>>> print(repr(string))
'abcd\n'

Find and replace with a newline in Visual Studio Code

  • Control F for search, or Control Shift F for global search
  • Replace >< by >\n< with Regular Expressions enabled

enter image description here

How to get multiline input from user

no_of_lines = 5
lines = ""
for i in xrange(5):
    lines+=input()+"\n"
    a=raw_input("if u want to continue (Y/n)")
    ""
    if(a=='y'):
        continue
    else:
        break
    print lines

Android statusbar icons color

Setting windowLightStatusBar to true not works with Mi phones, some Meizu phones, Blackview phones, WileyFox etc. I've found such hack for Mi and Meizu devices. This is not a comprehensive solution of this perfomance problem, but maybe it would be useful to somebody.

And I think, it would be better to tell your customer that coloring status bar (for example) white - is not a good idea. instead of using different hacks it would be better to define appropriate colorPrimaryDark according to the guidelines

Best way to update data with a RecyclerView adapter

@inmyth's answer is correct, just modify the code a bit, to handle empty list.

public class NewsAdapter extends RecyclerView.Adapter<...> {    
    ...
    private static List mFeedsList;
    ...    
    public void swap(List list){
            if (mFeedsList != null) {
                mFeedsList.clear();
                mFeedsList.addAll(list);
            }
            else {
                mFeedsList = list;
            }
            notifyDataSetChanged();
    }

I am using Retrofit to fetch the list, on Retrofit's onResponse() use,

adapter.swap(feedList);

What is the symbol for whitespace in C?

To check a space symbol you can use the following approach

if ( c == ' ' ) { /*...*/ }

To check a space and/or a tab symbol (standard blank characters) you can use the following approach

#include <ctype.h>

//...

if ( isblank( c ) ) { /*...*/ }

To check a white space you can use the following approach

#include <ctype.h>

//...

if ( isspace( c ) ) { /*...*/ }

I just assigned a variable, but echo $variable shows something else

In addition to other issues caused by failing to quote, -n and -e can be consumed by echo as arguments. (Only the former is legal per the POSIX spec for echo, but several common implementations violate the spec and consume -e as well).

To avoid this, use printf instead of echo when details matter.

Thus:

$ vars="-e -n -a"
$ echo $vars      # breaks because -e and -n can be treated as arguments to echo
-a
$ echo "$vars"
-e -n -a

However, correct quoting won't always save you when using echo:

$ vars="-n"
$ echo $vars
$ ## not even an empty line was printed

...whereas it will save you with printf:

$ vars="-n"
$ printf '%s\n' "$vars"
-n

Out-File -append in Powershell does not produce a new line and breaks string into characters

Out-File defaults to unicode encoding which is why you are seeing the behavior you are. Use -Encoding Ascii to change this behavior. In your case

Out-File -Encoding Ascii -append textfile.txt. 

Add-Content uses Ascii and also appends by default.

"This is a test" | Add-Content textfile.txt.

As for the lack of newline: You did not send a newline so it will not write one to file.

Add newline to VBA or Visual Basic 6

There are actually two ways of doing this:

  1. st = "Line 1" + vbCrLf + "Line 2"

  2. st = "Line 1" + vbNewLine + "Line 2"

These even work for message boxes (and all other places where strings are used).

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

Using tr to replace newline with space

Best guess is you are on windows and your line ending settings are set for windows. See this topic: How to change line-ending settings

or use:

tr '\r\n' ' '

SQL Server Service not available in service list after installation of SQL Server Management Studio

downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?

You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.

http://www.microsoft.com/en-us/download/details.aspx?id=1695

Why is it that "No HTTP resource was found that matches the request URI" here?

Have you tried using the [FromUri] attribute when sending parameters over the query string.

Here is an example:

[HttpGet]
[Route("api/department/getndeptsfromid")]
public List<Department> GetNDepartmentsFromID([FromUri]int FirstId, [FromUri] int CountToFetch)
{
    return HHSService.GetNDepartmentsFromID(FirstId, CountToFetch);
}

Include this package at the top also, using System.Web.Http;

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

Adding a newline character within a cell (CSV)

This question was answered well at Can you encode CR/LF in into CSV files?.

Consider also reverse engineering multiple lines in Excel. To embed a newline in an Excel cell, press Alt+Enter. Then save the file as a .csv. You'll see that the double-quotes start on one line and each new line in the file is considered an embedded newline in the cell.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

Here is my solution to this problem,make sure the version number in appconfig or packageconfig is same as the reference version in your references. See here

How to align text below an image in CSS?

Since the default for block elements is to order one on top of the other you should also be able to do this:

<div>
    <img src="path/to/img">
    <div>Text Under Image</div>
</div

img {
    display: block;
}

Print a list of space-separated elements in Python 3

Joining elements in a list space separated:

word = ["test", "crust", "must", "fest"]
word.reverse()
joined_string = ""
for w in word:
   joined_string = w + joined_string + " "
print(joined_string.rstrim())

Sublime Text 3, convert spaces to tabs

Here is how you to do it automatically on save: https://coderwall.com/p/zvyg7a/convert-tabs-to-spaces-on-file-save

Unfortunately the package is not working when you install it from the Package Manager.

The model backing the 'ApplicationDbContext' context has changed since the database was created

This can happen when you change the data annotation of a model property. for example: adding [Required] to a property will cause a pending change in the database design.

The safest solution is to run on the Package Manager Console:

add-migration myMirgrationName

which will display the exact changes in the Up() method. Therefore, you can decide if you really want to apply such changes via the:

update-database

Otherwise, you may just delete the latest migration from the __MigrationHistory table and from the Migrations folder the Solution Explorer.

Line break in SSRS expression

Use the vbcrlf for new line in SSSR. e.g.

= First(Fields!SAPName.Value, "DataSet1") & vbcrlf & First(Fields!SAPStreet.Value, "DataSet1") & vbcrlf & First(Fields!SAPCityPostal.Value, "DataSet1") & vbcrlf & First(Fields!SAPCountry.Value, "DataSet1") 

Split string using a newline delimiter with Python

There is a method specifically for this purpose:

data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Form/JavaScript not working on IE 11 with error DOM7011

I faced the same issue before. I cleared all the IE caches/browsing history/cookies & re-launch IE. It works after caches removed.

You may have a try. :)

How in node to split string by newline ('\n')?

It looks like regex /\r\n|\r|\n/ handles CR, LF, and CRLF line endings, their mixed sequences, and keeps all the empty lines inbetween. Try that!

_x000D_
_x000D_
    function splitLines(t) { return t.split(/\r\n|\r|\n/); }

    // single newlines
    console.log(splitLines("AAA\rBBB\nCCC\r\nDDD"));
    // double newlines
    console.log(splitLines("EEE\r\rFFF\n\nGGG\r\n\r\nHHH"));
    // mixed sequences
    console.log(splitLines("III\n\r\nJJJ\r\r\nKKK\r\n\nLLL\r\n\rMMM"));
_x000D_
_x000D_
_x000D_

You should get these arrays as a result:

[ "AAA", "BBB", "CCC", "DDD" ]
[ "EEE", "", "FFF", "", "GGG", "", "HHH" ]
[ "III", "", "JJJ", "", "KKK", "", "LLL", "", "MMM" ]

You can also teach that regex to recognize other legit Unicode line terminators by adding |\xHH or |\uHHHH parts, where H's are hexadecimal digits of the additional terminator character codepoint (as seen in Wikipedia article as U+HHHH).

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

Install Entity Framework in each project (Ex: In Web, In Class Libraries) from NuGet Package Manager orelse Open Tools - Nuget Package Manager - Package Manager Console and use Install-Package EntityFramework to install the Entity Framework.

Don't need to add the below code in every config file. By default it will be added in the project where the database is called through Entity Framework.

<entityFramework> <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" /> <providers> <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /> </providers> </entityFramework>

How to receive JSON as an MVC 5 action method parameter

fwiw, this didn't work for me until I had this in the ajax call:

contentType: "application/json; charset=utf-8",

using Asp.Net MVC 4.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

Since [^a-z0-9] character class contains all that is not alnum, it contains white characters too!

 text.replace(/[^a-z0-9]+/gi, " ");

The process cannot access the file because it is being used by another process (File is created but contains nothing)

File.AppendAllText does not know about the stream you have opened, so will internally try to open the file again. Because your stream is blocking access to the file, File.AppendAllText will fail, throwing the exception you see.

I suggest you used str.Write or str.WriteLine instead, as you already do elsewhere in your code.

Your file is created but contains nothing because the exception is thrown before str.Flush() and str.Close() are called.

Concrete Javascript Regex for Accented Characters (Diacritics)

The easier way to accept all accents is this:

[A-zÀ-ú] // accepts lowercase and uppercase characters
[A-zÀ-ÿ] // as above but including letters with an umlaut (includes [ ] ^ \ × ÷)
[A-Za-zÀ-ÿ] // as above but not including [ ] ^ \
[A-Za-zÀ-ÖØ-öø-ÿ] // as above but not including [ ] ^ \ × ÷

See https://unicode-table.com/en/ for characters listed in numeric order.

Ansible playbook shell output

Expanding on what leucos said in his answer, you can also print information with Ansible's humble debug module:

- hosts: all
  gather_facts: no
  tasks:
    - shell: ps -eo pcpu,user,args | sort -r -k1 | head -n5
      register: ps

    # Print the shell task's stdout.
    - debug: msg={{ ps.stdout }}

    # Print all contents of the shell task's output.
    - debug: var=ps

Pythonically add header to a csv file

The DictWriter() class expects dictionaries for each row. If all you wanted to do was write an initial header, use a regular csv.writer() and pass in a simple row for the header:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.writer(outcsv)
    writer.writerow(["Date", "temperature 1", "Temperature 2"])

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row + [0.0] for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows(row[:1] + [0.0] + row[1:] for row in reader)

The alternative would be to generate dictionaries when copying across your data:

import csv

with open('combined_file.csv', 'w', newline='') as outcsv:
    writer = csv.DictWriter(outcsv, fieldnames = ["Date", "temperature 1", "Temperature 2"])
    writer.writeheader()

    with open('t1.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': row[1], 'temperature 2': 0.0} for row in reader)

    with open('t2.csv', 'r', newline='') as incsv:
        reader = csv.reader(incsv)
        writer.writerows({'Date': row[0], 'temperature 1': 0.0, 'temperature 2': row[1]} for row in reader)

Match linebreaks - \n or \r\n?

In PCRE \R matches \n, \r and \r\n.

Split bash string by newline characters

There is another way if all you want is the text up to the first line feed:

x='some
thing'

y=${x%$'\n'*}

After that y will contain some and nothing else (no line feed).

What is happening here?

We perform a parameter expansion substring removal (${PARAMETER%PATTERN}) for the shortest match up to the first ANSI C line feed ($'\n') and drop everything that follows (*).

Preserve line breaks in angularjs

Try:

<div ng-repeat="item in items">
  <pre>{{item.description}}</pre>
</div>

The <pre> wrapper will print text with \n as text

also if you print the json, for better look use json filter, like:

<div ng-repeat="item in items">
  <pre>{{item.description|json}}</pre>
</div>

Demo

I agree with @Paul Weber that white-space: pre-wrap; is better approach, anyways using <pre> - the quick way mostly for debug some stuff (if you don't want to waste time on styling)

Iterating through directories with Python

Another way of returning all files in subdirectories is to use the pathlib module, introduced in Python 3.4, which provides an object oriented approach to handling filesystem paths (Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi):

from pathlib import Path

rootdir = Path('C:/Users/sid/Desktop/test')
# Return a list of regular files only, not directories
file_list = [f for f in rootdir.glob('**/*') if f.is_file()]

# For absolute paths instead of relative the current dir
file_list = [f for f in rootdir.resolve().glob('**/*') if f.is_file()]

Since Python 3.5, the glob module also supports recursive file finding:

import os
from glob import iglob

rootdir_glob = 'C:/Users/sid/Desktop/test/**/*' # Note the added asterisks
# This will return absolute paths
file_list = [f for f in iglob(rootdir_glob, recursive=True) if os.path.isfile(f)]

The file_list from either of the above approaches can be iterated over without the need for a nested loop:

for f in file_list:
    print(f) # Replace with desired operations

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.

Just check the following snapshot.

enter image description here

For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179

Remember: you can avoid server rebooting using setup's SkipRules switch:

setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck

setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck

Extract csv file specific columns to list in Python

This looks like a problem with line endings in your code. If you're going to be using all these other scientific packages, you may as well use Pandas for the CSV reading part, which is both more robust and more useful than just the csv module:

import pandas
colnames = ['year', 'name', 'city', 'latitude', 'longitude']
data = pandas.read_csv('test.csv', names=colnames)

If you want your lists as in the question, you can now do:

names = data.name.tolist()
latitude = data.latitude.tolist()
longitude = data.longitude.tolist()

How to remove a newline from a string in Bash

Using bash:

echo "|${COMMAND/$'\n'}|"

(Note that the control character in this question is a 'newline' (\n), not a carriage return (\r); the latter would have output REBOOT| on a single line.)

Explanation

Uses the Bash Shell Parameter Expansion ${parameter/pattern/string}:

The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. [...] If string is null, matches of pattern are deleted and the / following pattern may be omitted.

Also uses the $'' ANSI-C quoting construct to specify a newline as $'\n'. Using a newline directly would work as well, though less pretty:

echo "|${COMMAND/
}|"

Full example

#!/bin/bash
COMMAND="$'\n'REBOOT"
echo "|${COMMAND/$'\n'}|"
# Outputs |REBOOT|

Or, using newlines:

#!/bin/bash
COMMAND="
REBOOT"
echo "|${COMMAND/
}|"
# Outputs |REBOOT|

How do I use shell variables in an awk script?

Use either of these depending how you want backslashes in the shell variables handled (avar is an awk variable, svar is a shell variable):

awk -v avar="$svar" '... avar ...' file
awk 'BEGIN{avar=ARGV[1];ARGV[1]=""}... avar ...' "$svar" file

See http://cfajohnson.com/shell/cus-faq-2.html#Q24 for details and other options. The first method above is almost always your best option and has the most obvious semantics.

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient'

When the error happens in tests projects the prettiest solution is to decorate the test class with:

[DeploymentItem("EntityFramework.SqlServer.dll")]

What is the newline character in the C language: \r or \n?

What is the newline character in the C language: \r or \n?

The new-line may be thought of a some char and it has the value of '\n'. C11 5.2.1

This C new-line comes up in 3 places: C source code, as a single char and as an end-of-line in file I/O when in text mode.

  1. Many compilers will treat source text as ASCII. In that case, codes 10, sometimes 13, and sometimes paired 13,10 as new-line for source code. Had the source code been in another character set, different codes may be used. This new-line typically marks the end of a line of source code (actually a bit more complicated here), // comment, and # directives.

  2. In source code, the 2 characters \ and n represent the char new-line as \n. If ASCII is used, this char would have the value of 10.

  3. In file I/O, in text mode, upon reading the bytes of the input file (and stdin), depending on the environment, when bytes with the value(s) of 10 (Unix), 13,10, (*1) (Windows), 13 (Old Mac??) and other variations are translated in to a '\n'. Upon writing a file (or stdout), the reverse translation occurs.
    Note: File I/O in binary mode makes no translation.

The '\r' in source code is the carriage return char.

(*1) A lone 13 and/or 10 may also translate into \n.

List comprehension on a nested list?

I had a similar problem to solve so I came across this question. I did a performance comparison of Andrew Clark's and narayan's answer which I would like to share.

The primary difference between two answers is how they iterate over inner lists. One of them uses builtin map, while other is using list comprehension. Map function has slight performance advantage to its equivalent list comprehension if it doesn't require the use lambdas. So in context of this question map should perform slightly better than list comprehension.

Lets do a performance benchmark to see if it is actually true. I used python version 3.5.0 to perform all these tests. In first set of tests I would like to keep elements per list to be 10 and vary number of lists from 10-100,000

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*10]"
>>> 100000 loops, best of 3: 15.2 usec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*10]"
>>> 10000 loops, best of 3: 19.6 usec per loop 

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*100]"
>>> 100000 loops, best of 3: 15.2 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*100]"
>>> 10000 loops, best of 3: 19.6 usec per loop 

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*1000]"
>>> 1000 loops, best of 3: 1.43 msec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*1000]"
>>> 100 loops, best of 3: 1.91 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*10000]"
>>> 100 loops, best of 3: 13.6 msec per loop   
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*10000]"
>>> 10 loops, best of 3: 19.1 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,10))]*100000]"
>>> 10 loops, best of 3: 164 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,10))]*100000]"
>>> 10 loops, best of 3: 216 msec per loop

enter image description here

In the next set of tests I would like to raise number of elements per lists to 100.

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*10]"
>>> 10000 loops, best of 3: 110 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*10]"
>>> 10000 loops, best of 3: 151 usec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*100]"
>>> 1000 loops, best of 3: 1.11 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*100]"
>>> 1000 loops, best of 3: 1.5 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*1000]"
>>> 100 loops, best of 3: 11.2 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*1000]"
>>> 100 loops, best of 3: 16.7 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*10000]"
>>> 10 loops, best of 3: 134 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*10000]"
>>> 10 loops, best of 3: 171 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,100))]*100000]"
>>> 10 loops, best of 3: 1.32 sec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,100))]*100000]"
>>> 10 loops, best of 3: 1.7 sec per loop

enter image description here

Lets take a brave step and modify the number of elements in lists to be 1000

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*10]"
>>> 1000 loops, best of 3: 800 usec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*10]"
>>> 1000 loops, best of 3: 1.16 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*100]"
>>> 100 loops, best of 3: 8.26 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*100]"
>>> 100 loops, best of 3: 11.7 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*1000]"
>>> 10 loops, best of 3: 83.8 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*1000]"
>>> 10 loops, best of 3: 118 msec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*10000]"
>>> 10 loops, best of 3: 868 msec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*10000]"
>>> 10 loops, best of 3: 1.23 sec per loop

>>> python -m timeit "[list(map(float,k)) for k in [list(range(0,1000))]*100000]"
>>> 10 loops, best of 3: 9.2 sec per loop
>>> python -m timeit "[[float(y) for y in x] for x in [list(range(0,1000))]*100000]"
>>> 10 loops, best of 3: 12.7 sec per loop

enter image description here

From these test we can conclude that map has a performance benefit over list comprehension in this case. This is also applicable if you are trying to cast to either int or str. For small number of lists with less elements per list, the difference is negligible. For larger lists with more elements per list one might like to use map instead of list comprehension, but it totally depends on application needs.

However I personally find list comprehension to be more readable and idiomatic than map. It is a de-facto standard in python. Usually people are more proficient and comfortable(specially beginner) in using list comprehension than map.

How to append contents of multiple files into one file

You need the cat (short for concatenate) command, with shell redirection (>) into your output file

cat 1.txt 2.txt 3.txt > 0.txt

Creating a daemon in Linux

You cannot create a process in linux that cannot be killed. The root user (uid=0) can send a signal to a process, and there are two signals which cannot be caught, SIGKILL=9, SIGSTOP=19. And other signals (when uncaught) can also result in process termination.

You may want a more general daemonize function, where you can specify a name for your program/daemon, and a path to run your program (perhaps "/" or "/tmp"). You may also want to provide file(s) for stderr and stdout (and possibly a control path using stdin).

Here are the necessary includes:

#include <stdio.h>    //printf(3)
#include <stdlib.h>   //exit(3)
#include <unistd.h>   //fork(3), chdir(3), sysconf(3)
#include <signal.h>   //signal(3)
#include <sys/stat.h> //umask(3)
#include <syslog.h>   //syslog(3), openlog(3), closelog(3)

And here is a more general function,

int
daemonize(char* name, char* path, char* outfile, char* errfile, char* infile )
{
    if(!path) { path="/"; }
    if(!name) { name="medaemon"; }
    if(!infile) { infile="/dev/null"; }
    if(!outfile) { outfile="/dev/null"; }
    if(!errfile) { errfile="/dev/null"; }
    //printf("%s %s %s %s\n",name,path,outfile,infile);
    pid_t child;
    //fork, detach from process group leader
    if( (child=fork())<0 ) { //failed fork
        fprintf(stderr,"error: failed fork\n");
        exit(EXIT_FAILURE);
    }
    if (child>0) { //parent
        exit(EXIT_SUCCESS);
    }
    if( setsid()<0 ) { //failed to become session leader
        fprintf(stderr,"error: failed setsid\n");
        exit(EXIT_FAILURE);
    }

    //catch/ignore signals
    signal(SIGCHLD,SIG_IGN);
    signal(SIGHUP,SIG_IGN);

    //fork second time
    if ( (child=fork())<0) { //failed fork
        fprintf(stderr,"error: failed fork\n");
        exit(EXIT_FAILURE);
    }
    if( child>0 ) { //parent
        exit(EXIT_SUCCESS);
    }

    //new file permissions
    umask(0);
    //change to path directory
    chdir(path);

    //Close all open file descriptors
    int fd;
    for( fd=sysconf(_SC_OPEN_MAX); fd>0; --fd )
    {
        close(fd);
    }

    //reopen stdin, stdout, stderr
    stdin=fopen(infile,"r");   //fd=0
    stdout=fopen(outfile,"w+");  //fd=1
    stderr=fopen(errfile,"w+");  //fd=2

    //open syslog
    openlog(name,LOG_PID,LOG_DAEMON);
    return(0);
}

Here is a sample program, which becomes a daemon, hangs around, and then leaves.

int
main()
{
    int res;
    int ttl=120;
    int delay=5;
    if( (res=daemonize("mydaemon","/tmp",NULL,NULL,NULL)) != 0 ) {
        fprintf(stderr,"error: daemonize failed\n");
        exit(EXIT_FAILURE);
    }
    while( ttl>0 ) {
        //daemon code here
        syslog(LOG_NOTICE,"daemon ttl %d",ttl);
        sleep(delay);
        ttl-=delay;
    }
    syslog(LOG_NOTICE,"daemon ttl expired");
    closelog();
    return(EXIT_SUCCESS);
}

Note that SIG_IGN indicates to catch and ignore the signal. You could build a signal handler that can log signal receipt, and set flags (such as a flag to indicate graceful shutdown).

The type initializer for 'System.Data.Entity.Internal.AppConfig' threw an exception

I had the duplicit definition of connection string in my WCF service. I was able to debug the service and to see the inner error message (not displayed by default):

ConfigurationErrorsException: The entry 'xxxEntities' has 
already been added. (C:\Users\WcfService\web.config line 35). 

which was after web.config transformation (note duplicit values)

<connectionStrings>
    <add name="xxxEntities" connectionString="metadata=res://*/ ...
    <add name="xxxEntities" connectionString="metadata=res://*/ ...

Hence removing unwanted connection string solved my problem.

CSV new-line character seen in unquoted field error

This worked for me on OSX.

# allow variable to opened as files
from io import StringIO

# library to map other strange (accented) characters back into UTF-8
from unidecode import unidecode

# cleanse input file with Windows formating to plain UTF-8 string
with open(filename, 'rb') as fID:
    uncleansedBytes = fID.read()
    # decode the file using the correct encoding scheme
    # (probably this old windows one) 
    uncleansedText = uncleansedBytes.decode('Windows-1252')

    # replace carriage-returns with new-lines
    cleansedText = uncleansedText.replace('\r', '\n')

    # map any other non UTF-8 characters into UTF-8
    asciiText = unidecode(cleansedText)

# read each line of the csv file and store as an array of dicts, 
# use first line as field names for each dict. 
reader = csv.DictReader(StringIO(cleansedText))
for line_entry in reader:
    # do something with your read data 

How to read one single line of csv data in Python?

you could get just the first row like:

with open('some.csv', newline='') as f:
  csv_reader = csv.reader(f)
  csv_headings = next(csv_reader)
  first_line = next(csv_reader)

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

Check which version of Entity Framework reference you have in your References and make sure that it matches with your configSections node in Web.config file. In my case it was pointing to version 5.0.0.0 in my configSections and my reference was 6.0.0.0. I just changed it and it worked...

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

Python check if list items are integers?

The usual way to check whether something can be converted to an int is to try it and see, following the EAFP principle:

try:
    int_value = int(string_value)
except ValueError:
    # it wasn't an int, do something appropriate
else:
    # it was an int, do something appropriate

So, in your case:

for item in mylist:
    try:
        int_value = int(item)
    except ValueError:
        pass
    else:
        mynewlist.append(item) # or append(int_value) if you want numbers

In most cases, a loop around some trivial code that ends with mynewlist.append(item) can be turned into a list comprehension, generator expression, or call to map or filter. But here, you can't, because there's no way to put a try/except into an expression.

But if you wrap it up in a function, you can:

def raises(func, *args, **kw):
    try:
        func(*args, **kw)
    except:
        return True
    else:
        return False

mynewlist = [item for item in mylist if not raises(int, item)]

… or, if you prefer:

mynewlist = filter(partial(raises, int), item)

It's cleaner to use it this way:

def raises(exception_types, func, *args, **kw):
    try:
        func(*args, **kw)
    except exception_types:
        return True
    else:
        return False

This way, you can pass it the exception (or tuple of exceptions) you're expecting, and those will return True, but if any unexpected exceptions are raised, they'll propagate out. So:

mynewlist = [item for item in mylist if not raises(ValueError, int, item)]

… will do what you want, but:

mynewlist = [item for item in mylist if not raises(ValueError, item, int)]

… will raise a TypeError, as it should.

How to return dictionary keys as a list in Python?

You can also use a list comprehension:

>>> newdict = {1:0, 2:0, 3:0}
>>> [k  for  k in  newdict.keys()]
[1, 2, 3]

Or, shorter,

>>> [k  for  k in  newdict]
[1, 2, 3]

Note: Order is not guaranteed on versions under 3.7 (ordering is still only an implementation detail with CPython 3.6).

How to append multiple items in one line in Python

mylist = [1,2,3]

def multiple_appends(listname, *element):
    listname.extend(element)

multiple_appends(mylist, 4, 5, "string", False)
print(mylist)

OUTPUT:

[1, 2, 3, 4, 5, 'string', False]

How to use python numpy.savetxt to write strings and float number to an ASCII file?

You have to specify the format (fmt) of you data in savetxt, in this case as a string (%s):

num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s") 

The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.

Measuring code execution time

Example for how one might use the Stopwatch class in VB.NET.

Dim Stopwatch As New Stopwatch

Stopwatch.Start()
            ''// Test Code
Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)

Stopwatch.Restart()            
           ''// Test Again

Stopwatch.Stop()
Console.WriteLine(Stopwatch.Elapsed.ToString)

PHP: How to get referrer URL?

$_SERVER['HTTP_REFERER'];

But if you run a file (that contains the above code) by directly hitting the URL in the browser then you get the following error.

Notice: Undefined index: HTTP_REFERER

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

How to remove carriage return and newline from a variable in shell script

Because the file you source ends lines with carriage returns, the contents of $testVar are likely to look like this:

$ printf '%q\n' "$testVar"
$'value123\r'

(The first line's $ is the shell prompt; the second line's $ is from the %q formatting string, indicating $'' quoting.)

To get rid of the carriage return, you can use shell parameter expansion and ANSI-C quoting (requires Bash):

testVar=${testVar//$'\r'}

Which should result in

$ printf '%q\n' "$testVar"
value123

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

No need for a StringBuilder:

string path = @"c:\hereIAm.txt";
if (!File.Exists(path)) 
{
    // Create a file to write to.
    using (StreamWriter sw = File.CreateText(path)) 
    {
        sw.WriteLine("Here");
        sw.WriteLine("I");
        sw.WriteLine("am.");
    }    
} 

But of course you can use the StringBuilder to create all lines and write them to the file at once.

sw.Write(stringBuilder.ToString());

StreamWriter.Write Method (String) (.NET Framework 1.1)

Writing Text to a File (.NET Framework 1.1)

notifyDataSetChange not working from custom adapter

I had the same problem using ListAdapter

I let Android Studio implement methods for me and this is what I got:

public class CustomAdapter implements ListAdapter {
    ...
    @Override
    public void registerDataSetObserver(DataSetObserver observer) {

    }

    @Override
    public void unregisterDataSetObserver(DataSetObserver observer) {

    }
    ...
}

The problem is that these methods do not call super implementations so notifyDataSetChange is never called.

Either remove these overrides manually or add super calls and it should work again.

@Override
public void registerDataSetObserver(DataSetObserver observer) {
    super.registerDataSetObserver(observer);
}

@Override
public void unregisterDataSetObserver(DataSetObserver observer) {
    super.unregisterDataSetObserver(observer);
}

C# Foreach statement does not contain public definition for GetEnumerator

You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

Your code also seems a bit strange, like you are nesting lists?

_csv.Error: field larger than field limit (131072)

Find the cqlshrc file usually placed in .cassandra directory.

In that file append,

[csv]
field_size_limit = 1000000000

AngularJS is rendering <br> as text not as a newline

I could be wrong because I've never used Angular, but I believe you are probably using ng-bind, which will create just a TextNode.

You will want to use ng-bind-html instead.

http://docs.angularjs.org/api/ngSanitize.directive:ngBindHtml

Update: It looks like you'll need to use ng-bind-html-unsafe='q.category'

http://docs.angularjs.org/api/ng.directive:ngBindHtmlUnsafe

Here's a demo:

http://jsfiddle.net/VFVMv/

Model backing a DB Context has changed; Consider Code First Migrations

In my case this error was caused by the existence of the _MigrationsHistory table in the database. Deleting that table fixed the problem. Not sure how that table got into our test environment database.

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Can't access Eclipse marketplace

If you're able to successfully load a page from Eclipses internal web browser (by going to "Window"=>"Show View"=>"Other"=>"Internal Web Browser" and trying to open a page) BUT installing software from the eclipse marketplace and the "Help"=>"Install New Software" window are not working then this fix may help you (worked for me on a Windows 7 machine):

  1. Go to "Window"=>"Preferences"=>"General"=>"Network Connections" and set the Active Provider to "Native".
  2. Go into the Windows Control pannel and search firewall. Then select "Allow Program Through Windows Firewall" and click "Allow Other Program..." and add your eclipse installation.

enter image description here enter image description here

  1. Restart Eclipse and try refreshing a repository on the "Help"=>"Install New Software" window. It was able to successfull grab it for me.

Python - Join with newline

You have to print it:

In [22]: "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
Out[22]: 'I\nwould\nexpect\nmultiple\nlines'

In [23]: print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines

How to append a newline to StringBuilder

It should be

r.append("\n");

But I recommend you to do as below,

r.append(System.getProperty("line.separator"));

System.getProperty("line.separator") gives you system-dependent newline in java. Also from Java 7 there's a method that returns the value directly: System.lineSeparator()

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

C# An established connection was aborted by the software in your host machine

An established connection was aborted by the software in your host machine

That is a boiler-plate error message, it comes out of Windows. The underlying error code is WSAECONNABORTED. Which really doesn't mean more than "connection was aborted". You have to be a bit careful about the "your host machine" part of the phrase. In the vast majority of Windows application programs, it is indeed the host that the desktop app is connected to that aborted the connection. Usually a server somewhere else.

The roles are reversed however when you implement your own server. Now you need to read the error message as "aborted by the application at the other end of the wire". Which is of course not uncommon when you implement a server, client programs that use your server are not unlikely to abort a connection for whatever reason. It can mean that a fire-wall or a proxy terminated the connection but that's not very likely since they typically would not allow the connection to be established in the first place.

You don't really know why a connection was aborted unless you have insight what is going on at the other end of the wire. That's of course hard to come by. If your server is reachable through the Internet then don't discount the possibility that you are being probed by a port scanner. Or your customers, looking for a game cheat.

cannot convert data (type interface {}) to type string: need type assertion

Type Assertion

This is known as type assertion in golang, and it is a common practice.

Here is the explanation from a tour of go:

A type assertion provides access to an interface value's underlying concrete value.

t := i.(T)

This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.

If i does not hold a T, the statement will trigger a panic.

To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.

t, ok := i.(T)

If i holds a T, then t will be the underlying value and ok will be true.

If not, ok will be false and t will be the zero value of type T, and no panic occurs.

NOTE: value i should be interface type.

Pitfalls

Even if i is an interface type, []i is not interface type. As a result, in order to convert []i to its value type, we have to do it individually:

// var items []i
for _, item := range items {
    value, ok := item.(T)
    dosomethingWith(value)
}

Performance

As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.

newline character in c# string

They might be just a \r or a \n. I just checked and the text visualizer in VS 2010 displays both as newlines as well as \r\n.

This string

string test = "blah\r\nblah\rblah\nblah";

Shows up as

blah
blah
blah
blah

in the text visualizer.

So you could try

string modifiedString = originalString
    .Replace(Environment.NewLine, "<br />")
    .Replace("\r", "<br />")
    .Replace("\n", "<br />");

Entity Framework Provider type could not be loaded?

I checked Debug Output window in Unit Test project. EntityFramework.SqlServer.dll was not loaded. After adding it to the bin folder tests were run successfully.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

\n or \n in php echo not print

PHP only interprets escaped characters (with the exception of the escaped backslash \\ and the escaped single quote \') when in double quotes (")

This works (results in a newline):

"\n"

This does not result in a newline:

'\n'

Writelines writes lines without newline, Just fills the file

As others have noted, writelines is a misnomer (it ridiculously does not add newlines to the end of each line).

To do that, explicitly add it to each line:

with open(dst_filename, 'w') as f:
    f.writelines(s + '\n' for s in lines)

how to write an array to a file Java

Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:

public static void write (String filename, int[]x) throws IOException{
  BufferedWriter outputWriter = null;
  outputWriter = new BufferedWriter(new FileWriter(filename));
  for (int i = 0; i < x.length; i++) {
    // Maybe:
    outputWriter.write(x[i]+"");
    // Or:
    outputWriter.write(Integer.toString(x[i]);
    outputWriter.newLine();
  }
  outputWriter.flush();  
  outputWriter.close();  
}

If you just want to print out the array like [1, 2, 3, ....], you can replace the loop with this one liner:

outputWriter.write(Arrays.toString(x));

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Remove all newlines from inside a string

strip only removes characters from the beginning and end of a string. You want to use replace:

str2 = str.replace("\n", "")
re.sub('\s{2,}', ' ', str) # To remove more than one space 

How to use css style in php

I guess you have your css code in a database & you want to render a php file as a CSS. If that is the case...

In your html page:

<html>
<head>
   <!- head elements (Meta, title, etc) -->

   <!-- Link your php/css file -->
   <link rel="stylesheet" href="style.php" media="screen">
<head>

Then, within style.php file:

<?php
/*** set the content type header ***/
/*** Without this header, it wont work ***/
header("Content-type: text/css");


$font_family = 'Arial, Helvetica, sans-serif';
$font_size = '0.7em';
$border = '1px solid';
?>

table {
margin: 8px;
}

th {
font-family: <?=$font_family?>;
font-size: <?=$font_size?>;
background: #666;
color: #FFF;
padding: 2px 6px;
border-collapse: separate;
border: <?=$border?> #000;
}

td {
font-family: <?=$font_family?>;
font-size: <?=$font_size?>;
border: <?=$border?> #DDD;
}

Have fun!

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

Error happens in your function declarations,look the following sentence!You need a semicolon!


AST_NODE* Statement(AST_NODE* node)

Representing EOF in C code?

The answer is NO, but...

You may confused because of the behavior of fgets()

From http://www.cplusplus.com/reference/cstdio/fgets/ :

Reads characters from stream and stores them as a C string into str until (num-1) characters have been read or either a newline or the end-of-file is reached, whichever happens first.

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

How to read a file without newlines?

temp = open(filename,'r').read().splitlines()

Extracting substrings in Go

Go strings are not null terminated, and to remove the last char of a string you can simply do:

s = s[:len(s)-1]

How can I suppress the newline after a print statement?

The question asks: "How can it be done in Python 3?"

Use this construct with Python 3.x:

for item in [1,2,3,4]:
    print(item, " ", end="")

This will generate:

1  2  3  4

See this Python doc for more information:

Old: print x,           # Trailing comma suppresses newline
New: print(x, end=" ")  # Appends a space instead of a newline

--

Aside:

in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,

In [21]: print('this','is', 'a', 'test')  # default single space between items
this is a test

In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest

In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test

I want to exception handle 'list index out of range.'

A ternary will suffice. change:

gotdata = dlist[1]

to

gotdata = dlist[1] if len(dlist) > 1 else 'null'

this is a shorter way of expressing

if len(dlist) > 1:
    gotdata = dlist[1]
else: 
    gotdata = 'null'

Newline in markdown table?

Use an HTML line break (<br />) to force a line break within a table cell:

|Something|Something else<br />that's rather long|Something else|

Add CSS3 transition expand/collapse

OMG, I tried to find a simple solution to this for hours. I knew the code was simple but no one provided me what I wanted. So finally got to work on some example code and made something simple that anyone can use no JQuery required. Simple javascript and css and html. In order for the animation to work you have to set the height and width or the animation wont work. Found that out the hard way.

<script>
        function dostuff() {
            if (document.getElementById('MyBox').style.height == "0px") {

                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 200px; width: 200px; transition: all 2s ease;"); 
            }
            else {
                document.getElementById('MyBox').setAttribute("style", "background-color: #45CEE0; height: 0px; width: 0px; transition: all 2s ease;"); 
             }
        }
    </script>
    <div id="MyBox" style="height: 0px; width: 0px;">
    </div>

    <input type="button" id="buttontest" onclick="dostuff()" value="Click Me">

"echo -n" prints "-n"

bash has a "built-in" command called "echo":

$ type echo
echo is a shell builtin

Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo, as opposed to interpreting echo and executing it):

$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21  2011 /bin/echo

The behavior of either echo's WRT to \c and -n varies. Your best bet is to use printf, which is available on four different *NIX flavors that I looked at:

$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

This one normally catches me when I run from IIS and the app pool for the default site is set to .NET version 2.0. When using IIS from visual studio it creates a virtual directory but still runs under the default site's app pool. If using the build in web server, right click on your web project, go to properties and make sure you're running it under the right version of .NET. On IIS check the .NET version on your app pool.

Following on from my last comment about how the project was created - are you correctly including the assemblies, as below (taken from the default web.config file generated by the MVC3 project template in VS10):

<compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </assemblies>
</compilation>

Replace comma with newline in sed on MacOS?

Though I am late to this post, just updating my findings. This answer is only for Mac OS X.

$ sed 's/new/
> /g' m1.json > m2.json
sed: 1: "s/new/
/g": unescaped newline inside substitute pattern

In the above command I tried with Shift+Enter to add new line which didn't work. So this time I tried with "escaping" the "unescaped newline" as told by the error.

$ sed 's/new/\
> /g' m1.json > m2.json 

Worked! (in Mac OS X 10.9.3)

Strip spaces/tabs/newlines - python

The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.

Here's what I do:

myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')

or if you had a bunch of things to remove such that a single line solution would be gratuitously long:

removal_list = [' ', '\t', '\n']
for s in removal_list:
  myString = myString.replace(s, '')

How do I add a newline using printf?

To write a newline use \n not /n the latter is just a slash and a n

Error: Could not find or load main class in intelliJ IDE

Follow these steps

  1. Go to run
  2. Go to edit configurations
  3. Click the green colored + sign in top left corner
  4. Select the type you are working, for instance "Applications"
  5. Now enter the name of the class which you want to run instead of unnamed
  6. Do the same where it is written Main class,just below it.

Yippee....your code will run:)

Breaking up long strings on multiple lines in Ruby without stripping newlines

I modified Zack's answer since I wanted spaces and interpolation but not newlines and used:

%W[
  It's a nice day "#{name}"
  for a walk!
].join(' ')

where name = 'fred' this produces It's a nice day "fred" for a walk!

Java - Convert image to Base64

You can create a large array and then copy it to a new array using System.arrayCopy

        int contentLength = 100000000;
        byte[] byteArray = new byte[contentLength];

        BufferedInputStream inputStream = new BufferedInputStream(connection.getInputStream());
        while ((bytesRead = inputStream.read()) != -1)
        {
            byteArray[count++] = (byte)bytesRead;
        }

        byte[] destArray = new byte[count];
        System.arraycopy(byteArray, 0, destArray , 0, count);

destArray will contain the information you want

Executing Javascript from Python

You can also use Js2Py which is written in pure python and is able to both execute and translate javascript to python. Supports virtually whole JavaScript even labels, getters, setters and other rarely used features.

import js2py

js = """
function escramble_758(){
var a,b,c
a='+1 '
b='84-'
a+='425-'
b+='7450'
c='9'
document.write(a+c+b)
}
escramble_758()
""".replace("document.write", "return ")

result = js2py.eval_js(js)  # executing JavaScript and converting the result to python string 

Advantages of Js2Py include portability and extremely easy integration with python (since basically JavaScript is being translated to python).

To install:

pip install js2py

How to Remove Line Break in String

mystring = Replace(mystring, Chr(10), "")

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

What are the differences between char literals '\n' and '\r' in Java?

The above answers provided are perfect. The LF(\n), CR(\r) and CRLF(\r\n) characters are platform dependent. However, the interpretation for these characters is not only defined by the platforms but also the console that you are using. In Intellij console (Windows), this \r character in this statement System.out.print("Happ\ry"); produces the output y. But, if you use the terminal (Windows), you will get yapp as the output.

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

Trying to embed newline in a variable in bash

There are three levels at which a newline could be inserted in a variable.
Well ..., technically four, but the first two are just two ways to write the newline in code.

1.1. At creation.

The most basic is to create the variable with the newlines already.
We write the variable value in code with the newlines already inserted.

$ var="a
> b
> c"
$ echo "$var"
a
b
c

Or, inside an script code:

var="a
b
c"

Yes, that means writing Enter where needed in the code.

1.2. Create using shell quoting.

The sequence $' is an special shell expansion in bash and zsh.

var=$'a\nb\nc'

The line is parsed by the shell and expanded to « var="anewlinebnewlinec" », which is exactly what we want the variable var to be.
That will not work on older shells.

2. Using shell expansions.

It is basically a command expansion with several commands:

  1. echo -e

    var="$( echo -e "a\nb\nc" )"
    
  2. The bash and zsh printf '%b'

    var="$( printf '%b' "a\nb\nc" )"
    
  3. The bash printf -v

    printf -v var '%b' "a\nb\nc"
    
  4. Plain simple printf (works on most shells):

    var="$( printf 'a\nb\nc' )"
    

3. Using shell execution.

All the commands listed in the second option could be used to expand the value of a var, if that var contains special characters.
So, all we need to do is get those values inside the var and execute some command to show:

var="a\nb\nc"                 # var will contain the characters \n not a newline.

echo -e "$var"                # use echo.
printf "%b" "$var"            # use bash %b in printf.
printf "$var"                 # use plain printf.

Note that printf is somewhat unsafe if var value is controlled by an attacker.

sqlplus error on select from external table: ORA-29913: error in executing ODCIEXTTABLEOPEN callout

We had this error on Oracle RAC 11g on Windows, and the solution was to create the same OS directory tree and external file on both nodes.

How to add minutes to my Date

Once you have you date parsed, I use this utility function to add hours, minutes or seconds:

public class DateTimeUtils {
    private static final long ONE_HOUR_IN_MS = 3600000;
    private static final long ONE_MIN_IN_MS = 60000;
    private static final long ONE_SEC_IN_MS = 1000;

    public static Date sumTimeToDate(Date date, int hours, int mins, int secs) {
        long hoursToAddInMs = hours * ONE_HOUR_IN_MS;
        long minsToAddInMs = mins * ONE_MIN_IN_MS;
        long secsToAddInMs = secs * ONE_SEC_IN_MS;
        return new Date(date.getTime() + hoursToAddInMs + minsToAddInMs + secsToAddInMs);
    }
}

Be careful when adding long periods of time, 1 day is not always 24 hours (daylight savings-type adjustments, leap seconds and so on), Calendar is recommended for that.

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

log4net hierarchy and logging levels

Its true the official documentation (Apache log4net™ Manual - Introduction) states there are the following levels...

  • ALL
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL
  • OFF

... but oddly when I view assembly log4net.dll, v1.2.15.0 sealed class log4net.Core.Level I see the following levels defined...

public static readonly Level Alert;
public static readonly Level All;
public static readonly Level Critical;
public static readonly Level Debug;
public static readonly Level Emergency;
public static readonly Level Error;
public static readonly Level Fatal;
public static readonly Level Fine;
public static readonly Level Finer;
public static readonly Level Finest;
public static readonly Level Info;
public static readonly Level Log4Net_Debug;
public static readonly Level Notice;
public static readonly Level Off;
public static readonly Level Severe;
public static readonly Level Trace;
public static readonly Level Verbose;
public static readonly Level Warn;

I have been using TRACE in conjunction with PostSharp OnBoundaryEntry and OnBoundaryExit for a long time. I wonder why these other levels are not in the documentation. Furthermore, what is the true priority of all these levels?

HTTP could not register URL http://+:8000/HelloWCF/. Your process does not have access rights to this namespace

You need some Administrator privilege to your account if your machine in local area network then you apply some administrator privilege to your User else you should start ide as Administrator...

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

When the callee throws an exception i.e. void showfile() throws java.io.IOException the caller should handle it or throw it again.

And also learn naming conventions. A class name should start with a capital letter.

Drawing a simple line graph in Java

Override the paintComponent method of your panel so you can custom draw. Like this:

@Override
public void paintComponent(Graphics g) {
    Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
    //now do the drawing here
    ...
}

Implementing a slider (SeekBar) in Android

For future readers!

Starting from material components android 1.2.0-alpha01, you have slider component

ex:

<com.google.android.material.slider.Slider
        android:id="@+id/slider"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:valueFrom="20f"
        android:valueTo="70f"
        android:stepSize="10" />

How to add a new line in textarea element?

My .replace()function using the patterns described on the other answers did not work. The pattern that worked for my case was:

var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'&#13;&#10;');

// str: "Test&#13;&#10;&#13;&#10;Test&#13;&#10;Test"

write newline into a file

if(!file3.exists()){
    file3.createNewFile();
}
FileOutputStream fop=new FileOutputStream(file3,true);
if(nodeValue!=null) fop.write(nodeValue.getBytes());

fop.write("\n".getBytes());

fop.flush();
fop.close();

You need to add a newline at the end of each write.

Echo newline in Bash prints literal \n

If you're writing scripts and will be echoing newlines as part of other messages several times, a nice cross-platform solution is to put a literal newline in a variable like so:

newline='
'

echo "first line$newlinesecond line"
echo "Error: example error message n${newline}${usage}" >&2 #requires usage to be defined

How to read a text file into a string variable and strip newlines?

Try the following:

with open('data.txt', 'r') as myfile:
    data = myfile.read()

    sentences = data.split('\\n')
    for sentence in sentences:
        print(sentence)

Caution: It does not remove the \n. It is just for viewing the text as if there were no \n

Regex to match any character including new lines

You want to use "multiline".

$string =~ /(START)(.+?)(END)/m;

How do you divide each element in a list by an int?

The way you tried first is actually directly possible with numpy:

import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt

If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise using numpy.

Android: how to draw a border to a LinearLayout

Do you really need to do that programmatically?

Just considering the title: You could use a ShapeDrawable as android:background…

For example, let's define res/drawable/my_custom_background.xml as:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
  <corners
      android:radius="2dp"
      android:topRightRadius="0dp"
      android:bottomRightRadius="0dp"
      android:bottomLeftRadius="0dp" />
  <stroke
      android:width="1dp"
      android:color="@android:color/white" />
</shape>

and define android:background="@drawable/my_custom_background".

I've not tested but it should work.

Update:

I think that's better to leverage the xml shape drawable resource power if that fits your needs. With a "from scratch" project (for android-8), define res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/border"
    android:padding="10dip" >
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
    [... more TextView ...]
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, SOnich"
        />
</LinearLayout>

and a res/drawable/border.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
   <stroke
        android:width="5dip"
        android:color="@android:color/white" />
</shape>

Reported to work on a gingerbread device. Note that you'll need to relate android:padding of the LinearLayout to the android:width shape/stroke's value. Please, do not use @android:color/white in your final application but rather a project defined color.

You could apply android:background="@drawable/border" android:padding="10dip" to each of the LinearLayout from your provided sample.

As for your other posts related to display some circles as LinearLayout's background, I'm playing with Inset/Scale/Layer drawable resources (see Drawable Resources for further information) to get something working to display perfect circles in the background of a LinearLayout but failed at the moment…

Your problem resides clearly in the use of getBorder.set{Width,Height}(100);. Why do you do that in an onClick method?

I need further information to not miss the point: why do you do that programmatically? Do you need a dynamic behavior? Your input drawables are png or ShapeDrawable is acceptable? etc.

To be continued (maybe tomorrow and as soon as you provide more precisions on what you want to achieve)…

Choose newline character in Notepad++

"Edit -> EOL Conversion". You can convert to Windows/Linux/Mac EOL there. The current format is displayed in the status bar.

Javascript how to split newline

Here is example with console.log instead of alert(). It is more convenient :)

var parse = function(){
  var str = $('textarea').val();
  var results = str.split("\n");
  $.each(results, function(index, element){
    console.log(element);
  });
};

$(function(){
  $('button').on('click', parse);
});

You can try it here

How to read from input until newline is found using scanf()?

//increase char array size if u want take more no. of characters.

#include <stdio.h>
int main()
{
    char s[10],s1[10];
    scanf("\n");//imp for below statement to work
    scanf("%[^\n]%c",s);//to take input till the you click enter
    scanf("%s",s1);//to take input till a space
    printf("%s",s);
    printf("%s",s1);
    return 0;
}

Remove trailing newline from the elements of a string list

All other answers, and mainly about list comprehension, are great. But just to explain your error:

strip_list = []
for lengths in range(1,20):
    strip_list.append(0) #longest word in the text file is 20 characters long
for a in lines:
    strip_list.append(lines[a].strip())

a is a member of your list, not an index. What you could write is this:

[...]
for a in lines:
    strip_list.append(a.strip())

Another important comment: you can create an empty list this way:

strip_list = [0] * 20

But this is not so useful, as .append appends stuff to your list. In your case, it's not useful to create a list with defaut values, as you'll build it item per item when appending stripped strings.

So your code should be like:

strip_list = []
for a in lines:
    strip_list.append(a.strip())

But, for sure, the best one is this one, as this is exactly the same thing:

stripped = [line.strip() for line in lines]

In case you have something more complicated than just a .strip, put this in a function, and do the same. That's the most readable way to work with lists.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

The 'packages' element is not declared

Oh ok - now I get it. You can ignore this one - the XML for this is just not correct - the packages-element is indeed not declared (there is no reference to a schema or whatever). I think this is a known minor bug that won't do a thing because only NuGet will use this.

See this similar question also.

Use CSS to remove the space between images

I prefer do like this

img { float: left; }

to remove the space between images

How to remove newlines from beginning and end of a string?

This Java code does exactly what is asked in the title of the question, that is "remove newlines from beginning and end of a string-java":

String.replaceAll("^[\n\r]", "").replaceAll("[\n\r]$", "")

Remove newlines only from the end of the line:

String.replaceAll("[\n\r]$", "")

Remove newlines only from the beginning of the line:

String.replaceAll("^[\n\r]", "")

Why does "return list.sort()" return None, not the list?

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).

Can you have multiline HTML5 placeholder text in a <textarea>?

With Vue.js:

<textarea name="story" :placeholder="'Enter story\n next line\n more'"></textarea>

identifier "string" undefined?

#include <string> would be the correct c++ include, also you need to specify the namespace with std::string or more generally with using namespace std;

Windows batch: echo without new line

You can suppress the new line by using the set /p command. The set /p command does not recognize a space, for that you can use a dot and a backspace character to make it recognize it. You can also use a variable as a memory and store what you want to print in it, so that you can print the variable instead of the sentence. For example:

@echo off
setlocal enabledelayedexpansion
for /f %%a in ('"prompt $H & for %%b in (1) do rem"') do (set "bs=%%a")
cls
set "var=Hello World! :)"
set "x=0"

:loop
set "display=!var:~%x%,1!"
<nul set /p "print=.%bs%%display%"
ping -n 1 localhost >nul
set /a "x=%x% + 1"
if "!var:~%x%,1!" == "" goto end
goto loop

:end
echo.
pause
exit

In this way you can print anything without a new line. I have made the program to print the characters one by one, but you can use words too instead of characters by changing the loop.

In the above example I used "enabledelayedexpansion" so the set /p command does not recognize "!" character and prints a dot instead of that. I hope that you don't have the use of the exclamation mark "!" ;)

How to make a deep copy of Java ArrayList

public class Person{

    String s;
    Date d;
    ...

    public Person clone(){
        Person p = new Person();
        p.s = this.s.clone();
        p.d = this.d.clone();
        ...
        return p;
    }
}

In your executing code:

ArrayList<Person> clone = new ArrayList<Person>();
for(Person p : originalList)
    clone.add(p.clone());

Linq Query Group By and Selecting First Items

var results = list.GroupBy(x => x.Category)
            .Select(g => g.OrderBy(x => x.SortByProp).FirstOrDefault());

For those wondering how to do this for groups that are not necessarily sorted correctly, here's an expansion of this answer that uses method syntax to customize the sort order of each group and hence get the desired record from each.

Note: If you're using LINQ-to-Entities you will get a runtime exception if you use First() instead of FirstOrDefault() here as the former can only be used as a final query operation.

Python: maximum recursion depth exceeded while calling a Python object

Python don't have a great support for recursion because of it's lack of TRE (Tail Recursion Elimination).

This means that each call to your recursive function will create a function call stack and because there is a limit of stack depth (by default is 1000) that you can check out by sys.getrecursionlimit (of course you can change it using sys.setrecursionlimit but it's not recommended) your program will end up by crashing when it hits this limit.

As other answer has already give you a much nicer way for how to solve this in your case (which is to replace recursion by simple loop) there is another solution if you still want to use recursion which is to use one of the many recipes of implementing TRE in python like this one.

N.B: My answer is meant to give you more insight on why you get the error, and I'm not advising you to use the TRE as i already explained because in your case a loop will be much better and easy to read.

Replace all whitespace characters

We can also use this if we want to change all multiple joined blank spaces with a single character:

str.replace(/\s+/g,'X');

See it in action here: https://regex101.com/r/d9d53G/1

Explanation

/ \s+ / g

  • \s+ matches any whitespace character (equal to [\r\n\t\f\v ])
  • + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

  • Global pattern flags
    • g modifier: global. All matches (don't return after first match)

Converting newline formatting from Mac to Windows

vim also can convert files from UNIX to DOS format. For example:

vim hello.txt <<EOF
:set fileformat=dos
:wq
EOF

Efficient way to remove ALL whitespace from String?

My solution is to use Split and Join and it is surprisingly fast, in fact the fastest of the top answers here.

str = string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));

Timings for 10,000 loop on simple string with whitespace inc new lines and tabs

  • split/join = 60 milliseconds
  • linq chararray = 94 milliseconds
  • regex = 437 milliseconds

Improve this by wrapping it up in method to give it meaning, and also make it an extension method while we are at it ...

public static string RemoveWhitespace(this string str) {
    return string.Join("", str.Split(default(string[]), StringSplitOptions.RemoveEmptyEntries));
}

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

How can I replace newline or \r\n with <br/>?

There is already the nl2br() function that inserts <br> tags before new line characters:

Example (codepad):

<?php
// Won't work
$desc = 'Line one\nline two';
// Should work
$desc2 = "Line one\nline two";

echo nl2br($desc);
echo '<br/>';
echo nl2br($desc2);
?>

But if it is still not working make sure the text $desciption is double-quoted.

That's because single quotes do not 'expand' escape sequences such as \n comparing to double quoted strings. Quote from PHP documentation:

Note: Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

Multiline TextBox multiple newline

While dragging the TextBox it self Press F4 for Properties and under the Textmode set to Multiline, The representation of multiline to a text box is it can be sizable at 6 sides. And no need to include any newline characters for getting multiline. May be you set it multiline but you dint increased the size of the Textbox at design time.

No newline at end of file

The reason this convention came into practice is because on UNIX-like operating systems a newline character is treated as a line terminator and/or message boundary (this includes piping between processes, line buffering, etc.).

Consider, for example, that a file with just a newline character is treated as a single, empty line. Conversely, a file with a length of zero bytes is actually an empty file with zero lines. This can be confirmed according to the wc -l command.

Altogether, this behavior is reasonable because there would be no other way to distinguish between an empty text file versus a text file with a single empty line if the \n character was merely a line-separator rather than a line-terminator. Thus, valid text files should always end with a newline character. The only exception is if the text file is intended to be empty (no lines).

How to enter newline character in Oracle?

According to the Oracle PLSQL language definition, a character literal can contain "any printable character in the character set". https://docs.oracle.com/cd/A97630_01/appdev.920/a96624/02_funds.htm#2876

@Robert Love's answer exhibits a best practice for readable code, but you can also just type in the linefeed character into the code. Here is an example from a Linux terminal using sqlplus:

SQL> set serveroutput on
SQL> begin   
  2  dbms_output.put_line( 'hello' || chr(10) || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

SQL> begin
  2  dbms_output.put_line( 'hello
  3  world' );
  4  end;
  5  /
hello
world

PL/SQL procedure successfully completed.

Instead of the CHR( NN ) function you can also use Unicode literal escape sequences like u'\0085' which I prefer because, well you know we are not living in 1970 anymore. See the equivalent example below:

SQL> begin
  2  dbms_output.put_line( 'hello' || u'\000A' || 'world' );
  3  end;
  4  /
hello
world

PL/SQL procedure successfully completed.

For fair coverage I guess it is worth noting that different operating systems use different characters/character sequences for end of line handling. You've got to have a think about the context in which your program output is going to be viewed or printed, in order to determine whether you are using the right technique.

  • Microsoft Windows: CR/LF or u'\000D\000A'
  • Unix (including Apple MacOS): LF or u'\000A'
  • IBM OS390: NEL or u'\0085'
  • HTML: '<BR>'
  • XHTML: '<br />'
  • etc. etc.

Web.Config Debug/Release

To make the transform work in development (using F5 or CTRL + F5) I drop ctt.exe (https://ctt.codeplex.com/) in the packages folder (packages\ConfigTransform\ctt.exe).

Then I register a pre- or post-build event in Visual Studio...

$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)connectionStrings.config" transform:"$(ProjectDir)connectionStrings.$(ConfigurationName).config" destination:"$(ProjectDir)connectionStrings.config"
$(SolutionDir)packages\ConfigTransform\ctt.exe source:"$(ProjectDir)web.config" transform:"$(ProjectDir)web.$(ConfigurationName).config" destination:"$(ProjectDir)web.config"

For the transforms I use SlowCheeta VS extension (https://visualstudiogallery.msdn.microsoft.com/69023d00-a4f9-4a34-a6cd-7e854ba318b5).

How to draw lines in Java

You need to create a class that extends Component. There you can override the paint method and put your painting code in:

package blah.whatever;

import java.awt.Component;
import java.awt.Graphics;

public class TestAWT extends Component {

/** @see java.awt.Component#paint(java.awt.Graphics) */
@Override
public void paint(Graphics g) {
    super.paint(g);
    g.drawLine(0,0,100,100);
    g.drawLine(10, 10, 20, 300);
    // more drawing code here...
}

}

Put this component into the GUI of your application. If you're using Swing, you need to extend JComponent and override paintComponent, instead.

As Helios mentioned, the painting code actually tells the system how your component looks like. The system will ask for this information (call your painting code) when it thinks it needs to be (re)painted, for example, if a window is moved in front of your component.

read input separated by whitespace(s) or newline...?

int main()
{
    int m;
    while(cin>>m)
    {
    }
}

This would read from standard input if it space separated or line separated .

How to set border on jPanel?

BorderLayout(int Gap, int Gap) or GridLayout(int Gap, int Gap, int Gap, int Gap)

why paint Border() inside paintComponent( ...)

    Border line, raisedbevel, loweredbevel, title, empty;
    line = BorderFactory.createLineBorder(Color.black);
    raisedbevel = BorderFactory.createRaisedBevelBorder();
    loweredbevel = BorderFactory.createLoweredBevelBorder();
    title = BorderFactory.createTitledBorder("");
    empty = BorderFactory.createEmptyBorder(4, 4, 4, 4);
    Border compound = BorderFactory.createCompoundBorder(empty, xxx);
    Color crl = (Color.blue);
    Border compound1 = BorderFactory.createCompoundBorder(empty, xxx);

Windows Application has stopped working :: Event Name CLR20r3

This is just because the application is built in non unicode language fonts and you are running the system on unicode fonts. change your default non unicode fonts to arabic by going in regional settings advanced tab in control panel. That will solve your problem.

Cannot read configuration file due to insufficient permissions

There is no problem with your web.config. Your web site runs under a process. In iis you can define the identity of that process. The identity that your web site's application pool runs as (Network Services, Local System, etc.), should have permission to access and read web.config file.

Update:

This updated answer is same as above, but a little longer and simpler and improved.

First of all: you don't have to change anything in your config file. It's OK. The problem is with windows file permissions.

This problems occurs because your application can not access and read web.config file.

Make the file accessible to IIS_IUSRS group. Just right click web.config and click properties, under security tab, add IIS_IUSRS.

So what is this IIS_IUSRS thing?

Your web site is like an exe file. Just like any exe file, it should be started by a user and it runs according to permissions assigned to that user.

When your site is started in IIS, Application Pool of your web site is associated with a user (Network Services, Local System, Etc. ...) (and can be changed in IIS)

So when you say IIS_IUSRS, it means any user (Network Services, Local System, Etc. ...) that your site is running as.

And as @Seph mentioned in comment below: If your computer is on a domain, remember that IIS_IUSRS group is a local group. Also make sure that when you're trying to find this user check the location it should be set to local computer and not a corporate domain.

How to overwrite the previous print to stdout in python?

@Mike DeSimone answer will probably work most of the time. But...

for x in ['abc', 1]:
    print '{}\r'.format(x),

-> 1bc

This is because the '\r' only goes back to the beginning of the line but doesn't clear the output.

EDIT: Better solution (than my old proposal below)

If POSIX support is enough for you, the following would clear the current line and leave the cursor at its beginning:

print '\x1b[2K\r',

It uses ANSI escape code to clear the terminal line. More info can be found in wikipedia and in this great talk.

Old answer

The (not so good) solution I've found looks like this:

last_x = ''
for x in ['abc', 1]:
    print ' ' * len(str(last_x)) + '\r',
    print '{}\r'.format(x),
    last_x = x

-> 1

One advantage is that it will work on windows too.

Failed to add a service. Service metadata may not be accessible. Make sure your service is running and exposing metadata.`

changing the Binding Type from wsHttpbinding to basichttp binding in the endpoint tag and from wsHttpbinding to mexhttpbinginding in metadata endpoint tag helped to overcome the error. Thank you...

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

How to split a string in Haskell?

In addition to the efficient and pre-built functions given in answers I'll add my own which are simply part of my repertory of Haskell functions I was writing to learn the language on my own time:

-- Correct but inefficient implementation
wordsBy :: String -> Char -> [String]
wordsBy s c = reverse (go s []) where
    go s' ws = case (dropWhile (\c' -> c' == c) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> c' /= c) rem)) ((takeWhile (\c' -> c' /= c) rem) : ws)

-- Breaks up by predicate function to allow for more complex conditions (\c -> c == ',' || c == ';')
wordsByF :: String -> (Char -> Bool) -> [String]
wordsByF s f = reverse (go s []) where
    go s' ws = case ((dropWhile (\c' -> f c')) s') of
        "" -> ws
        rem -> go ((dropWhile (\c' -> (f c') == False)) rem) (((takeWhile (\c' -> (f c') == False)) rem) : ws)

The solutions are at least tail-recursive so they won't incur a stack overflow.

How can I turn a DataTable to a CSV?

StringBuilder sb = new StringBuilder();
        SaveFileDialog fileSave = new SaveFileDialog();
        IEnumerable<string> columnNames = tbCifSil.Columns.Cast<DataColumn>().
                                          Select(column => column.ColumnName);
        sb.AppendLine(string.Join(",", columnNames));

        foreach (DataRow row in tbCifSil.Rows)
        {
            IEnumerable<string> fields = row.ItemArray.Select(field =>string.Concat("\"", field.ToString().Replace("\"", "\"\""), "\""));
            sb.AppendLine(string.Join(",", fields));
        }

        fileSave.ShowDialog();
        File.WriteAllText(fileSave.FileName, sb.ToString());

Android: how to refresh ListView contents?

In my understanding, if you want to refresh ListView immediately when data has changed, you should call notifyDataSetChanged() in RunOnUiThread().

private void updateData() {
    List<Data> newData = getYourNewData();
    mAdapter.setList(yourNewList);

    runOnUiThread(new Runnable() {
        @Override
        public void run() {
                mAdapter.notifyDataSetChanged();
        }
    });
}

How to write to Console.Out during execution of an MSTest test

Use the Debug.WriteLine. This will display your message in the Output window immediately. The only restriction is that you must run your test in Debug mode.

[TestMethod]
public void TestMethod1()
{
    Debug.WriteLine("Time {0}", DateTime.Now);
    System.Threading.Thread.Sleep(30000);
    Debug.WriteLine("Time {0}", DateTime.Now);
}

Output

enter image description here

Where does this come from: -*- coding: utf-8 -*-

This is so called file local variables, that are understood by Emacs and set correspondingly. See corresponding section in Emacs manual - you can define them either in header or in footer of file

Easiest way to ignore blank lines when reading a file in Python

I would stack generator expressions:

with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in) # All lines including the blank ones
    lines = (line for line in lines if line) # Non-blank lines

Now, lines is all of the non-blank lines. This will save you from having to call strip on the line twice. If you want a list of lines, then you can just do:

with open(filename) as f_in:
    lines = (line.rstrip() for line in f_in) 
    lines = list(line for line in lines if line) # Non-blank lines in a list

You can also do it in a one-liner (exluding with statement) but it's no more efficient and harder to read:

with open(filename) as f_in:
    lines = list(line for line in (l.strip() for l in f_in) if line)

Update:

I agree that this is ugly because of the repetition of tokens. You could just write a generator if you prefer:

def nonblank_lines(f):
    for l in f:
        line = l.rstrip()
        if line:
            yield line

Then call it like:

with open(filename) as f_in:
    for line in nonblank_lines(f_in):
        # Stuff

update 2:

with open(filename) as f_in:
    lines = filter(None, (line.rstrip() for line in f_in))

and on CPython (with deterministic reference counting)

lines = filter(None, (line.rstrip() for line in open(filename)))

In Python 2 use itertools.ifilter if you want a generator and in Python 3, just pass the whole thing to list if you want a list.

No newline after div?

This works the best, in my case, I tried it all

.div_class {
    clear: left;
}

adding line break

\n in c3 working correctly

using System; namespace testing2

public class Test { 
    public static void Main(string[] args) {
        Console.WriteLine("Enter your name");
        String s = Console.ReadLine();
        Console.WriteLine("Your name is " + s + "\n" + "Thank You");
    }
}

jQuery text() and newlines

It's the year 2015. The correct answer to this question at this point is to use CSS white-space: pre-line or white-space: pre-wrap. Clean and elegant. The lowest version of IE that supports the pair is 8.

https://css-tricks.com/almanac/properties/w/whitespace/

P.S. Until CSS3 become common you'd probably need to manually trim off initial and/or trailing white-spaces.

Printing without newline (print 'a',) prints a space, how to remove?

If you want them to show up one at a time, you can do this:

import time
import sys
for i in range(20):
    sys.stdout.write('a')
    sys.stdout.flush()
    time.sleep(0.5)

sys.stdout.flush() is necessary to force the character to be written each time the loop is run.

How to create a property for a List<T>

public class MyClass<T>
{
  private List<T> list;

  public List<T> MyList { get { return list; } set { list = value; } }
}

Then you can do something like

MyClass<int> instance1 = new MyClass<int>();
List<int> integers = instance1.MyList;

MyClass<Person> instance2 = new MyClass<Person>();
IEnumerable<Person> persons = instance2.MyList;

Replace \n with <br />

thatLine = thatLine.replace('\n', '<br />')

Strings in Python are immutable. You might need to recreate it with the assignment operator.

Find and replace - Add carriage return OR Newline

Just a minor word of warning... a lot of environments use, or need, "\r\n" and not just "\n". I ran into an issue with Visual Studio not matching my regex string at the end of the line because I left off the "\r" of "\r\n", so my string couldn't match with a missing invisible character.

So, if you are doing a find, or a replace, consider the "\r".

For a little more detail on "\r" and "\n", see: https://stackoverflow.com/a/3451192/4427457

Escape sequence \f - form feed - what exactly is it?

If you were programming for a 1980s-style printer, it would eject the paper and start a new page. You are virtually certain to never need it.

http://en.wikipedia.org/wiki/Form_feed

How to import a .cer certificate into a java keystore?

An open source GUI tool is available at keystore-explorer.org

KeyStore Explorer

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

Following screens will help (they are from the official site)

Default screen that you get by running the command:

shantha@shantha:~$./Downloads/kse-521/kse.sh

enter image description here

And go to Examine and Examine a URL option and then give the web URL that you want to import.

The result window will be like below if you give google site link. enter image description here

This is one of Use case and rest is up-to the user(all credits go to the keystore-explorer.org)

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

Groovy write to file (newline)

It looks to me, like you're working in windows in which case a new line character in not simply \n but rather \r\n

You can always get the correct new line character through System.getProperty("line.separator") for example.

How to escape a JSON string containing newline characters using JavaScript?

A small update for single quotes

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val      
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'"); 
}

var myJSONString = JSON.stringify(myJSON,escape);

Updating GUI (WPF) using a different thread

there.

I am also developing a serial port testing tool using WPF, and I'd like to share some experience of mine.

I think you should refactor your source code according to MVVM design pattern.

At the beginning, I met the same problem as you met, and I solved it using this code:

new Thread(() => 
{
    while (...)
    {
        SomeTextBox.Dispatcher.BeginInvoke((Action)(() => SomeTextBox.Text = ...));
    }
}).Start();

This works, but is too ugly. I have no idea how to refactor it, until I saw this: http://www.codeproject.com/Articles/165368/WPF-MVVM-Quick-Start-Tutorial

This is a very kindly step-by-step MVVM tutorial for beginners. No shiny UI, no complex logic, only the basic of MVVM.

PHP - how to create a newline character?

For any echo statements, I always use <br> inside double quotes.

Counting number of words in a file

So easy we can get the String from files by method: getText();

public class Main {

    static int countOfWords(String str) {
        if (str.equals("") || str == null) {
            return 0;
        }else{
            int numberWords = 0;
            for (char c : str.toCharArray()) {
                if (c == ' ') {
                    numberWords++;
                }
            }

            return ++numberWordss;
        }
    }
}

How to insert newline in string literal?

string myText =
    @"<div class=""firstLine""></div>
      <div class=""secondLine""></div>
      <div class=""thirdLine""></div>";

that's not it:

string myText =
@"<div class=\"firstLine\"></div>
  <div class=\"secondLine\"></div>
  <div class=\"thirdLine\"></div>";

Printing newlines with print() in R

An alternative to cat() is writeLines():

> writeLines("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename
>

An advantage is that you don't have to remember to append a "\n" to the string passed to cat() to get a newline after your message. E.g. compare the above to the same cat() output:

> cat("File not supplied.\nUsage: ./program F=filename")
File not supplied.
Usage: ./program F=filename>

and

> cat("File not supplied.\nUsage: ./program F=filename","\n")
File not supplied.
Usage: ./program F=filename
>

The reason print() doesn't do what you want is that print() shows you a version of the object from the R level - in this case it is a character string. You need to use other functions like cat() and writeLines() to display the string. I say "a version" because precision may be reduced in printed numerics, and the printed object may be augmented with extra information, for example.

Delete newline in Vim

<CURSOR>Evaluator<T>():
    _bestPos(){
}

cursor in first line

NOW, in NORMAL MODE do

shift+v
2j
shift+j

or

V2jJ

:normal V2jJ

How to remove duplicate white spaces in string using Java?

String str = "   Text    with    multiple    spaces    ";
str = org.apache.commons.lang3.StringUtils.normalizeSpace(str);
// str = "Text with multiple spaces"

C# list.Orderby descending

var newList = list.OrderBy(x => x.Product.Name).Reverse()

This should do the job.

How do I output text without a newline in PowerShell?

Yes, as other answers have states, it cannot be done with Write-Output. Where PowerShell fails, turn to .NET, there are even a couple of .NET answers here but they are more complex than they need to be.

Just use:

[Console]::Write("Enabling feature XYZ.......")
Enable-SPFeature...
Write-Output "Done"

It is not purest PowerShell, but it works.

Why is there no ForEach extension method on IEnumerable?

Most of the LINQ extension methods return results. ForEach does not fit into this pattern as it returns nothing.

recursion versus iteration

Yes, as said by Thanakron Tandavas,

Recursion is good when you are solving a problem that can be solved by divide and conquer technique.

For example: Towers of Hanoi

  1. N rings in increasing size
  2. 3 poles
  3. Rings start stacked on pole 1. Goal is to move rings so that they are stacked on pole 3 ...But
    • Can only move one ring at a time.
    • Can’t put larger ring on top of smaller.
  4. Iterative solution is “powerful yet ugly”; recursive solution is “elegant”.

log4net hierarchy and logging levels

DEBUG will show all messages, INFO all besides DEBUG messages, and so on.
Usually one uses either INFO or WARN. This dependens on the company policy.

What is the proper way to re-attach detached objects in Hibernate?

So it seems that there is no way to reattach a stale detached entity in JPA.

merge() will push the stale state to the DB, and overwrite any intervening updates.

refresh() cannot be called on a detached entity.

lock() cannot be called on a detached entity, and even if it could, and it did reattach the entity, calling 'lock' with argument 'LockMode.NONE' implying that you are locking, but not locking, is the most counterintuitive piece of API design I've ever seen.

So you are stuck. There's an detach() method, but no attach() or reattach(). An obvious step in the object lifecycle is not available to you.

Judging by the number of similar questions about JPA, it seems that even if JPA does claim to have a coherent model, it most certainly does not match the mental model of most programmers, who have been cursed to waste many hours trying understand how to get JPA to do the simplest things, and end up with cache management code all over their applications.

It seems the only way to do it is discard your stale detached entity and do a find query with the same id, that will hit the L2 or the DB.

Mik

How to increase the max upload file size in ASP.NET?

To increase uploading file's size limit we have two ways

1. IIS6 or lower

By default, in ASP.Net the maximum size of a file to be uploaded to the server is around 4MB. This value can be increased by modifying the maxRequestLength attribute in web.config.

Remember : maxRequestLenght is in KB

Example: if you want to restrict uploads to 15MB, set maxRequestLength to “15360” (15 x 1024).

<system.web>
   <!-- maxRequestLength for asp.net, in KB --> 
   <httpRuntime maxRequestLength="15360" ></httpRuntime> 
</system.web>

2. IIS7 or higher

A slight different way used here to upload files.IIS7 has introduced request filtering module.Which executed before ASP.Net.Means the way pipeline works is that the IIS value(maxAllowedContentLength) checked first then ASP.NET value(maxRequestLength) is checked.The maxAllowedContentLength attribute defaults to 28.61 MB.This value can be increased by modifying both attribute in same web.config.

Remember : maxAllowedContentLength is in bytes

Example : if you want to restrict uploads to 15MB, set maxRequestLength to “15360” and maxAllowedContentLength to "15728640" (15 x 1024 x 1024).

<system.web>
   <!-- maxRequestLength for asp.net, in KB --> 
   <httpRuntime maxRequestLength="15360" ></httpRuntime> 
</system.web>

<system.webServer>              
   <security> 
      <requestFiltering> 
         <!-- maxAllowedContentLength, for IIS, in bytes --> 
         <requestLimits maxAllowedContentLength="15728640" ></requestLimits>
      </requestFiltering> 
   </security>
</system.webServer>

MSDN Reference link : https://msdn.microsoft.com/en-us/library/e1f13641(VS.80).aspx

How to make an element width: 100% minus padding?

Use padding in percentages too and remove from the width:

padding: 5%;
width: 90%;

Easiest way to toggle 2 classes in jQuery

Here's another 'non-conventional' way.

  • It implies the use of underscore or lodash.
  • It assumes a context where you:
    • the element doesn't have an init class (that means you cannot do toggleClass('a b'))
    • you have to get the class dynamically from somewhere

An example of this scenario could be buttons that has the class to be switched on another element (say tabs in a container).

// 1: define the array of switching classes:
var types = ['web','email'];

// 2: get the active class:
var type = $(mybutton).prop('class');

// 3: switch the class with the other on (say..) the container. You can guess the other by using _.without() on the array:
$mycontainer.removeClass(_.without(types, type)[0]).addClass(type);

Comparing boxed Long values 127 and 128

Comparing non-primitives (aka Objects) in Java with == compares their reference instead of their values. Long is a class and thus Long values are Objects.

The problem is that the Java Developers wanted people to use Long like they used long to provide compatibility, which led to the concept of autoboxing, which is essentially the feature, that long-values will be changed to Long-Objects and vice versa as needed. The behaviour of autoboxing is not exactly predictable all the time though, as it is not completely specified.

So to be safe and to have predictable results always use .equals() to compare objects and do not rely on autoboxing in this case:

Long num1 = 127, num2 = 127;
if(num1.equals(num2)) { iWillBeExecutedAlways(); }

./configure : /bin/sh^M : bad interpreter

This usually happens when you have edited a file from Windows and now trying to execute that from some unix based machine.

The solution presented on Linux Forum worked for me (many times):

perl -i -pe's/\r$//;' <file name here>

Hope this helps.

PS: you need to have perl installed on your unix/linux machine.

List all of the possible goals in Maven 2?

Strange nobody listed an actual command to do it:

mvn help:describe -e -Dplugin=site

If you want to list all goals of the site plugin. Output:

Name: Apache Maven Site Plugin Description: The Maven Site Plugin is a plugin that generates a site for the current project. Group Id: org.apache.maven.plugins Artifact Id: maven-site-plugin Version: 3.7.1 Goal Prefix: site

This plugin has 9 goals:

site:attach-descriptor Description: Adds the site descriptor (site.xml) to the list of files to be installed/deployed. For Maven-2.x this is enabled by default only when the project has pom packaging since it will be used by modules inheriting, but this can be enabled for other projects packaging if needed. This default execution has been removed from the built-in lifecycle of Maven 3.x for pom-projects. Users that actually use those projects to provide a common site descriptor for sub modules will need to explicitly define this goal execution to restore the intended behavior.

site:deploy Description: Deploys the generated site using wagon supported protocols to the site URL specified in the section of the POM. For scp protocol, the website files are packaged by wagon into zip archive, then the archive is transfered to the remote host, next it is un-archived which is much faster than making a file by file copy.

site:effective-site Description: Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of site.xml, for the first locale.

site:help Description: Display help information on maven-site-plugin. Call mvn site:help -Ddetail=true -Dgoal= to display parameter details.

site:jar Description: Bundles the site output into a JAR so that it can be deployed to a repository.

site:run Description: Starts the site up, rendering documents as requested for faster editing. It uses Jetty as the web server.

site:site Description: Generates the site for a single project. Note that links between module sites in a multi module build will not work, since local build directory structure doesn't match deployed site.

site:stage Description: Deploys the generated site to a local staging or mock directory based on the site URL specified in the section of the POM. It can be used to test that links between module sites in a multi-module build work.

This goal requires the site to already have been generated using the site goal, such as by calling mvn site.

site:stage-deploy Description: Deploys the generated site to a staging or mock URL to the site URL specified in the section of the POM, using wagon supported protocols

For more information, run 'mvn help:describe [...] -Ddetail'

More details on https://mkyong.com/maven/how-to-display-maven-plugin-goals-and-parameters/

PDO with INSERT INTO through prepared statements

I have just rewritten the code to the following:

    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
        VALUES(?,?,?)");

    $statement->execute(array("Bob","Desaunois",18));

And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.

Twitter-Bootstrap-2 logo image on top of navbar

You should remove navbar-fixed-top class otherwise navbar stays fixed on top of page where you want logo.


If you want to place logo inside navbar:

Navbar height (set in @navbarHeight LESS variable) is 40px by default. Your logo has to fit inside or you have to make navbar higher first.

Then use brand class:

<div class="navbar navbar-fixed-top">
  <div class="navbar-inner">
    <div class="container">
      <a href="/" class="brand"><img alt="" src="/logo.gif" /></a>
    </div>
  </div>
</div>

If your logo is higher than 20px, you have to fix stylesheets as well.

If you do that in LESS:

.navbar .brand {
  @elementHeight: 32px;
  padding: ((@navbarHeight - @elementHeight) / 2 - 2) 20px ((@navbarHeight - @elementHeight) / 2 + 2);
}

@elementHeight should be set to your image height.

Padding calculation is taken from Twitter Bootstrap LESS - https://github.com/twitter/bootstrap/blob/v2.0.4/less/navbar.less#L51-52

Alternatively you can calculate padding values yourself and use pure CSS.

This works for Twitter Bootstrap versions 2.0.x, should work in 2.1 as well, but padding calculation was changed a bit: https://github.com/twitter/bootstrap/blob/v2.1.0/less/navbar.less#L50

How to set border on jPanel?

An empty border is transparent. You need to specify a Line Border or some other visible border when you set the border in order to see it.

Based on Edit to question:

The painting does not honor the border. Add this line of code to your test and you will see the border:

    jboard.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
    jboard.add(new JButton("Test"));  //Add this line
    frame.add(jboard);

The meaning of NoInitialContextException error

Most of the time these settings are also defined in a jndi.properties file. Do you have that one lying around somewhere?

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

Correct modification of state arrays in React.js

Easiest, if you are using ES6.

initialArray = [1, 2, 3];

newArray = [ ...initialArray, 4 ]; // --> [1,2,3,4]

New array will be [1,2,3,4]

to update your state in React

this.setState({
  arrayvar:[...this.state.arrayvar, newelement]
});

Learn more about array destructuring

SQLite - UPSERT *not* INSERT or REPLACE

Here is a solution that really is an UPSERT (UPDATE or INSERT) instead of an INSERT OR REPLACE (which works differently in many situations).

It works like this:
1. Try to update if a record with the same Id exists.
2. If the update did not change any rows (NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0)), then insert the record.

So either an existing record was updated or an insert will be performed.

The important detail is to use the changes() SQL function to check if the update statement hit any existing records and only perform the insert statement if it did not hit any record.

One thing to mention is that the changes() function does not return changes performed by lower-level triggers (see http://sqlite.org/lang_corefunc.html#changes), so be sure to take that into account.

Here is the SQL...

Test update:

--Create sample table and records (and drop the table if it already exists)
DROP TABLE IF EXISTS Contact;
CREATE TABLE [Contact] (
  [Id] INTEGER PRIMARY KEY, 
  [Name] TEXT
);
INSERT INTO Contact (Id, Name) VALUES (1, 'Mike');
INSERT INTO Contact (Id, Name) VALUES (2, 'John');

-- Try to update an existing record
UPDATE Contact
SET Name = 'Bob'
WHERE Id = 2;

-- If no record was changed by the update (meaning no record with the same Id existed), insert the record
INSERT INTO Contact (Id, Name)
SELECT 2, 'Bob'
WHERE NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0);

--See the result
SELECT * FROM Contact;

Test insert:

--Create sample table and records (and drop the table if it already exists)
DROP TABLE IF EXISTS Contact;
CREATE TABLE [Contact] (
  [Id] INTEGER PRIMARY KEY, 
  [Name] TEXT
);
INSERT INTO Contact (Id, Name) VALUES (1, 'Mike');
INSERT INTO Contact (Id, Name) VALUES (2, 'John');

-- Try to update an existing record
UPDATE Contact
SET Name = 'Bob'
WHERE Id = 3;

-- If no record was changed by the update (meaning no record with the same Id existed), insert the record
INSERT INTO Contact (Id, Name)
SELECT 3, 'Bob'
WHERE NOT EXISTS(SELECT changes() AS change FROM Contact WHERE change <> 0);

--See the result
SELECT * FROM Contact;

When is the finalize() method called in Java?

finalize will print out the count for class creation.

protected void finalize() throws Throwable {
    System.out.println("Run F" );
    if ( checkedOut)
        System.out.println("Error: Checked out");
        System.out.println("Class Create Count: " + classCreate);
}

main

while ( true) {
    Book novel=new Book(true);
    //System.out.println(novel.checkedOut);
    //Runtime.getRuntime().runFinalization();
    novel.checkIn();
    new Book(true);
    //System.runFinalization();
    System.gc();

As you can see. The following out put show the gc got executed first time when the class count is 36.

C:\javaCode\firstClass>java TerminationCondition
Run F
Error: Checked out
Class Create Count: 36
Run F
Error: Checked out
Class Create Count: 48
Run F

How to catch exception output from Python subprocess.check_output()?

This did the trick for me. It captures all the stdout output from the subprocess(For python 3.8):

from subprocess import check_output, STDOUT
cmd = "Your Command goes here"
try:
    cmd_stdout = check_output(cmd, stderr=STDOUT, shell=True).decode()
except Exception as e:
    print(e.output.decode()) # print out the stdout messages up to the exception
    print(e) # To print out the exception message

OpenCV NoneType object has no attribute shape

try to handle the error, its an attribute error given by OpenCV

try:
    img.shape
    print("checked for shape".format(img.shape))
except AttributeError:
    print("shape not found")
    #code to move to next frame

PHP: Count a stdClass object

The object doesn't have 30 properties. It has one, which is an array that has 30 elements. You need the number of elements in that array.

Check if PHP-page is accessed from an iOS device

If you just want to detect mobile devices in generel, Cake has build in support using RequestHandler->isMobile() (http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent::isMobile)

How do I check that a Java String is not all whitespaces?

If you are using Java 11, the new isBlank string method will come in handy:

!s.isBlank();

If you are using Java 8, 9 or 10, you could build a simple stream to check that a string is not whitespace only:

!s.chars().allMatch(Character::isWhitespace));

In addition to not requiring any third-party libraries such as Apache Commons Lang, these solutions have the advantage of handling any white space character, and not just plain ' ' spaces as would a trim-based solution suggested in many other answers. You can refer to the Javadocs for an exhaustive list of all supported white space types. Note that empty strings are also covered in both cases.

Disable scrolling in all mobile devices

This prevents scrolling on mobile devices but not the single click/tap.

document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });

How to impose maxlength on textArea in HTML using JavaScript

This is some tweaked code I've just been using on my site. It is improved to display the number of remaining characters to the user.

(Sorry again to OP who requested no jQuery. But seriously, who doesn't use jQuery these days?)

$(function() {
    // Get all textareas that have a "maxlength" property.
    $("textarea[maxlength]").each(function() {

        // Store the jQuery object to be more efficient...
        var $textarea = $(this);

        // Store the maxlength and value of the field
        var maxlength = $textarea.attr("maxlength");

        // Add a DIV to display remaining characters to user
        $textarea.after($("<div>").addClass("charsRemaining"));

        // Bind the trimming behavior to the "keyup" & "blur" events (to handle mouse-based paste)
        $textarea.on("keyup blur", function(event) {
            // Fix OS-specific line-returns to do an accurate count
            var val = $textarea.val().replace(/\r\n|\r|\n/g, "\r\n").slice(0, maxlength);
            $textarea.val(val);
            // Display updated count to user
            $textarea.next(".charsRemaining").html(maxlength - val.length + " characters remaining");
        }).trigger("blur");

    });
});

Has NOT been tested with international multi-byte characters, so I'm not sure how it works with those exactly.

Test if executable exists in Python?

An important question is "Why do you need to test if executable exist?" Maybe you don't? ;-)

Recently I needed this functionality to launch viewer for PNG file. I wanted to iterate over some predefined viewers and run the first that exists. Fortunately, I came across os.startfile. It's much better! Simple, portable and uses the default viewer on the system:

>>> os.startfile('yourfile.png')

Update: I was wrong about os.startfile being portable... It's Windows only. On Mac you have to run open command. And xdg_open on Unix. There's a Python issue on adding Mac and Unix support for os.startfile.

Laravel 5.1 API Enable Cors

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

showing that a date is greater than current date

In sql server, you can do

SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())

Close all infowindows in Google Maps API v3

For loops that creates infowindows dynamically, declare a global variable

var openwindow;

and then in the addListenerfunction call (which is within the loop):

google.maps.event.addListener(marker<?php echo $id; ?>, 'click', function() {
if(openwindow){
    eval(openwindow).close();
}
openwindow="myInfoWindow<?php echo $id; ?>";
myInfoWindow<?php echo $id; ?>.open(map, marker<?php echo $id; ?>);
});

How to find Current open Cursors in Oracle

Oracle has a page for this issue with SQL and trouble shooting suggestions.

"Troubleshooting Open Cursor Issues" http://docs.oracle.com/cd/E40329_01/admin.1112/e27149/cursor.htm#OMADM5352

random.seed(): What does it do?

Here is a small test that demonstrates that feeding the seed() method with the same argument will cause the same pseudo-random result:

# testing random.seed()

import random

def equalityCheck(l):
    state=None
    x=l[0]
    for i in l:
        if i!=x:
            state=False
            break
        else:
            state=True
    return state


l=[]

for i in range(1000):
    random.seed(10)
    l.append(random.random())

print "All elements in l are equal?",equalityCheck(l)

jQuery multiselect drop down menu

<select id="mycontrolId" multiple="multiple">
   <option value="1" >one</option>
   <option value="2" >two</option>
   <option value="3">three</option>
   <option value="4">four</option>
</select>

var data = "1,3,4"; var dataarray = data.split(",");

$("#mycontrolId").val(dataarray);

What is href="#" and why is it used?

As some of the other answers have pointed out, the a element requires an href attribute and the # is used as a placeholder, but it is also a historical artifact.

From Mozilla Developer Network:

href

This was the single required attribute for anchors defining a hypertext source link, but is no longer required in HTML5. Omitting this attribute creates a placeholder link. The href attribute indicates the link target, either a URL or a URL fragment. A URL fragment is a name preceded by a hash mark (#), which specifies an internal target location (an ID) within the current document.

Also, per the HTML5 spec:

If the a element has no href attribute, then the element represents a placeholder for where a link might otherwise have been placed, if it had been relevant, consisting of just the element's contents.

How to use sed/grep to extract text between two words?

All the above solutions have deficiencies where the last search string is repeated elsewhere in the string. I found it best to write a bash function.

    function str_str {
      local str
      str="${1#*${2}}"
      str="${str%%$3*}"
      echo -n "$str"
    }

    # test it ...
    mystr="this is a string"
    str_str "$mystr" "this " " string"

How can I get client information such as OS and browser

This code is based on the most voted question but I might be easier to use

public enum OS {

    WINDOWS,
    MAC,
    LINUX,
    ANDROID,
    IPHONE,
    UNKNOWN;

    public static OS valueOf(HttpServletRequest request) {

        final String userAgent = request.getHeader("User-Agent");
        final OS toReturn;

        if (userAgent == null || userAgent.isEmpty()) {
            toReturn = UNKNOWN;
        } else if (userAgent.toLowerCase().contains("windows")) {
            toReturn = WINDOWS;
        } else if (userAgent.toLowerCase().contains("mac")) {
            toReturn = MAC;
        } else if (userAgent.toLowerCase().contains("x11")) {
            toReturn = LINUX;
        } else if (userAgent.toLowerCase().contains("android")) {
            toReturn = ANDROID;
        } else if (userAgent.toLowerCase().contains("iphone")) {
            toReturn = IPHONE;
        } else {
            toReturn = UNKNOWN;
        }

        return toReturn;
    }

}

Why is it OK to return a 'vector' from a function?

I think you are referring to the problem in C (and C++) that returning an array from a function isn't allowed (or at least won't work as expected) - this is because the array return will (if you write it in the simple form) return a pointer to the actual array on the stack, which is then promptly removed when the function returns.

But in this case, it works, because the std::vector is a class, and classes, like structs, can (and will) be copied to the callers context. [Actually, most compilers will optimise out this particular type of copy using something called "Return Value Optimisation", specifically introduced to avoid copying large objects when they are returned from a function, but that's an optimisation, and from a programmers perspective, it will behave as if the assignment constructor was called for the object]

As long as you don't return a pointer or a reference to something that is within the function returning, you are fine.

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

Laravel - Eloquent "Has", "With", "WhereHas" - What do they mean?

With

with() is for eager loading. That basically means, along the main model, Laravel will preload the relationship(s) you specify. This is especially helpful if you have a collection of models and you want to load a relation for all of them. Because with eager loading you run only one additional DB query instead of one for every model in the collection.

Example:

User > hasMany > Post

$users = User::with('posts')->get();
foreach($users as $user){
    $users->posts; // posts is already loaded and no additional DB query is run
}

Has

has() is to filter the selecting model based on a relationship. So it acts very similarly to a normal WHERE condition. If you just use has('relation') that means you only want to get the models that have at least one related model in this relation.

Example:

User > hasMany > Post

$users = User::has('posts')->get();
// only users that have at least one post are contained in the collection

WhereHas

whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.

Example:

User > hasMany > Post

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();
// only users that have posts from 2015 on forward are returned

Is there a Social Security Number reserved for testing/examples?

There are multiple number groups and some particular numbers that will never be allocated:

Consider using one of these (the obviously invalid 000-00-0000 would be a good one IMO).

(Answer has been updated to provide source information beyond Wikipedia and remove information that is no longer accurate after the SSA made its randomization change in mid 2011.)

Installing R with Homebrew

brew install homebrew/science/r

works on OS X 10.11.6.

How can I send an Ajax Request on button click from a form with 2 buttons?

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});

What is the difference between cache and persist?

For impatient:

Same

Without passing argument, persist() and cache() are the same, with default settings:

  • when RDD: MEMORY_ONLY
  • when Dataset: MEMORY_AND_DISK

Difference:

Unlike cache(), persist() allows you to pass argument inside the bracket, in order to specify the level:

  • persist(MEMORY_ONLY)
  • persist(MEMORY_ONLY_SER)
  • persist(MEMORY_AND_DISK)
  • persist(MEMORY_AND_DISK_SER )
  • persist(DISK_ONLY )

Voilà!

Python function overloading

I think a Bullet class hierarchy with the associated polymorphism is the way to go. You can effectively overload the base class constructor by using a metaclass so that calling the base class results in the creation of the appropriate subclass object. Below is some sample code to illustrate the essence of what I mean.

Updated

The code has been modified to run under both Python 2 and 3 to keep it relevant. This was done in a way that avoids the use Python's explicit metaclass syntax, which varies between the two versions.

To accomplish that objective, a BulletMetaBase instance of the BulletMeta class is created by explicitly calling the metaclass when creating the Bullet baseclass (rather than using the __metaclass__= class attribute or via a metaclass keyword argument depending on the Python version).

class BulletMeta(type):
    def __new__(cls, classname, bases, classdict):
        """ Create Bullet class or a subclass of it. """
        classobj = type.__new__(cls, classname, bases, classdict)
        if classname != 'BulletMetaBase':
            if classname == 'Bullet':  # Base class definition?
                classobj.registry = {}  # Initialize subclass registry.
            else:
                try:
                    alias = classdict['alias']
                except KeyError:
                    raise TypeError("Bullet subclass %s has no 'alias'" %
                                    classname)
                if alias in Bullet.registry: # unique?
                    raise TypeError("Bullet subclass %s's alias attribute "
                                    "%r already in use" % (classname, alias))
                # Register subclass under the specified alias.
                classobj.registry[alias] = classobj

        return classobj

    def __call__(cls, alias, *args, **kwargs):
        """ Bullet subclasses instance factory.

            Subclasses should only be instantiated by calls to the base
            class with their subclass' alias as the first arg.
        """
        if cls != Bullet:
            raise TypeError("Bullet subclass %r objects should not to "
                            "be explicitly constructed." % cls.__name__)
        elif alias not in cls.registry: # Bullet subclass?
            raise NotImplementedError("Unknown Bullet subclass %r" %
                                      str(alias))
        # Create designated subclass object (call its __init__ method).
        subclass = cls.registry[alias]
        return type.__call__(subclass, *args, **kwargs)


class Bullet(BulletMeta('BulletMetaBase', (object,), {})):
    # Presumably you'd define some abstract methods that all here
    # that would be supported by all subclasses.
    # These definitions could just raise NotImplementedError() or
    # implement the functionality is some sub-optimal generic way.
    # For example:
    def fire(self, *args, **kwargs):
        raise NotImplementedError(self.__class__.__name__ + ".fire() method")

    # Abstract base class's __init__ should never be called.
    # If subclasses need to call super class's __init__() for some
    # reason then it would need to be implemented.
    def __init__(self, *args, **kwargs):
        raise NotImplementedError("Bullet is an abstract base class")


# Subclass definitions.
class Bullet1(Bullet):
    alias = 'B1'
    def __init__(self, sprite, start, direction, speed):
        print('creating %s object' % self.__class__.__name__)
    def fire(self, trajectory):
        print('Bullet1 object fired with %s trajectory' % trajectory)


class Bullet2(Bullet):
    alias = 'B2'
    def __init__(self, sprite, start, headto, spead, acceleration):
        print('creating %s object' % self.__class__.__name__)


class Bullet3(Bullet):
    alias = 'B3'
    def __init__(self, sprite, script): # script controlled bullets
        print('creating %s object' % self.__class__.__name__)


class Bullet4(Bullet):
    alias = 'B4'
    def __init__(self, sprite, curve, speed): # for bullets with curved paths
        print('creating %s object' % self.__class__.__name__)


class Sprite: pass
class Curve: pass

b1 = Bullet('B1', Sprite(), (10,20,30), 90, 600)
b2 = Bullet('B2', Sprite(), (-30,17,94), (1,-1,-1), 600, 10)
b3 = Bullet('B3', Sprite(), 'bullet42.script')
b4 = Bullet('B4', Sprite(), Curve(), 720)
b1.fire('uniform gravity')
b2.fire('uniform gravity')

Output:

creating Bullet1 object
creating Bullet2 object
creating Bullet3 object
creating Bullet4 object
Bullet1 object fired with uniform gravity trajectory
Traceback (most recent call last):
  File "python-function-overloading.py", line 93, in <module>
    b2.fire('uniform gravity') # NotImplementedError: Bullet2.fire() method
  File "python-function-overloading.py", line 49, in fire
    raise NotImplementedError(self.__class__.__name__ + ".fire() method")
NotImplementedError: Bullet2.fire() method

How to select only the first rows for each unique value of a column?

You can use row_number() to get the row number of the row. It uses the over command - the partition by clause specifies when to restart the numbering and the order by selects what to order the row number on. Even if you added an order by to the end of your query, it would preserve the ordering in the over command when numbering.

select *
from mytable
where row_number() over(partition by Name order by AddressLine) = 1

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

#include <stdio.h>
#include <stdlib.h>

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

Import numpy on pycharm

Go to

  1. ctrl-alt-s
  2. click "project:projet name"
  3. click project interperter
  4. double click pip
  5. search numpy from the top bar
  6. click on numpy
  7. click install package button

if it doesnt work this can help you:

https://www.jetbrains.com/help/pycharm/installing-uninstalling-and-upgrading-packages.html

How to extract text from a PDF file?

In 2020 the solutions above were not working for the particular pdf I was working with. Below is what did the trick. I am on Windows 10 and Python 3.8

Test pdf file: https://drive.google.com/file/d/1aUfQAlvq5hA9kz2c9CyJADiY3KpY3-Vn/view?usp=sharing

#pip install pdfminer.six
import io

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


def convert_pdf_to_txt(path):
    '''Convert pdf content from a file path to text

    :path the file path
    '''
    rsrcmgr = PDFResourceManager()
    codec = 'utf-8'
    laparams = LAParams()

    with io.StringIO() as retstr:
        with TextConverter(rsrcmgr, retstr, codec=codec,
                           laparams=laparams) as device:
            with open(path, 'rb') as fp:
                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)

                return retstr.getvalue()


if __name__ == "__main__":
    print(convert_pdf_to_txt('C:\\Path\\To\\Test_PDF.pdf')) 

How do I pass options to the Selenium Chrome driver using Python?

Code which disable chrome extensions for ones, who uses DesiredCapabilities to set browser flags :

desired_capabilities['chromeOptions'] = {
    "args": ["--disable-extensions"],
    "extensions": []
}
webdriver.Chrome(desired_capabilities=desired_capabilities)

Converting JSONarray to ArrayList

With Kotlin, you can avoid a loop by wrapping the JSONArray with a MutableList, e.g.

val artistMetadata = player.metadata.optJSONArray("artist")
val artists = MutableList<String>(artistMetadata.length()) { i -> artistMetadata.getString(i)}

Generating 8-character only UUIDs

I do not think that it is possible but you have a good workaround.

  1. cut the end of your UUID using substring()
  2. use code new Random(System.currentTimeMillis()).nextInt(99999999); this will generate random ID up to 8 characters long.
  3. generate alphanumeric id:

    char[] chars = "abcdefghijklmnopqrstuvwxyzABSDEFGHIJKLMNOPQRSTUVWXYZ1234567890".toCharArray();
    Random r = new Random(System.currentTimeMillis());
    char[] id = new char[8];
    for (int i = 0;  i < 8;  i++) {
        id[i] = chars[r.nextInt(chars.length)];
    }
    return new String(id);
    

percentage of two int?

Well to make the decimal into a percent you can do this,

float percentage = (correct * 100.0f) / questionNum;

Gcc error: gcc: error trying to exec 'cc1': execvp: No such file or directory

What helped for me was to use llvm-gcc instead:

ln -s $(which llvm-gcc) /usr/local/bin/gcc

Job for mysqld.service failed See "systemctl status mysqld.service"

These are the steps I took to correct this:

Back up your my.cnf file in /etc/mysql and remove or rename it

sudo mv /etc/mysql/my.cnf /etc/mysql/my.cnf.bak

Remove the folder /etc/mysql/mysql.conf.d/ using

sudo rm -r /etc/mysql/mysql.conf.d/

Verify you don't have a my.cnf file stashed somewhere else (I did in my home dir!) or in /etc/alternatives/my.cnf use

sudo find / -name my.cnf

Now reinstall every thing

sudo apt purge mysql-server mysql-server-5.7 mysql-server-core-5.7
sudo apt install mysql-server

In case your syslog shows an error like "mysqld: Can't read dir of '/etc/mysql/conf.d/'" create a symbolic link:

sudo ln -s /etc/mysql/mysql.conf.d /etc/mysql/conf.d

Then the service should be able to start with sudo service mysql start.

I hope it work

Python webbrowser.open() to open Chrome browser

Please check this:

import webbrowser
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open('http://docs.python.org/')

Windows shell command to get the full path to the current directory?

Create a .bat file under System32, let us name it copypath.bat the command to copy current path could be:

echo %cd% | clip

Explanation:

%cd% will give you current path

CLIP

Description:
    Redirects output of command line tools to the Windows clipboard.
    This text output can then be pasted into other programs.

Parameter List:
    /?                  Displays this help message.

Examples:
    DIR | CLIP          Places a copy of the current directory
                        listing into the Windows clipboard.

    CLIP < README.TXT   Places a copy of the text from readme.txt
                        on to the Windows clipboard.

Now copyclip is available from everywhere.

object==null or null==object?

This is not of much value in Java (1.5+) except when the type of object is Boolean. In which case, this can still be handy.

if (object = null) will not cause compilation failure in Java 1.5+ if object is Boolean but would throw a NullPointerException at runtime.

Disable form autofill in Chrome without disabling autocomplete

You better use disabled for your inputs, in order to prevent auto-completion.

<input type="password" ... disabled />

RegEx for matching UK Postcodes

It looks like we're going to be using ^(GIR ?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]([0-9ABEHMNPRV-Y])?)|[0-9][A-HJKPS-UW]) ?[0-9][ABD-HJLNP-UW-Z]{2})$, which is a slightly modified version of that sugested by Minglis above.

However, we're going to have to investigate exactly what the rules are, as the various solutions listed above appear to apply different rules as to which letters are allowed.

After some research, we've found some more information. Apparently a page on 'govtalk.gov.uk' points you to a postcode specification govtalk-postcodes. This points to an XML schema at XML Schema which provides a 'pseudo regex' statement of the postcode rules.

We've taken that and worked on it a little to give us the following expression:

^((GIR &0AA)|((([A-PR-UWYZ][A-HK-Y]?[0-9][0-9]?)|(([A-PR-UWYZ][0-9][A-HJKSTUW])|([A-PR-UWYZ][A-HK-Y][0-9][ABEHMNPRV-Y]))) &[0-9][ABD-HJLNP-UW-Z]{2}))$

This makes spaces optional, but does limit you to one space (replace the '&' with '{0,} for unlimited spaces). It assumes all text must be upper-case.

If you want to allow lower case, with any number of spaces, use:

^(([gG][iI][rR] {0,}0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) {0,}[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$

This doesn't cover overseas territories and only enforces the format, NOT the existence of different areas. It is based on the following rules:

Can accept the following formats:

  • “GIR 0AA”
  • A9 9ZZ
  • A99 9ZZ
  • AB9 9ZZ
  • AB99 9ZZ
  • A9C 9ZZ
  • AD9E 9ZZ

Where:

  • 9 can be any single digit number.
  • A can be any letter except for Q, V or X.
  • B can be any letter except for I, J or Z.
  • C can be any letter except for I, L, M, N, O, P, Q, R, V, X, Y or Z.
  • D can be any letter except for I, J or Z.
  • E can be any of A, B, E, H, M, N, P, R, V, W, X or Y.
  • Z can be any letter except for C, I, K, M, O or V.

Best wishes

Colin

requestFeature() must be called before adding content

I had this issue with Dialogs based on an extended DialogFragment which worked fine on devices running API 26 but failed with API 23. The above strategies didn't work but I resolved the issue by removing the onCreateView method (which had been added by a more recent Android Studio template) from the DialogFragment and creating the dialog in onCreateDialog.

How to send 100,000 emails weekly?

Short answer: While it's technically possible to send 100k e-mails each week yourself, the simplest, easiest and cheapest solution is to outsource this to one of the companies that specialize in it (I did say "cheapest": there's no limit to the amount of development time (and therefore money) that you can sink into this when trying to DIY).

Long answer: If you decide that you absolutely want to do this yourself, prepare for a world of hurt (after all, this is e-mail/e-fail we're talking about). You'll need:

  • e-mail content that is not spam (otherwise you'll run into additional major roadblocks on every step, even legal repercussions)
  • in addition, your content should be easy to distinguish from spam - that may be a bit hard to do in some cases (I heard that a certain pharmaceutical company had to all but abandon e-mail, as their brand names are quite common in spams)
  • a configurable SMTP server of your own, one which won't buckle when you dump 100k e-mails onto it (your ISP's upstream server won't be sufficient here and you'll make the ISP violently unhappy; we used two dedicated boxes)
  • some mail wrapper (e.g. PhpMailer if PHP's your poison of choice; using PHP's mail() is horrible enough by itself)
  • your own sender function to run in a loop, create the mails and pass them to the wrapper (note that you may run into PHP's memory limits if your app has a memory leak; you may need to recycle the sending process periodically, or even better, decouple the "creating e-mails" and "sending e-mails" altogether)

Surprisingly, that was the easy part. The hard part is actually sending it:

  • some servers will ban you when you send too many mails close together, so you need to shuffle and watch your queue (e.g. send one mail to [email protected], then three to other domains, only then another to [email protected])
  • you need to have correct PTR, SPF, DKIM records
  • handling remote server timeouts, misconfigured DNS records and other network pleasantries
  • handling invalid e-mails (and no, regex is the wrong tool for that)
  • handling unsubscriptions (many legitimate newsletters have been reclassified as spam due to many frustrated users who couldn't unsubscribe in one step and instead chose to "mark as spam" - the spam filters do learn, esp. with large e-mail providers)
  • handling bounces and rejects ("no such mailbox [email protected]","mailbox [email protected] full")
  • handling blacklisting and removal from blacklists (Sure, you're not sending spam. Some recipients won't be so sure - with such large list, it will happen sometimes, no matter what precautions you take. Some people (e.g. your not-so-scrupulous competitors) might even go as far to falsely report your mailings as spam - it does happen. On average, it takes weeks to get yourself removed from a blacklist.)

And to top it off, you'll have to manage the legal part of it (various federal, state, and local laws; and even different tangles of laws once you send outside the U.S. (note: you have no way of finding if [email protected] lives in Southwest Elbonia, the country with world's most draconian antispam laws)).

I'm pretty sure I missed a few heads of this hydra - are you still sure you want to do this yourself? If so, there'll be another wave, this time merely the annoying problems inherent in sending an e-mail. (You see, SMTP is a store-and-forward protocol, which means that your e-mail will be shuffled across many SMTP servers around the Internet, in the hope that the next one is a bit closer to the final recipient. Basically, the e-mail is sent to an SMTP server, which puts it into its forward queue; when time comes, it will forward it further to a different SMTP server, until it reaches the SMTP server for the given domain. This forward could happen immediately, or in a few minutes, or hours, or days, or never.) Thus, you'll see the following issues - most of which could happen en route as well as at the destination:

  • the remote SMTP servers don't want to talk to your SMTP server
  • your mails are getting marked as spam (<blink> is not your friend here, nor is <font color=...>)
  • your mails are delivered days, even weeks late (contrary to popular opinion, SMTP is designed to make a best effort to deliver the message sometime in the future - not to deliver it now)
  • your mails are not delivered at all (already sent from e-mail server on hop #4, not sent yet from server on hop #5, the server that currently holds the message crashes, data is lost)
  • your mails are mangled by some braindead server en route (this one is somewhat solvable with base64 encoding, but then the size goes up and the e-mail looks more suspicious)
  • your mails are delivered and the recipients seem not to want them ("I'm sure I didn't sign up for this, I remember exactly what I did a year ago" (of course you do, sir))
  • users with various versions of Microsoft Outlook and its special handling of Internet mail
  • wizard's apprentice mode (a self-reinforcing positive feedback loop - in other words, automated e-mails as replies to automated e-mails as replies to...; you really don't want to be the one to set this off, as you'd anger half the internet at yourself)

and it'll be your job to troubleshoot and solve this (hint: you can't, mostly). The people who run a legit mass-mailing businesses know that in the end you can't solve it, and that they can't solve it either - and they have the reasons well researched, documented and outlined (maybe even as a Powerpoint presentation - complete with sounds and cool transitions - that your bosses can understand), as they've had to explain this a million times before. Plus, for the problems that are actually solvable, they know very well how to solve them.

If, after all this, you are not discouraged and still want to do this, go right ahead: it's even possible that you'll find a better way to do this. Just know that the road ahead won't be easy - sending e-mail is trivial, getting it delivered is hard.

To add server using sp_addlinkedserver

FOR SQL SERVER

EXEC sp_addlinkedserver @server='servername' 

No need to specify other parameters. You can go through this article.

CASE statement in SQLite query

Also, you do not have to use nested CASEs. You can use several WHEN-THEN lines and the ELSE line is also optional eventhough I recomend it

CASE 
   WHEN [condition.1] THEN [expression.1]
   WHEN [condition.2] THEN [expression.2]
   ...
   WHEN [condition.n] THEN [expression.n]
   ELSE [expression] 
END

How do I set an absolute include path in PHP?

The include_path setting works like $PATH in unix (there is a similar setting in Windows too).It contains multiple directory names, seperated by colons (:). When you include or require a file, these directories are searched in order, until a match is found or all directories are searched.

So, to make sure that your application always includes from your path if the file exists there, simply put your include dir first in the list of directories.

ini_set("include_path", "/your_include_path:".ini_get("include_path"));

This way, your include directory is searched first, and then the original search path (by default the current directory, and then PEAR). If you have no problem modifying include_path, then this is the solution for you.

How do you use the ? : (conditional) operator in JavaScript?

I want to add some to the given answers.

In case you encounter (or want to use) a ternary in a situation like 'display a variable if it's set, else...', you can make it even shorter, without a ternary.


Instead of:

var welcomeMessage  = 'Hello ' + (username ? username : 'guest');

You can use:

var welcomeMessage  = 'Hello ' + (username || 'guest');

This is Javascripts equivallent of PHP's shorthand ternary operator ?:

Or even:

var welcomeMessage  = 'Hello ' + (username || something || maybethis || 'guest');

It evaluates the variable, and if it's false or unset, it goes on to the next.

Difference between Destroy and Delete

Basically destroy runs any callbacks on the model while delete doesn't.

From the Rails API:

  • ActiveRecord::Persistence.delete

    Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted). Returns the frozen instance.

    The row is simply removed with an SQL DELETE statement on the record's primary key, and no callbacks are executed.

    To enforce the object's before_destroy and after_destroy callbacks or any :dependent association options, use #destroy.

  • ActiveRecord::Persistence.destroy

    Deletes the record in the database and freezes this instance to reflect that no changes should be made (since they can't be persisted).

    There's a series of callbacks associated with destroy. If the before_destroy callback return false the action is cancelled and destroy returns false. See ActiveRecord::Callbacks for further details.

How to get a MemoryStream from a Stream in .NET?

byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}

How do I Set Background image in Flutter?

Other answers are great. This is another way it can be done.

  1. Here I use SizedBox.expand() to fill available space and for passing tight constraints for its children (Container).
  2. BoxFit.cover enum to Zoom the image and cover whole screen
 Widget build(BuildContext context) {
    return Scaffold(
      body: SizedBox.expand( // -> 01
        child: Container(
          decoration: BoxDecoration(
            image: DecorationImage(
              image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
              fit: BoxFit.cover,    // -> 02
            ),
          ),
        ),
      ),
    );
  }

screenshot

Facebook Graph API error code list

While there does not appear to be a public, Facebook-curated list of error codes available, a number of folks have taken it upon themselves to publish lists of known codes.

Take a look at StackOverflow #4348018 - List of Facebook error codes for a number of useful resources.

Is "delete this" allowed in C++?

This is the core idiom for reference-counted objects.

Reference-counting is a strong form of deterministic garbage collection- it ensures objects manage their OWN lifetime instead of relying on 'smart' pointers, etc. to do it for them. The underlying object is only ever accessed via "Reference" smart pointers, designed so that the pointers increment and decrement a member integer (the reference count) in the actual object.

When the last reference drops off the stack or is deleted, the reference count will go to zero. Your object's default behavior will then be a call to "delete this" to garbage collect- the libraries I write provide a protected virtual "CountIsZero" call in the base class so that you can override this behavior for things like caching.

The key to making this safe is not allowing users access to the CONSTRUCTOR of the object in question (make it protected), but instead making them call some static member- the FACTORY- like "static Reference CreateT(...)". That way you KNOW for sure that they're always built with ordinary "new" and that no raw pointer is ever available, so "delete this" won't ever blow up.

git discard all changes and pull from upstream

while on branch master: git reset --hard origin/master

then do some clean up with git gc (more about this in the man pages)

Update: You will also probably need to do a git fetch origin (or git fetch origin master if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)

addClass and removeClass in jQuery - not removing class

I think that the problem is in the nesting of the elements. Once you attach an event to the outer element the clicks on the inner elements are actually firing the same click event for the outer element. So, you actually never go to the second state. What you can do is to check the clicked element. And if it is the close button then to avoid the class changing. Here is my solution:

var element = $(".clickable");
var closeButton = element.find(".close_button");
var onElementClick = function(e) {
    if(e.target !== closeButton[0]) {
        element.removeClass("spot").addClass("grown");
        element.off("click");
        closeButton.on("click", onCloseClick);
    }
}
var onCloseClick = function() {
    element.removeClass("grown").addClass("spot");
    closeButton.off("click");
    element.on("click", onElementClick);
}
element.on("click", onElementClick);

In addition I'm adding and removing event handlers.

JSFiddle -> http://jsfiddle.net/zmw9E/1/

Applications are expected to have a root view controller at the end of application launch

With my first view being MenuViewController I added:

MenuViewController *menuViewController = [[MenuViewController alloc]init];
self.window.rootViewController = menuViewController;

on the App Delegate method:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
}

That worked.

How to create a batch file to run cmd as administrator

Here's a more simple version of essentially the same file.

@echo off
break off
title C:\Windows\system32\cmd.exe
cls

:cmd
set /p cmd=C:\Enter Command:

%cmd%
echo.
goto cmd

html select only one checkbox in a group

Necromancing:
And without jQuery, for a checkbox structure like this:

<label>
<input type="checkbox" id="mytrackers_1" name="blubb_1" value="">--- Bitte ausw&#228;hlen ---
</label>
<label>
<input type="checkbox" id="mytrackers_2" name="blubb_2" value="7">Testtracker
</label>
<label>
<input type="checkbox" id="mytrackers_3" name="blubb_3" value="3">Kundenanfrage
</label>
<label>
<input type="checkbox" id="mytrackers_4" name="blubb_4" value="2">Anpassung
</label>
<label>
<input type="checkbox" id="mytrackers_5" name="blubb_5" value="1" checked="checked" >Fehler
</label>
<label>
<input type="checkbox" id="mytrackers_6" name="blubb_6" value="4">Bedienung
</label>
<label>
<input type="checkbox" id="mytrackers_7" name="blubb_7" value="5">Internes
</label>
<label>
<input type="checkbox" id="mytrackers_8" name="blubb_8" value="6">&#196;nderungswunsch
</label>

you would do it like this:

    /// attach an event handler, now or in the future, 
    /// for all elements which match childselector,
    /// within the child tree of the element maching parentSelector.
    function subscribeEvent(parentSelector, eventName, childSelector, eventCallback) {
        if (parentSelector == null)
            throw new ReferenceError("Parameter parentSelector is NULL");
        if (childSelector == null)
            throw new ReferenceError("Parameter childSelector is NULL");
        // nodeToObserve: the node that will be observed for mutations
        var nodeToObserve = parentSelector;
        if (typeof (parentSelector) === 'string')
            nodeToObserve = document.querySelector(parentSelector);
        var eligibleChildren = nodeToObserve.querySelectorAll(childSelector);
        for (var i = 0; i < eligibleChildren.length; ++i) {
            eligibleChildren[i].addEventListener(eventName, eventCallback, false);
        } // Next i 
        // https://stackoverflow.com/questions/2712136/how-do-i-make-this-loop-all-children-recursively
        function allDescendants(node) {
            if (node == null)
                return;
            for (var i = 0; i < node.childNodes.length; i++) {
                var child = node.childNodes[i];
                allDescendants(child);
            } // Next i 
            // IE 11 Polyfill 
            if (!Element.prototype.matches)
                Element.prototype.matches = Element.prototype.msMatchesSelector;
            if (node.matches) {
                if (node.matches(childSelector)) {
                    // console.log("match");
                    node.addEventListener(eventName, eventCallback, false);
                } // End if ((<Element>node).matches(childSelector))
                // else console.log("no match");
            } // End if ((<Element>node).matches) 
            // else console.log("no matchfunction");
        } // End Function allDescendants 
        // Callback function to execute when mutations are observed
        var callback = function (mutationsList, observer) {
            for (var _i = 0, mutationsList_1 = mutationsList; _i < mutationsList_1.length; _i++) {
                var mutation = mutationsList_1[_i];
                // console.log("mutation.type", mutation.type);
                // console.log("mutation", mutation);
                if (mutation.type == 'childList') {
                    for (var i = 0; i < mutation.addedNodes.length; ++i) {
                        var thisNode = mutation.addedNodes[i];
                        allDescendants(thisNode);
                    } // Next i 
                } // End if (mutation.type == 'childList') 
                // else if (mutation.type == 'attributes') { console.log('The ' + mutation.attributeName + ' attribute was modified.');
            } // Next mutation 
        }; // End Function callback 
        // Options for the observer (which mutations to observe)
        var config = { attributes: false, childList: true, subtree: true };
        // Create an observer instance linked to the callback function
        var observer = new MutationObserver(callback);
        // Start observing the target node for configured mutations
        observer.observe(nodeToObserve, config);
    } // End Function subscribeEvent 


    function radioCheckbox_onClick() 
    { 
        // console.log("click", this);
        let box = this;
        if (box.checked) 
        {
            let name = box.getAttribute("name");
            let pos = name.lastIndexOf("_");
            if (pos !== -1) name = name.substr(0, pos);

            let group = 'input[type="checkbox"][name^="' + name + '"]';
            // console.log(group);
            let eles = document.querySelectorAll(group);
            // console.log(eles);
            for (let j = 0; j < eles.length; ++j) 
            {
                eles[j].checked = false;
            }
            box.checked = true;
        }
        else
            box.checked = false;
    }


    // https://stackoverflow.com/questions/9709209/html-select-only-one-checkbox-in-a-group
    function radioCheckbox()
    { 
        // on instead of document...
        let elements = document.querySelectorAll('input[type="checkbox"]')

        for (let i = 0; i < elements.length; ++i)
        {
            // console.log(elements[i]);
            elements[i].addEventListener("click", radioCheckbox_onClick, false);

        } // Next i 

    } // End Function radioCheckbox 


    function onDomReady()
    {
        console.log("dom ready");
        subscribeEvent(document, "click", 
            'input[type="checkbox"]', 
            radioCheckbox_onClick
        ); 

        // radioCheckbox();
    }

    if (document.addEventListener) document.addEventListener("DOMContentLoaded", onDomReady, false);
    else if (document.attachEvent) document.attachEvent("onreadystatechange", onDomReady);
    else window.onload = onDomReady;

    function onPageLoaded() {
        console.log("page loaded");
    }

    if (window.addEventListener) window.addEventListener("load", onPageLoaded, false);
    else if (window.attachEvent) window.attachEvent("onload", onPageLoaded);
    else window.onload = onPageLoaded;

File Not Found when running PHP with Nginx

try this command

sudo chmod 755 -R htdocs/

Check whether a value is a number in JavaScript or jQuery

there is a function called isNaN it return true if it's (Not-a-number) , so u can check for a number this way

if(!isNaN(miscCharge))
{
   //do some thing if it's a number
}else{
   //do some thing if it's NOT a number
}

hope it works

How to retrieve a single file from a specific revision in Git?

Using git show

To complete your own answer, the syntax is indeed

git show object
git show $REV:$FILE
git show somebranch:from/the/root/myfile.txt
git show HEAD^^^:test/test.py

The command takes the usual style of revision, meaning you can use any of the following:

  1. branch name (as suggested by ash)
  2. HEAD + x number of ^ characters
  3. The SHA1 hash of a given revision
  4. The first few (maybe 5) characters of a given SHA1 hash

Tip It's important to remember that when using "git show", always specify a path from the root of the repository, not your current directory position.

(Although Mike Morearty mentions that, at least with git 1.7.5.4, you can specify a relative path by putting "./" at the beginning of the path. For example:

git show HEAD^^:./test.py

)

Using git restore

With Git 2.23+ (August 2019), you can also use git restore which replaces the confusing git checkout command

git restore -s <SHA1>     -- afile
git restore -s somebranch -- afile

That would restore on the working tree only the file as present in the "source" (-s) commit SHA1 or branch somebranch.
To restore also the index:

git restore -s <SHA1> -SW -- afile

(-SW: short for --staged --worktree)

Using low-level git plumbing commands

Before git1.5.x, this was done with some plumbing:

git ls-tree <rev>
show a list of one or more 'blob' objects within a commit

git cat-file blob <file-SHA1>
cat a file as it has been committed within a specific revision (similar to svn cat). use git ls-tree to retrieve the value of a given file-sha1

git cat-file -p $(git-ls-tree $REV $file | cut -d " " -f 3 | cut -f 1)::

git-ls-tree lists the object ID for $file in revision $REV, this is cut out of the output and used as an argument to git-cat-file, which should really be called git-cat-object, and simply dumps that object to stdout.


Note: since Git 2.11 (Q4 2016), you can apply a content filter to the git cat-file output.

See commit 3214594, commit 7bcf341 (09 Sep 2016), commit 7bcf341 (09 Sep 2016), and commit b9e62f6, commit 16dcc29 (24 Aug 2016) by Johannes Schindelin (dscho).
(Merged by Junio C Hamano -- gitster -- in commit 7889ed2, 21 Sep 2016)

git config diff.txt.textconv "tr A-Za-z N-ZA-Mn-za-m <"
git cat-file --textconv --batch

Note: "git cat-file --textconv" started segfaulting recently (2017), which has been corrected in Git 2.15 (Q4 2017)

See commit cc0ea7c (21 Sep 2017) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfbc2fc, 28 Sep 2017)

How to get an object's property's value by property name?

Try this :

$obj = @{
    SomeProp = "Hello"
}

Write-Host "Property Value is $($obj."SomeProp")"

Input type for HTML form for integer

You should change your type to number If you accept decimals first and remove them on keyUp, you might solve this...

$("#state").on('keyup', function(){
    $(this).val($(this).val().replace(".", ''));
})

or

$("#state").on('keyup', function(){
    $(this).val(parseInt($(this).val()));
})

This will remove the period, but there is no 'Integer Type'.

How to wrap async function calls into a sync function in Node.js or Javascript?

There is a npm sync module also. which is used for synchronize the process of executing the query.

When you want to run parallel queries in synchronous way then node restrict to do that because it never wait for response. and sync module is much perfect for that kind of solution.

Sample code

/*require sync module*/
var Sync = require('sync');
    app.get('/',function(req,res,next){
      story.find().exec(function(err,data){
        var sync_function_data = find_user.sync(null, {name: "sanjeev"});
          res.send({story:data,user:sync_function_data});
        });
    });


    /*****sync function defined here *******/
    function find_user(req_json, callback) {
        process.nextTick(function () {

            users.find(req_json,function (err,data)
            {
                if (!err) {
                    callback(null, data);
                } else {
                    callback(null, err);
                }
            });
        });
    }

reference link: https://www.npmjs.com/package/sync

What is the difference between baud rate and bit rate?

Bits per second is straightforward. It is exactly what it sounds like. If I have 1000 bits and am sending them at 1000 bps, it will take exactly one second to transmit them.

Baud is symbols per second. If these symbols — the indivisible elements of your data encoding — are not bits, the baud rate will be lower than the bit rate by the factor of bits per symbol. That is, if there are 4 bits per symbol, the baud rate will be ¼ that of the bit rate.

This confusion arose because the early analog telephone modems weren't very complicated, so bps was equal to baud. That is, each symbol encoded one bit. Later, to make modems faster, communications engineers invented increasingly clever ways to send more bits per symbol.¹

Analogy

System 1, bits: Imagine a communication system with a telescope on the near side of a valley and a guy on the far side holding up one hand or the other. Call his left hand "0" and his right hand "1," and you have a system for communicating one binary digit — one bit — at a time.

System 2, baud: Now imagine that the guy on the far side of the valley is holding up playing cards instead of his bare hands. He is using a subset of the cards, ace through 8 in each suit, for a total of 32 cards. Each card — each symbol — encodes 5 bits: 00000 through 11111 in binary.²

Analysis

The System 2 guy can convey 5 bits of information per card in the same time it takes the System 1 guy to convey one bit by revealing one of his bare hands.

You see how the analogy seems to break down: finding a particular card in a deck and showing it takes longer than simply deciding to show your left or right hand. But, that just provides an opportunity to extend the analogy profitably.

A communications system with many bits per symbol faces a similar difficulty, because the encoding schemes required to send multiple bits per symbol are much more complicated than those that send only one bit at a time. To extend the analogy, then, the guy showing playing cards could have several people behind him sharing the work of finding the next card in the deck, handing him cards as fast as he can show them. The helpers are analogous to the more powerful processors required to produce the many-bits-per-baud encoding schemes.

That is to say, by using more processing power, System 2 can send data 5 times faster than the more primitive System 1.

Historical Vignette

What shall we do with our 5-bit code? It seems natural to an English speaker to use 26 of the 32 available code points for the English alphabet. We can use the remaining 6 code points for a space character and a small set of control codes and symbols.

Or, we could just use Baudot code, a 5-bit code invented by Émile Baudot, after whom the unit "baud" was coined.³


Footnotes and Digressions:

  1. For example, the V.34 standard defined a 3,429 baud mode at 8.4 bits per symbol to achieve 28.8 kbit/sec throughput.

    That standard only talks about the POTS side of the modem. The RS-232 side remains a 1 bit per symbol system, so you could also correctly call it a 28.8k baud modem. Confusing, but technically correct.

  2. I've purposely kept things simple here.

    One thing you might think about is whether the absence of a playing card conveys information. If it does, that implies the existence of some clock or latch signal, so that you can tell the information-carrying absence of a card from the gap between the display of two cards.

    Also, what do you do with the cards left over in a poker deck, 9 through King, and the Jokers? One idea would be to use them as special flags to carry metadata. For example, you'll need a way to indicate a short trailing block. If you need to send 128 bits of information, you're going to need to show 26 cards. The first 25 cards convey 5×25=125 bits, with the 26th card conveying the trailing 3 bits. You need some way to signal that the last two bits in the symbol should be disregarded.

  3. This is why the early analog telephone modems were specified in terms of baud instead of bps: communications engineers had been using that terminology since the telegraph days. They weren't trying to confuse bps and baud; it was simply a fact, in their minds, that these modems were transmitting one bit per symbol.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

I think you have not installed these features. see below in picture.

enter image description here

I also suffered from this problem some days ago. After installing this feature then I solved it. If you have not installed this feature then installed it.

Install Process:

  1. go to android studio
  2. Tools
  3. Android
  4. SDK Manager
  5. Appearance & Behavior
  6. Android SDK

Creating a batch file, for simple javac and java command execution

@author MADMILK
@echo off
:getback1
set /p jump1=Do you want to compile? Write yes/no : 
if %jump1% = yes
goto loop
if %jump1% = no
goto getback2
:: Important part here
:getback2
set /p jump2=Do you want to run a java program? Write yes/no : 
if %jump2% = yes
goto loop2
if %jump2% = no
goto getback1
:: Make a folder anywhere what you want to use for scripts, for example i make one.
cd desktop
:: This is the folder where is gonna be your script(s)
mkdir My Scripts
cd My Scripts
title Java runner/compiler
echo REMEMBER! LOWER CASES AND UPPER CASES ARE IMPORTANT!
:loop
echo This is the java compiler program.
set /p jcVal=What java program do you want to compile? : 
javac %jcVal%
:loop2
echo This is the java code runner program.
set /p javaVal=What java program do you want to run? : 
java %javaVal%
pause >nul
echo Press NOTHING to leave

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

Since there's no mention of how to compile a .c file together with a bunch of .o files, and this comment asks for it:

where's the main.c in this answer? :/ if file1.c is the main, how do you link it with other already compiled .o files? – Tom Brito Oct 12 '14 at 19:45

$ gcc main.c lib_obj1.o lib_obj2.o lib_objN.o -o x0rbin

Here, main.c is the C file with the main() function and the object files (*.o) are precompiled. GCC knows how to handle these together, and invokes the linker accordingly and results in a final executable, which in our case is x0rbin.

You will be able to use functions not defined in the main.c but using an extern reference to functions defined in the object files (*.o).

You can also link with .obj or other extensions if the object files have the correct format (such as COFF).

AssertContains on strings in jUnit

use fest assert 2.0 whenever possible EDIT: assertj may have more assertions (a fork)

assertThat(x).contains("foo");

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Check Following : 1) Package names 2) Import Statements (import every required packages) 3) Proper set of braces ,i.e { } 4) Check Syntax too.. i.e semicolons,commas,etc.

JWT authentication for ASP.NET Web API

Here's a very minimal and secure implementation of a Claims based Authentication using JWT token in an ASP.NET Core Web API.

first of all, you need to expose an endpoint that returns a JWT token with claims assigned to a user:

 /// <summary>
        /// Login provides API to verify user and returns authentication token.
        /// API Path:  api/account/login
        /// </summary>
        /// <param name="paramUser">Username and Password</param>
        /// <returns>{Token: [Token] }</returns>
        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<IActionResult> Login([FromBody] UserRequestVM paramUser, CancellationToken ct)
        {

            var result = await UserApplication.PasswordSignInAsync(paramUser.Email, paramUser.Password, false, lockoutOnFailure: false);

            if (result.Succeeded)
            {
                UserRequestVM request = new UserRequestVM();
                request.Email = paramUser.Email;


                ApplicationUser UserDetails = await this.GetUserByEmail(request);
                List<ApplicationClaim> UserClaims = await this.ClaimApplication.GetListByUser(UserDetails);

                var Claims = new ClaimsIdentity(new Claim[]
                                {
                                    new Claim(JwtRegisteredClaimNames.Sub, paramUser.Email.ToString()),
                                    new Claim(UserId, UserDetails.UserId.ToString())
                                });


                //Adding UserClaims to JWT claims
                foreach (var item in UserClaims)
                {
                    Claims.AddClaim(new Claim(item.ClaimCode, string.Empty));
                }

                var tokenHandler = new JwtSecurityTokenHandler();
                  // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                var encryptionkey = Configuration["Jwt:Encryptionkey"];
                var key = Encoding.ASCII.GetBytes(encryptionkey);
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Issuer = Configuration["Jwt:Issuer"],
                    Subject = Claims,

                // this information will be retrived from you Configuration
                //I have injected Configuration provider service into my controller
                    Expires = DateTime.UtcNow.AddMinutes(Convert.ToDouble(Configuration["Jwt:ExpiryTimeInMinutes"])),

                    //algorithm to sign the token
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)

                };

                var token = tokenHandler.CreateToken(tokenDescriptor);
                var tokenString = tokenHandler.WriteToken(token);

                return Ok(new
                {
                    token = tokenString
                });
            }

            return BadRequest("Wrong Username or password");
        }

now you need to Add Authentication to your services in your ConfigureServices inside your startup.cs to add JWT authentication as your default authentication service like this:

services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
             .AddJwtBearer(cfg =>
             {
                 cfg.RequireHttpsMetadata = false;
                 cfg.SaveToken = true;
                 cfg.TokenValidationParameters = new TokenValidationParameters()
                 {
                     //ValidateIssuerSigningKey = true,
                     IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["JWT:Encryptionkey"])),
                     ValidateAudience = false,
                     ValidateLifetime = true,
                     ValidIssuer = configuration["Jwt:Issuer"],
                     //ValidAudience = Configuration["Jwt:Audience"],
                     //IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:Key"])),
                 };
             });

now you can add policies to your authorization services like this:

services.AddAuthorization(options =>
            {
                options.AddPolicy("YourPolicyNameHere",
                                policy => policy.RequireClaim("YourClaimNameHere"));
            });

ALTERNATIVELY, You can also (not necessary) populate all of your claims from your database as this will only run once on your application startup and add them to policies like this:

  services.AddAuthorization(async options =>
            {
                var ClaimList = await claimApplication.GetList(applicationClaim);
                foreach (var item in ClaimList)
                {                        
                    options.AddPolicy(item.ClaimCode, policy => policy.RequireClaim(item.ClaimCode));                       
                }
            });

now you can put the Policy filter on any of the methods that you want to be authorized like this:

 [HttpPost("update")]
        [Authorize(Policy = "ACC_UP")]
        public async Task<IActionResult> Update([FromBody] UserRequestVM requestVm, CancellationToken ct)
        {
//your logic goes here
}

Hope this helps

How to use LogonUser properly to impersonate domain user from workgroup client

this works for me, full working example (I wish more people would do this):

//logon impersonation
using System.Runtime.InteropServices; // DllImport
using System.Security.Principal; // WindowsImpersonationContext
using System.Security.Permissions; // PermissionSetAttribute

...

class Program {

    // obtains user token
    [DllImport("advapi32.dll", SetLastError = true)]
    public static extern bool LogonUser(string pszUsername, string pszDomain, string pszPassword,
        int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

    // closes open handes returned by LogonUser
    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    public extern static bool CloseHandle(IntPtr handle);

    public void DoWorkUnderImpersonation() {
        //elevate privileges before doing file copy to handle domain security
        WindowsImpersonationContext impersonationContext = null;
        IntPtr userHandle = IntPtr.Zero;
        const int LOGON32_PROVIDER_DEFAULT = 0;
        const int LOGON32_LOGON_INTERACTIVE = 2;
        string domain = ConfigurationManager.AppSettings["ImpersonationDomain"];
        string user = ConfigurationManager.AppSettings["ImpersonationUser"];
        string password = ConfigurationManager.AppSettings["ImpersonationPassword"];

        try {
            Console.WriteLine("windows identify before impersonation: " + WindowsIdentity.GetCurrent().Name);

            // if domain name was blank, assume local machine
            if (domain == "")
                domain = System.Environment.MachineName;

            // Call LogonUser to get a token for the user
            bool loggedOn = LogonUser(user,
                                        domain,
                                        password,
                                        LOGON32_LOGON_INTERACTIVE,
                                        LOGON32_PROVIDER_DEFAULT,
                                        ref userHandle);

            if (!loggedOn) {
                Console.WriteLine("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
                return;
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);

            Console.WriteLine("Main() windows identify after impersonation: " + WindowsIdentity.GetCurrent().Name);

            //run the program with elevated privileges (like file copying from a domain server)
            DoWork();

        } catch (Exception ex) {
            Console.WriteLine("Exception impersonating user: " + ex.Message);
        } finally {
            // Clean up
            if (impersonationContext != null) {
                impersonationContext.Undo();
            }

            if (userHandle != IntPtr.Zero) {
                CloseHandle(userHandle);
            }
        }
    }


    private void DoWork() {
        //everything in here has elevated privileges

        //example access files on a network share through e$ 
        string[] files = System.IO.Directory.GetFiles(@"\\domainserver\e$\images", "*.jpg");
    }
}

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

Any reason to prefer getClass() over instanceof when generating .equals()?

Angelika Langers Secrets of equals gets into that with a long and detailed discussion for a few common and well-known examples, including by Josh Bloch and Barbara Liskov, discovering a couple of problems in most of them. She also gets into the instanceof vs getClass. Some quote from it

Conclusions

Having dissected the four arbitrarily chosen examples of implementations of equals() , what do we conclude?

First of all: there are two substantially different ways of performing the check for type match in an implementation of equals() . A class can allow mixed-type comparison between super- and subclass objects by means of the instanceof operator, or a class can treat objects of different type as non-equal by means of the getClass() test. The examples above illustrated nicely that implementations of equals() using getClass() are generally more robust than those implementations using instanceof .

The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

Vector of structs initialization

Create vector, push_back element, then modify it as so:

struct subject {
    string name;
    int marks;
    int credits;
};


int main() {
    vector<subject> sub;

    //Push back new subject created with default constructor.
    sub.push_back(subject());

    //Vector now has 1 element @ index 0, so modify it.
    sub[0].name = "english";

    //Add a new element if you want another:
    sub.push_back(subject());

    //Modify its name and marks.
    sub[1].name = "math";
    sub[1].marks = 90;
}

You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

nginx showing blank PHP pages

I had a similar error , but in combination with Nextcloud. So in case this did not work, try: Having a look at the Nginx manual.

AngularJS - Trigger when radio button is selected

Should use ngChange instead of ngClick if trigger source is not from click.

Is the below what you want ? what exactly doesn't work in your case ?

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

function MyCtrl($scope) {
    $scope.value = "none" ;
    $scope.isChecked = false;
    $scope.checkStuff = function () {
        $scope.isChecked = !$scope.isChecked;
    }
}


<div ng-controller="MyCtrl">
    <input type="radio" ng-model="value" value="one" ng-change="checkStuff()" />
    <span> {{value}} isCheck:{{isChecked}} </span>
</div>   

ActionController::InvalidAuthenticityToken

I had the same issue on localhost. I have changed the domain for the app, but in URLs and hosts file there was still the old domain. Updated my browser bookmarks and hosts file to use new domain and now everything works fine.

How can I check the size of a file in a Windows batch script?

This was my solution for evaluating file sizes without using VB/perl/etc. and sticking with native windows shell commands:

FOR /F "tokens=4 delims= " %%i in ('dir /-C %temp% ^| find /i "filename.txt"') do (  
    IF %%i GTR 1000000 (  
        echo filename.txt filesize is greater than 1000000  
    ) ELSE (  
        echo filename.txt filesize is less than 1000000  
    )
)  

Not the cleanest solution, but it gets the job done.

What's the difference between lists enclosed by square brackets and parentheses in Python?

They are not lists, they are a list and a tuple. You can read about tuples in the Python tutorial. While you can mutate lists, this is not possible with tuples.

In [1]: x = (1, 2)

In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

/home/user/<ipython console> in <module>()

TypeError: 'tuple' object does not support item assignment

CSS: Auto resize div to fit container width

You could use css3 flexible box, it would go like this:

First your wrapper is wrapping a lot of things so you need a wrapper just for the 2 horizontal floated boxes:

 <div id="hor-box"> 
    <div id="left">
        left
      </div>
    <div id="content">
       content
    </div>
</div>

And your css3 should be:

#hor-box{   
  display: -webkit-box;
  display: -moz-box;
  display: box;

 -moz-box-orient: horizontal;
 box-orient: horizontal; 
 -webkit-box-orient: horizontal;

}  
#left   {
      width:200px;
      background-color:antiquewhite;
      margin-left:10px;

     -webkit-box-flex: 0;
     -moz-box-flex: 0;
     box-flex: 0;  
}  
#content   {
      min-width:700px;
      margin-left:10px;
      background-color:AppWorkspace;

     -webkit-box-flex: 1;
     -moz-box-flex: 1;
      box-flex: 1; 
}

Using FileSystemWatcher to monitor a directory

The problem was the notify filters. The program was trying to open a file that was still copying. I removed all of the notify filters except for LastWrite.

private void watch()
{
  FileSystemWatcher watcher = new FileSystemWatcher();
  watcher.Path = path;
  watcher.NotifyFilter = NotifyFilters.LastWrite;
  watcher.Filter = "*.*";
  watcher.Changed += new FileSystemEventHandler(OnChanged);
  watcher.EnableRaisingEvents = true;
}

Convert Date/Time for given Timezone - java

Your approach works without any modification.

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
// Timestamp for 2011-10-06 03:35:05 GMT
calendar.setTime(new Date(1317872105000L));

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z"); 
formatter.setTimeZone(TimeZone.getTimeZone("GMT+13"));

// Prints 2011-10-06 16:35:05 GMT+13:00
System.out.println(formatter.format(calendar.getTime()));

Implementing a HashMap in C

Well if you know the basics behind them, it shouldn't be too hard.

Generally you create an array called "buckets" that contain the key and value, with an optional pointer to create a linked list.

When you access the hash table with a key, you process the key with a custom hash function which will return an integer. You then take the modulus of the result and that is the location of your array index or "bucket". Then you check the unhashed key with the stored key, and if it matches, then you found the right place.

Otherwise, you've had a "collision" and must crawl through the linked list and compare keys until you match. (note some implementations use a binary tree instead of linked list for collisions).

Check out this fast hash table implementation:

https://attractivechaos.wordpress.com/2009/09/29/khash-h/

Retrofit 2.0 how to get deserialised error response.body

This way you do not need a Retrofit instance if you only are injecting a service created from Retrofit.

public class ErrorUtils {

  public static APIError parseError(Context context, Response<?> response) {

    APIError error = new APIError();

    try {
        Gson gson = new Gson();
        error = gson.fromJson(response.errorBody().charStream(), APIError.class);
    } catch (Exception e) {
        Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
    }

    if (TextUtils.isEmpty(error.getErrorMessage())) {
        error.setError(response.raw().message());
    }
    return error;
  }
}

Use it like this:

if (response.isSuccessful()) {

      ...

    } else {

      String msg = ErrorUtils.parseError(fragment.getActivity(), response).getError(); // would be from your error class
      Snackbar.make(someview, msg, Snackbar.LENGTH_LONG).show();
    }
  }

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

Make sure that your password doesn't have special characters and just keep a plain password (for ex: 12345), it will work. This is the strangest thing that I have ever seen. I spent about 2 hours to figure this out.

Note: 12345 mentioned below is your plain password

GRANT ALL PRIVILEGES ON dbname.* TO 'yourusername'@'%' IDENTIFIED BY '12345';

How to implement the ReLU function in Numpy

You can do it in much easier way:

def ReLU(x):
    return x * (x > 0)

def dReLU(x):
    return 1. * (x > 0)

How do I set the background color of my main screen in Flutter?

There are many ways of doing it, I am listing few here.

  1. Using backgroundColor

    Scaffold(
      backgroundColor: Colors.black,
      body: Center(...),
    )
    
  2. Using Container in SizedBox.expand

    Scaffold(
      body: SizedBox.expand(
        child: Container(
          color: Colors.black,
          child: Center(...)
        ),
      ),
    )
    
  3. Using Theme

    Theme(
      data: Theme.of(context).copyWith(scaffoldBackgroundColor: Colors.black),
      child: Scaffold(
        body: Center(...),
      ),
    )
    

How to retrieve form values from HTTPPOST, dictionary or?

You could have your controller action take an object which would reflect the form input names and the default model binder will automatically create this object for you:

[HttpPost]
public ActionResult SubmitAction(SomeModel model)
{
    var value1 = model.SimpleProp1;
    var value2 = model.SimpleProp2;
    var value3 = model.ComplexProp1.SimpleProp1;
    ...

    ... return something ...
}

Another (obviously uglier) way is:

[HttpPost]
public ActionResult SubmitAction()
{
    var value1 = Request["SimpleProp1"];
    var value2 = Request["SimpleProp2"];
    var value3 = Request["ComplexProp1.SimpleProp1"];
    ...

    ... return something ...
}

Convert character to Date in R

The easiest way is to use lubridate:

library(lubridate)
prods.all$Date2 <- mdy(prods.all$Date2)

This function automatically returns objects of class POSIXct and will work with either factors or characters.

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

Presumably, that's the Lombok @Slf4j annotation you're using. You'll need to install the Lombok plugin in IntelliJ if you want IntelliJ to recognize Lombok annotations. Otherwise, what do you expect if you try to use a field that doesn't exist?

How to resize image (Bitmap) to a given size?

Bitmap scaledBitmap = scaleDown(realImage, MAX_IMAGE_SIZE, true);

Scale down method:

public static Bitmap scaleDown(Bitmap realImage, float maxImageSize,
        boolean filter) {
    float ratio = Math.min(
            (float) maxImageSize / realImage.getWidth(),
            (float) maxImageSize / realImage.getHeight());
    int width = Math.round((float) ratio * realImage.getWidth());
    int height = Math.round((float) ratio * realImage.getHeight());

    Bitmap newBitmap = Bitmap.createScaledBitmap(realImage, width,
            height, filter);
    return newBitmap;
}

Limiting the output of PHP's echo to 200 characters

<?php echo substr($row['style_info'], 0, 200) .((strlen($row['style_info']) > 200) ? '...' : ''); ?> 

Are static methods inherited in Java?

All methods that are accessible are inherited by subclasses.

From the Sun Java Tutorials:

A subclass inherits all of the public and protected members of its parent, no matter what package the subclass is in. If the subclass is in the same package as its parent, it also inherits the package-private members of the parent. You can use the inherited members as is, replace them, hide them, or supplement them with new members

The only difference with inherited static (class) methods and inherited non-static (instance) methods is that when you write a new static method with the same signature, the old static method is just hidden, not overridden.

From the page on the difference between overriding and hiding.

The distinction between hiding and overriding has important implications. The version of the overridden method that gets invoked is the one in the subclass. The version of the hidden method that gets invoked depends on whether it is invoked from the superclass or the subclass

How to view table contents in Mysql Workbench GUI?

Inside the workbench right click the table in question and click "Select Rows - Limit 1000." It's the first option in the pop-up menu.

'"SDL.h" no such file or directory found' when compiling

the simplest idea is to add pkg-config --cflags --libs sdl2 while compiling the code.

g++ file.cpp `pkg-config --cflags --libs sdl2`

Remove "whitespace" between div element

The cleanest way to fix this is to apply the vertical-align: top property to you CSS rules:

#div1 div {
   width:30px;height:30px;
   border:blue 1px solid;
   display:inline-block;
   *display:inline;zoom:1;
   margin:0px;outline:none;
   vertical-align: top;
}

If you were to add content to your div's, then using either line-height: 0 or font-size: 0 would cause problems with your text layout.

See fiddle: http://jsfiddle.net/audetwebdesign/eJqaZ/

Where This Problem Comes From

This problem can arise when a browser is in "quirks" mode. In this example, changing the doctype from:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

to

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Strict//EN">

will change how the browser deals with extra whitespace.

In quirks mode, the whitespace is ignored, but preserved in strict mode.

References:

html doctype adds whitespace?

https://developer.mozilla.org/en/Images,_Tables,_and_Mysterious_Gaps

Conditional Logic on Pandas DataFrame

In [34]: import pandas as pd

In [35]: import numpy as np

In [36]:  df = pd.DataFrame([1,2,3,4], columns=["data"])

In [37]: df
Out[37]: 
   data
0     1
1     2
2     3
3     4

In [38]: df["desired_output"] = np.where(df["data"] <2.5, "False", "True")

In [39]: df
Out[39]: 
   data desired_output
0     1          False
1     2          False
2     3           True
3     4           True

What is the difference between synchronous and asynchronous programming (in node.js)

The difference between these two approaches is as follows:

Synchronous way: It waits for each operation to complete, after that only it executes the next operation. For your query: The console.log() command will not be executed until & unless the query has finished executing to get all the result from Database.

Asynchronous way: It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available. For your query: The console.log() command will be executed soon after the Database.Query() method. While the Database query runs in the background and loads the result once it is finished retrieving the data.

Use cases

  1. If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.

  2. In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.

iPhone X / 8 / 8 Plus CSS media queries

iPhone X

@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

iPhone 8

@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

iPhone 8 Plus

@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }


iPhone 6+/6s+/7+/8+ share the same sizes, while the iPhone 7/8 also do.


Looking for a specific orientation ?

Portrait

Add the following rule:

    and (orientation : portrait) 

Landscape

Add the following rule:

    and (orientation : landscape) 



References:

How to select the first element with a specific attribute using XPath

for ex.

<input b="demo">

And

(input[@b='demo'])[1]

Iterate over each line in a string in PHP

preg_split the variable containing the text, and iterate over the returned array:

foreach(preg_split("/((\r?\n)|(\r\n?))/", $subject) as $line){
    // do stuff with $line
} 

error: request for member '..' in '..' which is of non-class type

Certainly a corner case for this error, but I received it in a different situation, when attempting to overload the assignment operator=. It was a bit cryptic IMO (from g++ 8.1.1).

#include <cstdint>

enum DataType
{
  DT_INT32,
  DT_FLOAT
};

struct PrimitiveData
{
  union MyData
  {
    int32_t i;
    float f;
  } data;

  enum DataType dt;

  template<typename T>
  void operator=(T data)
  {
    switch(dt)
    {
      case DT_INT32:
      {
        data.i = data;
        break;
      }
      case DT_FLOAT:
      {
        data.f = data;
        break;
      }
      default:
      {
        break;
      }
    }
  }
};

int main()
{
  struct PrimitiveData pd;
  pd.dt = DT_FLOAT;
  pd = 3.4f;

  return 0;
}

I received 2 "identical" errors

error: request for member ‘i’ [and 'f'] in ‘data’, which is of non-class type ‘float’

(The equivalent error for clang is: error: member reference base type 'float' is not a structure or union)

for the lines data.i = data; and data.f = data;. Turns out the compiler was confusing local variable name 'data' and my member variable data. When I changed this to void operator=(T newData) and data.i = newData;, data.f = newData;, the error went away.

Show Hide div if, if statement is true

Probably the easiest to hide a div and show a div in PHP based on a variables and the operator.

<?php 
$query3 = mysql_query($query3);
$numrows = mysql_num_rows($query3);
?>
<html>
<?php if($numrows > null){ ?>
     no meow :-(
<?php } ?>

<?php if($numrows < null){ ?>
     lots of meow
<?php } ?>
</html>

Here is my original code before adding your requirements:

<?php 
$address = 'meow';
?>
<?php if($address == null){ ?>
     no meow :-(
<?php } ?>

<?php if($address != null){ ?>
     lots of meow
<?php } ?>

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

This warning also appears if you are using the log4jdbc-spring-boot-starter library directly.

However there is a config to choose the correct driver yourself. Put this in your application.properties:

log4jdbc.drivers=com.mysql.cj.jdbc.Driver
log4jdbc.auto.load.popular.drivers=false

See documentation on Github

How to export data to CSV in PowerShell?

simply use the Out-File cmd but DON'T forget to give an encoding type: -Encoding UTF8

so use it so:

$log | Out-File -Append C:\as\whatever.csv -Encoding UTF8

-Append is required if you want to write in the file more then once.

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

The (m) indicates the column display width; applications such as the MySQL client make use of this when showing the query results.

For example:

| v   | a   |  b  |   c |
+-----+-----+-----+-----+
| 1   | 1   |  1  |   1 |
| 10  | 10  | 10  |  10 |
| 100 | 100 | 100 | 100 |

Here a, b and c are using TINYINT(1), TINYINT(2) and TINYINT(3) respectively. As you can see, it pads the values on the left side using the display width.

It's important to note that it does not affect the accepted range of values for that particular type, i.e. TINYINT(1) still accepts [-128 .. 127].

How to open, read, and write from serial port in C?

I wrote this a long time ago (from years 1985-1992, with just a few tweaks since then), and just copy and paste the bits needed into each project.

You must call cfmakeraw on a tty obtained from tcgetattr. You cannot zero-out a struct termios, configure it, and then set the tty with tcsetattr. If you use the zero-out method, then you will experience unexplained intermittent failures, especially on the BSDs and OS X. "Unexplained intermittent failures" include hanging in read(3).

#include <errno.h>
#include <fcntl.h> 
#include <string.h>
#include <termios.h>
#include <unistd.h>

int
set_interface_attribs (int fd, int speed, int parity)
{
        struct termios tty;
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tcgetattr", errno);
                return -1;
        }

        cfsetospeed (&tty, speed);
        cfsetispeed (&tty, speed);

        tty.c_cflag = (tty.c_cflag & ~CSIZE) | CS8;     // 8-bit chars
        // disable IGNBRK for mismatched speed tests; otherwise receive break
        // as \000 chars
        tty.c_iflag &= ~IGNBRK;         // disable break processing
        tty.c_lflag = 0;                // no signaling chars, no echo,
                                        // no canonical processing
        tty.c_oflag = 0;                // no remapping, no delays
        tty.c_cc[VMIN]  = 0;            // read doesn't block
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        tty.c_iflag &= ~(IXON | IXOFF | IXANY); // shut off xon/xoff ctrl

        tty.c_cflag |= (CLOCAL | CREAD);// ignore modem controls,
                                        // enable reading
        tty.c_cflag &= ~(PARENB | PARODD);      // shut off parity
        tty.c_cflag |= parity;
        tty.c_cflag &= ~CSTOPB;
        tty.c_cflag &= ~CRTSCTS;

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
        {
                error_message ("error %d from tcsetattr", errno);
                return -1;
        }
        return 0;
}

void
set_blocking (int fd, int should_block)
{
        struct termios tty;
        memset (&tty, 0, sizeof tty);
        if (tcgetattr (fd, &tty) != 0)
        {
                error_message ("error %d from tggetattr", errno);
                return;
        }

        tty.c_cc[VMIN]  = should_block ? 1 : 0;
        tty.c_cc[VTIME] = 5;            // 0.5 seconds read timeout

        if (tcsetattr (fd, TCSANOW, &tty) != 0)
                error_message ("error %d setting term attributes", errno);
}


...
char *portname = "/dev/ttyUSB1"
 ...
int fd = open (portname, O_RDWR | O_NOCTTY | O_SYNC);
if (fd < 0)
{
        error_message ("error %d opening %s: %s", errno, portname, strerror (errno));
        return;
}

set_interface_attribs (fd, B115200, 0);  // set speed to 115,200 bps, 8n1 (no parity)
set_blocking (fd, 0);                // set no blocking

write (fd, "hello!\n", 7);           // send 7 character greeting

usleep ((7 + 25) * 100);             // sleep enough to transmit the 7 plus
                                     // receive 25:  approx 100 uS per char transmit
char buf [100];
int n = read (fd, buf, sizeof buf);  // read up to 100 characters if ready to read

The values for speed are B115200, B230400, B9600, B19200, B38400, B57600, B1200, B2400, B4800, etc. The values for parity are 0 (meaning no parity), PARENB|PARODD (enable parity and use odd), PARENB (enable parity and use even), PARENB|PARODD|CMSPAR (mark parity), and PARENB|CMSPAR (space parity).

"Blocking" sets whether a read() on the port waits for the specified number of characters to arrive. Setting no blocking means that a read() returns however many characters are available without waiting for more, up to the buffer limit.


Addendum:

CMSPAR is needed only for choosing mark and space parity, which is uncommon. For most applications, it can be omitted. My header file /usr/include/bits/termios.h enables definition of CMSPAR only if the preprocessor symbol __USE_MISC is defined. That definition occurs (in features.h) with

#if defined _BSD_SOURCE || defined _SVID_SOURCE
 #define __USE_MISC     1
#endif

The introductory comments of <features.h> says:

/* These are defined by the user (or the compiler)
   to specify the desired environment:

...
   _BSD_SOURCE          ISO C, POSIX, and 4.3BSD things.
   _SVID_SOURCE         ISO C, POSIX, and SVID things.
...
 */

Error handling in AngularJS http get then construct

https://docs.angularjs.org/api/ng/service/$http

$http.get(url).success(successCallback).error(errorCallback);

Replace successCallback and errorCallback with your functions.

Edit: Laurent's answer is more correct considering he is using then. Yet I'm leaving this here as an alternative for the folks who will visit this question.

Why split the <script> tag when writing it with document.write()?

</script> has to be broken up because otherwise it would end the enclosing <script></script> block too early. Really it should be split between the < and the /, because a script block is supposed (according to SGML) to be terminated by any end-tag open (ETAGO) sequence (i.e. </):

Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "</" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.

However in practice browsers only end parsing a CDATA script block on an actual </script> close-tag.

In XHTML there is no such special handling for script blocks, so any < (or &) character inside them must be &escaped; like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:

<script type="text/javascript">
    document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>

How to calculate percentage when old value is ZERO

How to deal with Zeros when calculating percentage changes is the researcher's call and requires some domain expertise. If the researcher believes that it would not be distorting the data, s/he may simply add a very small constant to all values to get rid of all zeros. In financial series, when dealing with trading volume, for example, we may not want to do this because trading volume = 0 just means that: the asset did not trade at all. The meaning of volume = 0 may be very different from volume = 0.00000000001. This is my preferred strategy in cases whereby I can not logically add a small constant to all values. Consider the percentage change formula ((New-Old)/Old) *100. If New = 0, then percentage change would be -100%. This number indeed makes financial sense as long as it is the minimum percentage change in the series (This is indeed guaranteed to be the minimum percentage change in the series). Why? Because it shows that trading volume experiences maximum possible decrease, which is going from any number to 0, -100%. So, I'll be fine with this value being in my percentage change series. If I normalize that series, then even better since this (possibly) relatively big number in absolute value will be analyzed on the same scale as other variables are. Now, what if the Old value = 0. That's a trickier case. Percentage change due to going from 0 to 1 will be equal to that due to going from 0 to a million: infinity. The fact that we call both "infinity" percentage change is problematic. In this case, I would set the infinities equal to np.nan and interpolate them.

The following graph shows what I discussed above. Starting from series 1, we get series 4, which is ready to be analyzed, with no Inf or NaNs.

enter image description here

One more thing: a lot of the time, the reason for calculating percentage change is to stationarize the data. So, if your original series contains zero and you wish to convert it to percentage change to achieve stationarity, first make sure it is not already stationary. Because if it is, you don't have to calculate percentage change. The point is that series that take the value of 0 a lot (the problem OP has) are very likely to be already stationary, for example the volume series I considered above. Imagine a series oscillating above and below zero, thus hitting 0 at times. Such a series is very likely already stationary.

Which Architecture patterns are used on Android?

Android also uses the ViewHolder design pattern.

It's used to improve performance of a ListView while scrolling it.

The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable processor cycles. Specifically, it avoids frequent calls of findViewById() during ListView scrolling, and that will make it smooth.

How to overcome "'aclocal-1.15' is missing on your system" warning?

Often, you don't need any auto* tools and the simplest solution is to simply run touch aclocal.m4 configure in the relevant folder (and also run touch on Makefile.am and Makefile.in if they exist). This will update the timestamp of aclocal.m4 and remind the system that aclocal.m4 is up-to-date and doesn't need to be rebuilt. After this, it's probably best to empty your build directory and rerun configure from scratch after doing this. I run into this problem regularly. For me, the root cause is that I copy a library (e.g. mpfr code for gcc) from another folder and the timestamps change.

Of course, this trick isn't valid if you really do need to regenerate those files, perhaps because you have manually changed them. But hopefully the developers of the package distribute up-to-date files.


And of course, if you do want to install automake and friends, then use the appropriate package-manager for your distribution.


Install aclocal which comes with automake:

brew install automake          # for Mac
apt-get install automake       # for Ubuntu

Try again:

./configure && make 

Why is __init__() always called after __new__()?

Use __new__ when you need to control the creation of a new instance.

Use __init__ when you need to control initialization of a new instance.

__new__ is the first step of instance creation. It's called first, and is responsible for returning a new instance of your class.

In contrast, __init__ doesn't return anything; it's only responsible for initializing the instance after it's been created.

In general, you shouldn't need to override __new__ unless you're subclassing an immutable type like str, int, unicode or tuple.

From April 2008 post: When to use __new__ vs. __init__? on mail.python.org.

You should consider that what you are trying to do is usually done with a Factory and that's the best way to do it. Using __new__ is not a good clean solution so please consider the usage of a factory. Here you have a good factory example.

Is Java RegEx case-insensitive?

Yes, case insensitivity can be enabled and disabled at will in Java regex.

It looks like you want something like this:

    System.out.println(
        "Have a meRry MErrY Christmas ho Ho hO"
            .replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
    );
    // Have a meRry Christmas ho

Note that the embedded Pattern.CASE_INSENSITIVE flag is (?i) not \?i. Note also that one superfluous \b has been removed from the pattern.

The (?i) is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.

It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w is case-insensitive.

To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA" to just "A".

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
    ); // A e I O u

Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i) in the appropriate place:

    System.out.println(
        "AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
            .replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
    ); // A eeEeeE I O uuUuUuu

More generally, you can enable and disable any flag within the pattern as you wish.

See also

Related questions

Uninstalling an MSI file from the command line without using msiexec

I'm assuming that when you type int file.msi into the command line, Windows is automatically calling msiexec file.msi for you. I'm assuming this because when you type in picture.png it brings up the default picture viewer.

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

Linq select objects in list where exists IN (A,B,C)

Just be careful, .Contains() will match any substring including the string that you do not expect. For eg. new[] { "A", "B", "AA" }.Contains("A") will return you both A and AA which you might not want. I have been bitten by it.

.Any() or .Exists() is safer choice

Shell script to copy files from one location to another location and rename add the current date to every file

path_src=./folder1
path_dst=./folder2
date=$(date +"%m%d%y")
for file_src in $path_src/*; do
  file_dst="$path_dst/$(basename $file_src | \
    sed "s/^\(.*\)\.\(.*\)/\1$date.\2/")"
  echo mv "$file_src" "$file_dst"
done

pgadmin4 : postgresql application server could not be contacted.

try this

I encountered the same problem and activated the setup file, it created a database, and was restarting again

sudo /usr/pgadmin4/bin/setup-web.sh

Combining multiple commits before pushing in Git

What you want to do is referred to as "squashing" in git. There are lots of options when you're doing this (too many?) but if you just want to merge all of your unpushed commits into a single commit, do this:

git rebase -i origin/master

This will bring up your text editor (-i is for "interactive") with a file that looks like this:

pick 16b5fcc Code in, tests not passing
pick c964dea Getting closer
pick 06cf8ee Something changed
pick 396b4a3 Tests pass
pick 9be7fdb Better comments
pick 7dba9cb All done

Change all the pick to squash (or s) except the first one:

pick 16b5fcc Code in, tests not passing
squash c964dea Getting closer
squash 06cf8ee Something changed
squash 396b4a3 Tests pass
squash 9be7fdb Better comments
squash 7dba9cb All done

Save your file and exit your editor. Then another text editor will open to let you combine the commit messages from all of the commits into one big commit message.

Voila! Googling "git squashing" will give you explanations of all the other options available.

How do I correctly clone a JavaScript object?

The most correct to copy object is use Object.create:

Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));

Such a notation will make identically the same object with right prototype and hidden properties.

How to fix Error: laravel.log could not be opened?

If problem persists after setting permissions right for the storage and bootstrap/cache folders, first confirm by turning off selinux with the command

setenforce 0 If this works after the above command, this should allow writing, but you've turned off added security server-wide. That's bad. Turn SELinux back.

setenforce 1 Then finally use SELinux to allow writing of the file by using this command

chcon -R -t httpd_sys_rw_content_t storage And you're good to go!

This link helped a lot!

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Java Wait for thread to finish

SwingWorker has doInBackground() which you can use to perform a task. You have the option to invoke get() and wait for the download to complete or you can override the done() method which will be invoked on the event dispatch thread once the SwingWorker completes.

The Swingworker has advantages to your current approach in that it has many of the features you are looking for so there is no need to reinvent the wheel. You are able to use the getProgress() and setProgress() methods as an alternative to an observer on the runnable for download progress. The done() method as I stated above is called after the worker finishes executing and is performed on the EDT, this allows you load the data after the download has completed.

How do I detect the Python version at runtime?

Per sys.hexversion and API and ABI Versioning:

import sys
if sys.hexversion >= 0x3000000:
    print('Python 3.x hexversion %s is in use.' % hex(sys.hexversion))

Convert JSON to Map

java.lang.reflect.Type mapType = new TypeToken<Map<String, Object>>(){}.getType();
Gson gson = new Gson();
Map<String, Object> categoryicons = gson.fromJson(json, mapType );

Xcode 'CodeSign error: code signing is required'

It happens when Xcode doesn't recognize your certificate.

It's just a pain in the ass to solve it, there are a lot of possibilities to help you.

But the first thing you should try is removing in the "Window" tab => Organizer, the provisioning that is in your device. Then re-add them (download them again on the apple website). And try to compile again.

By the way, did you check in the Project Info Window the "code signing identity" ?

Good Luck.

Inline IF Statement in C#

You can do inline ifs with

return y == 20 ? 1 : 2;

which will give you 1 if true and 2 if false.

Copy folder recursively, excluding some folders

You can use find with the -prune option.

An example from man find:

       cd /source-dir
       find . -name .snapshot -prune -o \( \! -name *~ -print0 \)|
       cpio -pmd0 /dest-dir

       This command copies the contents of /source-dir to /dest-dir, but omits
       files  and directories named .snapshot (and anything in them).  It also
       omits files or directories whose name ends in ~,  but  not  their  con-
       tents.  The construct -prune -o \( ... -print0 \) is quite common.  The
       idea here is that the expression before -prune matches things which are
       to  be  pruned.  However, the -prune action itself returns true, so the
       following -o ensures that the right hand side  is  evaluated  only  for
       those  directories  which didn't get pruned (the contents of the pruned
       directories are not even visited, so their  contents  are  irrelevant).
       The  expression on the right hand side of the -o is in parentheses only
       for clarity.  It emphasises that the -print0 action  takes  place  only
       for  things  that  didn't  have  -prune  applied  to them.  Because the
       default `and' condition between tests binds more tightly than -o,  this
       is  the  default anyway, but the parentheses help to show what is going
       on.

How to convert Blob to File in JavaScript

Use saveAs on FileSaver.js github project.

FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

codeigniter, result() vs. result_array()

result() returns Object type data. . . . result_array() returns Associative Array type data.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

How to read HDF5 files in Python

you can use Pandas.

import pandas as pd
pd.read_hdf(filename,key)

How to find rows that have a value that contains a lowercase letter

mysql> SELECT '1234aaaa578' REGEXP '^[a-z]';

Joining three tables using MySQL

Just adding a point to previous answers that in MySQL we can either use

table_factor syntax 

OR

joined_table syntax

mysql documentation

Table_factor example

SELECT prd.name, b.name 
FROM products prd, buyers b

Joined Table example

SELECT prd.name, b.name 
FROM products prd
 left join buyers b on b.bid = prd.bid;

FYI: Please ignore the fact the the left join on the joined table example doesnot make much sense (in reality we would use some sort of join table to link buyer to the product table instead of saving buyerID in product table).

Bootstrap Modal immediately disappearing

in case anyone using codeigniter 3 bootstrap with datatable.

below is my fix in config/ci_boostrap.php

//'assets/dist/frontend/lib.min.js',
//lib.min.js has conflict with datatables.js and i removed it replace with jquery.js
'assets/dist/frontend/jquery-3.3.1.min.js',
'assets/dist/frontend/app.min.js',
'assets/dist/datatables.js'

Largest and smallest number in an array

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Array_Small_and_lagest {
    class Program {
        static void Main(string[] args) {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for (int i = 0; i < 10; i++) {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            foreach (int i in array) {
                if (i < smallest) {
                    smallest = i;    
                }
            }
            int largest = array[9];
            foreach (int i in array) {    
                if (i > largest) {
                    largest = i;    
                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();        
        }
    }
}

How to add a custom right-click menu to a webpage?

<script language="javascript" type="text/javascript">
  document.oncontextmenu = RightMouseDown; 
  document.onmousedown = mouseDown; 

  function mouseDown(e) {
    if (e.which==3) {//righClick
      alert("Right-click menu goes here");
    } 
  }

  function RightMouseDown() { 
    return false; 
  }
</script>
</body> 
</html>

Disabling user input for UITextfield in swift

Another solution, declare your controller as UITextFieldDelegate, implement this call-back:

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    myTextField.delegate = self
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return false; //do not show keyboard nor cursor
    }
    return true
}

C# Double - ToString() formatting with two decimal places but no rounding

I know this is a old thread but I've just had to do this. While the other approaches here work, I wanted an easy way to be able to affect a lot of calls to string.format. So adding the Math.Truncate to all the calls to wasn't really a good option. Also as some of the formatting is stored in a database, it made it even worse.

Thus, I made a custom format provider which would allow me to add truncation to the formatting string, eg:

string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9

The implementation is pretty simple and is easily extendible to other requirements.

public class FormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof (ICustomFormatter))
        {
            return this;
        }
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null || arg.GetType() != typeof (double))
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
            }
        }

        if (format.StartsWith("T"))
        {
            int dp = 2;
            int idx = 1;
            if (format.Length > 1)
            {
                if (format[1] == '(')
                {
                    int closeIdx = format.IndexOf(')');
                    if (closeIdx > 0)
                    {
                        if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
                        {
                            idx = closeIdx + 1;
                        }
                    }
                    else
                    {
                        throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
                    }
                }
            }
            double mult = Math.Pow(10, dp);
            arg = Math.Truncate((double)arg * mult) / mult;
            format = format.Substring(idx);
        }

        try
        {
            return HandleOtherFormats(format, arg);
        }
        catch (FormatException e)
        {
            throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
        }
    }

    private string HandleOtherFormats(string format, object arg)
    {
        if (arg is IFormattable)
        {
            return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
        }
        return arg != null ? arg.ToString() : String.Empty;
    }
}

Postgres - Transpose Rows to Columns

If anyone else that finds this question and needs a dynamic solution for this where you have an undefined number of columns to transpose to and not exactly 3, you can find a nice solution here: https://github.com/jumpstarter-io/colpivot

SQL Switch/Case in 'where' clause

I'd say this is an indicator of a flawed table structure. Perhaps the different location types should be separated in different tables, enabling you to do much richer querying and also avoid having superfluous columns around.

If you're unable to change the structure, something like the below might work:

SELECT
    *
FROM
    Test
WHERE
    Account_Location = (
        CASE LocationType
          WHEN 'location' THEN @locationID
          ELSE Account_Location
        END
    )
    AND
    Account_Location_Area = (
        CASE LocationType
          WHEN 'area' THEN @locationID
          ELSE Account_Location_Area
        END
    )

And so forth... We can't change the structure of the query on the fly, but we can override it by making the predicates equal themselves out.

EDIT: The above suggestions are of course much better, just ignore mine.

What's the difference between select_related and prefetch_related in Django ORM?

As Django documentation says:

prefetch_related()

Returns a QuerySet that will automatically retrieve, in a single batch, related objects for each of the specified lookups.

This has a similar purpose to select_related, in that both are designed to stop the deluge of database queries that is caused by accessing related objects, but the strategy is quite different.

select_related works by creating an SQL join and including the fields of the related object in the SELECT statement. For this reason, select_related gets the related objects in the same database query. However, to avoid the much larger result set that would result from joining across a ‘many’ relationship, select_related is limited to single-valued relationships - foreign key and one-to-one.

prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python. This allows it to prefetch many-to-many and many-to-one objects, which cannot be done using select_related, in addition to the foreign key and one-to-one relationships that are supported by select_related. It also supports prefetching of GenericRelation and GenericForeignKey, however, it must be restricted to a homogeneous set of results. For example, prefetching objects referenced by a GenericForeignKey is only supported if the query is restricted to one ContentType.

More information about this: https://docs.djangoproject.com/en/2.2/ref/models/querysets/#prefetch-related

Setting WPF image source in code

Put the frame in a VisualBrush:

VisualBrush brush = new VisualBrush { TileMode = TileMode.None };

brush.Visual = frame;

brush.AlignmentX = AlignmentX.Center;
brush.AlignmentY = AlignmentY.Center;
brush.Stretch = Stretch.Uniform;

Put the VisualBrush in GeometryDrawing

GeometryDrawing drawing = new GeometryDrawing();

drawing.Brush = brush;

// Brush this in 1, 1 ratio
RectangleGeometry rect = new RectangleGeometry { Rect = new Rect(0, 0, 1, 1) };
drawing.Geometry = rect;

Now put the GeometryDrawing in a DrawingImage:

new DrawingImage(drawing);

Place this on your source of the image, and voilà!

You could do it a lot easier though:

<Image>
    <Image.Source>
        <BitmapImage UriSource="/yourassembly;component/YourImage.PNG"></BitmapImage>
    </Image.Source>
</Image>

And in code:

BitmapImage image = new BitmapImage { UriSource="/yourassembly;component/YourImage.PNG" };

Reverse HashMap keys and values in Java

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

Check if element is visible on screen

Could you use jQuery, since it's cross-browser compatible?

function isOnScreen(element)
{
    var curPos = element.offset();
    var curTop = curPos.top;
    var screenHeight = $(window).height();
    return (curTop > screenHeight) ? false : true;
}

And then call the function using something like:

if(isOnScreen($('#myDivId'))) { /* Code here... */ };

PHP move_uploaded_file() error?

On virtual hosting check your disk quota.

if quota exceed, move_uploaded_file return error.

PS : I've been looking for this for a long time :)

A reference to the dll could not be added

I just ran into that issue and after all the explanations about fixing it with command prompt I found that if you add it directly to the project you can then simply include the library on each page that it's needed

Any good, visual HTML5 Editor or IDE?

Just to point out, HTML5 per se is not "far from ready"; it is actually pretty much finished, "considered by the Working Group to fulfill the relevant requirements of its charter and any accompanying requirements documents." There will be some things to iron out, and the core spec has some accompanying addon bits, but the majority of it is actually ready to use right away, with much of it stable in latest browsers.

How do I convert certain columns of a data frame to become factors?

Given the following sample

myData <- data.frame(A=rep(1:2, 3), B=rep(1:3, 2), Pulse=20:25)  

then

myData$A <-as.factor(myData$A)
myData$B <-as.factor(myData$B)

or you could select your columns altogether and wrap it up nicely:

# select columns
cols <- c("A", "B")
myData[,cols] <- data.frame(apply(myData[cols], 2, as.factor))

levels(myData$A) <- c("long", "short")
levels(myData$B) <- c("1kg", "2kg", "3kg")

To obtain

> myData
      A   B Pulse
1  long 1kg    20
2 short 2kg    21
3  long 3kg    22
4 short 1kg    23
5  long 2kg    24
6 short 3kg    25

Check if a folder exist in a directory and create them using C#

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

How to list all the files in a commit?

Simplest form:

git show --stat (hash)

That's easier to remember and it will give you all the information you need.

If you really want only the names of the files you could add the --name-only option.

git show --stat --name-only (hash)

how to stop a for loop

To achieve this you would do something like:

n=L[0][0]
m=len(A)
for i in range(m):
    for j in range(m):
        if L[i][j]==n:
            //do some processing
        else:
            break;

Setting DataContext in XAML in WPF

First of all you should create property with employee details in the Employee class:

public class Employee
{
    public Employee()
    {
        EmployeeDetails = new EmployeeDetails();
        EmployeeDetails.EmpID = 123;
        EmployeeDetails.EmpName = "ABC";
    }

    public EmployeeDetails EmployeeDetails { get; set; }
}

If you don't do that, you will create instance of object in Employee constructor and you lose reference to it.

In the XAML you should create instance of Employee class, and after that you can assign it to DataContext.

Your XAML should look like this:

<Window x:Class="SampleApplication.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525"
    xmlns:local="clr-namespace:SampleApplication"
   >
    <Window.Resources>
        <local:Employee x:Key="Employee" />
    </Window.Resources>
    <Grid DataContext="{StaticResource Employee}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="200" />
        </Grid.ColumnDefinitions>

        <Label Grid.Row="0" Grid.Column="0" Content="ID:"/>
        <Label Grid.Row="1" Grid.Column="0" Content="Name:"/>
        <TextBox Grid.Column="1" Grid.Row="0" Margin="3" Text="{Binding EmployeeDetails.EmpID}" />
        <TextBox Grid.Column="1" Grid.Row="1" Margin="3" Text="{Binding EmployeeDetails.EmpName}" />
    </Grid>
</Window>

Now, after you created property with employee details you should binding by using this property:

Text="{Binding EmployeeDetails.EmpID}"

Using group by and having clause

1.Get supplier numbers and names for suppliers of parts supplied to at least two different projects.

 SELECT S.SID, S.NAME
 FROM SUPPLIES SP
 JOIN SUPPLIER S
 ON SP.SID = S.SID
 WHERE PID IN
 (SELECT PID FROM SUPPPLIES GROUP BY PID, JID HAVING COUNT(*) >= 2)

I am not slear about your second question

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child{
    color:red;
}
tr td:last-child {
    color:green
}

Or you can use other way like

// To first child 
tr td:nth-child(1){
    color:red;
}

// To last child 
tr td:nth-last-child(1){
    color:green;
}

Both way are perfectly working

html select option SELECTED

This is simple example by using ternary operator to set selected=selected

<?php $plan = array('1' => 'Green','2'=>'Red' ); ?>
<select class="form-control" title="Choose Plan">
<?php foreach ($plan as $key => $value) { ?>
  <option value="<?php echo $key;?>" <?php echo ($key ==  '2') ? ' selected="selected"' : '';?>><?php echo $value;?></option>
<?php } ?>
</select>

Get unicode value of a character

are you picky with using Unicode because with java its more simple if you write your program to use "dec" value or (HTML-Code) then you can simply cast data types between char and int

char a = 98;
char b = 'b';
char c = (char) (b+0002);

System.out.println(a);
System.out.println((int)b);
System.out.println((int)c);
System.out.println(c);

Gives this output

b
98
100
d

ImportError: No module named 'google'

kindly executed these commands.

pip install google
pip install google-core-api

will definitely solve your problem

Add new element to an existing object

You could store your JSON inside of an array and then insert the JSON data into the array with push

Check this out https://jsfiddle.net/cx2rk40e/2/

$(document).ready(function(){

  // using jQuery just to load function but will work without library.
  $( "button" ).on( "click", go );

  // Array of JSON we will append too.
  var jsonTest = [{
    "colour": "blue",
    "link": "http1"
  }]

  // Appends JSON to array with push. Then displays the data in alert.
  function go() {    
      jsonTest.push({"colour":"red", "link":"http2"});
      alert(JSON.stringify(jsonTest));    
    }

}); 

Result of JSON.stringify(jsonTest)

[{"colour":"blue","link":"http1"},{"colour":"red","link":"http2"}]

This answer maybe useful to users who wish to emulate a similar result.

css absolute position won't work with margin-left:auto margin-right: auto

I already had this same issue and I've got the solution writing a container (.divtagABS-container, in your case) absolutely positioned and then relatively positioning the content inside it (.divtagABS, in your case).

Done! The margin-left and margin-right AUTO for your .divtagABS will now work.

Xcode "Device Locked" When iPhone is unlocked

Another fix to this problem is to connect your iPhone with your Xcode open while your iPhone is in the homescreen, not in lockscreen or with an app opened.

How do I get JSON data from RESTful service using Python?

I would give the requests library a try for this. Essentially just a much easier to use wrapper around the standard library modules (i.e. urllib2, httplib2, etc.) you would use for the same thing. For example, to fetch json data from a url that requires basic authentication would look like this:

import requests

response = requests.get('http://thedataishere.com',
                         auth=('user', 'password'))
data = response.json()

For kerberos authentication the requests project has the reqests-kerberos library which provides a kerberos authentication class that you can use with requests:

import requests
from requests_kerberos import HTTPKerberosAuth

response = requests.get('http://thedataishere.com',
                         auth=HTTPKerberosAuth())
data = response.json()

How to get input type using jquery?

GetValue = function(id) {
  var tag = this.tagName;
  var type = this.attr("type");

  if (tag == "input" && (type == "checkbox" || type == "radio"))
    return this.is(":checked");

  return this.val();
};

Custom style to jquery ui dialogs

See http://jsfiddle.net/qP8DY/24/

You can add a class (such as "success-dialog" in my example) to div#success, either directly in your HTML, or in your JavaScript by adding to the dialogClass option, as I've done.

$('#success').dialog({
    height: 50,
    width: 350,
    modal: true,
    resizable: true,
    dialogClass: 'no-close success-dialog'
});

Then just add the success-dialog class to your CSS rules as appropriate. To indicate an element with two (or more) classes applied to it, just write them all together, with no spaces in between. For example:

.ui-dialog.success-dialog {
    font-family: Verdana,Arial,sans-serif;
    font-size: .8em;
}

How to make <div> fill <td> height

Modify the background image of the <td> itself.

Or apply some css to the div:

.thatSetsABackgroundWithAnIcon{
    height:100%;
}

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

The meaning of CascadeType.ALL is that the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

It seems in your case to be a bad idea, as removing an Address would lead to removing the related User. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.

BTW: you may want to add a mappedBy="addressOwner" attribute to your User to signal to the persistence provider that the join column should be in the ADDRESS table.

Flutter - Layout a Grid

Use whichever suits your need.

  1. GridView.count(...)

    GridView.count(
      crossAxisCount: 2,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  2. GridView.builder(...)

    GridView.builder(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      itemBuilder: (_, index) => FlutterLogo(),
      itemCount: 4,
    )
    
  3. GridView(...)

    GridView(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    
  4. GridView.custom(...)

    GridView.custom(
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
      childrenDelegate: SliverChildListDelegate(
        [
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
          FlutterLogo(),
        ],
      ),
    )
    
  5. GridView.extent(...)

    GridView.extent(
      maxCrossAxisExtent: 400,
      children: <Widget>[
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
        FlutterLogo(),
      ],
    )
    

Output (same for all):

enter image description here

Using Mockito to mock classes with generic parameters

I think you do need to cast it, but it shouldn't be too bad:

Foo<Bar> mockFoo = (Foo<Bar>) mock(Foo.class);
when(mockFoo.getValue()).thenReturn(new Bar());

Flutter: RenderBox was not laid out

Reason for the error:

Column tries to expands in vertical axis, and so does the ListView, hence you need to constrain the height of ListView.


Solutions

  1. Use either Expanded or Flexible if you want to allow ListView to take up entire left space in Column.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. Use SizedBox if you want to restrict the size of ListView to a certain height.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. Use shrinkWrap, if your ListView isn't too big.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

PHP Adding 15 minutes to Time value

strtotime returns the current timestamp and date is to format timestamp

  $date=strtotime(date("h:i:sa"))+900;//15*60=900 seconds
  $date=date("h:i:sa",$date);

This will add 15 mins to the current time

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

Passing array in GET for a REST call

Instead of using http GET, use http POST. And JSON. Or XML

This is how your request stream to the server would look like.

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

{users: [user:{id:id1}, user:{id:id2}]}

Or in XML,

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

<users><user id='id1'/><user id='id2'/></users>

You could certainly continue using GET as you have proposed, as it is certainly simpler.

/appointments?users=1d1,1d2

Which means you would have to keep your data structures very simple.

However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.

Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.

JQuery

If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.

Foreign key referencing a 2 columns primary key in SQL Server

Note that the fields must be in the same order. If the Primary Key you are referencing is specified as (Application, ID) then your foreign key must reference (Application, ID) and NOT (ID, Application) as they are seen as two different keys.

Get index of a key in json

Try this

var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
json = $.parseJSON(json);

var i = 0, req_index = "";
$.each(json, function(index, value){
    if(index == 'key2'){
        req_index = i;
    }
    i++;
});
alert(req_index);

What does "Error: object '<myvariable>' not found" mean?

Let's discuss why an "object not found" error can be thrown in R in addition to explaining what it means. What it means (to many) is obvious: the variable in question, at least according to the R interpreter, has not yet been defined, but if you see your object in your code there can be multiple reasons for why this is happening:

  1. check syntax of your declarations. If you mis-typed even one letter or used upper case instead of lower case in a later calling statement, then it won't match your original declaration and this error will occur.

  2. Are you getting this error in a notebook or markdown document? You may simply need to re-run an earlier cell that has your declarations before running the current cell where you are calling the variable.

  3. Are you trying to knit your R document and the variable works find when you run the cells but not when you knit the cells? If so - then you want to examine the snippet I am providing below for a possible side effect that triggers this error:

    {r sourceDataProb1, echo=F, eval=F} # some code here

The above snippet is from the beginning of an R markdown cell. If eval and echo are both set to False this can trigger an error when you try to knit the document. To clarify. I had a use case where I had left these flags as False because I thought i did not want my code echoed or its results to show in the markdown HTML I was generating. But since the variable was then used in later cells, this caused an error during knitting. Simple trial and error with T/F TRUE/FALSE flags can establish if this is the source of your error when it occurs in knitting an R markdown document from RStudio.

Lastly: did you remove the variable or clear it from memory after declaring it?

  • rm() removes the variable
  • hitting the broom icon in the evironment window of RStudio clearls everything in the current working environment
  • ls() can help you see what is active right now to look for a missing declaration.
  • exists("x") - as mentioned by another poster, can help you test a specific value in an environment with a very lengthy list of active variables

Access iframe elements in JavaScript

this code worked for me:

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId');

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

Another solution if you have installed android-studio-bundle-143.2915827-windows and gradle2.14

You can verify in C:\Program Files\Android\Android Studio\gradle if you have gradle-2.14.

Then you must go to C:\Users\\AndroidStudioProjects\android_app\

And in this build.gradle you put this code:

buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}

Then, go to C:\Users\Raul\AndroidStudioProjects\android_app\Desnutricion_infantil\app

And in this build.gradle you put:

apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion '24.0.0'
defaultConfig {
minSdkVersion 19
targetSdkVersion 23
versionCode 1
versionName "1.0"
}
}
dependencies {
compile 'com.android.support:appcompat-v7:23.3.0'
}

You must check your sdk version and the buildTools. compileSdkVersion 23 buildToolsVersion '24.0.0'

Save all changes and restart AndroidStudio and all should be fine !