Programs & Examples On #Value provider

Php header location redirect not working

This is likely a problem generated by the headers being already sent.

Why

This occurs if you have echoed anything before deciding to redirect. If so, then the initial (default) headers have been sent and the new headers cannot replace something that's already in the output buffer getting ready to be sent to the browser.

Sometimes it's not even necessary to have echoed something yourself:

  • if an error is being outputted to the browser it's also considered content so the headers must be sent before the error information;
  • if one of your files is encoded in one format (let's say ISO-8859-1) and another is encoded in another (let's say UTF-8 with BOM) the incompatibility between the two encodings may result in a few characters being outputted;

Let's check

To test if this is the case you have to enable error reporting: error_reporting(E_ALL); and set the errors to be displayed ini_set('display_errors', TRUE); after which you will likely see a warning referring to the headers being already sent.

Let's fix

Fixing this kinds of errors:

  • writing your redirect logic somewhere in the code before anything is outputted;
  • using output buffers to trap any outgoing info and only release it at some point when you know all redirect attempts have been run;
  • Using a proper MVC framework they already solve it;

More

MVC solves it both functionally by ensuring that the logic is in the controller and the controller triggers the display/rendering of a view only at the end of the controllers. This means you can decide to do a redirect somewhere within the action but not withing the view.

JQuery get data from JSON array

You're not looping over the items. Try this instead:

$.getJSON(url, function(data){
    $.each(data.response.venue.tips.groups.items, function (index, value) {
        console.log(this.text);
    });
});

How to create a sub array from another array in Java?

Arrays.copyOfRange(..) was added in Java 1.6. So perhaps you don't have the latest version. If it's not possible to upgrade, look at System.arraycopy(..)

How to blur background images in Android

The easiest way to do that is use a library. Take a look at this one: https://github.com/wasabeef/Blurry

With the library you only need to do this:

Blurry.with(context)
  .radius(10)
  .sampling(8)
  .color(Color.argb(66, 255, 255, 0))
  .async()
  .onto(rootView);

Use PHP composer to clone git repo

You can include git repository to composer.json like this:

"repositories": [
{
    "type": "package",
    "package": {
        "name": "example-package-name", //give package name to anything, must be unique
        "version": "1.0",
        "source": {
            "url": "https://github.com/example-package-name.git", //git url
            "type": "git",
            "reference": "master" //git branch-name
        }
    }
}],
"require" : {
  "example-package-name": "1.0"
}

SQL Query - how do filter by null or not null

I think this could work:

select * from tbl where statusid = isnull(@statusid,statusid)

Upgrade to python 3.8 using conda

You can update your python version to 3.8 in conda using the command

conda install -c anaconda python=3.8

as per https://anaconda.org/anaconda/python. Though not all packages support 3.8 yet, running

conda update --all

may resolve some dependency failures. You can also create a new environment called py38 using this command

conda create -n py38 python=3.8

Edit - note that the conda install option will potentially take a while to solve the environment, and if you try to abort this midway through you will lose your Python installation (usually this means it will resort to non-conda pre-installed system Python installation).

How to serialize/deserialize to `Dictionary<int, string>` from custom XML not using XElement?

Based on L.B.'s answer.

Usage:

var serializer = new DictionarySerializer<string, string>();
serializer.Serialize("dictionary.xml", _dictionary);
_dictionary = _titleDictSerializer.Deserialize("dictionary.xml");

Generic class:

public class DictionarySerializer<TKey, TValue>
{
    [XmlType(TypeName = "Item")]
    public class Item
    {
        [XmlAttribute("key")]
        public TKey Key;
        [XmlAttribute("value")]
        public TValue Value;
    }

    private XmlSerializer _serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute("Dictionary"));

    public Dictionary<TKey, TValue> Deserialize(string filename)
    {
        using (FileStream stream = new FileStream(filename, FileMode.Open))
        using (XmlReader reader = XmlReader.Create(stream))
        {
            return ((Item[])_serializer.Deserialize(reader)).ToDictionary(p => p.Key, p => p.Value);
        }
    }

    public void Serialize(string filename, Dictionary<TKey, TValue> dictionary)
    {
        using (var writer = new StreamWriter(filename))
        {
            _serializer.Serialize(writer, dictionary.Select(p => new Item() { Key = p.Key, Value = p.Value }).ToArray());
        }
    }
}

node.js require all files in a folder?

Expanding on this glob solution. Do this if you want to import all modules from a directory into index.js and then import that index.js in another part of the application. Note that template literals aren't supported by the highlighting engine used by stackoverflow so the code might look strange here.

const glob = require("glob");

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  /* see note about this in example below */
  allOfThem = { ...allOfThem, ...require(file) };
});
module.exports = allOfThem;

Full Example

Directory structure

globExample/example.js
globExample/foobars/index.js
globExample/foobars/unexpected.js
globExample/foobars/barit.js
globExample/foobars/fooit.js

globExample/example.js

const { foo, bar, keepit } = require('./foobars/index');
const longStyle = require('./foobars/index');

console.log(foo()); // foo ran
console.log(bar()); // bar ran
console.log(keepit()); // keepit ran unexpected

console.log(longStyle.foo()); // foo ran
console.log(longStyle.bar()); // bar ran
console.log(longStyle.keepit()); // keepit ran unexpected

globExample/foobars/index.js

const glob = require("glob");
/*
Note the following style also works with multiple exports per file (barit.js example)
but will overwrite if you have 2 exports with the same
name (unexpected.js and barit.js have a keepit function) in the files being imported. As a result, this method is best used when
your exporting one module per file and use the filename to easily identify what is in it.

Also Note: This ignores itself (index.js) by default to prevent infinite loop.
*/

let allOfThem = {};
glob.sync(`${__dirname}/*.js`).forEach((file) => {
  allOfThem = { ...allOfThem, ...require(file) };
});

module.exports = allOfThem;

globExample/foobars/unexpected.js

exports.keepit = () => 'keepit ran unexpected';

globExample/foobars/barit.js

exports.bar = () => 'bar run';

exports.keepit = () => 'keepit ran';

globExample/foobars/fooit.js

exports.foo = () => 'foo ran';

From inside project with glob installed, run node example.js

$ node example.js
foo ran
bar run
keepit ran unexpected
foo ran
bar run
keepit ran unexpected

Get an image extension from an uploaded file in Laravel

You can use the pathinfo() function built into PHP for that:

$info = pathinfo(storage_path().'/uploads/categories/featured_image.jpg');
$ext = $info['extension'];

Or more concisely, you can pass an option get get it directly;

$ext = pathinfo(storage_path().'/uploads/categories/featured_image.jpg', PATHINFO_EXTENSION);

Spring MVC: how to create a default controller for index page?

It can be solved in more simple way: in web.xml

<servlet-mapping>
    <servlet-name>dispatcher</servlet-name>
    <url-pattern>*.htm</url-pattern>
</servlet-mapping>
<welcome-file-list>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>

After that use any controllers that your want to process index.htm with @RequestMapping("index.htm"). Or just use index controller

<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
        <props>
            <prop key="index.htm">indexController</prop>
        </props>
    </property>
<bean name="indexController" class="org.springframework.web.servlet.mvc.ParameterizableViewController"
      p:viewName="index" />
</bean>

Update Eclipse with Android development tools v. 23

I have done following to resolve an issue.

  1. Go to http://developer.android.com/sdk/installing/installing-adt.html and download the latest ADT ZIP file (at the bottom of page).

  2. Go to Eclipse ? menu Help ? About Eclipse ? Installation details

  3. Delete Android DDM, Android Development Tools, Hierarchy Viewer, Native Development Tools, TraceView, etc., 22.X version.

  4. Menu Help* ? Install New Software ? Add ? Archive ? *Select the downloaded ZIP file in step 1.

  5. Select all the latest version of all 23 which I have deleted in step 3 and accept the license agreement.

Restart Eclipse, and it fixes my issue.

Python, compute list difference

One liner:

diff = lambda l1,l2: [x for x in l1 if x not in l2]
diff(A,B)
diff(B,A)

Or:

diff = lambda l1,l2: filter(lambda x: x not in l2, l1)
diff(A,B)
diff(B,A)

'Property does not exist on type 'never'

In my case it was happening because I had not typed a variable.

So I created the Search interface

export interface Search {
  term: string;
  ...
}

I changed that

searchList = [];

for that and it worked

searchList: Search[];

MySQL SELECT statement for the "length" of the field is greater than 1

Try:

SELECT
    *
FROM
    YourTable
WHERE
    CHAR_LENGTH(Link) > x

Pass variables by reference in JavaScript

Yet another approach to pass any (local, primitive) variables by reference is by wrapping variable with closure "on the fly" by eval. This also works with "use strict". (Note: be aware that eval is not friendly to JavaScript optimizers, and also missing quotes around variable name may cause unpredictive results)

"use strict"

// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
    return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}

// Demo

// Assign argument by reference
function modifyArgument(argRef, multiplier){
    argRef.value = argRef.value * multiplier;
}

(function(){
    var x = 10;

    alert("x before: " + x);
    modifyArgument(eval(byRef("x")), 42);
    alert("x after: " + x);
})()

Live sample: https://jsfiddle.net/t3k4403w/

Android: making a fullscreen application

in my case all works fine. See in logcat. Maybe logcat show something that can help you to resolve your problem

Anyway you can try do it programmatically:

 public class ActivityName extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            // remove title
            requestWindowFeature(Window.FEATURE_NO_TITLE);
            getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
            setContentView(R.layout.main);
        }
 }

When should we use Observer and Observable?

"I tried to figure out, why exactly we need Observer and Observable"

As previous answers already stated, they provide means of subscribing an observer to receive automatic notifications of an observable.

One example application where this may be useful is in data binding, let's say you have some UI that edits some data, and you want the UI to react when the data is updated, you can make your data observable, and subscribe your UI components to the data

Knockout.js is a MVVM javascript framework that has a great getting started tutorial, to see more observables in action I really recommend going through the tutorial. http://learn.knockoutjs.com/

I also found this article in Visual Studio 2008 start page (The Observer Pattern is the foundation of Model View Controller (MVC) development) http://visualstudiomagazine.com/articles/2013/08/14/the-observer-pattern-in-net.aspx

How to Compare two strings using a if in a stored procedure in sql server 2008?

What you want is a SQL case statement. The form of these is either:

  select case [expression or column]
  when [value] then [result]
  when [value2] then [result2]
  else [value3] end

or:

  select case 
  when [expression or column] = [value] then [result]
  when [expression or column] = [value2] then [result2]
  else [value3] end

In your example you are after:

declare @temp as varchar(100)
set @temp='Measure'

select case @temp 
   when 'Measure' then Measure 
   else OtherMeasure end
from Measuretable

Double Iteration in List Comprehension

ThomasH has already added a good answer, but I want to show what happens:

>>> a = [[1, 2], [3, 4]]
>>> [x for x in b for b in a]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

>>> [x for b in a for x in b]
[1, 2, 3, 4]
>>> [x for x in b for b in a]
[3, 3, 4, 4]

I guess Python parses the list comprehension from left to right. This means, the first for loop that occurs will be executed first.

The second "problem" of this is that b gets "leaked" out of the list comprehension. After the first successful list comprehension b == [3, 4].

Ruby on Rails - Import Data from a CSV file

If you want to Use SmartCSV

all_data = SmarterCSV.process(
             params[:file].tempfile, 
             { 
               :col_sep => "\t", 
               :row_sep => "\n" 
             }
           )

This represents tab delimited data in each row "\t" with rows separated by new lines "\n"

Can a normal Class implement multiple interfaces?

public class A implements C,D {...} valid

this is the way to implement multiple inheritence in java

Why javascript getTime() is not a function?

For all those who came here and did indeed use Date typed Variables, here is the solution I found. It does also apply to TypeScript.

I was facing this error because I tried to compare two dates using the following Method

var res = dat1.getTime() > dat2.getTime(); // or any other comparison operator

However Im sure I used a Date object, because Im using angularjs with typescript, and I got the data from a typed API call.

Im not sure why the error is raised, but I assume that because my Object was created by JSON deserialisation, possibly the getTime() method was simply not added to the prototype.

Solution

In this case, recreating a date-Object based on your dates will fix the issue.

var res = new Date(dat1).getTime() > new Date(dat2).getTime()

Edit:

I was right about this. Types will be cast to the according type but they wont be instanciated. Hence there will be a string cast to a date, which will obviously result in a runtime exception.

The trick is, if you use interfaces with non primitive only data such as dates or functions, you will need to perform a mapping after your http request.

class Details {
    description: string;
    date: Date;
    score: number;
    approved: boolean;

    constructor(data: any) {
      Object.assign(this, data);
    }
}

and to perform the mapping:

public getDetails(id: number): Promise<Details> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details/${id}`)
               .map(response => new Details(response.json()))
               .toPromise();
}

for arrays use:

public getDetails(): Promise<Details[]> {
    return this.http
               .get<Details>(`${this.baseUrl}/api/details`)
               .map(response => {
                   const array = JSON.parse(response.json()) as any[];
                   const details = array.map(data => new Details(data));
                   return details;
               })
               .toPromise();
}

For credits and further information about this topic follow the link.

how to clear JTable

I think you meant that you want to clear all the cells in the jTable and make it just like a new blank jTable. For an example, if your table is myTable, you can do following.

DefaultTableModel model = new DefaultTableModel();
myTable.setModel(model);

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

CSS: Change image src on img:hover

I had a similar problem but my solution was to have two images, one hidden (display:none) and one visible. On the hover over a surrounding span, the original image changes to display:none and the other image to display:block. (Might use 'inline' instead depending on your circumstances)

This example uses two span tags instead of images so you can see the result when running it here. I didn't have any online image sources to use unfortunately.

_x000D_
_x000D_
#onhover {_x000D_
  display: none;_x000D_
}_x000D_
#surround:hover span[id="initial"] {_x000D_
  display: none;_x000D_
}_x000D_
#surround:hover span[id="onhover"] {_x000D_
  display: block;_x000D_
}
_x000D_
<span id="surround">_x000D_
    <span id="initial">original</span>_x000D_
    <span id="onhover">replacement</span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

how to get all markers on google-maps-v3

The one way found is to use the geoXML3 library which is suitable for usage along with KML processor Version 3 of the Google Maps JavaScript API.

Importing Excel files into R, xlsx or xls

You may also want to try the XLConnect package. I've had better luck with it than xlsx (plus it can read .xls files too).

library(XLConnect)
theData <- readWorksheet(loadWorkbook("C:/AB_DNA_Tag_Numbers.xlsx"),sheet=1)

also, if you are having trouble with your file not being found, try selecting it with file.choose().

Convert python long/int to fixed size byte array

i = 0x12345678
s = struct.pack('<I',i)
b = struct.unpack('BBBB',s)

Setting a windows batch file variable to the day of the week

few more ways:

1.Robocopy not available in XP but can be downloaded form with win 2003 resource tool kit .Also might depend on localization:

@echo off
setlocal 
for /f "skip=8 tokens=2,3,4,5,6,7,8 delims=: " %%D in ('robocopy /l * \ \ /ns /nc /ndl /nfl /np /njh /XF * /XD *') do (
 set "dow=%%D"
 set "month=%%E"
 set "day=%%F"
 set "HH=%%G"
 set "MM=%%H"
 set "SS=%%I"
 set "year=%%J"
)

echo Day of the week: %dow%
endlocal

2.MAKECAB - works on every windows machine (but creates a small temp file).Function provided by carlos:

@Echo Off


Call :GetDate.Init
Rem :GetDate.Init should be called one time in the code before call to :Getdate
Call :GetDate
Echo weekday:%weekday%

Goto :EOF

:GetDate.Init
Set /A "jan=1,feb=2,mar=3,apr=4,may=5,jun=6,jul=7,aug=8,sep=9,oct=10,nov=11,dec=12"
Set /A "mon=1,tue=2,wed=3,thu=4,fri=5,sat=6,sun=7"
(
Echo .Set InfHeader=""
Echo .Set InfSectionOrder=""
Echo .Set InfFooter="%%2"
Echo .Set InfFooter1=""
Echo .Set InfFooter2=""
Echo .Set InfFooter3=""
Echo .Set InfFooter4=""
Echo .Set Cabinet="OFF"
Echo .Set Compress="OFF"
Echo .Set DoNotCopyFiles="ON"
Echo .Set RptFileName="NUL"
) >"%Temp%\~foo.ddf"
Goto :Eof

:GetDate
Set "tf=%Temp%\~%random%"
Makecab /D InfFileName="%tf%" /F "%Temp%\~foo.ddf" >NUL
For /F "usebackq tokens=1-7 delims=: " %%a In ("%tf%") Do (
Set /A "year=%%g,month=%%b,day=1%%c-100,weekday=%%a"
Set /A "hour=1%%d-100,minute=1%%e-100,second=1%%f-100")
Del "%tf%" >NUL 2>&1
Goto :Eof

3.W32TM - uses command switches introduced in Vista so will not work on windows 2003/XP:

@echo off
setlocal
call :w32dow day_ow
echo %day_ow%
pause
exit /b 0
endlocal
:w32dow [RrnVar]
setlocal

rem :: prints the day of the week
rem :: works on Vista and above


rem :: getting ansi date ( days passed from 1st jan 1601 ) , timer server hour and current hour
FOR /F "tokens=4,5 delims=:( " %%D in ('w32tm /stripchart /computer:localhost  /samples:1  /period:1 /dataonly /packetinfo^|find "Transmit Timestamp:" ') do (
 set "ANSI_DATE=%%D"
 set  "TIMESERVER_HOURS=%%E"
)

set  "LOCAL_HOURS=%TIME:~0,2%"
if "%TIMESERVER_HOURS:~0,1%0" EQU "00" set TIMESERVER_HOURS=%TIMESERVER_HOURS:~1,1%
if "%LOCAL_HOURS:~0,1%0" EQU "00" set LOCAL_HOURS=%LOCAL_HOURS:~1,1%
set /a OFFSET=TIMESERVER_HOURS-LOCAL_HOURS

rem :: day of the week will be the modulus of 7 of local ansi date +1
rem :: we need need +1 because Monday will be calculated as 0
rem ::  1st jan 1601 was Monday

rem :: if abs(offset)>12 we are in different days with the time server

IF %OFFSET%0 GTR 120 set /a DOW=(ANSI_DATE+1)%%7+1
IF %OFFSET%0 LSS -120 set /a DOW=(ANSI_DATE-1)%%7+1
IF %OFFSET%0 LEQ 120 IF %OFFSET%0 GEQ -120 set /a DOW=ANSI_DATE%%7+1


rem echo Day of the week: %DOW% 
endlocal & if "%~1" neq "" (set "%~1=%DOW%") else echo %DOW%

4..bat/jscript hybrid (must be saved as .bat):

 @if (@x)==(@y) @end /***** jscript comment ******
 @echo off
 for /f  %%d in ('cscript //E:JScript //nologo "%~f0"') do echo %%d
 exit /b 0
 *****  end comment *********/
 WScript.Echo((new Date).getDay());

5..bat/vbscript hybrid (must be saved as .bat)

 :sub echo(str) :end sub
echo off
'>nul 2>&1|| copy /Y %windir%\System32\doskey.exe '.exe >nul

'& echo/ 
'& for /f %%w in ('cscript /nologo /E:vbscript %~dpfn0') do echo day of the week %%w
'& echo/
'& del /q "'.exe" >nul 2>&1
'& exit /b

WScript.Echo Weekday(Date)
WScript.Quit

6.powershell can be downloaded from microsoft.Available by default in everything form win7 and above:

@echo off
setlocal
for /f %%d in ('"powershell (Get-Date).DayOfWeek.Value__"') do set dow=%%d

echo day of the week : %dow%
endlocal

7.WMIC already used as an answer but just want to have a full reference.And with cleared <CR>:

@echo off
setlocal
for /f "delims=" %%a in ('wmic path win32_localtime get dayofweek /format:list ') do for /f "delims=" %%d in ("%%a") do set %%d

echo day of the week : %dayofweek%
endlocal

9.Selfcompiled jscript.net (must be saved as .bat):

@if (@X)==(@Y) @end /****** silent line that start jscript comment ******

@echo off
::::::::::::::::::::::::::::::::::::
:::       compile the script    ::::
::::::::::::::::::::::::::::::::::::
setlocal
if exist "%~n0.exe" goto :skip_compilation

set "frm=%SystemRoot%\Microsoft.NET\Framework\"
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
    if exist "%%v\jsc.exe" (
        rem :: the javascript.net compiler
        set "jsc=%%~dpsnfxv\jsc.exe"
        goto :break_loop
    )
)
echo jsc.exe not found && exit /b 0
:break_loop


call %jsc% /nologo /out:"%~n0.exe" "%~dpsfnx0"
::::::::::::::::::::::::::::::::::::
:::       end of compilation    ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation

"%~n0.exe"

exit /b 0


****** end of jscript comment ******/
import System;
import System.IO;

var dt=DateTime.Now;
 Console.WriteLine(dt.DayOfWeek);

How to get the children of the $(this) selector?

Here's a functional code, you can run it (it's a simple demonstration).

When you click the DIV you get the image from some different methods, in this situation "this" is the DIV.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  // When you click the DIV, you take it with "this"_x000D_
  $('#my_div').click(function() {_x000D_
    console.info('Initializing the tests..');_x000D_
    console.log('Method #1: '+$(this).children('img'));_x000D_
    console.log('Method #2: '+$(this).find('img'));_x000D_
    // Here, i'm selecting the first ocorrence of <IMG>_x000D_
    console.log('Method #3: '+$(this).find('img:eq(0)'));_x000D_
  });_x000D_
});
_x000D_
.the_div{_x000D_
  background-color: yellow;_x000D_
  width: 100%;_x000D_
  height: 200px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="my_div" class="the_div">_x000D_
  <img src="...">_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

Simple file write function in C++

There are two solutions to this. You can either place the method above the method that calls it:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

int main()
{
    writeFile();
}

Or declare a prototype:

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int writeFile();

int main()
{
    writeFile();
}

int writeFile () 
{
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

pip not working in Python Installation in Windows 10

I faced a problem upgrading pip from version 9.0.1 to 9.0.3 The upgrade failed middle way(after uninstalling version 9.0.1 and without installing version 9.0.3). This usually creates a broken pip file. Broken pip can be solved by the command-->

easy_install pip

Which usually installs the latest version of pip, and solves the issue. In order to confirm, type

pip --version

Hope this was helpfull...

What do &lt; and &gt; stand for?

In HTML, the less-than sign is used at the beginning of tags. if you use this bracket "<test1>" in content, your bracket content will be unvisible, html renderer is assuming it as a html tag, changing chars with it's ASCI numbers prevents the issue.

with html friendly name:

  &lt;test1&gt; 

or with asci number:

 &#60;test1&#62;

or comple asci:

&#60;&#116;&#101;&#115;&#116;&#49;&#62;

result: <test1>

asci referance: https://www.w3schools.com/charsets/ref_html_ascii.asp

Failed to Connect to MySQL at localhost:3306 with user root

Steps:

1 - Right click on your task bar -->Start Task Manager

2 - Click on Services button (at bottom).

3 - Search for MYSQL57

4 - Right Click on MYSQL57 --> Start

Now again start your mysql-cmd-prompt or MYSQL WorkBench

How to install VS2015 Community Edition offline

As pointed in MSDN: Create an Offline Installation of Visual Studio:

To create an offline installation layout

  1. Choose the edition of Visual Studio that you want to install from the my.visualstudio.com download page.

  2. After you download the installer to a location on your file system, run "<executable name> /layout". For example, run: en_visual_studio_community_2015.exe /layout D:\VisualStudio2015

    By using the /layout switch, you can download almost all the installation packages, not just the ones that apply to the download machine. This approach gives you the files that you need to run this installer anywhere and it might be useful if you want to install components that weren't installed originally.

  3. After you run this command, a dialog box will appear that allows you to change the folder where you want the offline installation layout to reside. Next, click the Download button.

    When the package download is successful, you should see a message that says Setup Successful! All specified components have been acquired successfully.

  4. Locate the folder that you specified earlier. (For example, locate D:\VisualStudio2015.) This folder contains everything you need to copy to a shared location or install media.

    Caution: Currently, the Android SDK does not support an offline installation experience. If you install Android SDK Setup items on a computer that is not connected to the internet, the installation might fail. For more information, see the "Troubleshooting an offline installation" section in this topic.

  5. Run the installation from the file location or from the install media.

MYSQL query between two timestamps

You just need to convert your dates to UNIX_TIMESTAMP. You can write your query like this:

SELECT *
FROM eventList
WHERE
  date BETWEEN
      UNIX_TIMESTAMP('2013/03/26')
      AND
      UNIX_TIMESTAMP('2013/03/27 23:59:59');

When you don't specify the time, MySQL will assume 00:00:00 as the time for the given date.

Create a folder inside documents folder in iOS apps

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}

WCF error - There was no endpoint listening at

You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding, and the default value for securityMode\transport for that binding is Message.

Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration attribute:

<bindings>
  <wsHttpBinding>
    <binding name="ota2010AEndpoint" 
             .......>
      <readerQuotas maxDepth="32" ... />
        <reliableSession ordered="true" .... />
          <security mode="Transport">
            <transport clientCredentialType="None" proxyCredentialType="None"
                       realm="" />
            <message clientCredentialType="Windows" negotiateServiceCredential="true"
                     establishSecurityContext="true" />
          </security>
    </binding>
  </wsHttpBinding>
</bindings>    

(Snipped parts of the config to save space in the answer).

<service name="Synxis" behaviorConfiguration="SynxisWCF">
    <endpoint address="" name="wsHttpEndpoint" 
              binding="wsHttpBinding" 
              bindingConfiguration="ota2010AEndpoint"
              contract="Synxis" />

This will then assign your defined binding (with Transport security) to the endpoint.

How many threads is too many?

As Pax rightly said, measure, don't guess. That what I did for DNSwitness and the results were suprising: the ideal number of threads was much higher than I thought, something like 15,000 threads to get the fastest results.

Of course, it depends on many things, that's why you must measure yourself.

Complete measures (in French only) in Combien de fils d'exécution ?.

How to access host port from docker container

You can access the local webserver which is running in your host machine in two ways.

  1. Approach 1 with public IP

    Use host machine public IP address to access webserver in Jenkins docker container.

  2. Approach 2 with the host network

    Use "--net host" to add the Jenkins docker container on the host's network stack. Containers which are deployed on host's stack have entire access to the host interface. You can access local webserver in docker container with a private IP address of the host machine.

NETWORK ID          NAME                      DRIVER              SCOPE
b3554ea51ca3        bridge                    bridge              local
2f0d6d6fdd88        host                      host                local
b9c2a4bc23b2        none                      null                local

Start a container with the host network Eg: docker run --net host -it ubuntu and run ifconfig to list all available network IP addresses which are reachable from docker container.

Eg: I started a nginx server in my local host machine and I am able to access the nginx website URLs from Ubuntu docker container.

docker run --net host -it ubuntu

$ docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
a604f7af5e36        ubuntu              "/bin/bash"         22 seconds ago      Up 20 seconds                           ubuntu_server

Accessing the Nginx web server (running in local host machine) from Ubuntu docker container with private network IP address.

root@linuxkit-025000000001:/# curl 192.168.x.x -I
HTTP/1.1 200 OK
Server: nginx/1.15.10
Date: Tue, 09 Apr 2019 05:12:12 GMT
Content-Type: text/html
Content-Length: 612
Last-Modified: Tue, 26 Mar 2019 14:04:38 GMT
Connection: keep-alive
ETag: "5c9a3176-264"
Accept-Ranges: bytes

How do I detect what .NET Framework versions and service packs are installed?

Update for .NET 4.5.1

Now that .NET 4.5.1 is available the actual value of the key named Release in the registry needs to be checked, not just its existence. A value of 378758 means that .NET Framework 4.5.1 is installed. However, as described here this value is 378675 on Windows 8.1.

How do I check particular attributes exist or not in XML?

Just for the newcomers: the recent versions of C# allows the use of ? operator to check nulls assignments

parentSplit = xNode.ParentNode.Attributes["split"]?.Value;

Python: Fetch first 10 results from a list

check this

 list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]

 list[0:10]

Outputs:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

How do you assert that a certain exception is thrown in JUnit 4 tests?

We can use an assertion fail after the method that must return an exception:

try{
   methodThatThrowMyException();
   Assert.fail("MyException is not thrown !");
} catch (final Exception exception) {
   // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure
   assertTrue(exception instanceof MyException, "An exception other than MyException is thrown !");
   // In case of verifying the error message
   MyException myException = (MyException) exception;
   assertEquals("EXPECTED ERROR MESSAGE", myException.getMessage());
}

com.android.build.transform.api.TransformException

I changed a couple of pngs and the build number in the gradle and now I get this. No amount of cleaning and restarting helped. Disabling Instant Run fixed it for me. YMMV

Maximum request length exceeded.

If you can't update configuration files but control the code that handles file uploads use HttpContext.Current.Request.GetBufferlessInputStream(true).

The true value for disableMaxRequestLength parameter tells the framework to ignore configured request limits.

For detailed description visit https://msdn.microsoft.com/en-us/library/hh195568(v=vs.110).aspx

Fatal error: Call to undefined function pg_connect()

Easy install for ubuntu:

Just run:

sudo apt-get install php5-pgsql

then

sudo service apache2 restart //restart apache

or

Uncomment the following in php.ini by removing the ;

;extension=php_pgsql.dll

then restart apache

Return index of highest value in an array

My solution to get the higher key is as follows:

max(array_keys($values['Users']));

Have a div cling to top of screen if scrolled down past it

Use position:fixed; and set the top:0;left:0;right:0;height:100px; and you should be able to have it "stick" to the top of the page.

<div style="position:fixed;top:0;left:0;right:0;height:100px;">Some buttons</div>

Sum across multiple columns with dplyr

I would use regular expression matching to sum over variables with certain pattern names. For example:

df <- df %>% mutate(sum1 = rowSums(.[grep("x[3-5]", names(.))], na.rm = TRUE),
                    sum_all = rowSums(.[grep("x", names(.))], na.rm = TRUE))

This way you can create more than one variable as a sum of certain group of variables of your data frame.

Push an associative item into an array in JavaScript

Another method for creating a JavaScript associative array

First create an array of objects,

 var arr = {'name': []};

Next, push the value to the object.

  var val = 2;
  arr['name'].push(val);

To read from it:

var val = arr.name[0];

Swift - How to hide back button in navigation item?

In case you're using a UITabBarController:

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    self.tabBarController?.navigationItem.hidesBackButton = true
}

warning: implicit declaration of function

You need to declare the desired function before your main function:

#include <stdio.h>
int yourfunc(void);

int main(void) {

   yourfunc();
 }

tkinter: how to use after method

I believe, the 500ms run in the background, while the rest of the code continues to execute and empties the list.

Then after 500ms nothing happens, as no function-call is implemented in the after-callup (same as frame.after(500, function=None))

How can I create a product key for my C# application?

I have to admit I'd do something rather insane.

  1. Find a CPU bottleneck and extract it to a P/Invokeable DLL file.
  2. As a post build action, encrypt part of the DLL file with an XOR encryption key.
  3. Select a public/private key scheme, include public key in the DLL file
  4. Arrange so that decrypting the product key and XORing the two halves together results in the encryption key for the DLL.
  5. In the DLL's DllMain code, disable protection (PAGE_EXECUTE_READWRITE) and decrypt it with the key.
  6. Make a LicenseCheck() method that makes a sanity check of the license key and parameters, then checksums entire DLL file, throwing license violation on either. Oh, and do some other initialization here.

When they find and remove the LicenseCheck, what fun will follow when the DLL starts segmentation faulting.

How do I recognize "#VALUE!" in Excel spreadsheets?

in EXCEL 2013 i had to use IF function 2 times: 1st to identify error with ISERROR and 2nd to identify the specific type of error by ERROR.TYPE=3 in order to address this type of error. This way you can differentiate between error you want and other types.

How to get rid of punctuation using NLTK tokenizer?

I just used the following code, which removed all the punctuation:

tokens = nltk.wordpunct_tokenize(raw)

type(tokens)

text = nltk.Text(tokens)

type(text)  

words = [w.lower() for w in text if w.isalpha()]

How to get the Android device's primary e-mail address

Android locked down GET_ACCOUNTS recently so some of the answers did not work for me. I got this working on Android 7.0 with the caveat that your users have to endure a permission dialog.

AndroidManifest.xml

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

MainActivity.java

package com.example.patrick.app2;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.accounts.AccountManager;
import android.accounts.Account;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.*;

public class MainActivity extends AppCompatActivity {

    final static int requestcode = 4; //arbitrary constant less than 2^16

    private static String getEmailId(Context context) {
        AccountManager accountManager = AccountManager.get(context);
        Account[] accounts = accountManager.getAccountsByType("com.google");
        Account account;
        if (accounts.length > 0) {
            account = accounts[0];
        } else {
            return "length is zero";
        }
        return account.name;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case requestcode:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    String emailAddr = getEmailId(getApplicationContext());
                    ShowMessage(emailAddr);

                } else {
                    ShowMessage("Permission Denied");
                }
        }
    }

    public void ShowMessage(String email)
    {
        AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(email);
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Context context = getApplicationContext();

        if ( ContextCompat.checkSelfPermission( context, android.Manifest.permission.GET_ACCOUNTS )
                != PackageManager.PERMISSION_GRANTED )
        {
            ActivityCompat.requestPermissions( this, new String[]
                            {  android.Manifest.permission.GET_ACCOUNTS  },requestcode );
        }
        else
        {
            String possibleEmail = getEmailId(getApplicationContext());
            ShowMessage(possibleEmail);
        }
    }
}

'heroku' does not appear to be a git repository

I got the same error and it turned out I was in the wrong directory. It's a simple mistake to make so double check that you are in the root and then run heroku create and heroku git push master again. Of course you must have done git init, as mentioned in StickMaNX answer above, already before the heroku steps.

How to use SearchView in Toolbar Android

Integrating SearchView with RecyclerView

1) Add SearchView Item in Menu

SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="rohksin.com.searchviewdemo.MainActivity">
<item
    android:id="@+id/searchBar"
    app:showAsAction="always"
    app:actionViewClass="android.support.v7.widget.SearchView"
    />
</menu>

2) Implement SearchView.OnQueryTextListener in your Activity

SearchView.OnQueryTextListener has two abstract methods. So your activity skeleton would now look like this after implementing SearchView text listener.

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

   public boolean onQueryTextSubmit(String query)

   public boolean onQueryTextChange(String newText) 

}

3) Set up SerchView Hint text, listener etc

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);

    MenuItem searchItem = menu.findItem(R.id.searchBar);

    SearchView searchView = (SearchView) searchItem.getActionView();
    searchView.setQueryHint("Search People");
    searchView.setOnQueryTextListener(this);
    searchView.setIconified(false);

    return true;
}

4) Implement SearchView.OnQueryTextListener

This is how you can implement abstract methods of the listener.

@Override
public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

You can come up with your own logic based on your requirement. Here is the sample code snippet to show the list of Name which contains the text typed in the SearchView.

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
        list.addAll(copyList);
    }
    else
    {

        for(String name: copyList)
        {
            if(name.toLowerCase().contains(queryText.toLowerCase()))
            {
                list.add(name);
            }
        }

    }

    notifyDataSetChanged();
}

Full working code sample can be found > HERE
You can also check out the code on SearchView with an SQLite database in this Music App

Is JavaScript a pass-by-reference or pass-by-value language?

Observation: If there isn't any way for an observer to examine the underlying memory of the engine, there is no way to determine whether an immutable value gets copied or a reference gets passed.

JavaScript is more or less agnostic to the underlying memory model. There is no such thing as a reference². JavaScript has values. Two variables can hold the same value (or more accurate: two environment records can bind the same value). The only type of values that can be mutated are objects through their abstract [[Get]] and [[Set]] operations. If you forget about computers and memory, this is all you need to describe JavaScript's behaviour, and it allows you to understand the specification.

 let a = { prop: 1 };
 let b = a; // a and b hold the same value
 a.prop = "test"; // The object gets mutated, can be observed through both a and b
 b = { prop: 2 }; // b holds now a different value

Now you might ask yourself how two variables can hold the same value on a computer. You might then look into the source code of a JavaScript engine and you'll most likely find something which a programmer of the language the engine was written in would call a reference.

So in fact you can say that JavaScript is "pass by value", whereas the value can be shared, and you can say that JavaScript is "pass by reference", which might be a useful logical abstraction for programmers from low level languages, or you might call the behaviour "call by sharing".

As there is no such thing as a reference in JavaScript, all of these are neither wrong nor on point. Therefore I don't think the answer is particularly useful to search for.

² The term Reference in the specification is not a reference in the traditional sense. It is a container for an object and the name of a property, and it is an intermediate value (e.g., a.b evaluates to Reference { value = a, name = "b" }). The term reference also sometimes appears in the specification in unrelated sections.

API vs. Webservice

Basically, a webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.

You could very well have an API and the main method of interacting with that API is via a webservice.

The technical definitions (courtesy of Wikipedia) are:

API

An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.

Webservice

A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

How do I convert an enum to a list in C#?

Here for usefulness... some code for getting the values into a list, which converts the enum into readable form for the text

public class KeyValuePair
  {
    public string Key { get; set; }

    public string Name { get; set; }

    public int Value { get; set; }

    public static List<KeyValuePair> ListFrom<T>()
    {
      var array = (T[])(Enum.GetValues(typeof(T)).Cast<T>());
      return array
        .Select(a => new KeyValuePair
          {
            Key = a.ToString(),
            Name = a.ToString().SplitCapitalizedWords(),
            Value = Convert.ToInt32(a)
          })
          .OrderBy(kvp => kvp.Name)
         .ToList();
    }
  }

.. and the supporting System.String extension method:

/// <summary>
/// Split a string on each occurrence of a capital (assumed to be a word)
/// e.g. MyBigToe returns "My Big Toe"
/// </summary>
public static string SplitCapitalizedWords(this string source)
{
  if (String.IsNullOrEmpty(source)) return String.Empty;
  var newText = new StringBuilder(source.Length * 2);
  newText.Append(source[0]);
  for (int i = 1; i < source.Length; i++)
  {
    if (char.IsUpper(source[i]))
      newText.Append(' ');
    newText.Append(source[i]);
  }
  return newText.ToString();
}

How can I switch views programmatically in a view controller? (Xcode, iPhone)

This worked for me:

NSTimer *switchTo = [NSTimer scheduledTimerWithTimeInterval:0.1
           target:selfselector:@selector(switchToTimer)userInfo:nil repeats:NO];

- (void) switchToTimer {
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard_iPad" bundle:nil];
UIViewController *vc = [mainStoryboard instantiateViewControllerWithIdentifier:@"MyViewControllerID"]; // Storyboard ID
[self presentViewController:vc animated:FALSE completion:nil];
}

Java: print contents of text file to screen

Why hasn't anyone thought it was worth mentioning Scanner?

Scanner input = new Scanner(new File("foo.txt"));

while (input.hasNextLine())
{
   System.out.println(input.nextLine());
}

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

To complete the answer: Symfony2 comes with a wrapper around json_encode: Symfony/Component/HttpFoundation/JsonResponse

Typical usage in your Controllers:

...
use Symfony\Component\HttpFoundation\JsonResponse;
...
public function acmeAction() {
...
return new JsonResponse($array);
}

Adding value labels on a matplotlib bar chart

Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.

You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

This produces a labeled plot that looks like:

enter image description here

How do I use Ruby for shell scripting?

Go get yourself a copy of Everyday Scripting with Ruby. It has plenty of useful tips on how to do the types of things your are wanting to do.

Remove folder and its contents from git/GitHub's history

I find that the --tree-filter option used in other answers can be very slow, especially on larger repositories with lots of commits.

Here is the method I use to completely remove a directory from the git history using the --index-filter option, which runs much quicker:

# Make a fresh clone of YOUR_REPO
git clone YOUR_REPO
cd YOUR_REPO

# Create tracking branches of all branches
for remote in `git branch -r | grep -v /HEAD`; do git checkout --track $remote ; done

# Remove DIRECTORY_NAME from all commits, then remove the refs to the old commits
# (repeat these two commands for as many directories that you want to remove)
git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch DIRECTORY_NAME/' --prune-empty --tag-name-filter cat -- --all
git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

# Ensure all old refs are fully removed
rm -Rf .git/logs .git/refs/original

# Perform a garbage collection to remove commits with no refs
git gc --prune=all --aggressive

# Force push all branches to overwrite their history
# (use with caution!)
git push origin --all --force
git push origin --tags --force

You can check the size of the repository before and after the gc with:

git count-objects -vH

Unable to use Intellij with a generated sources folder

The only working condition, after several attempts, was to remove the hidden .idea folder from the root project folder and re-import it from Intellij

Node.js Write a line into a .txt file

Step 1

If you have a small file Read all the file data in to memory

Step 2

Convert file data string into Array

Step 3

Search the array to find a location where you want to insert the text

Step 4

Once you have the location insert your text

yourArray.splice(index,0,"new added test");

Step 5

convert your array to string

yourArray.join("");

Step 6

write your file like so

fs.createWriteStream(yourArray);

This is not advised if your file is too big

How to mock location on device?

The solution mentioned by icyerasor and provided by Pedro at http://pedroassuncao.com/blog/2009/11/12/android-location-provider-mock/ worked very well for me. However, it does not offer support for properly starting, stopping and restarting the mock GPS provider.

I have changed his code a bit and rewritten the class to be an AsyncTask instead of a Thread. This allows us to communicate with the UI Thread, so we can restart the provider at the point where we were when we stopped it. This comes in handy when the screen orientation changes.

The code, along with a sample project for Eclipse, can be found on GitHub: https://github.com/paulhoux/Android-MockProviderGPS

All credit should go to Pedro for doing most of the hard work.

Matplotlib-Animation "No MovieWriters Available"

(be sure to follow JPH feedback above about the proper ffmpeg download) Not sure why, but in my case here is the one that worked (in my case was on windows).

Initialize a writer:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.FFMpegWriter(fps=30, codec='libx264')  #or 
Writer = animation.FFMpegWriter(fps=20, metadata=dict(artist='Me'), bitrate=1800) ==> This is WORKED FINE ^_^

Writer = animation.writers['ffmpeg'] ==> GIVES ERROR ""RuntimeError: Requested MovieWriter (ffmpeg) not available""

ASP.Net MVC How to pass data from view to controller

In case you don't want/need to post:

@Html.ActionLink("link caption", "actionName", new { Model.Page })  // view's controller
@Html.ActionLink("link caption", "actionName", "controllerName", new { reportID = 1 }, null);

[HttpGet]
public ActionResult actionName(int reportID)
{

Note that the reportID in the new {} part matches reportID in the action parameters, you can add any number of parameters this way, but any more than 2 or 3 (some will argue always) you should be passing a model via a POST (as per other answer)

Edit: Added null for correct overload as pointed out in comments. There's a number of overloads and if you specify both action+controller, then you need both routeValues and htmlAttributes. Without the controller (just caption+action), only routeValues are needed but may be best practice to always specify both.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Best /Fastest way to read an Excel Sheet into a DataTable?

Here is another way of doing it

public DataSet CreateTable(string source)
{
    using (var connection = new OleDbConnection(GetConnectionString(source, true)))
    {
        var dataSet = new DataSet();
        connection.Open();
        var schemaTable = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
        if (schemaTable == null)
            return dataSet;

        var sheetName = "";
        foreach (DataRow row in schemaTable.Rows)
        {
            sheetName = row["TABLE_NAME"].ToString();
            break;
        }

        var command = string.Format("SELECT * FROM [{0}$]", sheetName);
        var adapter = new OleDbDataAdapter(command, connection);
        adapter.TableMappings.Add("TABLE", "TestTable");
        adapter.Fill(dataSet);
        connection.Close();

        return dataSet;
    }
}

//

private string GetConnectionString(string source, bool hasHeader)
{
    return string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};
    Extended Properties=\"Excel 12.0;HDR={1};IMEX=1\"", source, (hasHeader ? "YES" : "NO"));
}

Auto height div with overflow and scroll when needed

This is what I managed to do so far. I guess this is kind of what you're trying to pull out. The only thing is that I can still not manage to assign the proper height to the container DIV.

JSFIDDLE

The HTML:

<div id="container">
    <div id="header">HEADER</div>
    <div id="fixeddiv-top">FIXED DIV (TOP)</div>
    <div id="content-container">
        <div id="content">CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT<br>CONTENT</div>
    </div>
    <div id="fixeddiv-bottom">FIXED DIV (BOTTOM)</div>
</div>

And the CSS:

html {
    height:100%;
}
body {
    height:100%;
    margin:0;
    padding:0;
}
#container {
    width:600px;
    height:50%;
    text-align:center;
    display:block;
    position:relative;
}
#header {
    background:#069;
    text-align:center;
    width:100%;
    height:80px;
}
#fixeddiv-top {
    background:#AAA;
    text-align:center;
    width:100%;
    height:20px;
}
#content-container {
    height:100%;
}
#content {
    text-align:center;
    height:100%;
    background:#F00;
    margin:0 auto;
    overflow:auto;
}
#fixeddiv-bottom {
    background:#AAA;
    text-align:center;
    width:100%;
    height:20px;
}

Inserting line breaks into PDF

You state that

2 is the height of the multi-line text box

No it's not. 2 is the distance between lines of text.

I don't think there is a real way for calculating the height of the actual resulting text box, unless you use GetY() and then subtract the original Y value used in your SetXY() statement for placing the Multicell in the first place.

Cannot ping AWS EC2 instance

Security groups enable you to control traffic to your instance, including the kind of traffic that can reach your instance.

1. Check the Security Groups (Enabled the PORTS to be OPEN)
2. Check the correct VPC 
3. Attached the correct Subnet 
4. AWS EC2 to be in Public Subnet 
5. Enable Internet Gateway 

Open the Ports in AWS EC2 check this link offical AWS link

Fatal error: Call to undefined function mysql_connect()

Verify that your installation of PHP has been compiled with mysql support. Create a test web page containing <?php phpinfo(); exit(); ?> and load it in your browser. Search the page for MySQL. If you don't see it, you need to recompile PHP with MySQL support, or reinstall a PHP package that has it built-in

How can I introduce multiple conditions in LIKE operator?

This might help:

select * from tbl where col like '[ABC-XYZ-PQR]%'

I've used this in SQL Server 2005 and it worked.

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

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

How to grep a string in a directory and all its subdirectories?

If your grep supports -R, do:

grep -R 'string' dir/

If not, then use find:

find dir/ -type f -exec grep -H 'string' {} +

Javascript : get <img> src and set as variable?

in this situation, you would grab the element by its id using getElementById and then just use .src

var youtubeimgsrc = document.getElementById("youtubeimg").src;

What's the difference between nohup and ampersand

Correct me if I'm wrong

  nohup myprocess.out &

nohup catches the hangup signal, which mean it will send a process when terminal closed.

 myprocess.out &

Process can run but will stopped once the terminal is closed.

nohup myprocess.out

Process able to run even terminal closed, but you are able to stop the process by pressing ctrl + z in terminal. Crt +z not working if & is existing.

Finding multiple occurrences of a string within a string in Python

This version should be linear in length of the string, and should be fine as long as the sequences aren't too repetitive (in which case you can replace the recursion with a while loop).

def find_all(st, substr, start_pos=0, accum=[]):
    ix = st.find(substr, start_pos)
    if ix == -1:
        return accum
    return find_all(st, substr, start_pos=ix + 1, accum=accum + [ix])

bstpierre's list comprehension is a good solution for short sequences, but looks to have quadratic complexity and never finished on a long text I was using.

findall_lc = lambda txt, substr: [n for n in xrange(len(txt))
                                   if txt.find(substr, n) == n]

For a random string of non-trivial length, the two functions give the same result:

import random, string; random.seed(0)
s = ''.join([random.choice(string.ascii_lowercase) for _ in range(100000)])

>>> find_all(s, 'th') == findall_lc(s, 'th')
True
>>> findall_lc(s, 'th')[:4]
[564, 818, 1872, 2470]

But the quadratic version is about 300 times slower

%timeit find_all(s, 'th')
1000 loops, best of 3: 282 µs per loop

%timeit findall_lc(s, 'th')    
10 loops, best of 3: 92.3 ms per loop

Convert A String (like testing123) To Binary In Java

You can also do this with the ol' good method :

String inputLine = "test123";
String translatedString = null;
char[] stringArray = inputLine.toCharArray();
for(int i=0;i<stringArray.length;i++){
      translatedString += Integer.toBinaryString((int) stringArray[i]);
}

How to move all HTML element children to another parent using JavaScript?

This answer only really works if you don't need to do anything other than transferring the inner code (innerHTML) from one to the other:

// Define old parent
var oldParent = document.getElementById('old-parent');

// Define new parent
var newParent = document.getElementById('new-parent');

// Basically takes the inner code of the old, and places it into the new one
newParent.innerHTML = oldParent.innerHTML;

// Delete / Clear the innerHTML / code of the old Parent
oldParent.innerHTML = '';

Hope this helps!

What charset does Microsoft Excel use when saving files?

From memory, Excel uses the machine-specific ANSI encoding. So this would be Windows-1252 for a EN-US installation, 1251 for Russian, etc.

Excel CSV - Number cell format

This works for Microsoft Office 2010, Excel Version 14

I misread the OP's preference "to do something to the file itself." I'm still keeping this for those who want a solution to format the import directly

  1. Open a blank (new) file (File -> New from workbook)
  2. Open the Import Wizard (Data -> From Text)
  3. Select your .csv file and Import
  4. In the dialogue box, choose 'Delimited', and click Next.
  5. Choose your delimiters (uncheck everything but 'comma'), choose your Text qualifiers (likely {None}), click Next
  6. In the Data preview field select the column you want to be text. It should highlight.
  7. In the Column data format field, select 'Text'.
  8. Click finished.

How to define an enumerated type (enum) in C?

It's worth mentioning that in C++ you can use "enum" to define a new type without needing a typedef statement.

enum Strategy {RANDOM, IMMEDIATE, SEARCH};
...
Strategy myStrategy = IMMEDIATE;

I find this approach a lot more friendly.

[edit - clarified C++ status - I had this in originally, then removed it!]

Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?

In addition to the native versions, but you may want to try BitNami MAMP Stacks (disclaimer, I am one of the developers). They are completely free, all-in-one bundles of Apache, MySQL, PHP and a several other third-party libraries and utilities that are useful when developing locally. In particular, they are completely self-contained so you can have several one installed at the same time, with different versions of Apache and MySQL and they will not interfere with each other. You can get them from http://bitnami.org/stack/mampstack or directly from the Mac OS X app store https://itunes.apple.com/app/mamp-stack/id571310406

font-weight is not working properly?

i was also facing the same issue, I resolved it by after selecting the Google's font that i was using, then I clicked on (Family-Selected) minimized tab and then clicked on "CUSTOMIZE" button. Then I selected the font weights that I want and then embedded the updated link in my html..

How to use order by with union all in sql?

select CONCAT(Name, '(',substr(occupation, 1, 1), ')') AS f1
from OCCUPATIONS
union
select temp.str AS f1 from 
(select count(occupation) AS counts, occupation, concat('There are a total of ' ,count(occupation) ,' ', lower(occupation),'s.') As str  from OCCUPATIONS group by occupation order by counts ASC, occupation ASC
 ) As temp
 order by f1

Reloading the page gives wrong GET request with AngularJS HTML5 mode

I wrote a simple connect middleware for simulating url-rewriting on grunt projects. https://gist.github.com/muratcorlu/5803655

You can use like that:

module.exports = function(grunt) {
  var urlRewrite = require('grunt-connect-rewrite');

  // Project configuration.
  grunt.initConfig({
    connect: {
      server: {
        options: {
          port: 9001,
          base: 'build',
          middleware: function(connect, options) {
            // Return array of whatever middlewares you want
            return [
              // redirect all urls to index.html in build folder
              urlRewrite('build', 'index.html'),

              // Serve static files.
              connect.static(options.base),

              // Make empty directories browsable.
              connect.directory(options.base)
            ];
          }
        }
      }
    }
  })
};

What's an object file in C?

Object files are codes that are dependent on functions, symbols, and text to run the program. Just like old telex machines, which required teletyping to send signals to other telex machine.

In the same way processor's require binary code to run, object files are like binary code but not linked. Linking creates additional files so that the user does not have to have compile the C language themselves. Users can directly open the exe file once the object file is linked with some compiler like c language , or vb etc.

Difference between an API and SDK

Suppose company C offers product P and P involves software in some way. Then C can offer a library/set of libraries to software developers that drive P's software systems.

That library/libraries are an SDK. It is part of the systems of P. It is a kit for software developers to use in order to modify, configure, fix, improve, etc the software piece of P.

If C wants to offer P's functionality to other companies/systems, it does so with an API.

This is an interface to P. A way for external systems to interact with P.

If you think in terms of implementation, they will seem quite similar. Especially now that the internet has become like one large distributed operating system.

In purpose, though, they are actually quite distinct.

You build something with an SDK and you use or consume something with an API.

How to get docker-compose to always re-create containers from fresh images?

$docker-compose build

If there is something new it will be rebuilt.

How to change port for jenkins window service when 8080 is being used

Use Default Port

If the default port 8080 has been bind with other process, Then kill that process.

DOS> netstat -a -o -n

Find the process id (PID) XXXX of the process which occupied 8080.

DOS> taskkill /F /PID XXXX

Now, start Jenkins (on default port)

DOS> Java -jar jenkins.war

Use Custom Port

DOS> Java -jar jenkins.war --httpPort=8008

Awaiting multiple Tasks with different results

You can use Task.WhenAll as mentioned, or Task.WaitAll, depending on whether you want the thread to wait. Take a look at the link for an explanation of both.

WaitAll vs WhenAll

How to Parse JSON Array with Gson

Some of the answers of this post are valid, but using TypeToken, the Gson library generates a Tree objects whit unreal types for your application.

To get it I had to read the array and convert one by one the objects inside the array. Of course this method is not the fastest and I don't recommend to use it if you have the array is too big, but it worked for me.

It is necessary to include the Json library in the project. If you are developing on Android, it is included:

/**
 * Convert JSON string to a list of objects
 * @param sJson String sJson to be converted
 * @param tClass Class
 * @return List<T> list of objects generated or null if there was an error
 */
public static <T> List<T> convertFromJsonArray(String sJson, Class<T> tClass){

    try{
        Gson gson = new Gson();
        List<T> listObjects = new ArrayList<>();

        //read each object of array with Json library
        JSONArray jsonArray = new JSONArray(sJson);
        for(int i=0; i<jsonArray.length(); i++){

            //get the object
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            //get string of object from Json library to convert it to real object with Gson library
            listObjects.add(gson.fromJson(jsonObject.toString(), tClass));
        }

        //return list with all generated objects
        return listObjects;

    }catch(Exception e){
        e.printStackTrace();
    }

    //error: return null
    return null;
}

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

If you need to load a file that's relative to some directory where you already are (like in the current directory), here's an easy solution:

File f;

if (System.getProperty("sun.arch.data.model").equals("32")) {
    // 32-bit JVM
    f = new File("mylibfile32.so");
} else {
    // 64-bit JVM
    f = new File("mylibfile64.so");
}
System.load(f.getAbsolutePath());

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

This happened to me on Windows 10 and VS 2013. Apparently there is a maximum port number IIS Express handles. Ports above 62546 don't work for me.

Redirect all to index.php using htaccess

There is one "trick" for this problem that fits all scenarios, a so obvious solution that you will have to try it to believe it actually works... :)

Here it is...

<IfModule mod_rewrite.c>

   RewriteEngine On

   RewriteCond %{REQUEST_FILENAME}  -f [OR]
   RewriteCond %{REQUEST_FILENAME} !-f
   RewriteRule ^(.*)$ index.php [L,QSA]

</IfModule>

Basically, you are asking MOD_REWRITE to forward to index.php the URI request always when a file exists AND always when the requested file doesn't exist!

When investigating the source code of MOD-REWRITE to understand how it works I realized that all its checks always happen after the verification if the referenced file exists or not. Only then the RegEx are processed. Even when your URI points to a folder, Apache will enforce the check for the index files listed in its configuration file.

Based on that simple discovery, turned obvious a simple file validation would be enough for all possible calls, as far as we double-tap the file presence check and route both results to the same end-point, covering 100% of the possibilities.

IMPORTANT: Notice there is no "/" in index.php. By default, MOD_REWRITE will use the folder it is set as "base folder" for the forwarding. The beauty of it is that it doesn't necessarily need to be the "root folder" of the site, allowing this solution work for localhost/ and/or any subfolder you apply it.

Ultimately, some other solutions I tested before (the ones that appeared to be working fine) broke the PHP ability to "require" a file via its relative path, which is a bummer. Be careful.

Some people may say this is an inelegant solution. It may be, actually, but as far as tests, in several scenarios, several servers, several different Apache versions, etc., this solution worked 100% on all cases!

Implement a loading indicator for a jQuery AJAX call

I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like

$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });

Is there StartsWith or Contains in t sql with variables?

I would use

like 'Express Edition%'

Example:

DECLARE @edition varchar(50); 
set @edition = cast((select SERVERPROPERTY ('edition')) as varchar)

DECLARE @isExpress bit
if @edition like 'Express Edition%'
    set @isExpress = 1;
else
    set @isExpress = 0;

print @isExpress

What is the C# version of VB.net's InputDialog?

There is no such thing: I recommend to write it for yourself and use it whenever you need.

Selenium wait until document is ready

For the people who need to wait for a specific element to show up. (used c#)

public static void WaitForElement(IWebDriver driver, By element)
{
    WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
    wait.Until(ExpectedConditions.ElementIsVisible(element));
}

Then if you want to wait for example if an class="error-message" exists in the DOM you simply do:

WaitForElement(driver, By.ClassName("error-message"));

For id, it will then be

WaitForElement(driver, By.Id("yourid"));

Datetime in C# add days

Assign the enddate to some date variable because AddDays method returns new Datetime as the result..

Datetime somedate=endDate.AddDays(2);

How to debug Google Apps Script (aka where does Logger.log log to?)

Just as a notice. I made a test function for my spreadsheet. I use the variable google throws in the onEdit(e) function (I called it e). Then I made a test function like this:

function test(){
var testRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,7)
var testObject = {
    range:testRange,
    value:"someValue"
}
onEdit(testObject)
SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GetItemInfoSheetName).getRange(2,6).setValue(Logger.getLog())
}

Calling this test function makes all the code run as you had an event in the spreadsheet. I just put in the possision of the cell i edited whitch gave me an unexpected result, setting value as the value i put into the cell. OBS! for more variables googles gives to the function go here: https://developers.google.com/apps-script/guides/triggers/events#google_sheets_events

PHP Function Comments

You must check this: Docblock Comment standards

http://pear.php.net/manual/en/standards.sample.php

To show a new Form on click of a button in C#

Game_Menu Form1 = new Game_Menu();
Form1.ShowDialog();

Game_Menu is the form name

Form1 is the object name

How to create a temporary directory/folder in Java?

Well, "createTempFile" actually creates the file. So why not just delete it first, and then do the mkdir on it?

Error: Argument is not a function, got undefined

In my case (having an overview page and an "add" page) I got this with my routing setup like below. It was giving the message for the AddCtrl that could not be injected...

$routeProvider.
  when('/', {
    redirectTo: '/overview'
  }).      
  when('/overview', {
    templateUrl: 'partials/overview.html',
    controller: 'OverviewCtrl'
  }).
  when('/add', {
    templateUrl: 'partials/add.html',
    controller: 'AddCtrl'
  }).
  otherwise({
    redirectTo: '/overview'
  });

Because of the when('/' route all my routes went to the overview and the controller could not be matched on the /add route page rendering. This was confusing because I DID see the add.html template but its controller was nowhere to be found.

Removing the '/'-route when case fixed this issue for me.

HRESULT: 0x800A03EC on Worksheet.range

This problem occurs if you are using a backwards compatible sheet (a .xls) instead of a .xlsx

To allow sheets to be opened in pre office 2007 version it can't contain more than 65k rows. You can check the number of rows in your sheet by using ctrl+arrowdown till you hit the bottom. If you try to get a range larger than that number of rows it will create an error

Oracle: Call stored procedure inside the package

To those that are incline to use GUI:

Click Right mouse button on procecdure name then select Test

enter image description here

Then in new window you will see script generated just add the parameters and click on Start Debugger or F9

enter image description here

Hope this saves you some time.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

I think this is best link for your solution to update postgres to 9.6

https://sandymadaan.wordpress.com/2017/02/21/upgrade-postgresql9-3-9-6-in-ubuntu-retaining-the-databases/

ORDER BY using Criteria API

It's hard to know for sure without seeing the mappings (see @Juha's comment), but I think you want something like the following:

Criteria c = session.createCriteria(Cat.class);
Criteria c2 = c.createCriteria("mother");
Criteria c3 = c2.createCriteria("kind");
c3.addOrder(Order.asc("value"));
return c.list();

python: creating list from string

More concise than others:

def parseString(string):
    try:
        return int(string)
    except ValueError:
        return string

b = [[parseString(s) for s in clause.split(', ')] for clause in a]

Alternatively if your format is fixed as <string>, <int>, <int>, you can be even more concise:

def parseClause(a,b,c):
    return [a, int(b), int(c)]

b = [parseClause(*clause) for clause in a]

What does it mean when an HTTP request returns status code 0?

wininet.dll returns both standard and non-standard status codes that are listed below.

401 - Unauthorized file
403 - Forbidden file
404 - File Not Found
500 - some inclusion or functions may missed
200 - Completed

12002 - Server timeout
12029,12030, 12031 - dropped connections (either web server or DB server)
12152 - Connection closed by server.
13030 - StatusText properties are unavailable, and a query attempt throws an exception

For the status code "zero" are you trying to do a request on a local webpage running on a webserver or without a webserver?

XMLHttpRequest status = 0 and XMLHttpRequest statusText = unknown can help you if you are not running your script on a webserver.

Convert array to JSON string in swift

If you're already using SwiftyJSON:

https://github.com/SwiftyJSON/SwiftyJSON

You can do this:

// this works with dictionaries too
let paramsDictionary = [
    "title": "foo",
    "description": "bar"
]
let paramsArray = [ "one", "two" ]
let paramsJSON = JSON(paramsArray)
let paramsString = paramsJSON.rawString(encoding: NSUTF8StringEncoding, options: nil)

SWIFT 3 UPDATE

 let paramsJSON = JSON(paramsArray)
 let paramsString = paramsJSON.rawString(String.Encoding.utf8, options: JSONSerialization.WritingOptions.prettyPrinted)!

JSON strings, which are good for transport, don't come up often because you can JSON encode an HTTP body. But one potential use-case for JSON stringify is Multipart Post, which AlamoFire nows supports.

Stupid error: Failed to load resource: net::ERR_CACHE_MISS

If you are using bootstrap that will be the problem. If you want to use same bootstrap file in two locations use it below the header section .(example - inside body)

Note : "specially when you use html editors. "

Thank you.

How do I configure git to ignore some files locally?

You can simply add a .gitignore file to your home directory, i.e. $HOME/.gitignore or ~/.gitignore. Then tell git to use that file with the command:

git config --global core.excludesfile ~/.gitignore

This is a normal .gitignore file which git references when deciding what to ignore. Since it's in your home directory, it applies only to you and doesn't pollute any project .gitignore files.

I've been using this approach for years with great results.

Get screenshot on Windows with Python?

You can use the ImageGrab module. ImageGrab works on Windows and macOS, and you need PIL (Pillow) to use it. Here is a little example:

from PIL import ImageGrab
snapshot = ImageGrab.grab()
save_path = "C:\\Users\\YourUser\\Desktop\\MySnapshot.jpg"
snapshot.save(save_path)

Quantile-Quantile Plot using SciPy

Using qqplot of statsmodels.api is another option:

Very basic example:

import numpy as np
import statsmodels.api as sm
import pylab

test = np.random.normal(0,1, 1000)

sm.qqplot(test, line='45')
pylab.show()

Result:

enter image description here

Documentation and more example are here

Junit test case for database insert method with DAO and web service

/*

public class UserDAO {

public boolean insertUser(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into regis values(?,?,?,?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getname());
        statement.setString(2, u.getlname());
        statement.setString(3, u.getemail());
        statement.setString(4, u.getusername());
        statement.setString(5, u.getpasswords());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public String userValidate(UserBean u) {
    String login = "";
    MySqlConnection msq = new MySqlConnection();
    try {
        String email = u.getemail();
        String Pass = u.getpasswords();

        String sql = "SELECT name FROM regis WHERE email=? and passwords=?";
        com.mysql.jdbc.Connection connection = msq.getConnection();
        com.mysql.jdbc.PreparedStatement statement = null;
        ResultSet rs = null;
        statement = (com.mysql.jdbc.PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, email);
        statement.setString(2, Pass);
        rs = statement.executeQuery();
        if (rs.next()) {
            login = rs.getString("name");
        } else {
            login = "false";
        }

    } catch (Exception e) {
    } finally {
        return login;
    }
}

public boolean getmessage(UserBean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {


        String sql = "insert into feedback values(?,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getemail());
        statement.setString(2, u.getfeedback());
        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
    } finally {
        return flag;
    }

}

public boolean insertOrder(cartbean u) {
    boolean flag = false;
    MySqlConnection msq = new MySqlConnection();
    try {

        String sql = "insert into cart (product_id, email, Tprice, quantity) values (?,?,2000,?)";

        Connection connection = msq.getConnection();
        PreparedStatement statement = null;
        statement = (PreparedStatement) connection.prepareStatement(sql);
        statement.setString(1, u.getpid());
        statement.setString(2, u.getemail());
        statement.setString(3, u.getquantity());

        statement.executeUpdate();

        flag = true;
    } catch (Exception e) {
        System.out.print("hi");
    } finally {
        return flag;
    }

}

}

SQL Server stored procedure parameters

CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@Id INT
AS
BEGIN
-- SP Logic
END

Procedure Calling

DECLARE @return_value nvarchar(50)

EXEC  @return_value = GetTaskEvents
        @TaskName = 'TaskName',
        @Id =2  

SELECT  'Return Value' = @return_value

Editing specific line in text file in Python

#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

How to call a function, PostgreSQL

if your function does not want to return anything you should declare it to "return void" and then you can call it like this "perform functionName(parameter...);"

Adjusting and image Size to fit a div (bootstrap)

I used this and works for me.

<div class="col-sm-3">
  <img src="xxx.png" style="width: auto; height: 195px;">
</div>

Checking whether a string starts with XXXX

Can also be done this way..

regex=re.compile('^hello')

## THIS WAY YOU CAN CHECK FOR MULTIPLE STRINGS
## LIKE
## regex=re.compile('^hello|^john|^world')

if re.match(regex, somestring):
    print("Yes")

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

how to remove "," from a string in javascript

<script type="text/javascript">var s = '/Controller/Action#11112';if(typeof s == 'string' && /\?*/.test(s)){s = s.replace(/\#.*/gi,'');}document.write(s);</script>

It's more common answer. And can be use with s= document.location.href;

SQL Error with Order By in Subquery

Add the Top command to your sub query...

SELECT 
(
SELECT TOP 100 PERCENT 
    COUNT(1) 
FROM 
    Seanslar 
WHERE 
    MONTH(tarihi) = 4
GROUP BY 
    refKlinik_id
ORDER BY 
    refKlinik_id
) as dorduncuay

:)

Casting a number to a string in TypeScript

"Casting" is different than conversion. In this case, window.location.hash will auto-convert a number to a string. But to avoid a TypeScript compile error, you can do the string conversion yourself:

window.location.hash = ""+page_number; 
window.location.hash = String(page_number); 

These conversions are ideal if you don't want an error to be thrown when page_number is null or undefined. Whereas page_number.toString() and page_number.toLocaleString() will throw when page_number is null or undefined.

When you only need to cast, not convert, this is how to cast to a string in TypeScript:

window.location.hash = <string>page_number; 
// or 
window.location.hash = page_number as string;

The <string> or as string cast annotations tell the TypeScript compiler to treat page_number as a string at compile time; it doesn't convert at run time.

However, the compiler will complain that you can't assign a number to a string. You would have to first cast to <any>, then to <string>:

window.location.hash = <string><any>page_number;
// or
window.location.hash = page_number as any as string;

So it's easier to just convert, which handles the type at run time and compile time:

window.location.hash = String(page_number); 

(Thanks to @RuslanPolutsygan for catching the string-number casting issue.)

Elegant way to read file into byte[] array in Java

Use a ByteArrayOutputStream. Here is the process:

  • Get an InputStream to read data
  • Create a ByteArrayOutputStream.
  • Copy all the InputStream into the OutputStream
  • Get your byte[] from the ByteArrayOutputStream using the toByteArray() method

How to get build time stamp from Jenkins build variables?

Generate environment variables from script (Unix script) :

echo "BUILD_DATE=$(date +%F-%T)"

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Difference between /res and /assets directories

Following are some key points :

  1. Raw files Must have names that are valid Java identifiers , whereas files in Assets Have no location and name restrictions. In other words they can be grouped in whatever directories we wish
  2. Raw files Are easy to refer to from Java as well as from xml (i.e you can refer a file in raw from manifest or other xml file).
  3. Saving asset files here instead of in the assets/ directory only differs in the way that you access them as documented here http://developer.android.com/tools/projects/index.html.
  4. Resources defined in a library project are automatically imported to application projects that depend on the library. For assets, that doesn't happen; asset files must be present in the assets directory of the application project(s)
  5. The assets directory is more like a filesystem provides more freedom to put any file you would like in there. You then can access each of the files in that system as you would when accessing any file in any file system through Java . like Game data files , Fonts , textures etc.
  6. Unlike Resources, Assets can can be organized into subfolders in the assets directory However, the only thing you can do with an asset is get an input stream. Thus, it does not make much sense to store your strings or bitmaps in assets, but you can store custom-format data such as input correction dictionaries or game maps.
  7. Raw can give you a compile time check by generating your R.java file however If you want to copy your database to private directory you can use Assets which are made for streaming.

Conclusion

  1. Android API includes a very comfortable Resources framework that is also optimized for most typical use cases for various mobile apps. You should master Resources and try to use them wherever possible.
  2. However, if you need more flexibility for your special case, Assets are there to give you a lower level API that allows organizing and processing your resources with a higher degree of freedom.

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

Create AMI -> Boot AMI on large instance.

More info http://docs.amazonwebservices.com/AmazonEC2/gsg/2006-06-26/creating-an-image.html

You can do this all from the admin console too at aws.amazon.com

Reflection generic get field value

I use the reflections in the toString() implementation of my preference class to see the class members and values (simple and quick debugging).

The simplified code I'm using:

@Override
public String toString() {
    StringBuilder sb = new StringBuilder();

    Class<?> thisClass = null;
    try {
        thisClass = Class.forName(this.getClass().getName());

        Field[] aClassFields = thisClass.getDeclaredFields();
        sb.append(this.getClass().getSimpleName() + " [ ");
        for(Field f : aClassFields){
            String fName = f.getName();
            sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
        }
        sb.append("]");
    } catch (Exception e) {
        e.printStackTrace();
    }

    return sb.toString();
}

I hope that it will help someone, because I also have searched.

How do I copy to the clipboard in JavaScript?

Reading and modifying the clipboard from a webpage raises security and privacy concerns. However, in Internet Explorer, it is possible to do it. I found this example snippet:

_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function select_all(obj) {_x000D_
            var text_val=eval(obj);_x000D_
            text_val.focus();_x000D_
            text_val.select();_x000D_
            r = text_val.createTextRange();_x000D_
            if (!r.execCommand) return; // feature detection_x000D_
            r.execCommand('copy');_x000D_
        }_x000D_
    </script>_x000D_
    <input value="http://www.sajithmr.com"_x000D_
     onclick="select_all(this)" name="url" type="text" />
_x000D_
_x000D_
_x000D_

Convert varchar to float IF ISNUMERIC

..extending Mikaels' answers

SELECT
  CASE WHEN ISNUMERIC(QTY + 'e0') = 1 THEN CAST(QTY AS float) ELSE null END AS MyFloat
  CASE WHEN ISNUMERIC(QTY + 'e0') = 0 THEN QTY ELSE null END AS MyVarchar
FROM
  ...
  • Two data types requires two columns
  • Adding e0 fixes some ISNUMERIC issues (such as + - . and empty string being accepted)

Javascript get the text value of a column from a particular row of an html table

document.getElementById("tblBlah").rows[i].columns[j].innerHTML;

Should be:

document.getElementById("tblBlah").rows[i].cells[j].innerHTML;

But I get the distinct impression that the row/cell you need is the one clicked by the user. If so, the simplest way to achieve this would be attaching an event to the cells in your table:

function alertInnerHTML(e)
{
    e = e || window.event;//IE
    alert(this.innerHTML);
}

var theTbl = document.getElementById('tblBlah');
for(var i=0;i<theTbl.length;i++)
{
    for(var j=0;j<theTbl.rows[i].cells.length;j++)
    {
        theTbl.rows[i].cells[j].onclick = alertInnerHTML;
    }
}

That makes all table cells clickable, and alert it's innerHTML. The event object will be passed to the alertInnerHTML function, in which the this object will be a reference to the cell that was clicked. The event object offers you tons of neat tricks on how you want the click event to behave if, say, there's a link in the cell that was clicked, but I suggest checking the MDN and MSDN (for the window.event object)

Iterate two Lists or Arrays with one ForEach statement in C#

You can use Union or Concat, the former removes duplicates, the later doesn't

foreach (var item in List1.Union(List1))
{
   //TODO: Real code goes here
}

foreach (var item in List1.Concat(List1))
{
   //TODO: Real code goes here
}

Effectively use async/await with ASP.NET Web API

I would change your service layer to:

public Task<BackOfficeResponse<List<Country>>> ReturnAllCountries()
{
    return Task.Run(() =>
    {
        return _service.Process<List<Country>>(BackOfficeEndpoint.CountryEndpoint, "returnCountries");
    }      
}

as you have it, you are still running your _service.Process call synchronously, and gaining very little or no benefit from awaiting it.

With this approach, you are wrapping the potentially slow call in a Task, starting it, and returning it to be awaited. Now you get the benefit of awaiting the Task.

How to replace NaN value with zero in a huge data frame?

In fact, in R, this operation is very easy:

If the matrix 'a' contains some NaN, you just need to use the following code to replace it by 0:

a <- matrix(c(1, NaN, 2, NaN), ncol=2, nrow=2)
a[is.nan(a)] <- 0
a

If the data frame 'b' contains some NaN, you just need to use the following code to replace it by 0:

#for a data.frame: 
b <- data.frame(c1=c(1, NaN, 2), c2=c(NaN, 2, 7))
b[is.na(b)] <- 0
b

Note the difference is.nan when it's a matrix vs. is.na when it's a data frame.

Doing

#...
b[is.nan(b)] <- 0
#...

yields: Error in is.nan(b) : default method not implemented for type 'list' because b is a data frame.

Note: Edited for small but confusing typos

PostgreSQL next value of the sequences?

If your are not in a session you can just nextval('you_sequence_name') and it's just fine.

How to set a default value for an existing column

in case a restriction already exists with its default name:

-- Drop existing default constraint on Employee.CityBorn
DECLARE @default_name varchar(256);
SELECT @default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + @default_name);

-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;

SQL Server after update trigger

Try this (update, not after update)

CREATE TRIGGER [dbo].[xxx_update] ON [dbo].[MYTABLE]
    FOR UPDATE
    AS
    BEGIN

        UPDATE MYTABLE
        SET mytable.CHANGED_ON = GETDATE()
            ,CHANGED_BY = USER_NAME(USER_ID())
        FROM inserted
        WHERE MYTABLE.ID = inserted.ID

    END

Fastest way to get the first object from a queryset in django?

You can use array slicing:

Entry.objects.all()[:1].get()

Which can be used with .filter():

Entry.objects.filter()[:1].get()

You wouldn't want to first turn it into a list because that would force a full database call of all the records. Just do the above and it will only pull the first. You could even use .order_by() to ensure you get the first you want.

Be sure to add the .get() or else you will get a QuerySet back and not an object.

jQuery animate backgroundColor

For anyone finding this. Your better off using the jQuery UI version because it works on all browsers. The color plugin has issues with Safari and Chrome. It only works sometimes.

Proper usage of Java -D command-line parameters

I suspect the problem is that you've put the "-D" after the -jar. Try this:

java -Dtest="true" -jar myApplication.jar

From the command line help:

java [-options] -jar jarfile [args...]

In other words, the way you've got it at the moment will treat -Dtest="true" as one of the arguments to pass to main instead of as a JVM argument.

(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)

What are the benefits of using C# vs F# or F# vs C#?

You're asking for a comparison between a procedural language and a functional language so I feel your question can be answered here: What is the difference between procedural programming and functional programming?

As to why MS created F# the answer is simply: Creating a functional language with access to the .Net library simply expanded their market base. And seeing how the syntax is nearly identical to OCaml, it really didn't require much effort on their part.

`React/RCTBridgeModule.h` file not found

I've encountered this issue while upgrading from 0.58.4 to new react-native version 0.60.4. Nothing from what i found on the internet helped me, but I managed to get it working:

Go to build settings, search for 'Header search paths', select the entry, press DELETE button.

I had these values overriden, and looks like they fell back to defaults after deletion. Also Cocoapods was complaining about it with messages in Terminal after pod install:

[!] The `app [Release]` target overrides the `HEADER_SEARCH_PATHS` build setting defined in `Pods/Target Support Files/Pods-app/Pods-app.release.xcconfig'. This can lead to problems with the CocoaPods installation

How to get input type using jquery?

Very Simple using jQuery... To check that selected element is type of input

$(".elementClass").is('input')

To check that selected element is type of textarea

$(".elementClass").is('textarea')

To check that selected element is type of Radio

$(".elementClass").is('input[type="radio"]')

To check that selected element is type of Checkbox

$(".elementClass").is('input[type="checkbox"]')

To check that selected element is type of Input type number

$(".elementClass").is('input[type="number"]')

To check that selected element is type of Input type password

$(".elementClass").is('input[type="password"]')

To check that selected element is type of Input type email

$(".elementClass").is('input[type="email"]')

.....

...

So Basically you can change selection and type to determine required input type

Check if element is clickable in Selenium Java

elementToBeClickable is used for checking an element is visible and enabled such that you can click it.

ExpectedConditions.elementToBeClickable returns WebElement if expected condition is true otherwise it will throw TimeoutException, It never returns null.

So if your using ExpectedConditions.elementToBeClickable to find an element which will always gives you the clickable element, so no need to check for null condition, you should try as below :-

WebDriverWait wait = new WebDriverWait(Scenario1Test.driver, 10); 
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath("(//div[@id='brandSlider']/div[1]/div/div/div/img)[50]")));
element.click();

As you are saying element.click() passes both on link and label that's doesn't mean element is not clickable, it means returned element clicked but may be there is no event performs on element by click action.

Note:- I'm suggesting you always try first to find elements by id, name, className and other locator. if you faced some difficulty to find then use cssSelector and always give last priority to xpath locator because it is slower than other locator to locate an element.

Hope it helps you..:)

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Can I pass parameters by reference in Java?

Java is confusing because everything is passed by value. However for a parameter of reference type (i.e. not a parameter of primitive type) it is the reference itself which is passed by value, hence it appears to be pass-by-reference (and people often claim that it is). This is not the case, as shown by the following:

Object o = "Hello";
mutate(o)
System.out.println(o);

private void mutate(Object o) { o = "Goodbye"; } //NOT THE SAME o!

Will print Hello to the console. The options if you wanted the above code to print Goodbye are to use an explicit reference as follows:

AtomicReference<Object> ref = new AtomicReference<Object>("Hello");
mutate(ref);
System.out.println(ref.get()); //Goodbye!

private void mutate(AtomicReference<Object> ref) { ref.set("Goodbye"); }

jQuery Ajax calls and the Html.AntiForgeryToken()

I feel like an advanced necromancer here, but this is still an issue 4 years later in MVC5.

To handle ajax requests properly the anti-forgery token needs to be passed to the server on ajax calls. Integrating it into your post data and models is messy and unnecessary. Adding the token as a custom header is clean and reusable - and you can configure it so you don't have to remember to do it every time.

There is an exception - Unobtrusive ajax does not need special treatment for ajax calls. The token is passed as usual in the regular hidden input field. Exactly the same as a regular POST.

_Layout.cshtml

In _layout.cshtml I have this JavaScript block. It doesn't write the token into the DOM, rather it uses jQuery to extract it from the hidden input literal that the MVC Helper generates. The Magic string that is the header name is defined as a constant in the attribute class.

<script type="text/javascript">
    $(document).ready(function () {
        var isAbsoluteURI = new RegExp('^(?:[a-z]+:)?//', 'i');
        //http://stackoverflow.com/questions/10687099/how-to-test-if-a-url-string-is-absolute-or-relative

        $.ajaxSetup({
            beforeSend: function (xhr) {
                if (!isAbsoluteURI.test(this.url)) {
                    //only add header to relative URLs
                    xhr.setRequestHeader(
                       '@.ValidateAntiForgeryTokenOnAllPosts.HTTP_HEADER_NAME', 
                       $('@Html.AntiForgeryToken()').val()
                    );
                }
            }
        });
    });
</script>

Note the use of single quotes in the beforeSend function - the input element that is rendered uses double quotes that would break the JavaScript literal.

Client JavaScript

When this executes the beforeSend function above is called and the AntiForgeryToken is automatically added to the request headers.

$.ajax({
  type: "POST",
  url: "CSRFProtectedMethod",
  dataType: "json",
  contentType: "application/json; charset=utf-8",
  success: function (data) {
    //victory
  }
});

Server Library

A custom attribute is required to process the non standard token. This builds on @viggity's solution, but handles unobtrusive ajax correctly. This code can be tucked away in your common library

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class ValidateAntiForgeryTokenOnAllPosts : AuthorizeAttribute
{
    public const string HTTP_HEADER_NAME = "x-RequestVerificationToken";

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        var request = filterContext.HttpContext.Request;

        //  Only validate POSTs
        if (request.HttpMethod == WebRequestMethods.Http.Post)
        {

            var headerTokenValue = request.Headers[HTTP_HEADER_NAME];

            // Ajax POSTs using jquery have a header set that defines the token.
            // However using unobtrusive ajax the token is still submitted normally in the form.
            // if the header is present then use it, else fall back to processing the form like normal
            if (headerTokenValue != null)
            {
                var antiForgeryCookie = request.Cookies[AntiForgeryConfig.CookieName];

                var cookieValue = antiForgeryCookie != null
                    ? antiForgeryCookie.Value
                    : null;

                AntiForgery.Validate(cookieValue, headerTokenValue);
            }
            else
            {
                new ValidateAntiForgeryTokenAttribute()
                    .OnAuthorization(filterContext);
            }
        }
    }
}

Server / Controller

Now you just apply the attribute to your Action. Even better you can apply the attribute to your controller and all requests will be validated.

[HttpPost]
[ValidateAntiForgeryTokenOnAllPosts]
public virtual ActionResult CSRFProtectedMethod()
{
  return Json(true, JsonRequestBehavior.DenyGet);
}

Java FileOutputStream Create File if not exists

You can potentially get a FileNotFoundException if the file does not exist.

Java documentation says:

Whether or not a file is available or may be created depends upon the underlying platform http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

If you're using Java 7 you can use the java.nio package:

The options parameter specifies how the the file is created or opened... it opens the file for writing, creating the file if it doesn't exist...

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

Why does my Spring Boot App always shutdown immediately after starting?

this work with spring boot 2.0.0

replace

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
        </dependency>

with

<dependency>
<groupId>org.apache.tomcat.embed</groupId>
<artifactId>tomcat-embed-core</artifactId>
<version>9.0.6</version>
    </dependency>

Centering Bootstrap input fields

The best way for centering your element it is using .center-block helper class. But must your bootstrap version not less than 3.1.1

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha/css/bootstrap.css" rel="stylesheet" />_x000D_
<div class="row">_x000D_
  <div class="col-lg-3 center-block">_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control">_x000D_
      <span class="input-group-btn">_x000D_
             <button class="btn btn-default" type="button">Go!</button>_x000D_
         </span>_x000D_
    </div>_x000D_
    <!-- /input-group -->_x000D_
  </div>_x000D_
  <!-- /.col-lg-6 -->_x000D_
</div>_x000D_
<!-- /.row -->
_x000D_
_x000D_
_x000D_

How can I change from SQL Server Windows mode to mixed mode (SQL Server 2008)?

If the problem is that you don't have access to SQL Server and now you are using mixed mode to enable sa or grant an account admin privileges, then it is far easier just to uninstall SQL Server and reinstall.

How to get the file path from HTML input form in Firefox 3

For preview in Firefox works this - attachment is object of attachment element in first example:

           if (attachment.files)
             previewImage.src = attachment.files.item(0).getAsDataURL();
           else
             previewImage.src = attachment.value;

TensorFlow: "Attempting to use uninitialized value" in variable initialization

run both:

sess.run(tf.global_variables_initializer())

sess.run(tf.local_variables_initializer())

Execute CMD command from code

How about you creat a batch file with the command you want, and call it with Process.Start

dir.bat content:

dir

then call:

Process.Start("dir.bat");

Will call the bat file and execute the dir

How to monitor network calls made from iOS Simulator

You can also use this open source library called Wormholy (and made by me).

You just need to integrate it in your project (no code needed), and that's it, you will be able to monitor all the API requests of your app, also on a real device.

And you don't need to manage certificates like with Charles. It all works by magic!

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

/**
 * If $header is an array of headers
 * It will format and return the correct $header
 * $header = [
 *  'Accept' => 'application/json',
 *  'Content-Type' => 'application/x-www-form-urlencoded'
 * ];
 */
$i_header = $header;
if(is_array($i_header) === true){
    $header = [];
    foreach ($i_header as $param => $value) {
        $header[] = "$param: $value";
    }
}

Hiding the R code in Rmarkdown/knit and just showing the results

Sure, just do

```{r someVar, echo=FALSE}
someVariable
```

to show some (previously computed) variable someVariable. Or run code that prints etc pp.

So for plotting, I have eg

### Impact of choice of ....
```{r somePlot, echo=FALSE}
plotResults(Res, Grid, "some text", "some more text")
```

where the plotting function plotResults is from a local package.

What design patterns are used in Spring framework?

There are loads of different design patterns used, but there are a few obvious ones:

  • Proxy - used heavily in AOP, and remoting.

  • Singleton - beans defined in spring config files are singletons by default.

  • Template method - used extensively to deal with boilerplate repeated code (such as closing connections cleanly, etc..). For example JdbcTemplate, JmsTemplate, JpaTemplate.


Update following comments: For MVC, you might want to read the MVC Reference

Some obvious patterns in use in MVC:

  • Model View Controller :-) . The advantage with Spring MVC is that your controllers are POJOs as opposed to being servlets. This makes for easier testing of controllers. One thing to note is that the controller is only required to return a logical view name, and the view selection is left to a separate ViewResolver. This makes it easier to reuse controllers for different view technologies.

  • Front Controller. Spring provides DispatcherServlet to ensure an incoming request gets dispatched to your controllers.

  • View Helper - Spring has a number of custom JSP tags, and velocity macros, to assist in separating code from presentation in views.

How can I get the last 7 characters of a PHP string?

For simplicity, if you do not want send a message, try this

$new_string = substr( $dynamicstring, -min( strlen( $dynamicstring ), 7 ) );

Should I make HTML Anchors with 'name' or 'id'?

I have to say if you are going to be linking to that area in the page... such as page.html#foo and Foo Title isn't a link you should be using:

<h1 id="foo">Foo Title</h1>

If you instead put an <a> reference around it your headline will be influenced by an <a> specific CSS within your site. It's just extra markup, and you shouldn't need it. I'd highly recommend placing an id on the headline, not only is it better formed, but it will allow you to either address that object in Javascript or CSS.

Forwarding port 80 to 8080 using NGINX

Simple is:

server {
    listen   80;
    server_name  p3000;
    location / {
        proxy_pass http://0.0.0.0:3000;
        include /etc/nginx/proxy_params;
    }
}

Python: Number of rows affected by cursor.execute("SELECT ...)

The number of rows effected is returned from execute:

rows_affected=cursor.execute("SELECT ... ")

of course, as AndiDog already mentioned, you can get the row count by accessing the rowcount property of the cursor at any time to get the count for the last execute:

cursor.execute("SELECT ... ")
rows_affected=cursor.rowcount

From the inline documentation of python MySQLdb:

 def execute(self, query, args=None):

    """Execute a query.

    query -- string, query to execute on server
    args -- optional sequence or mapping, parameters to use with query.

    Note: If args is a sequence, then %s must be used as the
    parameter placeholder in the query. If a mapping is used,
    %(key)s must be used as the placeholder.

    Returns long integer rows affected, if any

    """

How to edit binary file on Unix systems

For small changes, I have used hexedit:

http://rigaux.org/hexedit.html

Simple but fast and useful.

How to remove all the null elements inside a generic list in one go?

I do not know of any in-built method, but you could just use linq:

parameterList = parameterList.Where(x => x != null).ToList();

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You can use:

window.location.href = '/Branch/Details/' + id;

But your Ajax code is incomplete without success or error functions.

How to add title to seaborn boxplot

Try adding this at the end of your code:

import matplotlib.pyplot as plt

plt.title('add title here')

JUnit Testing private variables?

Despite the danger of stating the obvious: With a unit test you want to test the correct behaviour of the object - and this is defined in terms of its public interface. You are not interested in how the object accomplishes this task - this is an implementation detail and not visible to the outside. This is one of the things why OO was invented: That implementation details are hidden. So there is no point in testing private members. You said you need 100% coverage. If there is a piece of code that cannot be tested by using the public interface of the object, then this piece of code is actually never called and hence not testable. Remove it.

Turning off some legends in a ggplot

You can simply add show.legend=FALSE to geom to suppress the corresponding legend

How to create the pom.xml for a Java project with Eclipse

This works for me on Mac:

Right click on the project, select Configure ? Convert to Maven Project.

When to use static methods

No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.

Error - replacement has [x] rows, data has [y]

TL;DR ...and late to the party, but that short explanation might help future googlers..

In general that error message means that the replacement doesn't fit into the corresponding column of the dataframe.

A minimal example:

df <- data.frame(a = 1:2); df$a <- 1:3

throws the error

Error in $<-.data.frame(*tmp*, a, value = 1:3) : replacement has 3 rows, data has 2

which is clear, because the vector a of df has 2 entries (rows) whilst the vector we try to replace it has 3 entries (rows).

disable all form elements inside div

Following will disable all the input but will not able it to btn class and also added class to overwrite disable css.

$('#EditForm :input').not('.btn').attr("disabled", true).addClass('disabledClass');

css class

.disabledClass{
  background-color: rgb(235, 235, 228) !important;
}

How to configure PostgreSQL to accept all incoming connections

Addition to above great answers, if you want some range of IPs to be authorized, you could edit /var/lib/pgsql/{VERSION}/data file and put something like

host all all 172.0.0.0/8 trust

It will accept incoming connections from any host of the above range. Source: http://www.linuxtopia.org/online_books/database_guides/Practical_PostgreSQL_database/c15679_002.htm

PIG how to count a number of rows in alias

Arnon Rotem-Gal-Oz already answered this question a while ago, but I thought some may like this slightly more concise version.

LOGS = LOAD 'log';
LOG_COUNT = FOREACH (GROUP LOGS ALL) GENERATE COUNT(LOGS);

Does C have a "foreach" loop construct?

C has 'for' and 'while' keywords. If a foreach statement in a language like C# looks like this ...

foreach (Element element in collection)
{
}

... then the equivalent of this foreach statement in C might be be like:

for (
    Element* element = GetFirstElement(&collection);
    element != 0;
    element = GetNextElement(&collection, element)
    )
{
    //TODO: do something with this element instance ...
}

libpng warning: iCCP: known incorrect sRGB profile

To add to Glenn's great answer, here's what I did to find which files were faulty:

find . -name "*.png" -type f -print0 | xargs \
       -0 pngcrush_1_8_8_w64.exe -n -q > pngError.txt 2>&1

I used the find and xargs because pngcrush could not handle lots of arguments (which were returned by **/*.png). The -print0 and -0 is required to handle file names containing spaces.

Then search in the output for these lines: iCCP: Not recognizing known sRGB profile that has been edited.

./Installer/Images/installer_background.png:    
Total length of data found in critical chunks            =     11286  
pngcrush: iCCP: Not recognizing known sRGB profile that has been edited

And for each of those, run mogrify on it to fix them.

mogrify ./Installer/Images/installer_background.png

Doing this prevents having a commit changing every single png file in the repository when only a few have actually been modified. Plus it has the advantage to show exactly which files were faulty.

I tested this on Windows with a Cygwin console and a zsh shell. Thanks again to Glenn who put most of the above, I'm just adding an answer as it's usually easier to find than comments :)

Exporting data In SQL Server as INSERT INTO

Here is an example of creating a data migration script using a cursor to iterate the source table.

SET NOCOUNT ON;  
DECLARE @out nvarchar(max) = ''
DECLARE @row nvarchar(1024)
DECLARE @first int = 1

DECLARE cur CURSOR FOR 
    SELECT '(' + CONVERT(CHAR(1),[Stage]) + ',''' + [Label] + ''')'
    FROM CV_ORDER_STATUS
    ORDER BY [Stage]

PRINT 'SET IDENTITY_INSERT dbo.CV_ORDER_STATUS ON'
PRINT 'GO'

PRINT 'INSERT INTO dbo.CV_ORDER_STATUS ([Stage],[Label]) VALUES';

OPEN cur
FETCH NEXT FROM cur
    INTO @row

WHILE @@FETCH_STATUS = 0
BEGIN
    IF @first = 1
        SET @first = 0
    ELSE
        SET @out = @out + ',' + CHAR(13);

    SET @out = @out + @row

    FETCH NEXT FROM cur into @row
END

CLOSE cur
DEALLOCATE cur

PRINT @out

PRINT 'SET IDENTITY_INSERT dbo.CV_ORDER_STATUS OFF'
PRINT 'GO'

How do I check if a column is empty or null in MySQL?

You can also do

SELECT * FROM table WHERE column_name LIKE ''

The inverse being

SELECT * FROM table WHERE column_name NOT LIKE ''