Programs & Examples On #Intraweb 10

Prevent linebreak after </div>

I have many times succeeded to get div's without line breaks after them, by playing around with the float css attribute and the width css attribute.
Of course after working out the solution you have to test it in all browsers, and in each browser you have to re-size the windows to make sure that it works in all circumstances.

PHP: HTTP or HTTPS?

$protocol = strtolower(substr($_SERVER["SERVER_PROTOCOL"],0,5))=='https'?'https':'http';

$protocol = isset($_SERVER["HTTPS"]) ? 'https' : 'http';

These should both work

onchange equivalent in angular2

@Mark Rajcok gave a great solution for ion projects that include a range type input.

In any other case of non ion projects I will suggest this:

HTML:

<input type="text" name="points" #points maxlength="8" [(ngModel)]="range" (ngModelChange)="range=saverange($event, points)">

Component:

    onChangeAchievement(eventStr: string, eRef): string {

      //Do something (some manipulations) on input and than return it to be saved:

       //In case you need to force of modifing the Element-Reference value on-focus of input:
       var eventStrToReplace = eventStr.replace(/[^0-9,eE\.\+]+/g, "");
       if (eventStr != eventStrToReplace) {
           eRef.value = eventStrToReplace;
       }

      return this.getNumberOnChange(eventStr);

    }

The idea here:

  1. Letting the (ngModelChange) method to do the Setter job:

    (ngModelChange)="range=saverange($event, points)

  2. Enabling direct access to the native Dom element using this call:

    eRef.value = eventStrToReplace;

In python, how do I cast a class object to a dict

There is no magic method that will do what you want. The answer is simply name it appropriately. asdict is a reasonable choice for a plain conversion to dict, inspired primarily by namedtuple. However, your method will obviously contain special logic that might not be immediately obvious from that name; you are returning only a subset of the class' state. If you can come up with with a slightly more verbose name that communicates the concepts clearly, all the better.

Other answers suggest using __iter__, but unless your object is truly iterable (represents a series of elements), this really makes little sense and constitutes an awkward abuse of the method. The fact that you want to filter out some of the class' state makes this approach even more dubious.

Understanding colors on Android (six characters)

Android uses hexadecimal ARGB values, which are formatted as #AARRGGBB. That first pair of letters, the AA, represent the alpha channel. You must convert your decimal opacity values to a hexadecimal value. Here are the steps:

Alpha Hex Value Process

  1. Take your opacity as a decimal value and multiply it by 255. So, if you have a block that is 50% opaque the decimal value would be .5. For example: .5 x 255 = 127.5
  2. The fraction won't convert to hexadecimal, so you must round your number up or down to the nearest whole number. For example: 127.5 rounds up to 128; 55.25 rounds down to 55.
  3. Enter your decimal value in a decimal-to-hexadecimal converter, like http://www.binaryhexconverter.com/decimal-to-hex-converter, and convert your values.
  4. If you only get back a single value, prefix it with a zero. For example, if you're trying to get 5% opacity and you're going through this process, you'll end up with the hexadecimal value of D. Add a zero in front of it so it appears as 0D.

That's how you find the alpha channel value. I've taken the liberty to put together a list of values for you. Enjoy!

Hex Opacity Values

  • 100% — FF
  • 95% — F2
  • 90% — E6
  • 85% — D9
  • 80% — CC
  • 75% — BF
  • 70% — B3
  • 65% — A6
  • 60% — 99
  • 55% — 8C
  • 50% — 80
  • 45% — 73
  • 40% — 66
  • 35% — 59
  • 30% — 4D
  • 25% — 40
  • 20% — 33
  • 15% — 26
  • 10% — 1A
  • 5% — 0D
  • 0% — 00

What are ODEX files in Android?

ART

According to the docs: http://web.archive.org/web/20170909233829/https://source.android.com/devices/tech/dalvik/configure an .odex file:

contains AOT compiled code for methods in the APK.

Furthermore, they appear to be regular shared libraries, since if you get any app, and check:

file /data/app/com.android.appname-*/oat/arm64/base.odex

it says:

base.odex: ELF shared object, 64-bit LSB arm64, stripped

and aarch64-linux-gnu-objdump -d base.odex seems to work and give some meaningful disassembly (but also some rubbish sections).

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

How to use aria-expanded="true" to change a css property

If you were open to using JQuery, you could modify the background color for any link that has the property aria-expanded set to true by doing the following...

$("a[aria-expanded='true']").css("background-color", "#42DCA3");

Depending on how specific you want to be regarding which links this applies to, you may have to slightly modify your selector.

SyntaxError: missing ; before statement

I got this error, hope this will help someone:

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

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

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

jQuery datepicker, onSelect won't work

The function datepicker is case sensitive and all lowercase. The following however works fine for me:

$(document).ready(function() {
  $('.date-pick').datepicker( {
    onSelect: function(date) {
        alert(date);
    },
    selectWeek: true,
    inline: true,
    startDate: '01/01/2000',
    firstDay: 1
  });
});

JPanel Padding in Java

JPanel p=new JPanel();  
GridBagLayout layout=new GridBagLayout(); 
p.setLayout(layout); 
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill=GridBagConstraints.HORIZONTAL; 
gbc.gridx=0;   
gbc.gridy=0;   
p2.add("",gbc);

What's the difference between ViewData and ViewBag?

It uses the C# 4.0 dynamic feature. It achieves the same goal as viewdata and should be avoided in favor of using strongly typed view models (the same way as viewdata should be avoided).

So basically it replaces magic strings:

ViewData["Foo"]

with magic properties:

ViewBag.Foo

for which you have no compile time safety.

I continue to blame Microsoft for ever introducing this concept in MVC.

The name of the properties are case sensitive.

How to get image width and height in OpenCV?

You can use rows and cols:

cout << "Width : " << src.cols << endl;
cout << "Height: " << src.rows << endl;

or size():

cout << "Width : " << src.size().width << endl;
cout << "Height: " << src.size().height << endl;

Rendering HTML in a WebView with custom CSS

I assume that your style-sheet "style.css" is already located in the assets-folder

  1. load the web-page with jsoup:

    doc = Jsoup.connect("http://....").get();
    
  2. remove links to external style-sheets:

    // remove links to external style-sheets
    doc.head().getElementsByTag("link").remove();
    
  3. set link to local style-sheet:

    // set link to local stylesheet
    // <link rel="stylesheet" type="text/css" href="style.css" />
    doc.head().appendElement("link").attr("rel", "stylesheet").attr("type", "text/css").attr("href", "style.css");
    
  4. make string from jsoup-doc/web-page:

    String htmldata = doc.outerHtml();
    
  5. display web-page in webview:

    WebView webview = new WebView(this);
    setContentView(webview);
    webview.loadDataWithBaseURL("file:///android_asset/.", htmlData, "text/html", "UTF-8", null);
    

Android Material and appcompat Manifest merger failed

change your build.gradle dependencies into

 implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'

or

 implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'

Execute a large SQL script (with GO commands)

The "GO" batch separator keyword is actually used by SQL Management Studio itself, so that it knows where to terminate the batches it is sending to the server, and it is not passed to SQL server. You can even change the keyword in Management Studio, should you so desire.

Working with dictionaries/lists in R

Shorter variation of Dirk's answer:

# Create a Color Palette Dictionary 
> color <- c('navy.blue', 'gold', 'dark.gray')
> hex <- c('#336A91', '#F3C117', '#7F7F7F')

> # Create List
> color_palette <- as.list(hex)
> # Name List Items
> names(color_palette) <- color
> 
> color_palette
$navy.blue
[1] "#336A91"

$gold
[1] "#F3C117"

$dark.gray
[1] "#7F7F7F"

Finding the average of an array using JS

There's no built in function, but you can use this to get the sum,

Array.prototype.sum = function() {
    return this.reduce(function(a,b){return a+b;});
};

then divide by the arrays length, e.g.:

var arr = [1,2,3,4,5]
console.log(arr.sum() / arr.length)

How can I check if the current date/time is past a set date/time?

Check PHP's strtotime-function to convert your set date/time to a timestamp: http://php.net/manual/en/function.strtotime.php

If strtotime can't handle your date/time format correctly ("4:00PM" will probably work but not "at 4PM"), you'll need to use string-functions, e.g. substr to parse/correct your format and retrieve your timestamp through another function, e.g. mktime.

Then compare the resulting timestamp with the current date/time (if ($calulated_timestamp > time()) { /* date in the future */ }) to see whether the set date/time is in the past or the future.

I suggest to read the PHP-doc on date/time-functions and get back here with some of your source-code once you get stuck.

How do I disable log messages from the Requests library?

Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:

      ...
      'elasticsearch': {
          'handlers': ['console'],
          'level': logging.WARNING,
      },     
      ...

Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.

Choose File Dialog

Was looking for a file/folder browser myself recently and decided to make a new explorer activity (Android library): https://github.com/vaal12/AndroidFileBrowser

Matching Test application https://github.com/vaal12/FileBrowserTestApplication- is a sample how to use.

Allows picking directories and files from phone file structure.

Regex to extract substring, returning 2 results for some reason

Each group defined by parenthesis () is captured during processing and each captured group content is pushed into result array in same order as groups within pattern starts. See more on http://www.regular-expressions.info/brackets.html and http://www.regular-expressions.info/refcapture.html (choose right language to see supported features)

var source = "afskfsd33j"
var result = source.match(/a(.*)j/);

result: ["afskfsd33j", "fskfsd33"]

The reason why you received this exact result is following:

First value in array is the first found string which confirms the entire pattern. So it should definitely start with "a" followed by any number of any characters and ends with first "j" char after starting "a".

Second value in array is captured group defined by parenthesis. In your case group contain entire pattern match without content defined outside parenthesis, so exactly "fskfsd33".

If you want to get rid of second value in array you may define pattern like this:

/a(?:.*)j/

where "?:" means that group of chars which match the content in parenthesis will not be part of resulting array.

Other options might be in this simple case to write pattern without any group because it is not necessary to use group at all:

/a.*j/

If you want to just check whether source text matches the pattern and does not care about which text it found than you may try:

var result = /a.*j/.test(source);

The result should return then only true|false values. For more info see http://www.javascriptkit.com/javatutors/re3.shtml

An Authentication object was not found in the SecurityContext - Spring 3.2.2

This could also happens if you put a @PreAuthorize or @PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.

How to dismiss a Twitter Bootstrap popover by clicking outside?

We found out we had an issue with the solution from @mattdlockyer (thanks for the solution!). When using the selector property for the popover constructor like this...

$(document.body').popover({selector: '[data-toggle=popover]'});

...the proposed solution for BS3 won't work. Instead it creates a second popover instance local to its $(this). Here is our solution to prevent that:

$(document.body).on('click', function (e) {
    $('[data-toggle="popover"]').each(function () {
        //the 'is' for buttons that trigger popups
        //the 'has' for icons within a button that triggers a popup
        if (!$(this).is(e.target) && $(this).has(e.target).length === 0 && $('.popover').has(e.target).length === 0) {
            var bsPopover = $(this).data('bs.popover'); // Here's where the magic happens
            if (bsPopover) bsPopover.hide();
        }
    });
});

As mentioned the $(this).popover('hide'); will create a second instance due to the delegated listener. The solution provided only hides popovers which are already instanciated.

I hope I could save you guys some time.

Show / hide div on click with CSS

A little hack-ish but it works. Note that the label tag can be placed any where. The key parts are:

  • The css input:checked+div selects the div immediately next to/after the input
  • The label for said checkbox (or hey leave out the label and just have the checkbox)
  • display:none hides stuff

Code:

<head>
    <style>
        #sidebar {height:100%; background:blue; width:200px; clear:none; float:left;}
        #content {height:100%; background:green; width:400px; clear:none; float:left;}
        label {background:yellow;float:left;}
        input{display:none;}
        input:checked+#sidebar{display:none;}
    </style>
</head>
<body>
<div>
<label for="hider">Hide</label>
<input type="checkbox" id="hider">
<div id="sidebar">foo</div>

<div id="content">hello</div>

</div>
</body>

EDIT: Sorry could have read the question better.

One could also use css3 elements to create the slide/fade effect. I am not familiar enough with them to be much help with that aspect but they do exist. Browser support is iffy though.

You could combine the above effect with javascript to use fancy transitions and still have a fall back. jquery has a css method to override the above and slide and fade for transitions.

  • Tilda(~) mean some sibling after; not next sibling like plus(+).
  • [key="value"] is an attribute selector.
  • Radio buttons must have same name

To string tabs together one could use:

<html>
<head>
<style>
input[value="1"]:checked ~ div[id="1"]{
display:none;
}
input[value="2"]:checked ~ div[id="2"]{
display:none;
}
</style>
</head>
<body>
<input type="radio" name="hider" value="1">
<input type="radio" name="hider" value="2">
<div id="1">div 1</div>
<div id="2">div 2</div>
</body>
</html>

How to remove title bar from the android activity?

Add this two line in your style.xml

<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Go To Definition: "Cannot navigate to the symbol under the caret."

I've done all things above but my problem did not solve (trying to open project by VS 2017),

after that I realized that the problem was my csproj file. My project (mvc)

was created by VS 2015... So I edit my csproj file and replace

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

by this :

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.7\build\net45\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

It was all about the version of DotNetCompilerPlatform.

(the way that I understood this issue was that I created new mvc project by VS 2017 and compared both csproj files - the new one and the one that created by VS 2015 - )


Additional related info by https://stackoverflow.com/users/15667/xan (since answers are locked)

For me (VS2019 opening an older solution) it was only affecting one project in the solution. The Imports looked like this:

<Import Project="..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />
<Import Project="..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props" Condition="Exists('..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

The working projects only had the

<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />

line, so I removed the first 2 and intelisense / go to definition etc. started working again.

HOWEVER the web project now wouldn't run due to missing Roslyn csc compiler.

In the end the solution that worked overall was to update the Microsoft.CodeDom.Providers.DotNetCompilerPlatform and Microsoft.Net.Compilers Nuget packages for the project.

PHP Notice: Undefined offset: 1 with array when reading data

The output of the error, is because you call an index of the Array that does not exist, for example

$arr = Array(1,2,3);
echo $arr[3]; 
// Error PHP Notice:  Undefined offset: 1 pointer 3 does not exist, the array only has 3 elements but starts at 0 to 2, not 3!

How to override application.properties during production in Spring-Boot?

Update with Spring Boot 2.2.2.Release.

Full example here, https://www.surasint.com/spring-boot-override-property-example/

Assume that, in your jar file, you have the application.properties which have these two line:

server.servlet.context-path=/test
server.port=8081

Then, in production, you want to override the server.port=8888 but you don't want to override the other properties.

First you create another file, ex override.properties and have online this line:

server.port=8888

Then you can start the jar like this

java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties

Rename all files in a folder with a prefix in a single command

Also works for items with spaces and ignores directories

for f in *; do [[ -f "$f" ]] && mv "$f" "unix_$f"; done

How to convert View Model into JSON object in ASP.NET MVC?

<htmltag id=’elementId’ data-ZZZZ’=’@Html.Raw(Json.Encode(Model))’ />

Refer https://highspeedlowdrag.wordpress.com/2014/08/23/mvc-data-to-jquery-data/

I did below and it works like charm.

<input id="hdnElement" class="hdnElement" type="hidden" value='@Html.Raw(Json.Encode(Model))'>

cannot connect to pc-name\SQLEXPRESS

Follow these steps then you solve your problem 100%.

  1. When you get this error then close everything(Microsoft SQL Server Managment):

error

  1. Then open command prompt by pressing (window + r) keys and type services.msc and click OK or press Enter key.

  2. And search **SQL Server (SQLEXPRESS) as I show in the image.

enter image description here

  1. Now see left upper side and click start.

  2. If you open Microsoft SQL Server Management then you not get any type error.

Enjoy!!!

In Java, how to find if first character in a string is upper case without regex

Make sure you first check for null and empty and ten converts existing string to upper. Use S.O.P if want to see outputs otherwise boolean like Rabiz did.

 public static void main(String[] args)
 {
     System.out.println("Enter name");
     Scanner kb = new Scanner (System.in);
     String text =  kb.next();

     if ( null == text || text.isEmpty())
     {
         System.out.println("Text empty");
     }
     else if (text.charAt(0) == (text.toUpperCase().charAt(0)))
     {
         System.out.println("First letter in word "+ text + " is upper case");
     }
  }

Should jQuery's $(form).submit(); not trigger onSubmit within the form tag?

Sorry, misunderstood your question.

According to Javascript - capturing onsubmit when calling form.submit():

I was recently asked: "Why doesn't the form.onsubmit event get fired when I submit my form using javascript?"

The answer: Current browsers do not adhere to this part of the html specification. The event only fires when it is activated by a user - and does not fire when activated by code.

(emphasis added).

Note: "activated by a user" also includes hitting submit buttons (probably including default submit behaviour from the enter key but I haven't tried this). Nor, I believe, does it get triggered if you (with code) click a submit button.

Why do we use __init__ in Python classes?

Following with your car example: when you get a car, you just don't get a random car, I mean, you choose the color, the brand, number of seats, etc. And some stuff is also "initialize" without you choosing for it, like number of wheels or registration number.

class Car:
    def __init__(self, color, brand, number_of_seats):
        self.color = color
        self.brand = brand
        self.number_of_seats = number_of_seats
        self.number_of_wheels = 4
        self.registration_number = GenerateRegistrationNumber()

So, in the __init__ method you defining the attributes of the instance you're creating. So, if we want a blue Renault car, for 2 people, we would initialize or instance of Car like:

my_car = Car('blue', 'Renault', 2)

This way, we are creating an instance of the Car class. The __init__ is the one that is handling our specific attributes (like color or brand) and its generating the other attributes, like registration_number.

Why Is `Export Default Const` invalid?

default is basically const someVariableName

You don't need a named identifier because it's the default export for the file and you can name it whatever you want when you import it, so default is just condensing the variable assignment into a single keyword.

Add a month to a Date

"mondate" is somewhat similar to "Date" except that adding n adds n months rather than n days:

> library(mondate)
> d <- as.Date("2004-01-31")
> as.mondate(d) + 1
mondate: timeunits="months"
[1] 2004-02-29

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.

The HttpClient is an interface for this class and other classes.

You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient.

This answer was given in the context of httpclient-4.3.

What does FETCH_HEAD in Git mean?

FETCH_HEAD is a short-lived ref, to keep track of what has just been fetched from the remote repository.

Actually, ... not always considering that, with Git 2.29 (Q4 2020), "git fetch"(man) learned --no-write-fetch-head option to avoid writing the FETCH_HEAD file.

See commit 887952b (18 Aug 2020) by Junio C Hamano (gitster).
(Merged by Junio C Hamano -- gitster -- in commit b556050, 24 Aug 2020)

fetch: optionally allow disabling FETCH_HEAD update

Signed-off-by: Derrick Stolee

If you run fetch but record the result in remote-tracking branches, and either if you do nothing with the fetched refs (e.g. you are merely mirroring) or if you always work from the remote-tracking refs (e.g. you fetch and then merge origin/branchname separately), you can get away with having no FETCH_HEAD at all.

Teach "git fetch"(man) a command line option "--[no-]write-fetch-head".

  • The default is to write FETCH_HEAD, and the option is primarily meant to be used with the "--no-" prefix to override this default, because there is no matching fetch.writeFetchHEAD configuration variable to flip the default to off (in which case, the positive form may become necessary to defeat it).

Note that under "--dry-run" mode, FETCH_HEAD is never written; otherwise you'd see list of objects in the file that you do not actually have.

Passing --write-fetch-head does not force [git fetch](https://github.com/git/git/blob/887952b8c680626f4721cb5fa57704478801aca4/Documentation/git-fetch.txt)<sup>([man](https://git-scm.com/docs/git-fetch))</sup> to write the file.

fetch-options now includes in its man page:

--[no-]write-fetch-head

Write the list of remote refs fetched in the FETCH_HEAD file directly under $GIT_DIR.
This is the default.

Passing --no-write-fetch-head from the command line tells Git not to write the file.
Under --dry-run option, the file is never written.


Consider also, still with Git 2.29 (Q4 2020), the FETCH_HEAD is now always read from the filesystem regardless of the ref backend in use, as its format is much richer than the normal refs, and written directly by "git fetch"(man) as a plain file..

See commit e811530, commit 5085aef, commit 4877c6c, commit e39620f (19 Aug 2020) by Han-Wen Nienhuys (hanwen).
(Merged by Junio C Hamano -- gitster -- in commit 98df75b, 27 Aug 2020)

refs: read FETCH_HEAD and MERGE_HEAD generically

Signed-off-by: Han-Wen Nienhuys

The FETCH_HEAD and MERGE_HEAD refs must be stored in a file, regardless of the type of ref backend. This is because they can hold more than just a single ref.

To accomodate them for alternate ref backends, read them from a file generically in refs_read_raw_ref().


With Git 2.29 (Q4 2020), Updates to on-demand fetching code in lazily cloned repositories.

See commit db3c293 (02 Sep 2020), and commit 9dfa8db, commit 7ca3c0a, commit 5c3b801, commit abcb7ee, commit e5b9421, commit 2b713c2, commit cbe566a (17 Aug 2020) by Jonathan Tan (jhowtan).
(Merged by Junio C Hamano -- gitster -- in commit b4100f3, 03 Sep 2020)

fetch: no FETCH_HEAD display if --no-write-fetch-head

Signed-off-by: Jonathan Tan

887952b8c6 ("fetch: optionally allow disabling FETCH_HEAD update", 2020-08-18, Git v2.29.0 -- merge listed in batch #10) introduced the ability to disable writing to FETCH_HEAD during fetch, but did not suppress the "<source> -> FETCH_HEAD" message when this ability is used.

This message is misleading in this case, because FETCH_HEAD is not written.

Also, because "fetch" is used to lazy-fetch missing objects in a partial clone, this significantly clutters up the output in that case since the objects to be fetched are potentially numerous.

Therefore, suppress this message when --no-write-fetch-head is passed (but not when --dry-run is set).

pip3: command not found

its possible if you already have a python installed (pip) you could do a upgrade on mac by

brew upgrade python

How to replace case-insensitive literal substrings in Java

I like smas's answer that uses replaceAll with a regular expression. If you are going to be doing the same replacement many times, it makes sense to pre-compile the regular expression once:

import java.util.regex.Pattern;

public class Test { 

    private static final Pattern fooPattern = Pattern.compile("(?i)foo");

    private static removeFoo(s){
        if (s != null) s = fooPattern.matcher(s).replaceAll("");
        return s;
    }

    public static void main(String[] args) {
        System.out.println(removeFoo("FOOBar"));
    }
}

Error in Eclipse: "The project cannot be built until build path errors are resolved"

If you can't find the build path error, sometimes menu Project ? Clean... works like a charm.

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

C# Return Different Types?

If there is no common base-type or interface, then public object GetAnything() {...} - but it would usually be preferable to have some kind of abstraction such as a common interface. For example if Hello, Computer and Radio all implemented IFoo, then it could return an IFoo.

In Java, how to append a string more efficiently?

You should use the StringBuilder class.

StringBuilder stringBuilder = new StringBuilder();

stringBuilder.append("Some text");
stringBuilder.append("Some text");
stringBuilder.append("Some text");

String finalString = stringBuilder.toString();

In addition, please visit:

Why did I get the compile error "Use of unassigned local variable"?

See this thread concerning uninitialized bools, but it should answer your question.

Local variables are not initialized unless you call their constructors (new) or assign them a value.

How do I read a file line by line in VB Script?

When in doubt, read the documentation:

filename = "C:\Temp\vblist.txt"

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile(filename)

Do Until f.AtEndOfStream
  WScript.Echo f.ReadLine
Loop

f.Close

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

Eclipse java debugging: source not found

Click -> Edit Source Lookup Path

after then

Click -> Add finally select Java project and select project path.

Source: https://www.youtube.com/watch?v=IGIKPY6q1Qw

How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

With PYTHONPATH set as in your example, you should be able to do

python -m gmbx

-m option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py, it looks for particular file and PYTHONPATH does not apply.

Can you get a Windows (AD) username in PHP?

I tried almost all of these suggestions, but they were all returning empty values. If anyone else has this issue, I found this handy function on php.net (http://php.net/manual/en/function.get-current-user.php):

get_current_user();
$username = get_current_user();
echo $username;

This was the only way I was finally able to get the user's active directory username. If none of the above answers has worked, give this a try.

Hiding elements in responsive layout?

New visible classes added to Bootstrap

Extra small devices Phones (<768px) (Class names : .visible-xs-block, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm-block, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md-block, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg-block, hidden-lg)

For more information : http://getbootstrap.com/css/#responsive-utilities


Below is deprecated as of v3.2.0


Extra small devices Phones (<768px) (Class names : .visible-xs, hidden-xs)

Small devices Tablets (=768px) (Class names : .visible-sm, hidden-sm)

Medium devices Desktops (=992px) (Class names : .visible-md, hidden-md)

Large devices Desktops (=1200px) (Class names : .visible-lg, hidden-lg)


Much older Bootstrap


.hidden-phone, .hidden-tablet etc. are unsupported/obsolete.

UPDATE:

In Bootstrap 4 there are 2 types of classes:

  • The hidden-*-up which hide the element when the viewport is at the given breakpoint or wider.
  • hidden-*-down which hide the element when the viewport is at the given breakpoint or smaller.

Also, the new xl viewport is added for devices that are more then 1200px width. For more information click here.

How to compare two floating point numbers in Bash?

num1=0.555
num2=2.555


if [ `echo "$num1>$num2"|bc` -eq 1 ]; then
       echo "$num1 is greater then $num2"
else
       echo "$num2 is greater then $num1"
fi

How to download videos from youtube on java?

ytd2 is a fully functional YouTube video downloader. Check out its source code if you want to see how it's done.

Alternatively, you can also call an external process like youtube-dl to do the job. This is probably the easiest solution but it isn't in "pure" Java.

RandomForestClassfier.fit(): ValueError: could not convert string to float

I had a similar issue and found that pandas.get_dummies() solved the problem. Specifically, it splits out columns of categorical data into sets of boolean columns, one new column for each unique value in each input column. In your case, you would replace train_x = test[cols] with:

train_x = pandas.get_dummies(test[cols])

This transforms the train_x Dataframe into the following form, which RandomForestClassifier can accept:

   C  A_Hello  A_Hola  B_Bueno  B_Hi
0  0        1       0        0     1
1  1        0       1        1     0

Can Windows' built-in ZIP compression be scripted?

Yes, this can be scripted with VBScript. For example the following code can create a zip from a directory:

Dim fso, winShell, MyTarget, MySource, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set winShell = createObject("shell.application")


MyTarget = Wscript.Arguments.Item(0)
MySource = Wscript.Arguments.Item(1)

Wscript.Echo "Adding " & MySource & " to " & MyTarget

'create a new clean zip archive
Set file = fso.CreateTextFile(MyTarget, True)
file.write("PK" & chr(5) & chr(6) & string(18,chr(0)))
file.close

winShell.NameSpace(MyTarget).CopyHere winShell.NameSpace(MySource).Items

do until winShell.namespace(MyTarget).items.count = winShell.namespace(MySource).items.count
    wscript.sleep 1000 
loop

Set winShell = Nothing
Set fso = Nothing

You may also find http://www.naterice.com/blog/template_permalink.asp?id=64 helpful as it includes a full Unzip/Zip implementation in VBScript.

If you do a size check every 500 ms rather than a item count it works better for large files. Win 7 writes the file instantly although it's not finished compressing:

set fso=createobject("scripting.filesystemobject")
Set h=fso.getFile(DestZip)
do
    wscript.sleep 500
    max = h.size
loop while h.size > max 

Works great for huge amounts of log files.

Directly export a query to CSV using SQL Developer

You can use the spool command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool can change the file that's being written to, so you can have several queries writing to different files just by putting spool commands between them:

spool "\path\to\spool1.txt"

select /*csv*/ * from employees;

spool "\path\to\spool2.txt"

select /*csv*/ * from locations;

spool off;

You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set command, though some of those do not translate to SQL Developer.

Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.

A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.

Convert JSON String To C# Object

Or, you can use the Newtownsoft.Json library as follows:

using Newtonsoft.Json;
...
var result = JsonConvert.DeserializeObject<T>(json);

Where T is your object type that matches your JSON string.

Colorplot of 2D array matplotlib

Here is the simplest example that has the key lines of code:

import numpy as np 
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
          [5, 6, 7, 8],
          [9, 10, 11, 12],
          [13, 14, 15, 16]])

plt.imshow(H, interpolation='none')
plt.show()

enter image description here

PHP foreach with Nested Array?

foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

For flutter projects you can also solve this issue

open your \android\app\build.gradle

you sould have the following:

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28

    }

}

If your minSdkVersion is set to 21 or higher, all you need to do is set multiDexEnabled to true in the defaultConfig. Like this

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true 

    }

}

if your minSdkVersion is set to 20 or lower add multiDexEnabled true to the defaultConfig

And define the implementation

dependencies {
  implementation 'com.android.support:multidex:1.0.3'// or 2.0.1
}

At the end you should have:

android {
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 28
        multiDexEnabled true  // added this
    }

}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

For more information read this: https://developer.android.com/studio/build/multidex

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

How to display the current time and date in C#

If you want to do it in XAML,

xmlns:sys="clr-namespace:System;assembly=mscorlib"
<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now}}"

With some formatting,

<TextBlock Text="{Binding Source={x:Static sys:DateTime.Now},
                  StringFormat='{}{0:dd-MMM-yyyy hh:mm:ss}'}"

Generating PDF files with JavaScript

Another javascript library worth mentioning is pdfmake.

The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.

Basic authentication with fetch?

This is not directly related to the initial issue, but probably will help somebody.

I faced same issue when was trying to send similar request using domain account. So mine issue was in not escaped character in login name.

Bad example:

'ABC\username'

Good example:

'ABC\\username'

javascript function wait until another function to finish

There are several ways I can think of to do this.

Use a callback:

 function FunctInit(someVarible){
      //init and fill screen
      AndroidCallGetResult();  // Enables Android button.
 }

 function getResult(){ // Called from Android button only after button is enabled
      //return some variables
 }

Use a Timeout (this would probably be my preference):

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      if (inited) {
           //return some variables
      } else {
           setTimeout(getResult, 250);
      }
 }

Wait for the initialization to occur:

 var inited = false;
 function FunctInit(someVarible){
      //init and fill screen
      inited = true;
 }

 function getResult(){
      var a = 1;
      do { a=1; }
      while(!inited);
      //return some variables
 }

Command copy exited with code 4 when building - Visual Studio restart solves it

To expand on rhughes answer,

The robocopy works beautifully, just incase you need to include sub directories you can use /e to include subs and copy empty directories or /s to include subs excluding empty directories.

Also robocopy will report back a few things like if new files were copied, this will cause VS to complain since anything above 0 is a failure and robocopy will return 1 if new files have been found. Its worth to mention that robocopy first compares the Source/Dest and only copies the updated/new files.

To get around this use:

(robocopy "$(SolutionDir)Solution Items\References\*.dll" "$(TargetDir)") ^& IF %ERRORLEVEL% LEQ 4 exit /B 0

Block direct access to a file over http but allow php script access

in httpd.conf to block browser & wget access to include files especially say db.inc or config.inc . Note you cannot chain file types in the directive instead create multiple file directives.

<Files ~ "\.inc$">
Order allow,deny
Deny from all
</Files>

to test your config before restarting apache

service httpd configtest

then (graceful restart)

service httpd graceful

Avoid trailing zeroes in printf()

Slight variation on above:

  1. Eliminates period for case (10000.0).
  2. Breaks after first period is processed.

Code here:

void EliminateTrailingFloatZeros(char *iValue)
{
  char *p = 0;
  for(p=iValue; *p; ++p) {
    if('.' == *p) {
      while(*++p);
      while('0'==*--p) *p = '\0';
      if(*p == '.') *p = '\0';
      break;
    }
  }
}

It still has potential for overflow, so be careful ;P

How do I get the object if it exists, or None if it does not exist?

you could use exists with a filter:

Content.objects.filter(name="baby").exists()
#returns False or True depending on if there is anything in the QS

just an alternative for if you only want to know if it exists

NuGet behind a proxy

I could be wrong but I thought it used IE's proxy settings.

If it sees that you need to login it opens a dialog and asks you to do so (login that is).

Please see the description of this here -> http://docs.nuget.org/docs/release-notes/nuget-1.5

Best Practices: working with long, multiline strings in PHP?

You should use heredoc or nowdoc.

$var = "some text";
$text = <<<EOT
  Place your text between the EOT. It's
  the delimiter that ends the text
  of your multiline string.
  $var
EOT;

The difference between heredoc and nowdoc is that PHP code embedded in a heredoc gets executed, while PHP code in nowdoc will be printed out as is.

$var = "foo";
$text = <<<'EOT'
  My $var
EOT;

In this case $text will have the value "My $var", not "My foo".

Notes:

  • Before the closing EOT; there should be no spaces or tabs. otherwise you will get an error.
  • The string/tag (EOT) that enclose the text is arbitrary, that is, one can use other strings, e.g. <<<FOO and FOO;
  • EOT : End of transmission, EOD: End of data. [Q]

Nginx not picking up site in sites-enabled?

I had the same problem. It was because I had accidentally used a relative path with the symbolic link.

Are you sure you used full paths, e.g.:

ln -s /etc/nginx/sites-available/example.com.conf /etc/nginx/sites-enabled/example.com.conf

AttributeError: 'module' object has no attribute 'model'

As the error message says in the last line: the module models in the file c:\projects\mysite..\mysite\polls\models.py contains no class model. This error occurs in the definition of the Poll class:

class Poll(models.model):

Either the class model is misspelled in the definition of the class Poll or it is misspelled in the module models. Another possibility is that it is completely missing from the module models. Maybe it is in another module or it is not yet implemented in models.

Changing the selected option of an HTML Select element

Slightly neater Vanilla.JS version. Assuming you've already fixed nodeList missing .forEach():

NodeList.prototype.forEach = Array.prototype.forEach

Just:

var requiredValue = 'i-50332a31',   
  selectBox = document.querySelector('select')

selectBox.childNodes.forEach(function(element, index){
  if ( element.value === requiredValue ) {
    selectBox.selectedIndex = index
  }
})

Purpose of returning by const value?

It could be used as a wrapper function for returning a reference to a private constant data type. For example in a linked list you have the constants tail and head, and if you want to determine if a node is a tail or head node, then you can compare it with the value returned by that function.

Though any optimizer would most likely optimize it out anyway...

How to upload (FTP) files to server in a bash script?

use this to upload a file to a remote location

#!/bin/bash
#$1 is the file name
#usage:this_script <filename>
HOST='your host'
USER="your user"
PASSWD="pass"
FILE="abc.php"
REMOTEPATH='/html'

ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
cd $REMOTEPATH
put $FILE 
quit
END_SCRIPT
exit 0

Play/pause HTML 5 video using JQuery

Sorry for my other answer. No-one liked it, but I have found another way that you can do it.

You can use Video.js! You can find the documentation and how-to's here.

How to URL encode a string in Ruby

You can use Addressable::URI gem for that:

require 'addressable/uri'   
string = '\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a'
Addressable::URI.encode_component(string, Addressable::URI::CharacterClasses::QUERY)
# "%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a%5Cxbc%5Cxde%5Cxf1%5Cx23%5Cx45%5Cx67%5Cx89%5Cxab%5Cxcd%5Cxef%5Cx12%5Cx34%5Cx56%5Cx78%5Cx9a" 

It uses more modern format, than CGI.escape, for example, it properly encodes space as %20 and not as + sign, you can read more in "The application/x-www-form-urlencoded type" on Wikipedia.

2.1.2 :008 > CGI.escape('Hello, this is me')
 => "Hello%2C+this+is+me" 
2.1.2 :009 > Addressable::URI.encode_component('Hello, this is me', Addressable::URI::CharacterClasses::QUERY)
 => "Hello,%20this%20is%20me" 

Importing text file into excel sheet

There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)

  1. Using a QueryTable
  2. Open the text file in memory and then write to the current sheet and finally applying Text To Columns if required.
  3. If you want to use the method that you are currently using then after you open the text file in a new workbook, simply copy it over to the current sheet using Cells.Copy

Using a QueryTable

Here is a simple macro that I recorded. Please amend it to suit your needs.

Sub Sample()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
        )
        .Name = "Sample"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

Open the text file in memory

Sub Sample()
    Dim MyData As String, strData() As String

    Open "C:\Sample.txt" For Binary As #1
    MyData = Space$(LOF(1))
    Get #1, , MyData
    Close #1
    strData() = Split(MyData, vbCrLf)
End Sub

Once you have the data in the array you can export it to the current sheet.

Using the method that you are already using

Sub Sample()
    Dim wbI As Workbook, wbO As Workbook
    Dim wsI As Worksheet

    Set wbI = ThisWorkbook
    Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import

    Set wbO = Workbooks.Open("C:\Sample.txt")

    wbO.Sheets(1).Cells.Copy wsI.Cells

    wbO.Close SaveChanges:=False
End Sub

FOLLOWUP

You can use the Application.GetOpenFilename to choose the relevant file. For example...

Sub Sample()
    Dim Ret

    Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")

    If Ret <> False Then
        With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;" & Ret, Destination:=Range("$A$1"))

            '~~> Rest of the code

        End With
    End If
End Sub

How to keep an iPhone app running on background fully operational

May be the link will Help bcz u might have to implement the code in Appdelegate in app run in background method .. Also consult the developer.apple.com site for application class Here is link for runing app in background

SQL grouping by all the columns

I wanted to do counts and sums over full resultset. I achieved grouping by all with GROUP BY 1=1.

Running javascript in Selenium using Python

Use execute_script, here's a python example:

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://stackoverflow.com/questions/7794087/running-javascript-in-selenium-using-python") 
driver.execute_script("document.getElementsByClassName('comment-user')[0].click()")

How to return a specific status code and no contents from Controller?

this.HttpContext.Response.StatusCode = 418; // I'm a teapot

How to end the request?

Try other solution, just:

return StatusCode(418);


You could use StatusCode(???) to return any HTTP status code.


Also, you can use dedicated results:

Success:

  • return Ok() ? Http status code 200
  • return Created() ? Http status code 201
  • return NoContent(); ? Http status code 204

Client Error:

  • return BadRequest(); ? Http status code 400
  • return Unauthorized(); ? Http status code 401
  • return NotFound(); ? Http status code 404


More details:

Insert a string at a specific index

You could prototype your own splice() into String.

Polyfill

if (!String.prototype.splice) {
    /**
     * {JSDoc}
     *
     * The splice() method changes the content of a string by removing a range of
     * characters and/or adding new characters.
     *
     * @this {String}
     * @param {number} start Index at which to start changing the string.
     * @param {number} delCount An integer indicating the number of old chars to remove.
     * @param {string} newSubStr The String that is spliced in.
     * @return {string} A new string with the spliced substring.
     */
    String.prototype.splice = function(start, delCount, newSubStr) {
        return this.slice(0, start) + newSubStr + this.slice(start + Math.abs(delCount));
    };
}

Example

_x000D_
_x000D_
String.prototype.splice = function(idx, rem, str) {_x000D_
    return this.slice(0, idx) + str + this.slice(idx + Math.abs(rem));_x000D_
};_x000D_
_x000D_
var result = "foo baz".splice(4, 0, "bar ");_x000D_
_x000D_
document.body.innerHTML = result; // "foo bar baz"
_x000D_
_x000D_
_x000D_


EDIT: Modified it to ensure that rem is an absolute value.

How to format strings in Java

I wrote this function it does just the right thing. Interpolate a word starting with $ with the value of the variable of the same name.

private static String interpol1(String x){
    Field[] ffield =  Main.class.getDeclaredFields();
    String[] test = x.split(" ") ;
    for (String v : test ) {
        for ( Field n: ffield ) {
            if(v.startsWith("$") && ( n.getName().equals(v.substring(1))  )){
                try {
                    x = x.replace("$" + v.substring(1), String.valueOf( n.get(null)));
                }catch (Exception e){
                    System.out.println("");
                }
            }
        }
    }
    return x;
}

Why can a function modify some arguments as perceived by the caller, but not others?

I will rename variables to reduce confusion. n -> nf or nmain. x -> xf or xmain:

def f(nf, xf):
    nf = 2
    xf.append(4)
    print 'In f():', nf, xf

def main():
    nmain = 1
    xmain = [0,1,2,3]
    print 'Before:', nmain, xmain
    f(nmain, xmain)
    print 'After: ', nmain, xmain

main()

When you call the function f, the Python runtime makes a copy of xmain and assigns it to xf, and similarly assigns a copy of nmain to nf.

In the case of n, the value that is copied is 1.

In the case of x the value that is copied is not the literal list [0, 1, 2, 3]. It is a reference to that list. xf and xmain are pointing at the same list, so when you modify xf you are also modifying xmain.

If, however, you were to write something like:

    xf = ["foo", "bar"]
    xf.append(4)

you would find that xmain has not changed. This is because, in the line xf = ["foo", "bar"] you have change xf to point to a new list. Any changes you make to this new list will have no effects on the list that xmain still points to.

Hope that helps. :-)

How to remove any URL within a string in Python

Python script:

import re
text = re.sub(r'^https?:\/\/.*[\r\n]*', '', text, flags=re.MULTILINE)

Output:

text1
text2
text3
text4
text5
text6

Test this code here.

Numpy array dimensions

The shape method requires that a be a Numpy ndarray. But Numpy can also calculate the shape of iterables of pure python objects:

np.shape([[1,2],[1,2]])

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

No String-argument constructor/factory method to deserialize from String value ('')

This exception says that you are trying to deserialize the object "Address" from string "\"\"" instead of an object description like "{…}". The deserializer can't find a constructor of Address with String argument. You have to replace "" by {} to avoid this error.

Have nginx access_log and error_log log to STDOUT and STDERR of master process

In docker image of PHP-FPM, i've see such approach:

# cat /usr/local/etc/php-fpm.d/docker.conf
[global]
error_log = /proc/self/fd/2

[www]
; if we send this to /proc/self/fd/1, it never appears
access.log = /proc/self/fd/2

Print all day-dates between two dates

Essentially the same as Gringo Suave's answer, but with a generator:

from datetime import datetime, timedelta


def datetime_range(start=None, end=None):
    span = end - start
    for i in xrange(span.days + 1):
        yield start + timedelta(days=i)

Then you can use it as follows:

In: list(datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)))
Out: 
[datetime.datetime(2014, 1, 1, 0, 0),
 datetime.datetime(2014, 1, 2, 0, 0),
 datetime.datetime(2014, 1, 3, 0, 0),
 datetime.datetime(2014, 1, 4, 0, 0),
 datetime.datetime(2014, 1, 5, 0, 0)]

Or like this:

In []: for date in datetime_range(start=datetime(2014, 1, 1), end=datetime(2014, 1, 5)):
   ...:     print date
   ...:     
2014-01-01 00:00:00
2014-01-02 00:00:00
2014-01-03 00:00:00
2014-01-04 00:00:00
2014-01-05 00:00:00

Where can I find the assembly System.Web.Extensions dll?

I had this issue when converting an older project to use a new version of Visual Studio. Upon conversion, the project target framework was set to 2.0

I was able to solve this issue by changing the target framework to be 3.5.

Form Submit jQuery does not work

If you are doing form validation such as

type="submit" onsubmit="return validateForm(this)"

validateForm = function(form) {
if ($('input#company').val() === "" || $('input#company').val() === "Company")  {
        $('input#company').val("Company").css('color','red'); finalReturn = false; 
        $('input#company').on('mouseover',(function() { 
            $('input#company').val("").css('color','black'); 
            $('input#company').off('mouseover');
            finalReturn = true; 
        }));
    } 

    return finalReturn; 
}

Double check you are returning true. This seems simple but I had

var finalReturn = false;

When the form was correct it was not being corrected by validateForm and so not being submitted as finalReturn was still initialized to false instead of true. By the way, above code works nicely with address, city, state and so on.

ng-model for `<input type="file"/>` (with directive DEMO)

function filesModelDirective(){
  return {
    controller: function($parse, $element, $attrs, $scope){
      var exp = $parse($attrs.filesModel);
      $element.on('change', function(){
        exp.assign($scope, this.files[0]);
        $scope.$apply();
      });
    }
  };
}
app.directive('filesModel', filesModelDirective);

Regular expression - starting and ending with a character string

Example: ajshdjashdjashdlasdlhdlSTARTasdasdsdaasdENDaknsdklansdlknaldknaaklsdn

1) START\w*END return: STARTasdasdsdaasdEND - will give you words between START and END

2) START\d*END return: START12121212END - will give you numbers between START and END

3) START\d*_\d*END return: START1212_1212END - will give you numbers between START and END having _

403 Forbidden You don't have permission to access /folder-name/ on this server

Solved the problem with:

sudo chown -R $USER:$USER /var/www/folder-name

sudo chmod -R 755 /var/www

Grant permissions

LoDash: Get an array of values from an array of object properties

And if you need to extract several properties from each object, then

let newArr = _.map(arr, o => _.pick(o, ['name', 'surname', 'rate']));

Execute bash script from URL

Use:

curl -s -L URL_TO_SCRIPT_HERE | bash

For example:

curl -s -L http://bitly/10hA8iC | bash

HTML radio buttons allowing multiple selections

I've done it this way in the past, JsFiddle:

CSS:

.radio-option {
    cursor: pointer;
    height: 23px;
    width: 23px;
    background: url(../images/checkbox2.png) no-repeat 0px 0px;
}

.radio-option.click {
    background: url(../images/checkbox1.png) no-repeat 0px 0px;
}

HTML:

<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>
<li><div class="radio-option"></div></li>

jQuery:

<script>
    $(document).ready(function() {
        $('.radio-option').click(function () {
            $(this).not(this).removeClass('click');
            $(this).toggleClass("click");
        });
    });
</script>

Entity Framework rollback and remove bad migration

You can also use

Remove-Migration -Force

This will revert and remove the last applied migration

Query for array elements inside JSON type

jsonb in Postgres 9.4+

You can use the same query as below, just with jsonb_array_elements().

But rather use the jsonb "contains" operator @> in combination with a matching GIN index on the expression data->'objects':

CREATE INDEX reports_data_gin_idx ON reports
USING gin ((data->'objects') jsonb_path_ops);

SELECT * FROM reports WHERE data->'objects' @> '[{"src":"foo.png"}]';

Since the key objects holds a JSON array, we need to match the structure in the search term and wrap the array element into square brackets, too. Drop the array brackets when searching a plain record.

More explanation and options:

json in Postgres 9.3+

Unnest the JSON array with the function json_array_elements() in a lateral join in the FROM clause and test for its elements:

SELECT data::text, obj
FROM   reports r, json_array_elements(r.data#>'{objects}') obj
WHERE  obj->>'src' = 'foo.png';

db<>fiddle here
Old sqlfiddle

The CTE (WITH query) just substitutes for a table reports.
Or, equivalent for just a single level of nesting:

SELECT *
FROM   reports r, json_array_elements(r.data->'objects') obj
WHERE  obj->>'src' = 'foo.png';

->>, -> and #> operators are explained in the manual.

Both queries use an implicit JOIN LATERAL.

Closely related:

log4j vs logback

Should you? Yes.

Why? Log4J has essentially been deprecated by Logback.

Is it urgent? Maybe not.

Is it painless? Probably, but it may depend on your logging statements.

Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.

Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)

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

What is happening here is that database route does not accept any url methods.

I would try putting the url methods in the app route just like you have in the entry_page function:

@app.route('/entry', methods=['GET', 'POST'])
def entry_page():
    if request.method == 'POST':
        date = request.form['date']
        title = request.form['blog_title']
        post = request.form['blog_main']
        post_entry = models.BlogPost(date = date, title = title, post = post)
        db.session.add(post_entry)
        db.session.commit()
        return redirect(url_for('database'))
    else:
        return render_template('entry.html')

@app.route('/database', methods=['GET', 'POST'])        
def database():
    query = []
    for i in session.query(models.BlogPost):
        query.append((i.title, i.post, i.date))
    return render_template('database.html', query = query)

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

String delimiter in string.split method

String[] strArray= str.split(Pattern.quote("||"));

where

  1. str = "1||1||Abdul-Jabbar||Karim||1996||1974";
  2. Pattern.quote("||") will ignore the special character.
  3. .split function will split the string for every occurrence of ||.
  4. strArray will have the array of string that is delimited by ||.

CSS: How to position two elements on top of each other, without specifying a height?

Here's another solution using display: flex instead of position: absolute or display: grid.

_x000D_
_x000D_
.container_row{_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.layer1 {_x000D_
  width: 100%;_x000D_
  background-color: rgba(255,0,0,0.5);  // red_x000D_
}_x000D_
_x000D_
.layer2{_x000D_
  width: 100%;_x000D_
  margin-left: -100%;_x000D_
  background-color: rgba(0,0,255,0.5);  // blue_x000D_
}
_x000D_
<div class="container_row">_x000D_
    <div class="layer1">_x000D_
        <span>Lorem ipsum...</span>_x000D_
    </div>_x000D_
    <div class="layer2">_x000D_
        More lorem ipsum..._x000D_
    </div>_x000D_
</div>_x000D_
<div class="container_row">_x000D_
    ...same HTML as above. This one should never overlap the .container_row above._x000D_
</div>
_x000D_
_x000D_
_x000D_

How to find the date of a day of the week from a date using PHP?

I think this is what you want.

$dayofweek = date('w', strtotime($date));
$result    = date('Y-m-d', strtotime(($day - $dayofweek).' day', strtotime($date)));

How to print SQL statement in codeigniter model

Neither last_query() or get_compiled_select() works for me, so a slight change of pedro's code works for me just fine. Do not include ->get() in your build, this must be before the ->get()

 echo $this->EE->db->_compile_select();

How to make a form close when pressing the escape key?

Paste this code into the "On Key Down" Property of your form, also make sure you set "Key Preview" Property to "Yes".

If KeyCode = vbKeyEscape Then DoCmd.Close acForm, "YOUR FORM NAME"

xsl: how to split strings?

If your XSLT processor supports EXSLT, you can use str:tokenize, otherwise, the link contains an implementation using functions like substring-before.

How to create XML file with specific structure in Java

public static void main(String[] args) {

try {

    DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    Element rootElement = doc.createElement("CONFIGURATION");
    doc.appendChild(rootElement);
    Element browser = doc.createElement("BROWSER");
    browser.appendChild(doc.createTextNode("chrome"));
    rootElement.appendChild(browser);
    Element base = doc.createElement("BASE");
    base.appendChild(doc.createTextNode("http:fut"));
    rootElement.appendChild(base);
    Element employee = doc.createElement("EMPLOYEE");
    rootElement.appendChild(employee);
    Element empName = doc.createElement("EMP_NAME");
    empName.appendChild(doc.createTextNode("Anhorn, Irene"));
    employee.appendChild(empName);
    Element actDate = doc.createElement("ACT_DATE");
    actDate.appendChild(doc.createTextNode("20131201"));
    employee.appendChild(actDate);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("/Users/myXml/ScoreDetail.xml"));
    transformer.transform(source, result);
    System.out.println("File saved!");
  } catch (ParserConfigurationException pce) {
    pce.printStackTrace();
  } catch (TransformerException tfe) {
    tfe.printStackTrace();}}

The values in you XML is Hard coded.

How to get the nth element of a python list or a default if not available

try:
   a = b[n]
except IndexError:
   a = default

Edit: I removed the check for TypeError - probably better to let the caller handle this.

jQuery .scrollTop(); + animation

you must see this

$(function () {
        $('a[href*="#"]:not([href="#"])').click(function () {
            if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
                var target = $(this.hash);
                target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
                if (target.length) {
                    $('html, body').animate({
                        scrollTop: target.offset().top
                    }, 1000);
                    return false;
                }
            }
        });
    });

or try them

$(function () {$('a').click(function () {
$('body,html').animate({
    scrollTop: 0
}, 600);
return false;});});

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How can I get the IP address from NIC in Python?

try below code, it works for me in Mac10.10.2:

import subprocess

if __name__ == "__main__":
    result = subprocess.check_output('ifconfig en0 |grep -w inet', shell=True) # you may need to use eth0 instead of en0 here!!!
    print 'output = %s' % result.strip()
    # result = None
    ip = ''
    if result:
        strs = result.split('\n')
        for line in strs:
            # remove \t, space...
            line = line.strip()
            if line.startswith('inet '):
                a = line.find(' ')
                ipStart = a+1
                ipEnd = line.find(' ', ipStart)
                if a != -1 and ipEnd != -1:
                    ip = line[ipStart:ipEnd]
                    break
    print 'ip = %s' % ip

Center Oversized Image in Div

based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200 works centered like that:

 .imageContainer {
  height: 100px;
  overflow: hidden;
  position: relative;
 }
 .imageCenter {
  width: auto;
  position: absolute;
  left: -10%;
  top: 0;
  margin-left: -500px;
 }
.imageCenter img {
 display: block;
 margin: 0 auto;
 }

I Hope this helps others to finish faster the task :)

Image scaling causes poor quality in firefox/internet explorer but not chrome

This is possible! At least now that css transforms have good support:

You need to use a CSS transform to scale the image - the trick is not just to use a scale(), but also to apply a very small rotation. This triggers IE to use a smoother interpolation of the image:

img {
    /* double desired size */
    width: 56px; 
    height: 56px;

    /* margins to reduce layout size to match the transformed size */ 
    margin: -14px -14px -14px -14px; 

    /* transform to scale with smooth interpolation: */
    transform: scale(0.5) rotate(0.1deg);
}

What is :: (double colon) in Python when subscripting sequences?

Python uses the :: to separate the End, the Start, and the Step value.

HTML anchor link - href and onclick both?

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
  //code
  return true;
}

This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.

How to scale a UIImageView proportionally?

Fixed easily, once I found the documentation!

 imageView.contentMode = .scaleAspectFit

How to get date representing the first day of a month?

SELECT DATEADD(day,1-DATEpart(day, GETDATE()),GETDATE())

How can I time a code segment for testing performance with Pythons timeit?

I see the question has already been answered, but still want to add my 2 cents for the same.

I have also faced similar scenario in which I have to test the execution times for several approaches and hence written a small script, which calls timeit on all functions written in it.

The script is also available as github gist here.

Hope it will help you and others.

from random import random
import types

def list_without_comprehension():
    l = []
    for i in xrange(1000):
        l.append(int(random()*100 % 100))
    return l

def list_with_comprehension():
    # 1K random numbers between 0 to 100
    l = [int(random()*100 % 100) for _ in xrange(1000)]
    return l


# operations on list_without_comprehension
def sort_list_without_comprehension():
    list_without_comprehension().sort()

def reverse_sort_list_without_comprehension():
    list_without_comprehension().sort(reverse=True)

def sorted_list_without_comprehension():
    sorted(list_without_comprehension())


# operations on list_with_comprehension
def sort_list_with_comprehension():
    list_with_comprehension().sort()

def reverse_sort_list_with_comprehension():
    list_with_comprehension().sort(reverse=True)

def sorted_list_with_comprehension():
    sorted(list_with_comprehension())


def main():
    objs = globals()
    funcs = []
    f = open("timeit_demo.sh", "w+")

    for objname in objs:
        if objname != 'main' and type(objs[objname]) == types.FunctionType:
            funcs.append(objname)
    funcs.sort()
    for func in funcs:
        f.write('''echo "Timing: %(funcname)s"
python -m timeit "import timeit_demo; timeit_demo.%(funcname)s();"\n\n
echo "------------------------------------------------------------"
''' % dict(
                funcname = func,
                )
            )

    f.close()

if __name__ == "__main__":
    main()

    from os import system

    #Works only for *nix platforms
    system("/bin/bash timeit_demo.sh")

    #un-comment below for windows
    #system("cmd timeit_demo.sh")

How to export the Html Tables data into PDF using Jspdf

"How to properly use jsPDF library" might give you a little more of what you need. The table won't render correctly (no css, per this answer), but you could do some parsing of the html table with jquery and manually style it yourself.

Another option would be to use screenshots of the HTML with HTML2Canvas or Casper.js.

EDIT

Here's a basic example using the jspdf cell plugin. It uses jquery and the tableToJson() function from HTML Table to JSON.

Be sure to include the Deflate lib (two js files) and jspdf.plugin.cell.js.

var table = tableToJson($('#table-id').get(0))
var doc = new jsPDF('p', 'pt', 'a4', true);
doc.cellInitialize();
$.each(table, function (i, row){
  $.each(row, function (j, cell){
    doc.cell(10, 200, 100, 20, cell, i);
  })
})
doc.save()

Excel CSV - Number cell format

There isn’t an easy way to control the formatting Excel applies when opening a .csv file. However listed below are three approaches that might help.

My preference is the first option.

Option 1 – Change the data in the file

You could change the data in the .csv file as follows ...,=”005”,... This will be displayed in Excel as ...,005,...

Excel will have kept the data as a formula, but copying the column and using paste special values will get rid of the formula but retain the formatting

Option 2 – Format the data

If it is simply a format issue and all your data in that column has a three digits length. Then open the data in Excel and then format the column containing the data with this custom format 000

Option 3 – Change the file extension to .dif (Data interchange format)

Change the file extension and use the file import wizard to control the formats. Files with a .dif extension are automatically opened by Excel when double clicked on.

Step by step:

  • Change the file extension from .csv to .dif
  • Double click on the file to open it in Excel.
  • The 'File Import Wizard' will be launched.
  • Set the 'File type' to 'Delimited' and click on the 'Next' button.
  • Under Delimiters, tick 'Comma' and click on the 'Next' button.
  • Click on each column of your data that is displayed and select a 'Column data format'. The column with the value '005' should be formatted as 'Text'.
  • Click on the finish button, the file will be opened by Excel with the formats that you have specified.

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

The provider is not compatible with the version of Oracle client

Just two steps to solve this issue.

  1. go to advance setting of application pool and set 'Enable 32 bit Application' flag to True.
  2. Make sure all Dlls in your Bin is 32 bit version now...

best of luck.

What does enctype='multipart/form-data' mean?

enctype='multipart/form-data is an encoding type that allows files to be sent through a POST. Quite simply, without this encoding the files cannot be sent through POST.

If you want to allow a user to upload a file via a form, you must use this enctype.

How can I update my ADT in Eclipse?

Running as administrator then following other comments fixed the problem for me :)

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

How to get the difference between two dictionaries in Python?

Try the following snippet, using a dictionary comprehension:

value = { k : second_dict[k] for k in set(second_dict) - set(first_dict) }

In the above code we find the difference of the keys and then rebuild a dict taking the corresponding values.

Selecting a row in DataGridView programmatically

Try This:

datagridview.Rows[currentRow].Cells[0];

how to convert a string to date in mysql?

As was told at MySQL Using a string column with date text as a date field, you can do

SELECT  STR_TO_DATE(yourdatefield, '%m/%d/%Y')
FROM    yourtable

You can also handle these date strings in WHERE clauses. For example

SELECT whatever
  FROM yourtable
 WHERE STR_TO_DATE(yourdatefield, '%m/%d/%Y') > CURDATE() - INTERVAL 7 DAY

You can handle all kinds of date/time layouts this way. Please refer to the format specifiers for the DATE_FORMAT() function to see what you can put into the second parameter of STR_TO_DATE().

How to get UTC value for SYSDATE on Oracle

select sys_extract_utc(systimestamp) from dual;

Won't work on Oracle 8, though.

How to make a HTTP request using Ruby on Rails?

My favorite two ways to grab the contents of URLs are either OpenURI or Typhoeus.

OpenURI because it's everywhere, and Typhoeus because it's very flexible and powerful.

MISCONF Redis is configured to save RDB snapshots

I know this thread is slightly older, but here's what worked for me when I got this error earlier, knowing I was nowhere near memory limit- both answers were found above.

Hopefully this could help someone in the future if they need it.

  1. Checked CHMOD on dir folder... found somehow the symbolic notation was different. CHMOD dir folder to 755
  2. dbfilename permissions were good, no changes needed
  3. Restarted redis-server
  4. (Should've done this first, but ah well) Referenced the redis-server.log and found that the error was the result of access being denied.

Again- unsure how the permissions on the DIR folder got changed, but I'm assuming CHMOD back to 755 and restarting redis-server took care of it as I was able to ping redis server afterwards.

Also- to note, redis did have ownership of the dbfilename and DIR folder.

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

Array.sort() doesn't sort numbers correctly

a.sort(function(a,b){return a - b})

These can be confusing.... check this link out.

How to see the CREATE VIEW code for a view in PostgreSQL?

GoodNews from v.9.6 and above, View editing are now native from psql. Just invoke \ev command. View definitions will show in your configured editor.

julian@assange=# \ev {your_view_names}

Bonus. Some useful command to interact with query buffer.

Query Buffer
  \e [FILE] [LINE]       edit the query buffer (or file) with external editor
  \ef [FUNCNAME [LINE]]  edit function definition with external editor
  \ev [VIEWNAME [LINE]]  edit view definition with external editor
  \p                     show the contents of the query buffer
  \r                     reset (clear) the query buffer
  \s [FILE]              display history or save it to file
  \w FILE                write query buffer to file

Catching exceptions from Guzzle

If the Exception is being thrown in that try block then at worst case scenario Exception should be catching anything uncaught.

Consider that the first part of the test is throwing the Exception and wrap that in the try block as well.

jQuery same click event for multiple elements

If you have or want to keep your elements as variables (jQuery objects), you can also loop over them:

var $class1 = $('.class1');
var $class2 = $('.class2');

$([$class1,$class2]).each(function() {
    $(this).on('click', function(e) {
        some_function();
    });
});

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

Google Chrome redirecting localhost to https

For someone who had the same problem I solved by pressing CTRL + SHIFT + DELETE to delete just the entire browser cache. Now I can access my localhost website on HTTP protocol.

How to make popup look at the centre of the screen?

If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:

In your CSS use (for example)

div.centered{
  width: 100px;
  height: 50px;
  position:fixed; 
  top: calc(50% - 25px); // half of width
  left: calc(50% - 50px); // half of height
}

No JS required.

How to return HTTP 500 from ASP.NET Core RC2 Web Api?

From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

[HttpPost]
public IActionResult Post([FromBody] string something)
{    
    //...
    try
    {
        DoSomething();
    }
    catch(Exception e)
    {
         LogException(e);
         return StatusCode(500);
    }
}

You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

Multiple ping script in Python

Try subprocess.call. It saves the return value of the program that was used.

According to my ping manual, it returns 0 on success, 2 when pings were sent but no reply was received and any other value indicates an error.

# typo error in import
import subprocess

for ping in range(1,10):
    address = "127.0.0." + str(ping)
    res = subprocess.call(['ping', '-c', '3', address])
    if res == 0:
        print "ping to", address, "OK"
    elif res == 2:
        print "no response from", address
    else:
        print "ping to", address, "failed!"

Maven Java EE Configuration Marker with Java Server Faces 1.2

I too had the same problem.

The solution for me was to add following in the pom.xml as suggested here.

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.0.2</version>
            <configuration>
                <source>1.7</source>
                <target>1.7</target>
            </configuration>
        </plugin>
    </plugins>
</build>

How to declare a variable in SQL Server and use it in the same Stored Procedure

What's going wrong with what you have? What error do you get, or what result do or don't you get that doesn't match your expectations?

I can see the following issues with that SP, which may or may not relate to your problem:

  • You have an extraneous ) after @BrandName in your SELECT (at the end)
  • You're not setting @CategoryID or @BrandName to anything anywhere (they're local variables, but you don't assign values to them)

Edit Responding to your comment: The error is telling you that you haven't declared any parameters for the SP (and you haven't), but you called it with parameters. Based on your reply about @CategoryID, I'm guessing you wanted it to be a parameter rather than a local variable. Try this:

CREATE PROCEDURE AddBrand
   @BrandName nvarchar(50),
   @CategoryID int
AS
BEGIN
   DECLARE @BrandID int

   SELECT @BrandID = BrandID FROM tblBrand WHERE BrandName = @BrandName

   INSERT INTO tblBrandinCategory (CategoryID, BrandID) VALUES (@CategoryID, @BrandID)
END

You would then call this like this:

EXEC AddBrand 'Gucci', 23

...assuming the brand name was 'Gucci' and category ID was 23.

Executing <script> injected by innerHTML after AJAX call

Here is the script that will evaluates all script tags in the text.

function evalJSFromHtml(html) {
  var newElement = document.createElement('div');
  newElement.innerHTML = html;

  var scripts = newElement.getElementsByTagName("script");
  for (var i = 0; i < scripts.length; ++i) {
    var script = scripts[i];
    eval(script.innerHTML);
  }
}

Just call this function after you receive your HTML from server. Be warned: using eval can be dangerous.

Demo: http://plnkr.co/edit/LA7OPkRfAtgOhwcAnLrl?p=preview

How to read the RGB value of a given pixel in Python?

Using Pillow (which works with Python 3.X as well as Python 2.7+), you can do the following:

from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())

Now you have all pixel values. If it is RGB or another mode can be read by im.mode. Then you can get pixel (x, y) by:

pixel_values[width*y+x]

Alternatively, you can use Numpy and reshape the array:

>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18  18  12]

A complete, simple to use solution is

# Third party modules
import numpy
from PIL import Image


def get_image(image_path):
    """Get a numpy array of an image so that one can access values[x][y]."""
    image = Image.open(image_path, "r")
    width, height = image.size
    pixel_values = list(image.getdata())
    if image.mode == "RGB":
        channels = 3
    elif image.mode == "L":
        channels = 1
    else:
        print("Unknown mode: %s" % image.mode)
        return None
    pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
    return pixel_values


image = get_image("gradient.png")

print(image[0])
print(image.shape)

Smoke testing the code

You might be uncertain about the order of width / height / channel. For this reason I've created this gradient:

enter image description here

The image has a width of 100px and a height of 26px. It has a color gradient going from #ffaa00 (yellow) to #ffffff (white). The output is:

[[255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   4]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]]
(100, 26, 3)

Things to note:

  • The shape is (width, height, channels)
  • The image[0], hence the first row, has 26 triples of the same color

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

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

Passing a variable to a powershell script via command line

Using param to name the parameters allows you to ignore the order of the parameters:

ParamEx.ps1

# Show how to handle command line parameters in Windows PowerShell
param(
  [string]$FileName,
  [string]$Bogus
)
write-output 'This is param FileName:'+$FileName
write-output 'This is param Bogus:'+$Bogus

ParaEx.bat

rem Notice that named params mean the order of params can be ignored
powershell -File .\ParamEx.ps1 -Bogus FooBar -FileName "c:\windows\notepad.exe"

How to check Oracle patches are installed?

I understand the original post is for Oracle 10 but this is for reference by anyone else who finds it via Google.

Under Oracle 12c, I found that that my registry$history is empty. This works instead:

select * from registry$sqlpatch;

What are the advantages of NumPy over regular Python lists?

NumPy's arrays are more compact than Python lists -- a list of lists as you describe, in Python, would take at least 20 MB or so, while a NumPy 3D array with single-precision floats in the cells would fit in 4 MB. Access in reading and writing items is also faster with NumPy.

Maybe you don't care that much for just a million cells, but you definitely would for a billion cells -- neither approach would fit in a 32-bit architecture, but with 64-bit builds NumPy would get away with 4 GB or so, Python alone would need at least about 12 GB (lots of pointers which double in size) -- a much costlier piece of hardware!

The difference is mostly due to "indirectness" -- a Python list is an array of pointers to Python objects, at least 4 bytes per pointer plus 16 bytes for even the smallest Python object (4 for type pointer, 4 for reference count, 4 for value -- and the memory allocators rounds up to 16). A NumPy array is an array of uniform values -- single-precision numbers takes 4 bytes each, double-precision ones, 8 bytes. Less flexible, but you pay substantially for the flexibility of standard Python lists!

Should Gemfile.lock be included in .gitignore?

The real problem happens when you are working on an open-source Rails app that needs to have a configurable database adapter. I'm developing the Rails 3 branch of Fat Free CRM. My preference is postgres, but we want the default database to be mysql2.

In this case, Gemfile.lock still needs be checked in with the default set of gems, but I need to ignore changes that I have made to it on my machine. To accomplish this, I run:

git update-index --assume-unchanged Gemfile.lock

and to reverse:

git update-index --no-assume-unchanged Gemfile.lock

It is also useful to include something like the following code in your Gemfile. This loads the appropriate database adapter gem, based on your database.yml.

# Loads the database adapter gem based on config/database.yml (Default: mysql2)
# -----------------------------------------------------------------------------
db_gems = {"mysql2"     => ["mysql2", ">= 0.2.6"],
           "postgresql" => ["pg",     ">= 0.9.0"],
           "sqlite3"    => ["sqlite3"]}
adapter = if File.exists?(db_config = File.join(File.dirname(__FILE__),"config","database.yml"))
  db = YAML.load_file(db_config)
  # Fetch the first configured adapter from config/database.yml
  (db["production"] || db["development"] || db["test"])["adapter"]
else
  "mysql2"
end
gem *db_gems[adapter]
# -----------------------------------------------------------------------------

I can't say if this is an established best practice or not, but it works well for me.

How to make remote REST call inside Node.js? any CURL?

var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
  var finalData = "";

  response.on("data", function (data) {
    finalData += data.toString();
  });

  response.on("end", function() {
    console.log(finalData.length);
    console.log(finalData.toString());
  });

});

How can I make grep print the lines below and above each matching line?

Use -A and -B switches (mean lines-after and lines-before):

grep -A 1 -B 1 FAILED file.txt

Difference between <? super T> and <? extends T> in Java

The generic wildcards target two primary needs:

Reading from a generic collection Inserting into a generic collection There are three ways to define a collection (variable) using generic wildcards. These are:

List<?>           listUknown = new ArrayList<A>();
List<? extends A> listUknown = new ArrayList<A>();
List<? super   A> listUknown = new ArrayList<A>();

List<?> means a list typed to an unknown type. This could be a List<A>, a List<B>, a List<String> etc.

List<? extends A> means a List of objects that are instances of the class A, or subclasses of A (e.g. B and C). List<? super A> means that the list is typed to either the A class, or a superclass of A.

Read more : http://tutorials.jenkov.com/java-generics/wildcards.html

Malformed String ValueError ast.literal_eval() with String representation of Tuple

Use eval() instead of ast.literal_eval() if the input is trusted (which it is in your case).

raw_data = userfile.read().split('\n')
for a in raw_data : 
    print a
    btc_history.append(eval(a))

This works for me in Python 3.6.0

What are POD types in C++?

With C++, Plain Old Data doesn't just mean that things like int, char, etc are the only types used. Plain Old Data really means in practice that you can take a struct memcpy it from one location in memory to another and things will work exactly like you would expect (i.e. not blow up). This breaks if your class, or any class your class contains, has as a member that is a pointer or a reference or a class that has a virtual function. Essentially, if pointers have to be involved somewhere, its not Plain Old Data.

Android - Launcher Icon Size

Launch image and Slash image size for Google Play Store app submission

  1. High-res icon. PFB the table for required sizes 32-bit PNG (with alpha), Dimensions: 512px by 512px, Maximum file size: 1024KB

Required Launch Icon And Splash Image size

  1. At least 2 screenshots are required overall (Max 8 screenshots per type, Types include "Phone", "7-inch tablet" and "10-inch tablet”). JPEG or 24-bit PNG (no alpha), Minimum dimension: 320px, Maximum dimension: 3840px, Sample sizes: 320 x 480, 480 x 800, 480 x 854,1280 x 720, 1280 x 800 24 bit PNG or JPEG

Use querystring variables in MVC controller

public ActionResult SomeAction(string start, string end)

The framework will map the query string parameters to the method parameters.

Write a function that returns the longest palindrome in a given string

Following code calculates Palidrom for even length and odd length strings.

Not the best solution but works for both the cases

HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE HYTBCABADEFGHABCDEDCBAGHTFYW1234567887654321ZWETYGDE

private static String getLongestPalindrome(String string) {
    String odd = getLongestPalindromeOdd(string);
    String even = getLongestPalindromeEven(string);
    return (odd.length() > even.length() ? odd : even);
}

public static String getLongestPalindromeOdd(final String input) {
    int rightIndex = 0, leftIndex = 0;
    String currentPalindrome = "", longestPalindrome = "";
    for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
        leftIndex = centerIndex;
        rightIndex = centerIndex + 1;
        while (leftIndex >= 0 && rightIndex < input.length()) {
            if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
                break;
            }
            currentPalindrome = input.substring(leftIndex, rightIndex + 1);
            longestPalindrome = currentPalindrome.length() > longestPalindrome
                    .length() ? currentPalindrome : longestPalindrome;
            leftIndex--;
            rightIndex++;
        }
    }
    return longestPalindrome;
}

public static String getLongestPalindromeEven(final String input) {
    int rightIndex = 0, leftIndex = 0;
    String currentPalindrome = "", longestPalindrome = "";
    for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
        leftIndex = centerIndex - 1;
        rightIndex = centerIndex + 1;
        while (leftIndex >= 0 && rightIndex < input.length()) {
            if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
                break;
            }
            currentPalindrome = input.substring(leftIndex, rightIndex + 1);
            longestPalindrome = currentPalindrome.length() > longestPalindrome
                    .length() ? currentPalindrome : longestPalindrome;
            leftIndex--;
            rightIndex++;
        }
    }
    return longestPalindrome;
}

Is there a way to continue broken scp (secure copy) command process in Linux?

This is all you need.

 rsync -e ssh file host:/directory/.

How do I use brew installed Python as the default Python?

python now points to python3, if you need python 2 then do: brew install python@2 and then in your .zshrc or .bashrc file export PATH="/usr/local/opt/python@2/libexec/bin:$PATH" Now, pyhon --version = Python 2.7.14 and python3 --version = Python 3.6.4. That's the behavior I'm used to seeing in my terminal.

How to build a DataTable from a DataGridView?

I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:

private DataTable GetDataTableFromDGV(DataGridView dgv) {
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }

    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
        dt.Rows.Add(cellValues);
    }

    return dt;
}

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.

Tips for debugging .htaccess rewrite rules

If you're creating redirections, test with curl to avoid browser caching issues. Use -I to fetch http headers only. Use -L to follow all redirections.

Variable number of arguments in C++?

// spawn: allocate and initialize (a simple function)
template<typename T>
T * spawn(size_t n, ...){
  T * arr = new T[n];
  va_list ap;
  va_start(ap, n);
  for (size_t i = 0; i < n; i++)
    T[i] = va_arg(ap,T);
  return arr;
}

User writes:

auto arr = spawn<float> (3, 0.1,0.2,0.3);

Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

Visual Studio 2013 License Product Key

I solved this, without having to completely reinstall Visual Studio 2013.

For those who may come across this in the future, the following steps worked for me:

  1. Run the ISO (or vs_professional.exe).
  2. If you get the error below, you need to update the Windows Registry to trick the installer into thinking you still have the base version. If you don't get this error, skip to step 3 "The product version that you are trying to set up is earlier than the version already installed on this computer."

    • Click the link for 'examine the log file' and look near the bottom of the log, for this line: Detected related bundle ... operation: Downgrade

    • open regedit.exe and do an Edit > Find... for that GUID. In my case it was {6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}. This was found in:

      HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall{6dff50d0-3bc3-4a92-b724-bf6d6a99de4f}

    • Edit the BundleVersion value and change it to a lower version. I changed mine from 12.0.21005.13 to 12.0.21000.13: BundleVersion for Visual Studio lower the version for BundleVersion

    • Exit the registry

  3. Run the ISO (or vs_professional.exe) again. If it has a repair button like the image below, you can skip to step 4.

    Visual Studio Repair button

    • Otherwise you have to let the installer fix the registry. I did this by "installing" at least one feature, even though I think I already had all features (they were not detected). This took about 20 minutes.
  4. Run the ISO (or vs_professional.exe) again. This time repair should be visible.

  5. Click Repair and let it update your installation and apply its embedded license key. This took about 20 minutes.


Now when you run Visual Studio 2013, it should indicate that a license key was applied, under Help > Register Product:

License: Product key applied

Hope this helps somebody in the future!

Reference blog 'story'

What is the difference between window, screen, and document in Javascript?

Briefly, with more detail below,

  • window is the execution context and global object for that context's JavaScript
  • document contains the DOM, initialized by parsing HTML
  • screen describes the physical display's full screen

See W3C and Mozilla references for details about these objects. The most basic relationship among the three is that each browser tab has its own window, and a window has window.document and window.screen properties. The browser tab's window is the global context, so document and screen refer to window.document and window.screen. More details about the three objects are below, following Flanagan's JavaScript: Definitive Guide.

window

Each browser tab has its own top-level window object. Each <iframe> (and deprecated <frame>) element has its own window object too, nested within a parent window. Each of these windows gets its own separate global object. window.window always refers to window, but window.parent and window.top might refer to enclosing windows, giving access to other execution contexts. In addition to document and screen described below, window properties include

  • setTimeout() and setInterval() binding event handlers to a timer
  • location giving the current URL
  • history with methods back() and forward() giving the tab's mutable history
  • navigator describing the browser software

document

Each window object has a document object to be rendered. These objects get confused in part because HTML elements are added to the global object when assigned a unique id. E.g., in the HTML snippet

<body>
  <p id="holyCow"> This is the first paragraph.</p>
</body>

the paragraph element can be referenced by any of the following:

  • window.holyCow or window["holyCow"]
  • document.getElementById("holyCow")
  • document.querySelector("#holyCow")
  • document.body.firstChild
  • document.body.children[0]

screen

The window object also has a screen object with properties describing the physical display:

  • screen properties width and height are the full screen

  • screen properties availWidth and availHeight omit the toolbar

The portion of a screen displaying the rendered document is the viewport in JavaScript, which is potentially confusing because we call an application's portion of the screen a window when talking about interactions with the operating system. The getBoundingClientRect() method of any document element will return an object with top, left, bottom, and right properties describing the location of the element in the viewport.

What's the difference between a null pointer and a void pointer?

A Null pointer has the value 0. void pointer is a generic pointer introduced by ANSI. Generic pointer can hold the address of any data type.

Resize command prompt through commands

mode con:cols=[whatever you want] lines=[whatever you want].

The unit is the number of characters that fit in the command prompt, eg.

mode con:cols=80 lines=100

will make the command prompt 80 ASCII chars of width and 100 of height

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

It seems daft, but I think when you use the same bind variable twice you have to set it twice:

cmd.Parameters.Add("VarA", "24");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarB", "test");
cmd.Parameters.Add("VarC", "1234");
cmd.Parameters.Add("VarC", "1234");

Certainly that's true with Native Dynamic SQL in PL/SQL:

SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name'
  3     using 'KING';
  4  end;
  5  /
begin
*
ERROR at line 1:
ORA-01008: not all variables bound


SQL> begin
  2     execute immediate 'select * from emp where ename=:name and ename=:name' 
  3     using 'KING', 'KING';
  4  end;
  5  /

PL/SQL procedure successfully completed.

Hive load CSV with commas in quoted fields

keep the delimiter in single quotes it will work.

ROW FORMAT DELIMITED 
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n';

This will work

add new element in laravel collection object

If you want to add item to the beginning of the collection you can use prepend:

$item->prepend($product, 'key');

iPhone/iPad browser simulator?

There's no good substitute to testing on an actual device.

Real devices have higher display densities, meaning that pixels are smaller. If you don't test on a real device, you may not realise that your design includes text that is too small to read or buttons that are too small to tap.

You use real devices with your fingers, not a mouse. This means that the accuracy of your taps is much lower and what you are tapping is obscured by your finger. If you don't test on a real device, you may not realise you've introduced usability problems into your design.

Ruby on Rails: Clear a cached page

rake tmp:cache:clear might be what you're looking for.

jQuery UI Color Picker

That is because you are trying to access the plugin before it's loaded. You should try making a call to it when the DOM is loaded by surrounding it with this:

$(document).ready(function(){
    $("#colorpicker").colorpicker();
}

How to get the difference between two arrays in JavaScript?

The hard way (in case you would like to do something more fancy than .indexOf)

var difference = function (source, target) {
    return source.reduce(function (diff, current) { 
        if (target.indexOf(current) === -1) { 
            diff.push(current); 
        }

        return diff; 
    }, []);
}

The easy way

var difference = function (source, target) {
    return source.filter(function (current) {
        return target.indexOf(current) === -1;
    });
}

What is N-Tier architecture?

When constructing the usual MCV (a 3-tier architecture) one can decide to implement the MCV with double-deck interfaces, such that one can in fact replace a particular tier without having to modify even one line of code.

We often see the benefits of this, for instance in scenarios where you want to be able to use more than one database (in which case you have a double-interface between the control and data-layers).

When you put it on the View-layer (presentation), then you can (hold on!!) replace the USER interface with another machine, thereby automate REAL input (!!!) - and you can thereby run tedious usability tests thousands of times without any user having to tap and re-tap and re-re-tap the same things over and over again.

Some describe such 3-tier architecture with 1 or 2 double-interfaces as 4-tier or 5-tier architecture, implicitly implying the double-interfaces.

Other cases include (but are not limited to) the fact that you - in case of semi-or-fully replicated database-systems would practically be able to consider one of the databases as the "master", and thereby you would have a tier comprising of the master and another comprising of the slave database.

Mobile example

Therefore, multi-tier - or N-tier - indeed has a few interpretations, whereas I would surely stick to the 3-tier + extra tiers comprising of thin interface-disks wedged in between to enable said tier-swaps, and in terms of testing (particularly used on mobile devices), you can now run user tests on the real software, by simulating a users tapping in ways which the control logic cannot distinguish from a real user tapping. This is almost paramount in simulating real user tests, in that you can record all inputs from the users OTA, and then re-use the same input when doing regression tests.

Node - how to run app.js?

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => res.send('Hello World!'))

app.listen(port, () => console.log(`Example app listening on port ${port}!`))

How to install SQL Server Management Studio 2012 (SSMS) Express?

When I installed: ENU\x64\SQLManagementStudio_x64_ENU.exe

I had to choose the following options to get the management Tools:

  1. "New SQL Server stand-alone installation or add features to an existing installation."
  2. "Add features to an existing instance of SQL Server 2012"
  3. Accept the license.
  4. Check the box for "Management Tools - Basic".
  5. Wait a long time as it installs.

When I was done I had an option "SQL Server Management Studio" within my Start Menu.

Searching for "Management" pulled it up faster within the Start Menu.

How to implement a binary tree?

# simple binary tree
# in this implementation, a node is inserted between an existing node and the root


class BinaryTree():

    def __init__(self,rootid):
      self.left = None
      self.right = None
      self.rootid = rootid

    def getLeftChild(self):
        return self.left
    def getRightChild(self):
        return self.right
    def setNodeValue(self,value):
        self.rootid = value
    def getNodeValue(self):
        return self.rootid

    def insertRight(self,newNode):
        if self.right == None:
            self.right = BinaryTree(newNode)
        else:
            tree = BinaryTree(newNode)
            tree.right = self.right
            self.right = tree

    def insertLeft(self,newNode):
        if self.left == None:
            self.left = BinaryTree(newNode)
        else:
            tree = BinaryTree(newNode)
            tree.left = self.left
            self.left = tree


def printTree(tree):
        if tree != None:
            printTree(tree.getLeftChild())
            print(tree.getNodeValue())
            printTree(tree.getRightChild())



# test tree

def testTree():
    myTree = BinaryTree("Maud")
    myTree.insertLeft("Bob")
    myTree.insertRight("Tony")
    myTree.insertRight("Steven")
    printTree(myTree)

Read more about it Here:-This is a very simple implementation of a binary tree.

This is a nice tutorial with questions in between

Write to Windows Application Event Log

Yes, there is a way to write to the event log you are looking for. You don't need to create a new source, just simply use the existent one, which often has the same name as the EventLog's name and also, in some cases like the event log Application, can be accessible without administrative privileges*.

*Other cases, where you cannot access it directly, are the Security EventLog, for example, which is only accessed by the operating system.

I used this code to write directly to the event log Application:

using (EventLog eventLog = new EventLog("Application")) 
{
    eventLog.Source = "Application"; 
    eventLog.WriteEntry("Log message example", EventLogEntryType.Information, 101, 1); 
}

As you can see, the EventLog source is the same as the EventLog's name. The reason of this can be found in Event Sources @ Windows Dev Center (I bolded the part which refers to source name):

Each log in the Eventlog key contains subkeys called event sources. The event source is the name of the software that logs the event. It is often the name of the application or the name of a subcomponent of the application if the application is large. You can add a maximum of 16,384 event sources to the registry.

Excel VBA - select a dynamic cell range

So it depends on how you want to pick the incrementer, but this should work:

Range("A1:" & Cells(1, i).Address).Select

Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)

If you want the beginning to be dynamic as well, you can try this:

Sub SelectCols()

    Dim Col1 As Integer
    Dim Col2 As Integer

    Col1 = 2
    Col2 = 4

    Range(Cells(1, Col1), Cells(1, Col2)).Select

End Sub

What exactly is the meaning of an API?

Application program interface (API) is a set of routines, protocols, and tools for building software applications. An API specifies how software components should interact and APIs are used when programming graphical user interface (GUI) components. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.

source: http://www.webopedia.com/TERM/A/API.html

Converting bytes to megabytes

Use the computation your users will most likely expect. Do your users care to know how many actual bytes are on a disk or in memory or whatever, or do they only care about usable space? The answer to that question will tell you which calculation makes the most sense.

This isn't a precision question as much as it is a usability question. Provide the calculation that is most useful to your users.

MySQL SELECT AS combine two columns into one

If both columns can contain NULL, but you still want to merge them to a single string, the easiest solution is to use CONCAT_WS():

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT_WS('', ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

This way you won't have to check for NULL-ness of each column separately.

Alternatively, if both columns are actually defined as NOT NULL, CONCAT() will be quite enough:

SELECT FirstName AS First_Name
     , LastName AS Last_Name
     , CONCAT(ContactPhoneAreaCode1, ContactPhoneNumber1) AS Contact_Phone 
  FROM TABLE1

As for COALESCE, it's a bit different beast: given the list of arguments, it returns the first that's not NULL.

c# .net change label text

Have you tried running the code in the Page_Load() method?

protected void Page_Load(object sender, EventArgs e) 
{

         Label1.Text = "test";
        if (Request.QueryString["ID"] != null)
        {

            string test = Request.QueryString["ID"];
            Label1.Text = "Du har nu lånat filmen:" + test;
        }
}

error MSB6006: "cmd.exe" exited with code 1

Simple and better solution : %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe MyProject.sln I make a bat file like this %WINDIR%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe D:\GESTION-SOMECOPA\GestionCommercial\GestionCommercial.sln pause

Then I can see all errors and correct them. Because when you change the folder name (without spaces as seen above) you will have another problems. Visual Studio 2015 works fine after this.

Put a Delay in Javascript

Actually only setTimeout is fine for that job and normally you cannot set exact delays with non determined methods as busy loops.

Delete data with foreign key in SQL Server table

If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE.

For more information, see the MSDN page on Cascading Referential Integrity Constraints.

ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.

PostgreSQL: export resulting data from SQL query to Excel/CSV

The correct script for postgres (Ubuntu) is:

COPY (SELECT * FROM tbl) TO '/var/lib/postgres/myfile1.csv';