Programs & Examples On #Cocoa design patterns

Use this tag for questions about design patterns that apply specifically to using the Cocoa and Cocoa-Touch frameworks used in MacOS and iOS development. Examples of such design patterns include, but are not limited to, 'MVC' (model-view-controller), 'delegation', 'observer', 'singleton', 'responder chain', and more. Some of these are well-known patterns but may be used in Cocoa and Cocoa-Touch in more specialised ways.

Java optional parameters

Overloading is fine, but if there's a lot of variables that needs default value, you will end up with :

public void methodA(A arg1) {  }
public void methodA( B arg2,) {  }
public void methodA(C arg3) {  }
public void methodA(A arg1, B arg2) {  }
public void methodA(A arg1, C arg3) {  }
public void methodA( B arg2, C arg3) {  }
public void methodA(A arg1, B arg2, C arg3) {  }

So I would suggest use the Variable Argument provided by Java. Here's a link for explanation.

Exiting out of a FOR loop in a batch file?

Based on Tim's second edit and this page you could do this:

@echo off
if "%1"=="loop" (
  for /l %%f in (1,1,1000000) do (
    echo %%f
    if exist %%f exit
  )
  goto :eof
)
cmd /v:on /q /d /c "%0 loop"
echo done

This page suggests a way to use a goto inside a loop, it seems it does work, but it takes some time in a large loop. So internally it finishes the loop before the goto is executed.

How to fit Windows Form to any screen resolution?

If you want to set the form size programmatically, set the form's StartPosition property to Manual. Otherwise the form's own positioning and sizing algorithm will interfere with yours. This is why you are experiencing the problems mentioned in your question.

Example: Here is how I resize the form to a size half-way between its original size and the size of the screen's working area. I also center the form in the working area:

public MainView()
{
    InitializeComponent();

    // StartPosition was set to FormStartPosition.Manual in the properties window.
    Rectangle screen = Screen.PrimaryScreen.WorkingArea;
    int w = Width >= screen.Width ? screen.Width : (screen.Width + Width) / 2;
    int h = Height >= screen.Height ? screen.Height : (screen.Height + Height) / 2;
    this.Location = new Point((screen.Width - w) / 2, (screen.Height - h) / 2);
    this.Size = new Size(w, h);
}

Note that setting WindowState to FormWindowState.Maximized alone does not change the size of the restored window. So the window might look good as long as it is maximized, but when restored, the window size and location can still be wrong. So I suggest setting size and location even when you intend to open the window as maximized.

Get PHP class property by string

There might be answers to this question, but you may want to see these migrations to PHP 7

backward incompatible change

source: php.net

Resetting a form in Angular 2 after submit

Use NgForm's .resetForm() rather than .reset() because it is the method that is officially documented in NgForm's public api. (Ref [1])

<form (ngSubmit)="mySubmitHandler(); myNgForm.resetForm()" #myNgForm="ngForm">

The .resetForm() method will reset the NgForm's FormGroup and set it's submit flag to false (See [2]).

Tested in @angular versions 2.4.8 and 4.0.0-rc3

Is it possible that one domain name has multiple corresponding IP addresses?

This is round robin DNS. This is a quite simple solution for load balancing. Usually DNS servers rotate/shuffle the DNS records for each incoming DNS request. Unfortunately it's not a real solution for fail-over. If one of the servers fail, some visitors will still be directed to this failed server.

Why should we include ttf, eot, woff, svg,... in a font-face

WOFF 2.0, based on the Brotli compression algorithm and other improvements over WOFF 1.0 giving more than 30 % reduction in file size, is supported in Chrome, Opera, and Firefox.

http://en.wikipedia.org/wiki/Web_Open_Font_Format http://en.wikipedia.org/wiki/Brotli

http://sth.name/2014/09/03/Speed-up-webfonts/ has an example on how to use it.

Basically you add a src url to the woff2 file and specify the woff2 format. It is important to have this before the woff-format: the browser will use the first format that it supports.

SQL Query - Concatenating Results into One String

For SQL Server 2005 and above use Coalesce for nulls and I am using Cast or Convert if there are numeric values -

declare @CodeNameString  nvarchar(max)
select  @CodeNameString = COALESCE(@CodeNameString + ',', '')  + Cast(CodeName as varchar) from AccountCodes  ORDER BY Sort
select  @CodeNameString

Action Image MVC3 Razor

This would be work very fine

<a href="<%:Url.Action("Edit","Account",new {  id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>

Create a zip file and download it

I have experienced exactly the same problem. In my case, the source of it was the permissions of the folder in which I wanted to create the zip file that were all set to read only. I changed it to read and write and it worked.

If the file is not created on your local-server when you run the script, you most probably have the same problem as I did.

xxxxxx.exe is not a valid Win32 application

It's Feb 2013, and I can now target XP in VS2012 by setting:

Project Properties -> General -> Platform Toolset to:

Visual Studio 2012 - Windows XP (v110_xp)

You will have to redistribute the msvcp110.dll libraries et al with your application, which are found here: "<Program Files>\Microsoft Visual Studio 11.0\VC\redist\x86\Microsoft.VC110.CRT\"


Update Aug 2015 with Visual Studio 2015

There seems to be quite a selection now. I was able to compile application in VS2015 using Visual Studio 2015 - Windows XP (v140_xp) setting. To make it actually run on Win XP I had to deploy (copy alongside application) msvcr100.dll for Release build and msvcr110.dll and msvcr100d.dll for Debug build (note there is a difference in numbers 100 and 110, also debug lib msvcr100d.dll may not be redistributable) Targeting Windows XP with Visual Studio 2015

Writing/outputting HTML strings unescaped

In ASP.NET MVC 3 You should do something like this:

// Say you have a bit of HTML like this in your controller:
ViewBag.Stuff = "<li>Menu</li>"
//  Then you can do this in your view:
@MvcHtmlString.Create(ViewBag.Stuff)

What is `git push origin master`? Help with git's refs, heads and remotes

Or as a single command:

git push -u origin master:my_test

Pushes the commits from your local master branch to a (possibly new) remote branch my_test and sets up master to track origin/my_test.

Java - ignore exception and continue

You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.

 try{
      throw new Exception();
 }catch (Exception ex){
   ex.printStackTrace();
 }
 System.out.println("Made it!");

However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.

Makefile, header dependencies

How about something like:

includes = $(wildcard include/*.h)

%.o: %.c ${includes}
    gcc -Wall -Iinclude ...

You could also use the wildcards directly, but I tend to find I need them in more than one place.

Note that this only works well on small projects, since it assumes that every object file depends on every header file.

Twitter Bootstrap Form File Element Upload Button

No fancy shiz required:

HTML:

<form method="post" action="/api/admin/image" enctype="multipart/form-data">
    <input type="hidden" name="url" value="<%= boxes[i].url %>" />
    <input class="image-file-chosen" type="text" />
    <br />
    <input class="btn image-file-button" value="Choose Image" />
    <input class="image-file hide" type="file" name="image"/> <!-- Hidden -->
    <br />
    <br />
    <input class="btn" type="submit" name="image" value="Upload" />
    <br />
</form>

JS:

$('.image-file-button').each(function() {
      $(this).off('click').on('click', function() {
           $(this).siblings('.image-file').trigger('click');
      });
});
$('.image-file').each(function() {
      $(this).change(function () {
           $(this).siblings('.image-file-chosen').val(this.files[0].name);
      });
});

CAUTION: The three form elements in question MUST be siblings of each other (.image-file-chosen, .image-file-button, .image-file)

Hash Table/Associative Array in VBA

I think you are looking for the Dictionary object, found in the Microsoft Scripting Runtime library. (Add a reference to your project from the Tools...References menu in the VBE.)

It pretty much works with any simple value that can fit in a variant (Keys can't be arrays, and trying to make them objects doesn't make much sense. See comment from @Nile below.):

Dim d As dictionary
Set d = New dictionary

d("x") = 42
d(42) = "forty-two"
d(CVErr(xlErrValue)) = "Excel #VALUE!"
Set d(101) = New Collection

You can also use the VBA Collection object if your needs are simpler and you just want string keys.

I don't know if either actually hashes on anything, so you might want to dig further if you need hashtable-like performance. (EDIT: Scripting.Dictionary does use a hash table internally.)

What is the syntax for Typescript arrow functions with generics?

The full example explaining the syntax referenced by Robin... brought it home for me:

Generic functions

Something like the following works fine:

function foo<T>(x: T): T { return x; }

However using an arrow generic function will not:

const foo = <T>(x: T) => x; // ERROR : unclosed `T` tag

Workaround: Use extends on the generic parameter to hint the compiler that it's a generic, e.g.:

const foo = <T extends unknown>(x: T) => x;

How to do Base64 encoding in node.js?

Buffers can be used for taking a string or piece of data and doing base64 encoding of the result. For example:

You can install Buffer via npm like :- npm i buffer --save

you can use this in your js file like this :-

var buffer = require('buffer/').Buffer;

->> console.log(buffer.from("Hello Vishal Thakur").toString('base64'));
SGVsbG8gVmlzaGFsIFRoYWt1cg==  // Result

->> console.log(buffer.from("SGVsbG8gVmlzaGFsIFRoYWt1cg==", 'base64').toString('ascii'))
Hello Vishal Thakur   // Result

How to make scipy.interpolate give an extrapolated result beyond the input range?

I'm afraid that there is no easy to do this in Scipy to my knowledge. You can, as I'm fairly sure that you are aware, turn off the bounds errors and fill all function values beyond the range with a constant, but that doesn't really help. See this question on the mailing list for some more ideas. Maybe you could use some kind of piecewise function, but that seems like a major pain.

HTTP Status 404 - The requested resource (/) is not available

Following steps helped me solve the issue.

  1. In the eclipse right click on server and click on properties.
  2. If Location is set workspace/metadata click on switch location and so that it refers to /servers/tomcatv7server at localhost.server
  3. Save and close
  4. Next double click on server
  5. Under server locations mostly it would be selected as use workspace metadata Instead, select use tomcat installation
  6. Save changes
  7. Restart server and verify localhost:8080 works.

Why does CSV file contain a blank line in between each data line when outputting with Dictwriter in Python

Changing the 'w' (write) in this line:

output = csv.DictWriter(open('file3.csv','w'), delimiter=',', fieldnames=headers)

To 'wb' (write binary) fixed this problem for me:

output = csv.DictWriter(open('file3.csv','wb'), delimiter=',', fieldnames=headers)

Python v2.75: Open()

Credit to @dandrejvv for the solution in the comment on the original post above.

Chart.js v2 hide dataset labels

new Chart('idName', {
      type: 'typeChar',
      data: data,
      options: {
        legend: {
          display: false
        }
      }
    });

Sequence contains more than one element

The problem is that you are using SingleOrDefault. This method will only succeed when the collections contains exactly 0 or 1 element. I believe you are looking for FirstOrDefault which will succeed no matter how many elements are in the collection.

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

ORA-00972 identifier is too long alias column name

I'm using Argos reporting system as a front end and Oracle in back. I just encountered this error and it was caused by a string with a double quote at the start and a single quote at the end. Replacing the double quote with a single solved the issue.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

Get parent directory of running script

If your script is located in /var/www/dir/index.php then the following would return:

dirname(__FILE__); // /var/www/dir

or

dirname( dirname(__FILE__) ); // /var/www

Edit

This is a technique used in many frameworks to determine relative paths from the app_root.

File structure:

 /var/
      www/
          index.php
          subdir/
                 library.php

index.php is my dispatcher/boostrap file that all requests are routed to:

define(ROOT_PATH, dirname(__FILE__) ); // /var/www

library.php is some file located an extra directory down and I need to determine the path relative to the app root (/var/www/).

$path_current = dirname( __FILE__ ); // /var/www/subdir
$path_relative = str_replace(ROOT_PATH, '', $path_current); // /subdir

There's probably a better way to calculate the relative path then str_replace() but you get the idea.

How to find index of list item in Swift?

Update for Swift 2:

sequence.contains(element): Returns true if a given sequence (such as an array) contains the specified element.

Swift 1:

If you're looking just to check if an element is contained inside an array, that is, just get a boolean indicator, use contains(sequence, element) instead of find(array, element):

contains(sequence, element): Returns true if a given sequence (such as an array) contains the specified element.

See example below:

var languages = ["Swift", "Objective-C"]
contains(languages, "Swift") == true
contains(languages, "Java") == false
contains([29, 85, 42, 96, 75], 42) == true
if (contains(languages, "Swift")) {
  // Use contains in these cases, instead of find.   
}

Javascript - Get Image height

Try this:

var curHeight;
var curWidth;

function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
curHeight = newImg.height;
curWidth = newImg.width;

}

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Reading Excel file using node.js

You can use read-excel-file npm.

In that, you can specify JSON Schema to convert XLSX into JSON Format.

const readXlsxFile = require('read-excel-file/node');

const schema = {
    'Segment': {
        prop: 'Segment',
        type: String
    },
    'Country': {
        prop: 'Country',
        type: String
    },
    'Product': {
        prop: 'Product',
        type: String
    }
}

readXlsxFile('sample.xlsx', { schema }).then(({ rows, errors }) => {
    console.log(rows);
});

What is a callback?

A callback is a function pointer that you pass in to another function. The function you are calling will 'callback' (execute) the other function when it has completed.

Check out this link.

How to change css property using javascript

Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.

Java error - "invalid method declaration; return type required"

I had a similar issue when adding a class to the main method. Turns out it wasn't an issue, it was me not checking my spelling. So, as a noob, I learned that mis-spelling can and will mess things up. These posts helped me "see" my mistake and all is good now.

Can I add color to bootstrap icons only using CSS?

This is all a bit roundabout..

I've used the glyphs like this

  </div>
        <div class="span2">
            <span class="glyphicons thumbs_up"><i class="green"></i></span>
        </div>
        <div class="span2">
            <span class="glyphicons thumbs_down"><i class="red"></i></span>
        </div>

and to affect the color, i included a bit of css at the head like this

<style>
        i.green:before {
            color: green;
        }
        i.red:before {
            color: red;
        }
    </style>

Voila, green and red thumbs.

Opposite of %in%: exclude rows with values specified in a vector

How about:

'%ni%' <- Negate('%in%')
c(1,3,11) %ni% 1:10
# [1] FALSE FALSE  TRUE

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Skipping Iterations in Python

I think you're looking for continue

Mobile Safari: Javascript focus() method on inputfield only works with click?

This solution works well, I tested on my phone:

document.body.ontouchend = function() { document.querySelector('[name="name"]').focus(); };

enjoy

Is Unit Testing worth the effort?

One thing no-one has mentioned yet is getting the commitment of all developers to actually run and update any existing automated test. Automated tests that you get back to and find broken because of new development looses a lot of the value and make automated testing really painful. Most of those tests will not be indicating bugs since the developer has tested the code manually, so the time spent updating them is just waste.

Convincing the skeptics to not destroy the work the others are doing on unit-tests is a lot more important for getting value from the testing and might be easier.

Spending hours updating tests that has broken because of new features each time you update from the repository is neither productive nor fun.

python multithreading wait till all threads finished

You need to use join method of Thread object in the end of the script.

t1 = Thread(target=call_script, args=(scriptA + argumentsA))
t2 = Thread(target=call_script, args=(scriptA + argumentsB))
t3 = Thread(target=call_script, args=(scriptA + argumentsC))

t1.start()
t2.start()
t3.start()

t1.join()
t2.join()
t3.join()

Thus the main thread will wait till t1, t2 and t3 finish execution.

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

Best way to center a <div> on a page vertically and horizontally?

If you guys are using JQuery, you can do this by using .position();

<div class="positionthis"></div>

CSS

.positionthis {
    width:100px;
    height:100px;
    position: absolute;
    background:blue;
}

Javascript (JQuery)

$(document).ready(function () {
    $('.positionthis').position({
        of: $(document),
        my: 'center center',
        at: 'center center',
        collision: 'flip flip'
    });
});

JSFiddle : http://jsfiddle.net/vx9gV/

Why is it common to put CSRF prevention tokens in cookies?

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

Cannot construct instance of - Jackson

In your concrete example the problem is that you don't use this construct correctly:

@JsonSubTypes({ @JsonSubTypes.Type(value = MyAbstractClass.class, name = "MyAbstractClass") })

@JsonSubTypes.Type should contain the actual non-abstract subtypes of your abstract class.

Therefore if you have:

abstract class Parent and the concrete subclasses

Ch1 extends Parent and Ch2 extends Parent

Then your annotation should look like:

@JsonSubTypes({ 
          @JsonSubTypes.Type(value = Ch1.class, name = "ch1"),
          @JsonSubTypes.Type(value = Ch2.class, name = "ch2")
})

Here name should match the value of your 'discriminator':

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, 
include = JsonTypeInfo.As.WRAPPER_OBJECT, 
property = "type")

in the property field, here it is equal to type. So type will be the key and the value you set in name will be the value.

Therefore, when the json string comes if it has this form:

{
 "type": "ch1",
 "other":"fields"
}

Jackson will automatically convert this to a Ch1 class.

If you send this:

{
 "type": "ch2",
 "other":"fields"
}

You would get a Ch2 instance.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How do you overcome the svn 'out of date' error?

If once solved a similar issue by simply checking out a new working copy and replacing the .svn directory throwing the commit errors with this newly checked out one. The reason in my case was that after a repository corruption and restore from a backup the working copy was pointing towards a revision that didn't exist in the restored repository. Also got "item out of date" errors. Updating the working copy before commit didn't solve this but replacing the .svn as described above did.

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

PHP append one array to another (not array_push or +)

How about this:

$appended = $a + $b;

Git on Windows: How do you set up a mergetool?

Under Cygwin, the only thing that worked for me is the following:

git config --global merge.tool myp4merge
git config --global mergetool.myp4merge.cmd 'p4merge.exe "$(cygpath -wla $BASE)" "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)" "$(cygpath -wla $MERGED)"'
git config --global diff.tool myp4diff
git config --global difftool.myp4diff.cmd 'p4merge.exe "$(cygpath -wla $LOCAL)" "$(cygpath -wla $REMOTE)"'

Also, I like to turn off the prompt message for difftool:

git config --global difftool.prompt false

How do I get a reference to the app delegate in Swift?

Try simply this:

Swift 4

// Call the method
(UIApplication.shared.delegate as? AppDelegate)?.whateverWillOccur()

where in your AppDelegate:

// MARK: - Whatever
func whateverWillOccur() {

    // Your code here.

}

How to truncate float values?

When using a pandas df this worked for me

import math
def truncate(number, digits) -> float:
    stepper = 10.0 ** digits
    return math.trunc(stepper * number) / stepper

df['trunc'] = df['float_val'].apply(lambda x: truncate(x,1))
df['trunc']=df['trunc'].map('{:.1f}'.format)

How to create my json string by using C#?

No real need for the JSON.NET package. You could use JavaScriptSerializer. The Serialize method will turn a managed type instance into a JSON string.

var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(instanceOfThing);

while EOF in JAVA?

you should use while (fileReader.hasNextLine())

CSS flexbox vertically/horizontally center image WITHOUT explicitely defining parent height

Without explicitly defining the height I determined I need to apply the flex value to the parent and grandparent div elements...

<div style="display: flex;">
<div style="display: flex;">
 <img alt="No, he'll be an engineer." src="theknack.png" style="margin: auto;" />
</div>
</div>

If you're using a single element (e.g. dead-centered text in a single flex element) use the following:

align-items: center;
display: flex;
justify-content: center;

Variable declaration in a header file

If you declare it like

int x;

in a header file which is then included in multiple places, you'll end up with multiple instances of x (and potentially compile or link problems).

The correct way to approach this is to have the header file say

extern int x; /* declared in foo.c */

and then in foo.c you can say

int x; /* exported in foo.h */

THen you can include your header file in as many places as you like.

Delete ActionLink with confirm dialog

I wanted the same thing; a delete button on my Details view. I eventually realised I needed to post from that view:

@using (Html.BeginForm())
        {
            @Html.AntiForgeryToken()
            @Html.HiddenFor(model => model.Id)
            @Html.ActionLink("Edit", "Edit", new { id = Model.Id }, new { @class = "btn btn-primary", @style="margin-right:30px" })

            <input type="submit" value="Delete" class="btn btn-danger" onclick="return confirm('Are you sure you want to delete this record?');" />
        }

And, in the Controller:

 // this action deletes record - called from the Delete button on Details view
    [HttpPost]
    public ActionResult Details(MainPlus mainPlus)
    {
        if (mainPlus != null)
        {
            try
            {
                using (IDbConnection db = new SqlConnection(PCALConn))
                {
                    var result = db.Execute("DELETE PCAL.Main WHERE Id = @Id", new { Id = mainPlus.Id });
                }
                return RedirectToAction("Calls");
            } etc

Check if the number is integer

I am not sure what you are trying to accomplish. But here are some thoughts:
1. Convert to integer:
num = as.integer(123.2342)
2. Check if a variable is an integer:
is.integer(num)
typeof(num)=="integer"

Detect URLs in text with JavaScript

let str = 'https://example.com is a great site'
str.replace(/(https?:\/\/[^\s]+)/g,"<a href='$1' target='_blank' >$1</a>")

Short Code Big Work!...

Result:-

 <a href="https://example.com" target="_blank" > https://example.com </a>

Javascript: Fetch DELETE and PUT requests

Here is good example of the CRUD operation using fetch API:

“A practical ES6 guide on how to perform HTTP requests using the Fetch API” by Dler Ari https://link.medium.com/4ZvwCordCW

Here is the sample code I tried for PATCH or PUT

function update(id, data){
  fetch(apiUrl + "/" + id, {
    method: 'PATCH',
    body: JSON.stringify({
     data
    })
  }).then((response) => {
    response.json().then((response) => {
      console.log(response);
    })
  }).catch(err => {
    console.error(err)
  })

For DELETE:

function remove(id){
  fetch(apiUrl + "/" + id, {
    method: 'DELETE'
  }).then(() => {
     console.log('removed');
  }).catch(err => {
    console.error(err)
  });

For more info visit Using Fetch - Web APIs | MDN https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch > Fetch_API.

C# DateTime to "YYYYMMDDHHMMSS" format

DateTime.Now.ToString("yyyyMMddHHmmss");

if you just want it displayed as a string

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

Can my enums have friendly names?

Enum names live under the same rules as normal variable names, i.e. no spaces or dots in the middle of the names... I still consider the first one to be rather friendly though...

How to pass data to all views in Laravel 5?

In the documentation:

Typically, you would place calls to the share method within a service provider's boot method. You are free to add them to the AppServiceProvider or generate a separate service provider to house them.

I'm agree with Marwelln, just put it in AppServiceProvider in the boot function:

public function boot() {
    View::share('youVarName', [1, 2, 3]);
}

I recommend use an specific name for the variable, to avoid confussions or mistakes with other no 'global' variables.

How to index an element of a list object in R

Indexing a list is done using double bracket, i.e. hypo_list[[1]] (e.g. have a look here: http://www.r-tutor.com/r-introduction/list). BTW: read.table does not return a table but a dataframe (see value section in ?read.table). So you will have a list of dataframes, rather than a list of table objects. The principal mechanism is identical for tables and dataframes though.

Note: In R, the index for the first entry is a 1 (not 0 like in some other languages).

Dataframes

l <- list(anscombe, iris)   # put dfs in list
l[[1]]             # returns anscombe dataframe

anscombe[1:2, 2]   # access first two rows and second column of dataset
[1] 10  8

l[[1]][1:2, 2]     # the same but selecting the dataframe from the list first
[1] 10  8

Table objects

tbl1 <- table(sample(1:5, 50, rep=T))
tbl2 <- table(sample(1:5, 50, rep=T))
l <- list(tbl1, tbl2)  # put tables in a list

tbl1[1:2]              # access first two elements of table 1 

Now with the list

l[[1]]                 # access first table from the list

1  2  3  4  5 
9 11 12  9  9 

l[[1]][1:2]            # access first two elements in first table

1  2 
9 11 

What's the easy way to auto create non existing dir in ansible

you can create the folder using the following depending on your ansible version.

Latest version 2<

- name: Create Folder
  file: 
   path: "{{project_root}}/conf"
   recurse: yes
   state: directory

Older version:

- name: Create Folder
  file: 
      path="{{project_root}}/conf"
      recurse: yes
      state=directory

Refer - http://docs.ansible.com/ansible/latest/file_module.html

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

Probably going overboard a bit but i provided call backs for both the execution code and the results. obviously for thread safety you want to be careful what you access in your execution callback.

The AsyncTask implementation:

public class AsyncDbCall<ExecuteType,ResultType> extends AsyncTask<ExecuteType, Void,  
ResultType>
{
    public interface ExecuteCallback<E, R>
    {
        public R execute(E executeInput);
    }
    public interface PostExecuteCallback<R>
    {
        public void finish(R result);
    }

    private PostExecuteCallback<ResultType> _resultCallback = null;
    private ExecuteCallback<ExecuteType,ResultType> _executeCallback = null;


    AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback, PostExecuteCallback<ResultType> postExecuteCallback)
    {
        _resultCallback = postExecuteCallback;
        _executeCallback = executeCallback;
    }

    AsyncDbCall(ExecuteCallback<ExecuteType,ResultType> executeCallback)
    {
        _executeCallback = executeCallback;
    }

    @Override
    protected ResultType doInBackground(final ExecuteType... params)
    {
        return  _executeCallback.execute(params[0]);
    }

    @Override
    protected void onPostExecute(ResultType result)
    {
        if(_resultCallback != null)
            _resultCallback.finish(result);
    }
}

A callback:

 AsyncDbCall.ExecuteCallback<Device, Device> updateDeviceCallback = new 
 AsyncDbCall.ExecuteCallback<Device, Device>()
    {
        @Override
        public Device execute(Device device)
        {
            deviceDao.updateDevice(device);
            return device;
        }
    };

And finally execution of the async task:

 new AsyncDbCall<>(addDeviceCallback, resultCallback).execute(device);

Error: Could not find or load main class

If the class is in a package

package thepackagename;

public class TheClassName {
  public static final void main(String[] cmd_lineParams)  {
     System.out.println("Hello World!");
  } 
}

Then calling:

java -classpath . TheClassName

results in Error: Could not find or load main class TheClassName. This is because it must be called with its fully-qualified name:

java -classpath . thepackagename.TheClassName

And this thepackagename directory must exist in the classpath. In this example, ., meaning the current directory, is the entirety of classpath. Therefore this particular example must be called from the directory in which thepackagename exists.

To be clear, the name of this class is not TheClassName, It's thepackagename.TheClassName. Attempting to execute TheClassName does not work, because no class having that name exists. Not on the current classpath anyway.

Finally, note that the compiled (.class) version is executed, not the source code (.java) version. Hence “CLASSPATH.”

sql insert into table with select case values

You need commas after end finishing the case statement. And, the "as" goes after the case statement, not inside it:

Insert into TblStuff(FullName, Address, City, Zip)
    Select (Case When Middle is Null Then Fname + LName
                 Else Fname +' ' + Middle + ' '+ Lname
            End)  as FullName,
           (Case When Address2 is Null Then Address1
                 else Address1 +', ' + Address2
            End)  as  Address,
           City as City,
           Zip as Zip
    from tblImport

Cordova app not displaying correctly on iPhone X (Simulator)

Please note that this article: https://medium.com/the-web-tub/supporting-iphone-x-for-mobile-web-cordova-app-using-onsen-ui-f17a4c272fcd has different sizes than above and cordova plugin page:

Default@2x~iphone~anyany.png (= 1334x1334 = 667x667@2x)
Default@2x~iphone~comany.png (= 750x1334 = 375x667@2x)
Default@2x~iphone~comcom.png (= 750x750 = 375x375@2x)
Default@3x~iphone~anyany.png (= 2436x2436 = 812x812@3x)
Default@3x~iphone~anycom.png (= 2436x1242 = 812x414@3x)
Default@3x~iphone~comany.png (= 1242x2436 = 414x812@3x)
Default@2x~ipad~anyany.png (= 2732x2732 = 1366x1366@2x)
Default@2x~ipad~comany.png (= 1278x2732 = 639x1366@2x)

I resized images as above and updated ios platform and cordova-plugin-splashscreen to latest and the flash to white screen after a second issue was fixed. However the initial spash image has a white border at bottom now.

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

Converting Numpy Array to OpenCV Array

The simplest solution would be to use Pillow lib:

from PIL import Image

image = Image.fromarray(<your_numpy_array>.astype(np.uint8))

And you can use it as an image.

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

This has support for both title and image.

For iOS 11 and afterwards:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
    let action = UIContextualAction(
        style: .normal,
        title: "My Title",
        handler: { (action, view, completion) in
            //do what you want here
            completion(true)
    })

    action.image = UIImage(named: "My Image")
    action.backgroundColor = .red
    let configuration = UISwipeActionsConfiguration(actions: [action])
    configuration.performsFirstActionWithFullSwipe = false
    return configuration
}

Also, similar method is available for leadingSwipeActions

Source:

https://developer.apple.com/videos/play/wwdc2017/201/ (Talks about this at around 16 mins time) https://developer.apple.com/videos/play/wwdc2017/204/ (Talks about this at around 23 mins time)

What's the difference between align-content and align-items?

I had the same confusion. After some tinkering based on many of the answers above, I can finally see the differences. In my humble opinion, the distinction is best demonstrated with a flex container that satisfies the following two conditions:

  1. The flex container itself has a height constraint (e.g., min-height: 60rem) and thus can become too tall for its content
  2. The child items enclosed in the container have uneven heights

Condition 1 helps me understand what content means relative to its parent container. When the content is flush with the container, we will not be able to see any positioning effects coming from align-content. It is only when we have extra space along the cross axis, we start to see its effect: It aligns the content relative to the boundaries of the parent container.

Condition 2 helps me visualize the effects of align-items: it aligns items relative to each other.


Here is a code example. Raw materials come from Wes Bos' CSS Grid tutorial (21. Flexbox vs. CSS Grid)

  • Example HTML:
  <div class="flex-container">
    <div class="item">Short</div>
    <div class="item">Longerrrrrrrrrrrrrr</div>
    <div class="item"></div>
    <div class="item" id="tall">This is Many Words</div>
    <div class="item">Lorem, ipsum.</div>
    <div class="item">10</div>
    <div class="item">Snickers</div>
    <div class="item">Wes Is Cool</div>
    <div class="item">Short</div>
  </div>
  • Example CSS:
.flex-container {
  display: flex;
  /*dictates a min-height*/
  min-height: 60rem;
  flex-flow: row wrap;
  border: 5px solid white;
  justify-content: center;
  align-items: center;
  align-content: flex-start;
 }

#tall {
  /*intentionally made tall*/
  min-height: 30rem;
}

.item {
  margin: 10px;
  max-height: 10rem;
}

Example 1: Let's narrow the viewport so that the content is flush with the container. This is when align-content: flex-start; has no effects since the entire content block is tightly fit inside the container (no extra room for repositioning!)

Also, note the 2nd row--see how the items are center aligned among themselves.

enter image description here

Example 2: As we widen the viewport, we no longer have enough content to fill the entire container. Now we start to see the effects of align-content: flex-start;--it aligns the content relative to the top edge of the container. enter image description here


These examples are based on flexbox, but the same principles are applicable to CSS grid. Hope this helps :)

In Java, how do you determine if a thread is running?

You can use this method:

boolean isAlive()

It returns true if the thread is still alive and false if the Thread is dead. This is not static. You need a reference to the object of the Thread class.

One more tip: If you're checking it's status to make the main thread wait while the new thread is still running, you may use join() method. It is more handy.

Swift Error: Editor placeholder in source file

Clean Build folder + Build

will clear any error you may have even after fixing your code.

Android Studio error: "Environment variable does not point to a valid JVM installation"

It started happening to me when I changed variables for Android Studio. Go to your studio64.exe.vmoptions file (located in c:\users\userName\.AndroidStudio{version}\ and comments the arguments.

Import Excel Data into PostgreSQL 9.3

As explained here http://www.postgresonline.com/journal/categories/journal/archives/339-OGR-foreign-data-wrapper-on-Windows-first-taste.html

With ogr_fdw module, its possible to open the excel sheet as foreign table in pgsql and query it directly like any other regular tables in pgsql. This is useful for reading data from the same regularly updated table

To do this, the table header in your spreadsheet must be clean, the current ogr_fdw driver can't deal with wide-width character or new lines etc. with these characters, you will probably not be able to reference the column in pgsql due to encoding issue. (Major reason I can't use this wonderful extension.)

The ogr_fdw pre-build binaries for windows are located here http://winnie.postgis.net/download/windows/pg96/buildbot/extras/ change the version number in link to download corresponding builds. extract the file to pgsql folder to overwrite the same name sub-folders. restart pgsql. Before the test drive, the module needs to be installed by executing:

CREATE EXTENSION ogr_fdw;

Usage in brief:

  1. use ogr_fdw_info.exe to prob the excel file for sheet name list

    ogr_fdw_info -s "C:/excel.xlsx"
    
  2. use "ogr_fdw_info.exe -l" to prob a individual sheet and generate a table definition code.

    ogr_fdw_info -s "C:/excel.xlsx" -l "sheetname"
    

Execute the generated definition code in pgsql, a foreign table is created and mapped to your excel file. it can be queried like regular tables.

This is especially useful, if you have many small files with the same table structure. Just change the path and name in definition, and update the definition will be enough.

This plugin supports both XLSX and XLS file. According to the document it also possible to write data back into the spreadsheet file, but all the fancy formatting in your excel will be lost, the file is recreated on write.

If the excel file is huge. This will not work. which is another reason I didn't use this extension. It load data in one time. But this extension also support ODBC interface, it should be possible to use windows' ODBC excel file driver to create a ODBC source for the excel file and use ogr_fdw or any other pgsql's ODBC foreign data wrapper to query this intermediate ODBC source. This should be fairly stable.

The downside is that you can't change file location or name easily within pgsql like in the previous approach.

A friendly reminder. The permission issue applies to this fdw extensions. since its loaded into pgsql service. pgsql must have access privileged to the excel files.

What is ViewModel in MVC?

A lot of big examples, let me explain in clear and crispy way.

ViewModel = Model that is created to serve the view.

ASP.NET MVC view can't have more than one model so if we need to display properties from more than one models into the view, it is not possible. ViewModel serves this purpose.

View Model is a model class that can hold only those properties that is required for a view. It can also contains properties from more than one entities (tables) of the database. As the name suggests, this model is created specific to the View requirements.

Few examples of View Models are below

  • To list data from more than entities in a view page – we can create a View model and have properties of all the entities for which we want to list data. Join those database entities and set View model properties and return to the View to show data of different entities in one tabular form
  • View model may define only specific fields of a single entity that is required for the View.

ViewModel can also be used to insert, update records into more than one entities however the main use of ViewModel is to display columns from multiple entities (model) into a single view.

The way of creating ViewModel is same as creating Model, the way of creating view for the Viewmodel is same as creating view for Model.

Here is a small example of List data using ViewModel.

Hope this will be useful.

How to print all information from an HTTP request to the screen, in PHP

Well, you can read the entirety of the POST body like so

echo file_get_contents( 'php://input' );

And, assuming your webserver is Apache, you can read the request headers like so

$requestHeaders = apache_request_headers();

How to get everything after a certain character?

Another simple way, using strchr() or strstr():

$str = '233718_This_is_a_string';

echo ltrim(strstr($str, '_'), '_'); // This_is_a_string

The "backspace" escape character '\b': unexpected behavior?

Your result will vary depending on what kind of terminal or console program you're on, but yes, on most \b is a nondestructive backspace. It moves the cursor backward, but doesn't erase what's there.

So for the hello worl part, the code outputs

hello worl
          ^

...(where ^ shows where the cursor is) Then it outputs two \b characters which moves the cursor backward two places without erasing (on your terminal):

hello worl
        ^

Note the cursor is now on the r. Then it outputs d, which overwrites the r and gives us:

hello wodl
         ^

Finally, it outputs \n, which is a non-destructive newline (again, on most terminals, including apparently yours), so the l is left unchanged and the cursor is moved to the beginning of the next line.

Remove/ truncate leading zeros by javascript/jquery

If number is int use

"" + parseInt(str)

If the number is float use

"" + parseFloat(str)

How can I select rows with most recent timestamp for each key value?

There is one common answer I haven't see here yet, which is the Window Function. It is an alternative to the correlated sub-query, if your DB supports it.

SELECT sensorID,timestamp,sensorField1,sensorField2 
FROM (
    SELECT sensorID,timestamp,sensorField1,sensorField2
        , ROW_NUMBER() OVER(
            PARTITION BY sensorID
            ORDER BY timestamp
        ) AS rn
    FROM sensorTable s1
WHERE rn = 1
ORDER BY sensorID, timestamp;

I acually use this more than correlated sub-queries. Feel free to bust me in the comments over effeciancy, I'm not too sure how it stacks up in that regard.

Background color on input type=button :hover state sticks in IE

Try using the type attribute selector to find buttons (maybe this'll fix it too):

input[type=button]
{
  background-color: #E3E1B8; 
}

input[type=button]:hover
{
  background-color: #46000D
}

The project cannot be built until the build path errors are resolved.

If you think you've done everything correctly but Eclipse still complains about the jars, refresh the folder where the jars are and make sure eclipse knows they've been added to the project. Specifying the file path alone is (apparently) not enough

Insert current date/time using now() in a field using MySQL/PHP

NOW() normally works in SQL statements and returns the date and time. Check if your database field has the correct type (datetime). Otherwise, you can always use the PHP date() function and insert:

date('Y-m-d H:i:s')

But I wouldn't recommend this.

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Check if a value is in an array (C#)

Note: The question is about arrays of strings. The mentioned routines are not to be mixed with the .Contains method of single strings.

I would like to add an extending answer referring to different C# versions and because of two reasons:

  • The accepted answer requires Linq which is perfectly idiomatic C# while it does not come without costs, and is not available in C# 2.0 or below. When an array is involved, performance may matter, so there are situations where you want to stay with Array methods.

  • No answer directly attends to the question where it was asked also to put this in a function (As some answers are also mixing strings with arrays of strings, this is not completely unimportant).

Array.Exists() is a C#/.NET 2.0 method and needs no Linq. Searching in arrays is O(n). For even faster access use HashSet or similar collections.

Since .NET 3.5 there also exists a generic method Array<T>.Exists() :

public void PrinterSetup(string[] printer)
{
   if (Array.Exists(printer, x => x == "jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

You could write an own extension method (C# 3.0 and above) to add the syntactic sugar to get the same/similar ".Contains" as for strings for all arrays without including Linq:

// Using the generic extension method below as requested.
public void PrinterSetup(string[] printer)
{
   if (printer.ArrayContains("jupiter"))
   {
      Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC");
   }
}

public static bool ArrayContains<T>(this T[] thisArray, T searchElement)
{
   // If you want this to find "null" values, you could change the code here
   return Array.Exists<T>(thisArray, x => x.Equals(searchElement));
}

In this case this ArrayContains() method is used and not the Contains method of Linq.

The elsewhere mentioned .Contains methods refer to List<T>.Contains (since C# 2.0) or ArrayList.Contains (since C# 1.1), but not to arrays itself directly.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

In my case reference of System.Web.MVC was missing from my project. But after adding references issue was same so i checked properties of my Bin folder it was ReadOnly. Just after making it writable,everything working fine.

SQL Server - SELECT FROM stored procedure

use OPENQUERY and befor Execute set 'SET FMTONLY OFF; SET NOCOUNT ON;'

Try this sample code:

SELECT top(1)*
FROM
OPENQUERY( [Server], 'SET FMTONLY OFF; SET NOCOUNT ON; EXECUTE  [database].[dbo].[storedprocedure]  value,value ')

How to position background image in bottom right corner? (CSS)

Voilà:

body {
   background-color: #000; /*Default bg, similar to the background's base color*/
   background-image: url("bg.png");
   background-position: right bottom; /*Positioning*/
   background-repeat: no-repeat; /*Prevent showing multiple background images*/
}

The background properties can be combined together, in one background property. See also: https://developer.mozilla.org/en/CSS/background-position

How to find a value in an array of objects in JavaScript?

There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)

obj = {
   1 : { name : 'bob' , dinner : 'pizza' },
   2 : { name : 'john' , dinner : 'sushi' },
   3 : { name : 'larry', dinner : 'hummus' }
}

_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

I had the same problem. You have to write mysql -u root -p

NOT mysql or mysql -u root -p root_password

Removing pip's cache?

On my mac I had to remove the cache directory ~/Library/Caches/pip/

CSS: Position text in the middle of the page

Try this CSS:

h1 {
    left: 0;
    line-height: 200px;
    margin-top: -100px;
    position: absolute;
    text-align: center;
    top: 50%;
    width: 100%;
}

jsFiddle: http://jsfiddle.net/wprw3/

Batch Renaming of Files in a Directory

Be in the directory where you need to perform the renaming.

import os
# get the file name list to nameList
nameList = os.listdir() 
#loop through the name and rename
for fileName in nameList:
    rename=fileName[15:28]
    os.rename(fileName,rename)
#example:
#input fileName bulk like :20180707131932_IMG_4304.JPG
#output renamed bulk like :IMG_4304.JPG

Responsive image map

For responsive image maps you will need to use a plugin:

https://github.com/stowball/jQuery-rwdImageMaps (No longer maintained)

Or

https://github.com/davidjbradshaw/imagemap-resizer


No major browsers understand percentage coordinates correctly, and all interpret percentage coordinates as pixel coordinates.

http://www.howtocreate.co.uk/tutorials/html/imagemaps

And also this page for testing whether browsers implement

http://home.comcast.net/~urbanjost/IMG/resizeimg3.html

Executing multiple SQL queries in one statement with PHP

You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.

The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.

Finally, I would suggest either using PDO or some other method.

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

Better way to convert an int to a boolean

Joking aside, if you're only expecting your input integer to be a zero or a one, you should really be checking that this is the case.

int yourInteger = whatever;
bool yourBool;
switch (yourInteger)
{
    case 0: yourBool = false; break;
    case 1: yourBool = true;  break;
    default:
        throw new InvalidOperationException("Integer value is not valid");
}

The out-of-the-box Convert won't check this; nor will yourInteger (==|!=) (0|1).

What is the proper way to test if a parameter is empty in a batch file?

Using ! instead of " for empty string checking

@echo off
SET a=
SET b=Hello
IF !%a%! == !! echo String a is empty
IF !%b%! == !! echo String b is empty

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

All the previous posts bring valid points, but some don't answer the question precisely.

The question is: Why would someone prefer money when we already know it is a less precise data type and can cause errors if used in complex calculations?

You use money when you won't make complex calculations and can trade this precision for other needs.

For example, when you don't have to make those calculations, and need to import data from valid currency text strings. This automatic conversion works only with MONEY data type:

SELECT CONVERT(MONEY, '$1,000.68')

I know you can make your own import routine. But sometimes you don't want to recreate a import routine with worldwide specific locale formats.

Another example, when you don't have to make those calculations (you need just to store a value) and need to save 1 byte (money takes 8 bytes and decimal(19,4) takes 9 bytes). In some applications (fast CPU, big RAM, slow IO), like just reading huge amount of data, this can be faster too.

Determine a user's timezone

Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work!

On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:

<?php
    session_start();
    $timezone = $_SESSION['time'];
?>

This will read the session variable "time", which we are now about to create.

On the same page, in the <head>, you need to first of all include jQuery:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>

Also in the <head>, below the jQuery, paste this:

<script type="text/javascript">
    $(document).ready(function() {
        if("<?php echo $timezone; ?>".length==0){
            var visitortime = new Date();
            var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
            $.ajax({
                type: "GET",
                url: "http://example.org/timezone.php",
                data: 'time='+ visitortimezone,
                success: function(){
                    location.reload();
                }
            });
        }
    });
</script>

You may or may not have noticed, but you need to change the URL to your actual domain.

One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above URL)

<?php
    session_start();
    $_SESSION['time'] = $_GET['time'];
?>

If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.

Get month and year from date cells Excel

Please try something like:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

You seem to have three main possible scenarios:

  1. Space-separated date with time as text (eg as A1 below)
  2. Hyphen-separated date as text (eg as A2 below)
  3. Formatted date index (as A4 and A5 below)

ColumnA below is formatted General and ColumnB as Date (my default setting). ColumnC also as date but with custom formatting to suit the appearances mentioned in your question.
A clue as to whether or not text format is the left or right alignment of the cells’ contents.

I am suggesting separate treatment for each of the above three main cases, so use =IF to differentiate them.

Case #1

This is longer than any of the others, so can be distinguished as having a length greater than say 10 characters, with =LEN.
In this case we want all but the last six characters but for added flexibility (for instance, in case the time element included seconds) I have chosen to count from the left rather than from the right. The problem then is that the month names may vary in length, so I have chosen to look for the space that immediately follows the year to indicate the limit for the relevant number of characters.

This with =FIND which looks for a space (" ") in C1, starting with the eighth character within C1 counting from the left, on the assumption that for this case days will be expressed as two characters and months as three or more.

Since =LEFT is a string function it returns a string, but this can be converted to a value with=VALUE.

So

=VALUE(LEFT(C1,FIND(" ",C1,8))) 

returns 40671 in this example – in Excel’s 1900 date system the date serial number for May 5, 2011.

Case #2

If the length of C1 is not greater than 10 characters, we still need to distinguish between a text entry or a value entry which I have chosen to do with =ISTEXT and, where the if condition is TRUE (as for C2) apply =DATE which takes three parameters, here provided by:

=RIGHT(C2,4)  

Takes the last four characters of C2, hence 2011 in this example.

=MID(C2,4,2) 

Starting at the fourth character, takes the next two characters of C2, hence 05 in this example (representing May).

=LEFT(C2,2))  

Takes the first two characters of C2, hence 08 in this example (representing the 8th day of the month). Date is not a text function so does not need to be wrapped in =VALUE.

Taken together

=DATE(RIGHT(C2,4),MID(C2,4,2),LEFT(C2,2)) 

also returns 40671 in this example, but from different input from Case #1.

Case #3

Is simple because already a date serial number, so just

=C2  

is sufficient.


Put the above together to cover all three cases in a single formula:

=IF(LEN(C1)>10,VALUE(LEFT(C1,FIND(" ",C1,8))),IF(ISTEXT(C1),DATE(RIGHT(C1,4),MID(C1,4,2),LEFT(C1,2)),C1))  

as applied in ColumnF (formatted to suit OP) or in General format (to show values are integers) in ColumnH:

SO23928568 example

Passing data to components in vue.js

A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.

index.html:

<script>
    var rspData; // global - transfer data between components
</script>

Ammlogin.vue:

....    
export default {
data: function() {return vueData}, 
methods: {
    login: function(event){
        event.preventDefault(); // otherwise the page is submitted...
        vueData.errortxt = "";
        axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
            .then(function (response) {
                vueData.user = '';
                vueData.password = '';
                // activate v-link via JS click...
                // JSON.parse is not needed because it is already an object
                if (response.data.result === "ok") {
                    rspData = response.data; // set global rspData
                    document.getElementById("loginid").click();
                } else {
                    vueData.errortxt = "Felaktig avändare eller lösenord!"
                }
            })
            .catch(function (error) {
                // Wu oh! Something went wrong
                vueData.errortxt = error.message;
            });
    },
....

Options.vue:

<template>
<main-layout>
  <p>Alternativ</p>
  <p>Resultat: {{rspData.result}}</p>
  <p>Meddelande: {{rspData.data}}</p>
  <v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
 import MainLayout from '../layouts/Main.vue'
 import VLink from '../components/VLink.vue'
 var optData = { rspData: rspData}; // rspData is global
 export default {
   data: function() {return optData},
   components: {
     MainLayout,
     VLink
   }
 }
</script>

How to reset a form using jQuery with .reset() method

You can use the following.

@using (Html.BeginForm("MyAction", "MyController", new { area = "MyArea" }, FormMethod.Post, new { @class = "" }))
{
<div class="col-md-6">
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
        @Html.LabelFor(m => m.MyData, new { @class = "col-form-label" })
    </div>
    <div class="col-lg-9 col-md-9 col-sm-9 col-xs-12">
        @Html.TextBoxFor(m => m.MyData, new { @class = "form-control" })
    </div>
</div>
<div class="col-md-6">
    <div class="">
        <button class="btn btn-primary" type="submit">Send</button>
        <button class="btn btn-danger" type="reset"> Clear</button>
    </div>
</div>
}

Then clear the form:

    $('.btn:reset').click(function (ev) {
        ev.preventDefault();
        $(this).closest('form').find("input").each(function(i, v) {
            $(this).val("");
        });
    });

Replace line break characters with <br /> in ASP.NET MVC Razor view

I prefer this method as it doesn't require manually emitting markup. I use this because I'm rendering Razor Pages to strings and sending them out via email, which is an environment where the white-space styling won't always work.

public static IHtmlContent RenderNewlines<TModel>(this IHtmlHelper<TModel> html, string content)
{
    if (string.IsNullOrEmpty(content) || html is null)
    {
        return null;
    }

    TagBuilder brTag = new TagBuilder("br");
    IHtmlContent br = brTag.RenderSelfClosingTag();
    HtmlContentBuilder htmlContent = new HtmlContentBuilder();

    // JAS: On the off chance a browser is using LF instead of CRLF we strip out CR before splitting on LF.
    string lfContent = content.Replace("\r", string.Empty, StringComparison.InvariantCulture);
    string[] lines = lfContent.Split('\n', StringSplitOptions.None);
    foreach(string line in lines)
    {
        _ = htmlContent.Append(line);
        _ = htmlContent.AppendHtml(br);
    }

    return htmlContent;
}

APT command line interface-like yes/no input?

as mentioned by @Alexander Artemenko, here's a simple solution using strtobool

from distutils.util import strtobool

def user_yes_no_query(question):
    sys.stdout.write('%s [y/n]\n' % question)
    while True:
        try:
            return strtobool(raw_input().lower())
        except ValueError:
            sys.stdout.write('Please respond with \'y\' or \'n\'.\n')

#usage

>>> user_yes_no_query('Do you like cheese?')
Do you like cheese? [y/n]
Only on tuesdays
Please respond with 'y' or 'n'.
ok
Please respond with 'y' or 'n'.
y
>>> True

Best way to add Gradle support to IntelliJ Project

Another way, simpler.

Add your

build.gradle

file to the root of your project. Close the project. Manually remove *.iml file. Then choose "Import Project...", navigate to your project directory, select the build.gradle file and click OK.

how to change namespace of entire project?

Just right click the solution, go to properties, change "default namespace" under 'Application' section.

enter image description here

PostgreSQL Exception Handling

Use the DO statement, a new option in version 9.0:

DO LANGUAGE plpgsql
$$
BEGIN
CREATE TABLE "Logs"."Events"
    (
        EventId BIGSERIAL NOT NULL PRIMARY KEY,
        PrimaryKeyId bigint NOT NULL,
        EventDateTime date NOT NULL DEFAULT(now()),
        Action varchar(12) NOT NULL,
        UserId integer NOT NULL REFERENCES "Office"."Users"(UserId),
        PrincipalUserId varchar(50) NOT NULL DEFAULT(user)
    );

    CREATE TABLE "Logs"."EventDetails"
    (
        EventDetailId BIGSERIAL NOT NULL PRIMARY KEY,
        EventId bigint NOT NULL REFERENCES "Logs"."Events"(EventId),
        Resource varchar(64) NOT NULL,
        OldVal varchar(4000) NOT NULL,
        NewVal varchar(4000) NOT NULL
    );

    RAISE NOTICE 'Task completed sucessfully.';    
END;
$$;

Difference of keywords 'typename' and 'class' in templates?

typename and class are interchangeable in the basic case of specifying a template:

template<class T>
class Foo
{
};

and

template<typename T>
class Foo
{
};

are equivalent.

Having said that, there are specific cases where there is a difference between typename and class.

The first one is in the case of dependent types. typename is used to declare when you are referencing a nested type that depends on another template parameter, such as the typedef in this example:

template<typename param_t>
class Foo
{
    typedef typename param_t::baz sub_t;
};

The second one you actually show in your question, though you might not realize it:

template < template < typename, typename > class Container, typename Type >

When specifying a template template, the class keyword MUST be used as above -- it is not interchangeable with typename in this case (note: since C++17 both keywords are allowed in this case).

You also must use class when explicitly instantiating a template:

template class Foo<int>;

I'm sure that there are other cases that I've missed, but the bottom line is: these two keywords are not equivalent, and these are some common cases where you need to use one or the other.

Origin is not allowed by Access-Control-Allow-Origin

When you receive the request you can

var origin = (req.headers.origin || "*");

than when you have to response go with something like that:

res.writeHead(
    206,
    {
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': origin,
    }
);

How to search for a part of a word with ElasticSearch

I'm using nGram, too. I use standard tokenizer and nGram just as a filter. Here is my setup:

{
  "index": {
    "index": "my_idx",
    "type": "my_type",
    "analysis": {
      "index_analyzer": {
        "my_index_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "mynGram"
          ]
        }
      },
      "search_analyzer": {
        "my_search_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "standard",
            "lowercase",
            "mynGram"
          ]
        }
      },
      "filter": {
        "mynGram": {
          "type": "nGram",
          "min_gram": 2,
          "max_gram": 50
        }
      }
    }
  }
}

Let's you find word parts up to 50 letters. Adjust the max_gram as you need. In german words can get really big, so I set it to a high value.

"Debug certificate expired" error in Eclipse Android plugins

On a Mac, open the Terminal (current user's directory should open), cd ".android" ("ls" to validate debug.keystore is there). Finally "rm debug.keystore" to remove the file.

Get specific object by id from array of objects in AngularJS

I know I am too late to answer but it's always better to show up rather than not showing up at all :). ES6 way to get it:

$http.get("data/SampleData.json").then(response => {
let id = 'xyz';
let item = response.data.results.find(result => result.id === id);
console.log(item); //your desired item
});

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I had the same problem with Eclipse 3.4(Ganymede) and dynamic web project.
The message didn't influence successfull deploy.But I had to delete row

<wb-resource deploy-path="/WEB-INF/classes" source-path="/src/main/resources"/>

from org.eclipse.wst.common.component file in .settings folder of Eclipse

Implementing Singleton with an Enum (in Java)

Like all enum instances, Java instantiates each object when the class is loaded, with some guarantee that it's instantiated exactly once per JVM. Think of the INSTANCE declaration as a public static final field: Java will instantiate the object the first time the class is referred to.

The instances are created during static initialization, which is defined in the Java Language Specification, section 12.4.

For what it's worth, Joshua Bloch describes this pattern in detail as item 3 of Effective Java Second Edition.

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

It's a bit worse, I use a calling card for international calls, so its local number in the US + account# (6 digits) + pin (4 digits) + "pause" + what you described above.

I suspect there might be other cases

phpmailer - The following SMTP Error: Data not accepted

For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.

To add a verified sender:

  1. Log in to your Amazon AWS console: https://console.aws.amazon.com

  2. Select "Amazon SES" from your list of available AWS applications

  3. Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"

  4. Navigate to that new sender's email, click the confirmation e-mail's link.

And you're all set.

Style input element to fill remaining width of its container

Please use flexbox for this. You have a container that is going to flex its children into a row. The first child takes its space as needed. The second one flexes to take all the remaining space:

_x000D_
_x000D_
<div style="display:flex;flex-direction:row">_x000D_
    <label for="MyInput">label&nbsp;text</label>_x000D_
    <input type="text" id="MyInput" style="flex:1" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to disable logging on the standard error stream in Python?

To fully disable logging:

logging.disable(sys.maxint) # Python 2

logging.disable(sys.maxsize) # Python 3

To enable logging:

logging.disable(logging.NOTSET)

Other answers provide work arounds which don't fully solve the problem, such as

logging.getLogger().disabled = True

and, for some n greater than 50,

logging.disable(n)

The problem with the first solution is that it only works for the root logger. Other loggers created using, say, logging.getLogger(__name__) are not disabled by this method.

The second solution does affect all logs. But it limits output to levels above that given, so one could override it by logging with a level greater than 50.

That can be prevented by

logging.disable(sys.maxint)

which as far as I can tell (after reviewing the source) is the only way to fully disable logging.

How to format strings in Java

I've wrote my simple method for it :

public class SomeCommons {
    /** Message Format like 'Some String {0} / {1}' with arguments */
    public static String msgFormat(String s, Object... args) {
        return new MessageFormat(s).format(args);
    }
}

so you can use it as:

SomeCommons.msfgFormat("Step {1} of {2}", 1 , "two");

Loop structure inside gnuplot?

Use the following if you have discrete columns to plot in a graph

do for [indx in "2 3 7 8"] {
  column = indx + 0
  plot ifile using 1:column ;  
}

Changing Background Image with CSS3 Animations

Updated for 2020: Yes, it can be done! Here's how.

Snippet demo:

_x000D_
_x000D_
#mydiv{ animation: changeBg 1s infinite; width:143px; height:100px; }
@keyframes changeBg{
   0%,100%  {background-image: url("https://i.stack.imgur.com/YdrqG.png");}
   25% {background-image: url("https://i.stack.imgur.com/2wKWi.png");}
   50% {background-image: url("https://i.stack.imgur.com/HobHO.png");}
   75% {background-image: url("https://i.stack.imgur.com/3hiHO.png");}
}
_x000D_
<div id='mydiv'></div>
_x000D_
_x000D_
_x000D_


Background image [isn't a property that can be animated][1] - you can't tween the property.

Original Answer: (still a good alternative) Instead, try laying out all the images on top of each other using position:absolute, then animate the opacity of all of them to 0 except the one you want repeatedly.

Learning Ruby on Rails

There is a site called Softies on Rails that is written by a couple of ex-.NET developers that may be of some use. They have a book called Rails for .NET Developers coming out in the next few months...

I started out on a Windows box using the RadRails plugin for Eclipse and the RubyWeaver extension for Dreamweaver (back during the 1.x days of Rails). Since then I have moved to a Mac running TextMate and haven't thought of going back.

As for books, I started with The Ruby Way and Agile Web Development with Rails. It definately helps to build a background in Ruby as you start to make your way into Rails development.

Definately watch the Railscast series by Ryan Bates.

How to comment out a block of code in Python

comm='''
Junk, or working code 
that I need to comment.
'''

You can replace comm by a variable of your choice that is perhaps shorter, easy to touch-type, and you know does not (and will not) occur in your programs. Examples: xxx, oo, null, nil.

How can I get double quotes into a string literal?

Escape the quotes with backslashes:

printf("She said \"time flies like an arrow, but fruit flies like a banana\"."); 

There are special escape characters that you can use in string literals, and these are denoted with a leading backslash.

Eclipse JUnit - possible causes of seeing "initializationError" in Eclipse window

This problem also occurs if you have a private Rule in you class:

@Rule
private TemporaryFolder folderRule;

Make it public.

Why Anaconda does not recognize conda command?

You probably need to update your PATH variable to include where you have installed Anaconda.

See https://github.com/ContinuumIO/anaconda-issues/issues/41 for a similar issue.

HTTP response code for POST when resource already exists

What about 208 - http://httpstatusdogs.com/208-already-reported ? Is that a option?

In my opinion, if the only thing is a repeat resource no error should be raised. After all, there is no error neither on the client or server sides.

How to assign an exec result to a sql variable?

Here is solution for dynamic queries.

For example if you have more tables with different suffix:

dbo.SOMETHINGTABLE_ONE, dbo.SOMETHINGTABLE_TWO

Code:

DECLARE @INDEX AS NVARCHAR(20)
DECLARE @CheckVALUE AS NVARCHAR(max) = 'SELECT COUNT(SOMETHING) FROM 
dbo.SOMETHINGTABLE_'+@INDEX+''
DECLARE @tempTable Table (TempVALUE int)
DECLARE @RESULTVAL INT

INSERT INTO @tempTable
    EXEC sp_executesql @CheckVALUE

SET @RESULTVAL = (SELECT * FROM @tempTable)

DELETE @tempTable

SELECT @RESULTVAL 

Converting an int or String to a char array on Arduino

  1. To convert and append an integer, use operator += (or member function concat):

    String stringOne = "A long integer: ";
    stringOne += 123456789;
    
  2. To get the string as type char[], use toCharArray():

    char charBuf[50];
    stringOne.toCharArray(charBuf, 50)
    

In the example, there is only space for 49 characters (presuming it is terminated by null). You may want to make the size dynamic.

Overhead

The cost of bringing in String (it is not included if not used anywhere in the sketch), is approximately 1212 bytes program memory (flash) and 48 bytes RAM.

This was measured using Arduino IDE version 1.8.10 (2019-09-13) for an Arduino Leonardo sketch.

How do I divide so I get a decimal value?

You can do like,

int a = 3;
int b = 2;
int quotient = a / b;
int remainder = a % b;

To get quotient in real numbers

System.out.println((double) a / b);

To get quotient in integer numbers

System.out.println("Quotient: " + quotient);
System.out.println("Remainder: " + remainder);

To get quotient in real number such that one number after decimal

System.out.println(a / b + "." + a % b * 10 / b);

Note: In the last method it will not round the number up after the decimal.

adb devices command not working

HTC One m7 running fresh Cyanogenmod 11.

Phone is connected USB and tethering my data connection.

Then I get this surprise:

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb shell
error: insufficient permissions for device

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
????????????    no permissions

SOLUTION: Turn tethering OFF on phone.

cinder@ultrabook:~/temp/htc_m7/2015-11-11$ adb devices
List of devices attached
HT36AW908858    device

Scale iFrame css width 100% like an image

I like this solution best. Simple, scalable, responsive. The idea here is to create a zero-height outer div with bottom padding set to the aspect ratio of the video. The iframe is scaled to 100% in both width and height, completely filling the outer container. The outer container automatically adjusts its height according to its width, and the iframe inside adjusts itself accordingly.

<div style="position:relative; width:100%; height:0px; padding-bottom:56.25%;">
    <iframe style="position:absolute; left:0; top:0; width:100%; height:100%"
        src="http://www.youtube.com/embed/RksyMaJiD8Y">
    </iframe>
</div>

The only variable here is the padding-bottom value in the outer div. It's 75% for 4:3 aspect ratio videos, and 56.25% for widescreen 16:9 aspect ratio videos.

Array slices in C#

Starting from C# 8.0/.Net Core 3.0

Array slicing will be supported, along with the new types Index and Range being added.

Range Struct docs
Index Struct docs

Index i1 = 3;  // number 3 from beginning
Index i2 = ^4; // number 4 from end
int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
Console.WriteLine($"{a[i1]}, {a[i2]}"); // "3, 6"

var slice = a[i1..i2]; // { 3, 4, 5 }

Above code sample taken from the C# 8.0 blog.

note that the ^ prefix indicates counting from the end of the array. As shown in the docs example

var words = new string[]
{
                // index from start    index from end
    "The",      // 0                   ^9
    "quick",    // 1                   ^8
    "brown",    // 2                   ^7
    "fox",      // 3                   ^6
    "jumped",   // 4                   ^5
    "over",     // 5                   ^4
    "the",      // 6                   ^3
    "lazy",     // 7                   ^2
    "dog"       // 8                   ^1
};              // 9 (or words.Length) ^0

Range and Index also work outside of slicing arrays, for example with loops

Range range = 1..4; 
foreach (var name in names[range])

Will loop through the entries 1 through 4


note that at the time of writing this answer, C# 8.0 is not yet officially released
C# 8.x and .Net Core 3.x are now available in Visual Studio 2019 and onwards

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

How to set back button text in Swift

You can just modify the NavigationItem in the storyboard

enter image description here

In the Back Button add a space and press Enter.

Note: Do this in the previous VC.

How to return a file (FileContentResult) in ASP.NET WebAPI

Here is an implementation that streams the file's content out without buffering it (buffering in byte[] / MemoryStream, etc. can be a server problem if it's a big file).

public class FileResult : IHttpActionResult
{
    public FileResult(string filePath)
    {
        if (filePath == null)
            throw new ArgumentNullException(nameof(filePath));

        FilePath = filePath;
    }

    public string FilePath { get; }

    public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
    {
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(File.OpenRead(FilePath));
        var contentType = MimeMapping.GetMimeMapping(Path.GetExtension(FilePath));
        response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);
        return Task.FromResult(response);
    }
}

It can be simply used like this:

public class MyController : ApiController
{
    public IHttpActionResult Get()
    {
        string filePath = GetSomeValidFilePath();
        return new FileResult(filePath);
    }
}

How can I multiply all items in a list together with Python?

You can use:

import operator
import functools
functools.reduce(operator.mul, [1,2,3,4,5,6], 1)

See reduce and operator.mul documentations for an explanation.

You need the import functools line in Python 3+.

How to update parent's state in React?

I like the answer regarding passing functions around, its a very handy technique.

On the flip side you can also achieve this using pub/sub or using a variant, a dispatcher, as Flux does. The theory is super simple, have component 5 dispatch a message which component 3 is listening for. Component 3 then updates its state which triggers the re-render. This requires stateful components, which, depending on your viewpoint, may or may not be an anti-pattern. I'm against them personally and would rather that something else is listening for dispatches and changes state from the very top-down (Redux does this, but adds additional terminology).

import { Dispatcher } from flux
import { Component } from React

const dispatcher = new Dispatcher()

// Component 3
// Some methods, such as constructor, omitted for brevity
class StatefulParent extends Component {
  state = {
    text: 'foo'
  } 

  componentDidMount() {
    dispatcher.register( dispatch => {
      if ( dispatch.type === 'change' ) {
        this.setState({ text: 'bar' })
      }
    }
  }

  render() {
    return <h1>{ this.state.text }</h1>
  }
}

// Click handler
const onClick = event => {
  dispatcher.dispatch({
    type: 'change'
  })
}

// Component 5 in your example
const StatelessChild = props => {
  return <button onClick={ onClick }>Click me</button> 
}

The dispatcher bundles with Flux is very simple, it simply registers callbacks and invokes them when any dispatch occurs, passing through the contents on the dispatch (in the above terse example there is no payload with the dispatch, simply a message id). You could adapt this to traditional pub/sub (e.g. using the EventEmitter from events, or some other version) very easily if that makes more sense to you.

Warning message: In `...` : invalid factor level, NA generated

The easiest way to fix this is to add a new factor to your column. Use the levels function to determine how many factors you have and then add a new factor.

    > levels(data$Fireplace.Qu)
    [1] "Ex" "Fa" "Gd" "Po" "TA"
    > levels(data$Fireplace.Qu) = c("Ex", "Fa", "Gd", "Po", "TA", "None")
    [1] "Ex"   "Fa"   "Gd"   "Po"   " TA"  "None"

Find the paths between two given nodes?

If you want all the paths, use recursion.

Using an adjacency list, preferably, create a function f() that attempts to fill in a current list of visited vertices. Like so:

void allPaths(vector<int> previous, int current, int destination)
{
    previous.push_back(current);

    if (current == destination)
        //output all elements of previous, and return

    for (int i = 0; i < neighbors[current].size(); i++)
        allPaths(previous, neighbors[current][i], destination);
}

int main()
{
    //...input
    allPaths(vector<int>(), start, end);
}

Due to the fact that the vector is passed by value (and thus any changes made further down in the recursive procedure aren't permanent), all possible combinations are enumerated.

You can gain a bit of efficiency by passing the previous vector by reference (and thus not needing to copy the vector over and over again) but you'll have to make sure that things get popped_back() manually.

One more thing: if the graph has cycles, this won't work. (I assume in this case you'll want to find all simple paths, then) Before adding something into the previous vector, first check if it's already in there.

If you want all shortest paths, use Konrad's suggestion with this algorithm.

Git submodule push

Note that since git1.7.11 ([ANNOUNCE] Git 1.7.11.rc1 and release note, June 2012) mentions:

"git push --recurse-submodules" learned to optionally look into the histories of submodules bound to the superproject and push them out.

Probably done after this patch and the --on-demand option:

recurse-submodules=<check|on-demand>::

Make sure all submodule commits used by the revisions to be pushed are available on a remote tracking branch.

  • If check is used, it will be checked that all submodule commits that changed in the revisions to be pushed are available on a remote.
    Otherwise the push will be aborted and exit with non-zero status.
  • If on-demand is used, all submodules that changed in the revisions to be pushed will be pushed.
    If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status.

So you could push everything in one go with (from the parent repo) a:

git push --recurse-submodules=on-demand

This option only works for one level of nesting. Changes to the submodule inside of another submodule will not be pushed.


With git 2.7 (January 2016), a simple git push will be enough to push the parent repo... and all its submodules.

See commit d34141c, commit f5c7cd9 (03 Dec 2015), commit f5c7cd9 (03 Dec 2015), and commit b33a15b (17 Nov 2015) by Mike Crowe (mikecrowe).
(Merged by Junio C Hamano -- gitster -- in commit 5d35d72, 21 Dec 2015)

push: add recurseSubmodules config option

The --recurse-submodules command line parameter has existed for some time but it has no config file equivalent.

Following the style of the corresponding parameter for git fetch, let's invent push.recurseSubmodules to provide a default for this parameter.
This also requires the addition of --recurse-submodules=no to allow the configuration to be overridden on the command line when required.

The most straightforward way to implement this appears to be to make push use code in submodule-config in a similar way to fetch.

The git config doc now include:

push.recurseSubmodules:

Make sure all submodule commits used by the revisions to be pushed are available on a remote-tracking branch.

  • If the value is 'check', then Git will verify that all submodule commits that changed in the revisions to be pushed are available on at least one remote of the submodule. If any commits are missing, the push will be aborted and exit with non-zero status.
  • If the value is 'on-demand' then all submodules that changed in the revisions to be pushed will be pushed. If on-demand was not able to push all necessary revisions it will also be aborted and exit with non-zero status. -
  • If the value is 'no' then default behavior of ignoring submodules when pushing is retained.

You may override this configuration at time of push by specifying '--recurse-submodules=check|on-demand|no'.

So:

git config push.recurseSubmodules on-demand
git push

Git 2.12 (Q1 2017)

git push --dry-run --recurse-submodules=on-demand will actually work.

See commit 0301c82, commit 1aa7365 (17 Nov 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 12cf113, 16 Dec 2016)

push run with --dry-run doesn't actually (Git 2.11 Dec. 2016 and lower/before) perform a dry-run when push is configured to push submodules on-demand.
Instead all submodules which need to be pushed are actually pushed to their remotes while any updates for the superproject are performed as a dry-run.
This is a bug and not the intended behaviour of a dry-run.

Teach push to respect the --dry-run option when configured to recursively push submodules 'on-demand'.
This is done by passing the --dry-run flag to the child process which performs a push for a submodules when performing a dry-run.


And still in Git 2.12, you now havea "--recurse-submodules=only" option to push submodules out without pushing the top-level superproject.

See commit 225e8bf, commit 6c656c3, commit 14c01bd (19 Dec 2016) by Brandon Williams (mbrandonw).
(Merged by Junio C Hamano -- gitster -- in commit 792e22e, 31 Jan 2017)

Datatables on-the-fly resizing

Have you tried capturing the div resize event and doing .fnDraw() on the datatable? fnDraw should resize the table for you

How to darken a background using CSS?

It might be possible to do this with box-shadow

however, I can't get it to actually apply to an image. Only on solid color backgrounds

_x000D_
_x000D_
body {_x000D_
  background: #131418;_x000D_
  color: #999;_x000D_
  text-align: center;_x000D_
}_x000D_
.mycooldiv {_x000D_
  width: 400px;_x000D_
  height: 300px;_x000D_
  margin: 2% auto;_x000D_
  border-radius: 100%;_x000D_
}_x000D_
.red {_x000D_
  background: red_x000D_
}_x000D_
.blue {_x000D_
  background: blue_x000D_
}_x000D_
.yellow {_x000D_
  background: yellow_x000D_
}_x000D_
.green {_x000D_
  background: green_x000D_
}_x000D_
#darken {_x000D_
  box-shadow: inset 0px 0px 400px 110px rgba(0, 0, 0, .7);_x000D_
  /*darkness level control - change the alpha value for the color for darken/ligheter effect */_x000D_
}
_x000D_
Red_x000D_
<div class="mycooldiv red"></div>_x000D_
Darkened Red_x000D_
<div class="mycooldiv red" id="darken"></div>_x000D_
Blue_x000D_
<div class="mycooldiv blue"></div>_x000D_
Darkened Blue_x000D_
<div class="mycooldiv blue" id="darken"></div>_x000D_
Yellow_x000D_
<div class="mycooldiv yellow"></div>_x000D_
Darkened Yellow_x000D_
<div class="mycooldiv yellow" id="darken"></div>_x000D_
Green_x000D_
<div class="mycooldiv green"></div>_x000D_
Darkened Green_x000D_
<div class="mycooldiv green" id="darken"></div>
_x000D_
_x000D_
_x000D_

Non-invocable member cannot be used like a method?

Where you've written "OffenceBox.Text()", you need to replace this with "OffenceBox.Text". It's a property, not a method - the clue's in the error!

How to compile and run a C/C++ program on the Android system

if you have installed NDK succesfully then start with it sample application

http://developer.android.com/sdk/ndk/overview.html#samples

if you are interested another ways of this then may this will help

http://shareprogrammingtips.blogspot.com/2018/07/cross-compile-cc-based-programs-and-run.html

I also want to know is it possible to push the compiled binary into android device or AVD and run using the terminal of the android device or AVD?

here you can see NestedVM

NestedVM provides binary translation for Java Bytecode. This is done by having GCC compile to a MIPS binary which is then translated to a Java class file. Hence any application written in C, C++, Fortran, or any other language supported by GCC can be run in 100% pure Java with no source changes.


Example: Cross compile Hello world C program and run it on android

What do pty and tty mean?

"tty" originally meant "teletype" and "pty" means "pseudo-teletype".

In UNIX, /dev/tty* is any device that acts like a "teletype", ie, a terminal. (Called teletype because that's what we had for terminals in those benighted days.)

A pty is a pseudotty, a device entry that acts like a terminal to the process reading and writing there, but is managed by something else. They first appeared (as I recall) for X Window and screen and the like, where you needed something that acted like a terminal but could be used from another program.

Python ValueError: too many values to unpack

for k, m in self.materials.items():

example:

miles_dict = {'Monday':1, 'Tuesday':2.3, 'Wednesday':3.5, 'Thursday':0.9}
for k, v in miles_dict.items():
    print("%s: %s" % (k, v))

border-radius not working

For my case, I have a dropdown list in my div container, so I can not use overflow: hidden or my dropdown list will be hidden.

Inspired by this discussion: https://twitter.com/siddharthkp/status/1094821277452234752 I use border-bottom-left-radius and border-bottom-right-radius in the child element to fix this issue.

make sure you add it the correct value for each child separately

enter image description here

Accessing post variables using Java Servlets

For getting all post parameters there is Map which contains request param name as key and param value as key.

Map params = servReq.getParameterMap();

And to get parameters with known name normal

String userId=servReq.getParameter("user_id");

What does template <unsigned int N> mean?

It's perfectly possible to template a class on an integer rather than a type. We can assign the templated value to a variable, or otherwise manipulate it in a way we might with any other integer literal:

unsigned int x = N;

In fact, we can create algorithms which evaluate at compile time (from Wikipedia):

template <int N>
struct Factorial 
{
     enum { value = N * Factorial<N - 1>::value };
};

template <>
struct Factorial<0> 
{
    enum { value = 1 };
};

// Factorial<4>::value == 24
// Factorial<0>::value == 1
void foo()
{
    int x = Factorial<4>::value; // == 24
    int y = Factorial<0>::value; // == 1
}

Python: get key of index in dictionary

By definition dictionaries are unordered, and therefore cannot be indexed. For that kind of functionality use an ordered dictionary. Python Ordered Dictionary

HTML Canvas Full Screen

function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}

https://jsfiddle.net/jy8k6hfd/2/

Can't import org.apache.http.HttpResponse in Android Studio

HttpClient was deprecated in Android 5.1 and is removed from the Android SDK in Android 6.0. While there is a workaround to continue using HttpClient in Android 6.0 with Android Studio, you really need to move to something else. That "something else" could be:

Or, depending upon the nature of your HTTP work, you might choose a library that supports higher-order operations (e.g., Retrofit for Web service APIs).

In a pinch, you could enable the legacy APIs, by having useLibrary 'org.apache.http.legacy' in your android closure in your module's build.gradle file. However, Google has been advising people for years to stop using Android's built-in HttpClient, and so at most, this should be a stop-gap move, while you work on a more permanent shift to another API.

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

 sudo nano /etc/nginx/nginx.conf

Add these variables to nginx.conf file:

http {  
  # .....
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

And then restart:

service nginx reload

Difference between window.location.href and top.location.href

The first one adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

The second replaces the current history item so you can't go back to it.

See window.location:

  • assign(url): Load the document at the provided URL.

  • replace(url): Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

window.location.href = url;

is favoured over:

window.location = url;

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

the short term solution is to use the default iis host and port normally 120.0.0.1 and 80 respectively. However am still looking for a more versatile solution.

Loop and get key/value pair for JSON array using jQuery

You have a string representing a JSON serialized JavaScript object. You need to deserialize it back to a JavaScript object before being able to loop through its properties. Otherwise you will be looping through each individual character of this string.

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
$.each(result, function(k, v) {
    //display the key and value pair
    alert(k + ' is ' + v);
});

Live demo.

CSS 3 slide-in from left transition

You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

For browser support: http://caniuse.com/

I made two quick examples just to show you how I mean.

CSS transition (on hover)

Demo One

Relevant Code

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

In this case, Im just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

CSS animation

Demo Two

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    -webkit-animation: slide 0.5s forwards;
    -webkit-animation-delay: 2s;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
}

@-webkit-keyframes slide {
    100% { left: 0; }
}

@keyframes slide {
    100% { left: 0; }
}

Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

Like I said, two quick example to show you how it could be done.

EDIT: For details regarding CSS Animations and Transitions see:

Animations

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

Transitions

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Hope this helped.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

This is just the XML Name Space declaration. We use this Name Space in order to specify that the attributes listed below, belongs to Android. Thus they starts with "android:"

You can actually create your own custom attributes. So to prevent the name conflicts where 2 attributes are named the same thing, but behave differently, we add the prefix "android:" to signify that these are Android attributes.

Thus, this Name Space declaration must be included in the opening tag of the root view of your XML file.

Delete forked repo from GitHub

Deleting your forked repository will not affect the master(original) repository.

Like I have shown an example by deleting a forked repo

This is my forked repo (Image)

Deleting the forked repo

And no changes to the original repository.

The master repo is something like an original one.

Forking is same as creating a xerox copy of the original one. Even if you get your xeroxed paper damaged, will it be that the original document also gets damaged. Obviously No.

So its the same as that.

Hope this helps.

Matplotlib figure facecolor (background color)

I had to use the transparent keyword to get the color I chose with my initial

fig=figure(facecolor='black')

like this:

savefig('figname.png', facecolor=fig.get_facecolor(), transparent=True)

How to create the most compact mapping n ? isprime(n) up to a limit N?

I have got a prime function which works until (2^61)-1 Here:

from math import sqrt
def isprime(num): num > 1 and return all(num % x for x in range(2, int(sqrt(num)+1)))

Explanation:

The all() function can be redefined to this:

def all(variables):
    for element in variables:
        if not element: return False
    return True

The all() function just goes through a series of bools / numbers and returns False if it sees 0 or False.

The sqrt() function is just doing the square root of a number.

For example:

>>> from math import sqrt
>>> sqrt(9)
>>> 3
>>> sqrt(100)
>>> 10

The num % x part returns the remainder of num / x.

Finally, range(2, int(sqrt(num))) means that it will create a list that starts at 2 and ends at int(sqrt(num)+1)

For more information about range, have a look at this website!

The num > 1 part is just checking if the variable num is larger than 1, becuase 1 and 0 are not considered prime numbers.

I hope this helped :)

HttpWebRequest-The remote server returned an error: (400) Bad Request

400 Bad request Error will be thrown due to incorrect authentication entries.

  1. Check if your API URL is correct or wrong. Don't append or prepend spaces.
  2. Verify that your username and password are valid. Please check any spelling mistake(s) while entering.

Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.

wkhtmltopdf: cannot connect to X server

This solved the issue for me:

sudo apt-get install xvfb
xvfb-run --server-args="-screen 0, 1024x768x24" wkhtmltopdf file1.html file2.pdf

How do you check in python whether a string contains only numbers?

Use str.isdigit:

>>> "12345".isdigit()
True
>>> "12345a".isdigit()
False
>>>

Connection timeout for SQL server

If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .

It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.

In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?

Also as it creates an Object and its always good to assign value in object rather than manipulating string.

Here is the code sample:

var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);

sscsb.ConnectTimeout = 30;

var conn = new SqlConnection(sscsb.ConnectionString);

Specify sudo password for Ansible

I was tearing my hair out over this one, now I found a solution which does what i want:

1 encrypted file per host containing the sudo password

/etc/ansible/hosts:

[all:vars]
ansible_ssh_connection=ssh ansible_ssh_user=myuser ansible_ssh_private_key_file=~/.ssh/id_rsa

[some_service_group]
node-0
node-1

then you create for each host an encrypted var-file like so:

ansible-vault create /etc/ansible/host_vars/node-0

with content

ansible_sudo_pass: "my_sudo_pass_for_host_node-0"

how you organize the vault password (enter via --ask-vault-pass) or by cfg is up to you

based on this i suspect you can just encrypt the whole hosts file...

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

how to console.log result of this ajax call?

Why not handle the error within the call?

i.e.

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    error: function(req, err){ console.log('my message' + err); }
});

Characters allowed in GET parameter

I did a test using the Chrome address bar and a $QUERY_STRING in bash, and observed the following:

~!@$%^&*()-_=+[{]}\|;:',./? and grave (backtick) are passed through as plaintext.

, ", < and > are converted to %20, %22, %3C and %3E respectively.

# is ignored, since it is used by ye olde anchor.

Personally, I'd say bite the bullet and encode with base64 :)

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

I wasn't able to remotely connect to the SQL server either. Both SQL server and remote server where in the same domain. And I had been requested a password change some days before. Restarting both the SQL server and the remote server I was trying to access SQL server from did the trick for me.

How can I capitalize the first letter of each word in a string using JavaScript?

I usually prefer not to use regexp because of readability and also I try to stay away from loops. I think this is kind of readable.

function capitalizeFirstLetter(string) {
    return string && string.charAt(0).toUpperCase() + string.substring(1);
};

Why specify @charset "UTF-8"; in your CSS file?

This is useful in contexts where the encoding is not told per HTTP header or other meta data, e.g. the local file system.

Imagine the following stylesheet:

[rel="external"]::after
{
    content: ' ?';
}

If a reader saves the file to a hard drive and you omit the @charset rule, most browsers will read it in the OS’ locale encoding, e.g. Windows-1252, and insert ↗ instead of an arrow.

Unfortunately, you cannot rely on this mechanism as the support is rather … rare. And remember that on the net an HTTP header will always override the @charset rule.

The correct rules to determine the character set of a stylesheet are in order of priority:

  1. HTTP Charset header.
  2. Byte Order Mark.
  3. The first @charset rule.
  4. UTF-8.

The last rule is the weakest, it will fail in some browsers.
The charset attribute in <link rel='stylesheet' charset='utf-8'> is obsolete in HTML 5.
Watch out for conflict between the different declarations. They are not easy to debug.

Recommended reading

Print all but the first three columns

Perl solution which does not add leading or trailing whitespace:

perl -lane 'splice @F,0,3; print join " ",@F' file

The perl @F autosplit array starts at index 0 while awk fields start with $1


Perl solution for comma-delimited data:

perl -F, -lane 'splice @F,0,3; print join ",",@F' file

Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[3:]) + '\n') for line in sys.stdin]" < file

How to use underscore.js as a template engine?

I am giving a very simple example

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

This is html

<div>
  <ul id="list_2"></ul>
</div>

This is the javascript code which contains json object and putting template into html

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

Last non-empty cell in a column

=INDEX(A:A, COUNTA(A:A), 1) taken from here

How to replace multiple strings in a file using PowerShell

With version 3 of PowerShell you can chain the replace calls together:

 (Get-Content $sourceFile) | ForEach-Object {
    $_.replace('something1', 'something1').replace('somethingElse1', 'somethingElse2')
 } | Set-Content $destinationFile

What is the 'override' keyword in C++ used for?

The override keyword serves two purposes:

  1. It shows the reader of the code that "this is a virtual method, that is overriding a virtual method of the base class."
  2. The compiler also knows that it's an override, so it can "check" that you are not altering/adding new methods that you think are overrides.

To explain the latter:

class base
{
  public:
    virtual int foo(float x) = 0; 
};


class derived: public base
{
   public:
     int foo(float x) override { ... } // OK
}

class derived2: public base
{
   public:
     int foo(int x) override { ... } // ERROR
};

In derived2 the compiler will issue an error for "changing the type". Without override, at most the compiler would give a warning for "you are hiding virtual method by same name".

What is __main__.py?

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

Change bootstrap datepicker date format on select

for me with bootstrap 4 datetime picker (http://www.eyecon.ro/bootstrap-datepicker/) format worked only with upper case:

$('.datepicker').datetimepicker({
            format: 'DD/MM/YYYY'
        });

Apache Cordova - uninstall globally

Try sudo npm uninstall cordova -g to uninstall it globally and then just npm install cordova without the -g flag after cding to the local app directory

What does it mean to write to stdout in C?

stdout is the standard output stream in UNIX. See http://www.gnu.org/software/libc/manual/html_node/Standard-Streams.html#Standard-Streams. When running in a terminal, you will see data written to stdout in the terminal and you can redirect it as you choose.

escaping question mark in regex javascript

Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:

var re = /I like your Apartment\. Could we schedule a viewing\?/g;
                               ^^                            ^^

Whenever you need to build a RegExp dynamically, use RegExp constructor notation where you MUST double backslashes for them to denote a literal backslash:

var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");

And if you use the String.raw string literal you may use \ as is (see an example of using a template string literal where you may put variables into the regex pattern):

_x000D_
_x000D_
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
_x000D_
_x000D_

A must-read: RegExp: Description at MDN.

Node.js + Nginx - What now?

answering your question 2:

I would use option b simply because it consumes much less resources. with option 'a', every client will cause the server to consume a lot of memory, loading all the files you need (even though i like php, this is one of the problems with it). With option 'b' you can load your libraries (reusable code) and share them among all client requests.

But be ware that if you have multiple cores you should tweak node.js to use all of them.

How to delete all files and folders in a folder by cmd call

I think the easiest way to do it is:

rmdir /s /q "C:\FolderToNotToDelete\"

The last "\" in the path is the important part.

What is a web service endpoint?

This is a shorter and hopefully clearer answer... Yes, the endpoint is the URL where your service can be accessed by a client application. The same web service can have multiple endpoints, for example in order to make it available using different protocols.

"UnboundLocalError: local variable referenced before assignment" after an if statement

I was facing same issue in my exercise. Although not related, yet might give some reference. I didn't get any error once I placed addition_result = 0 inside function. Hope it helps! Apologize if this answer is not in context.

user_input = input("Enter multiple values separated by comma > ")

def add_numbers(num_list):
    addition_result = 0
    for i in num_list:
        addition_result = addition_result + i
    print(addition_result)

add_numbers(user_input)

"Javac" doesn't work correctly on Windows 10

Maybe a bit late, but i had same problem.

Click on "Move up" button for Java path and move it at top.

It fixed problem for me