Programs & Examples On #Program transformation

A program transformation is (a usually mechanical) process to modify one program to produce another.

Aren't Python strings immutable? Then why does a + " " + b work?

Python strings are immutable. However, a is not a string: it is a variable with a string value. You can't mutate the string, but can change what value of the variable to a new string.

Fastest way to check a string contain another substring in JavaScript?

For finding a simple string, using the indexOf() method and using regex is pretty much the same: http://jsperf.com/substring - so choose which ever one that seems easier to write.

Creating a list/array in excel using VBA to get a list of unique names in a column

You can try my suggestion for a work around in Doug's approach.
But if you want to stick with your logic though, you can try this:

Option Explicit

Sub GetUnique()

Dim rng As Range
Dim myarray, myunique
Dim i As Integer

ReDim myunique(1)

With ThisWorkbook.Sheets("Sheet1")
    Set rng = .Range(.Range("A1"), .Range("A" & .Rows.Count).End(xlUp))
    myarray = Application.Transpose(rng)
    For i = LBound(myarray) To UBound(myarray)
        If IsError(Application.Match(myarray(i), myunique, 0)) Then
            myunique(UBound(myunique)) = myarray(i)
            ReDim Preserve myunique(UBound(myunique) + 1)
        End If
    Next
End With

For i = LBound(myunique) To UBound(myunique)
    Debug.Print myunique(i)
Next

End Sub

This uses array instead of range.
It also uses Match function instead of a nested For Loop.
I didn't have the time to check the time difference though.
So I leave the testing to you.

Spring boot Security Disable security

The only thing that worked for me:

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().anyRequest().permitAll();
    }

and

security.ignored=/**

Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.

How to import a module given its name as string?

You can use exec:

exec("import myapp.commands.%s" % command)

Pandas: Looking up the list of sheets in an excel file

If you:

  • care about performance
  • don't need the data in the file at execution time.
  • want to go with conventional libraries vs rolling your own solution

Below was benchmarked on a ~10Mb xlsx, xlsb file.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

Benchmarks: ~ 14x speed improvement

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

Benchmarks: ~ 56x speed improvement

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Notes:

Artificially create a connection timeout error

You might install Microsoft Loopback driver that will create a separate interface for you. Then you can connect on it to some service of yours (your own host). Then in Network Connections you can disable/enable such interface...

Prevent any form of page refresh using jQuery/Javascript

Number (2) is possible by using a socket implementation (like websocket, socket.io, etc.) with a custom heartbeat for each session the user is engaged in. If a user attempts to open another window, you have a javascript handler check with the server if it's ok, and then respond with an error messages.

However, a better solution is to synchronize the two sessions if possible like in google docs.

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

PHP Excel Header

You are giving multiple Content-Type headers. application/vnd.ms-excel is enough.

And there are couple of syntax error too. To statement termination with ; on the echo statement and wrong filename extension.

header("Content-Type:   application/vnd.ms-excel; charset=utf-8");
header("Content-Disposition: attachment; filename=abc.xls");  //File name extension was wrong
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
echo "Some Text"; //no ending ; here

How to convert int to char with leading zeros?

Not very elegant, but I add a set value with the same number of leading zeroes I desire to the numeric I want to convert, and use RIGHT function.

Example:

SELECT RIGHT(CONVERT(CHAR(7),1000000 + @number2),6)

Result: '000867'

Gerrit error when Change-Id in commit messages are missing

I got this error message too.

and what makes me think it is useful to give an answer here is that the answer from @Rafal Rawicki is a good solution in some cases but not for all circumstances. example that i met:

1.run "git log" we can get the HEAD commit change-id

2.we also can get a 'HEAD' commit change-id on Gerrit website.

3.they are different ,which makes us can not push successfully and get the "missing change-id error"

solution:

0.'git add .'

1.save your HEAD commit change-id got from 'git log',it will be used later.

2.copy the HEAD commit change-id from Gerrit website.

3.'git reset HEAD'

4.'git commit --amend' and copy the change-id from **Gerrit website** to the commit message in the last paragraph(replace previous change-id)

5.'git push *' you can push successfully now but can not find the HEAD commit from **git log** on Gerrit website too

6.'git reset HEAD'

7.'git commit --amend' and copy the change-id from **git log**(we saved in step 1) to the commit message in the last paragraph(replace previous change-id)

8.'git push *' you can find the HEAD commit from **git log** on Gerrit website,they have the same change-id

9.done

How to get max value of a column using Entity Framework?

maxAge = Persons.Max(c => c.age)

or something along those lines.

Adding Apostrophe in every field in particular column for excel

The way I'd do this is:

  • In Cell L2, enter the formula ="'"&K2
  • Use the fill handle or Ctrl+D to fill it down to the length of Column K's values.
  • Select the whole of Column L's values and copy them to the clipboard
  • Select the same range in Column K, right-click to select 'Paste Special' and choose 'Values'

How to solve "Unresolved inclusion: <iostream>" in a C++ file in Eclipse CDT?

For those using a fresh install of Ubuntu, or another Linux distro, make sure your have at least the package "build-essential" before you try to compile Eclipse CDT projects.

At Terminal, type:

sudo apt-get install build-essential

It should be enough to compile and run your apps.

Of course, you can also perform full g++ install, using:

sudo apt-get install g++

Add a default value to a column through a migration

change_column_default :employees, :foreign, false

Maximum packet size for a TCP connection

At the application level, the application uses TCP as a stream oriented protocol. TCP in turn has segments and abstracts away the details of working with unreliable IP packets.

TCP deals with segments instead of packets. Each TCP segment has a sequence number which is contained inside a TCP header. The actual data sent in a TCP segment is variable.

There is a value for getsockopt that is supported on some OS that you can use called TCP_MAXSEG which retrieves the maximum TCP segment size (MSS). It is not supported on all OS though.

I'm not sure exactly what you're trying to do but if you want to reduce the buffer size that's used you could also look into: SO_SNDBUF and SO_RCVBUF.

Filezilla FTP Server Fails to Retrieve Directory Listing

It worked for me:

General -> Encryption -> Only use plain FTP

Transfer settings -> Transfer Mode -> Active

Consider that it is very insecure, and must be used only for testing.

What is the perfect counterpart in Python for "while not EOF"

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

line = obj.readlines()

How can I get (query string) parameters from the URL in Next.js?

url prop is deprecated as of Next.js version 6: https://github.com/zeit/next.js/blob/master/errors/url-deprecated.md

To get the query parameters, use getInitialProps:

For stateless components

import Link from 'next/link'
const About = ({query}) => (
  <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>
)

About.getInitialProps = ({query}) => {
  return {query}
}

export default About;

For regular components

class About extends React.Component {

  static getInitialProps({query}) {
    return {query}
  }

  render() {
    console.log(this.props.query) // The query is available in the props object
    return <div>Click <Link href={{ pathname: 'about', query: { name: 'leangchhean' }}}><a>here</a></Link> to read more</div>

  }
}

The query object will be like: url.com?a=1&b=2&c=3 becomes: {a:1, b:2, c:3}

Is there a Google Sheets formula to put the name of the sheet into a cell?

An old thread, but a useful one... so here's some additional code.

First, in response to Craig's point about the regex being overly greedy and failing for sheet names containing a single quote, this should do the trick (replace 'SHEETNAME'!A1 with your own sheet & cell reference):

=IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), "")

It uses a lazy match (the ".+?") to find a character string (squotes included) that may or may not be enclosed by squotes but is definitely terminated by bang dollar ("!$") followed by any number of characters. Google Sheets actually protects squotes within a sheet name by appending another squote (as in ''), so the SUBSTITUTE is needed to reduce these back to single squotes.

The formula also allows for sheet names that contain bangs ("!"), but will fail for names using bang dollars ("!$") - if you really need to make your sheet names to look like full absolute cell references then put a separating character between the bang and the dollar (such as a space).

Note that it will only work correctly when pointed at a different sheet from the one that the formula resides! This is because CELL("address" returns just the cell reference (not the sheet name) when used on the same sheet. If you need a sheet to show its own name then put the formula in a cell on another sheet, point it at your target sheet, and then reference the formula cell from the target sheet. I often have a "Meta" sheet in my workbooks to hold settings, common values, database matching criteria, etc so that's also where I put this formula.

As others have said many times above, Google Sheets will only notice changes to the sheet name if you set the workbook's recalculation to "On change and every minute" which you can find on the File|Settings|Calculation menu. It can take up to a whole minute for the change to be picked up.


Secondly, if like me you happen to need an inter-operable formula that works on both Google Sheets and Excel (which for older versions at least doesn't have the REGEXREPLACE function), try:

=IF(IFERROR(INFO("release"), 0)=0, IF(TODAY()=TODAY(), SUBSTITUTE(REGEXREPLACE(CELL("address",'SHEETNAME'!A1),"'?(.+?)'?!\$.*","$1"),"''","'", ""), ""), MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255))

This uses INFO("release") to determine which platform we are on... Excel returns a number >0 whereas Google Sheets does not implement the INFO function and generates an error which the formula traps into a 0 and uses for numerical comparison. The Google code branch is as above.

For clarity and completeness, this is the Excel-only version (which does correctly return the name of the sheet it resides on):

=MID(CELL("filename",'SHEETNAME'!A1),FIND("]",CELL("filename",'SHEETNAME'!A1))+1,255)

It looks for the "]" filename terminator in the output of CELL("filename" and extracts the sheet name from the remaining part of the string using the MID function. Excel doesn't allow sheet names to contain "]" so this works for all possible sheet names. In the inter-operable version, Excel is happy to be fed a call to the non-existent REGEXREPLACE function because it never gets to execute the Google code branch.

Can I create links with 'target="_blank"' in Markdown?

With Markdown-2.5.2, you can use this:

[link](url){:target="_blank"}

deleting rows in numpy array

The simplest way to delete rows and columns from arrays is the numpy.delete method.

Suppose I have the following array x:

x = array([[1,2,3],
        [4,5,6],
        [7,8,9]])

To delete the first row, do this:

x = numpy.delete(x, (0), axis=0)

To delete the third column, do this:

x = numpy.delete(x,(2), axis=1)

So you could find the indices of the rows which have a 0 in them, put them in a list or a tuple and pass this as the second argument of the function.

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space

There is a another best/effective way to solve this error,

for example, let's take a loop which counts till 10 thousand, here you may get the error Out of memory, do to solve it you can give the computer time to recover.

So, you can sleep for 400-500ms before you're loop counts the next number :

new Thread(new Runnable() {
            public void run() {
                try {
                    sleep(550); // 550 ms (milli seconds)
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

By doing this, will make you're program slower but you don't get any error till the heap space is full again, so by waiting some ms, you can prevent that error.

You can apply this method other than loop.

Hope it helped you, :D

How do I change the IntelliJ IDEA default JDK?

One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.

<build>
<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>2.3.2</version>
        <configuration>
            <source>1.8</source>
            <target>1.8</target>
            <encoding>UTF-8</encoding>
        </configuration>
    </plugin>
</plugins>
</build>

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

How to pass a value from one jsp to another jsp page?

Using Query parameter

<a href="edit.jsp?userId=${user.id}" />  

Using Hidden variable .

<form method="post" action="update.jsp">  
...  
   <input type="hidden" name="userId" value="${user.id}">  

you can send Using Session object.

   session.setAttribute("userId", userid);

These values will now be available from any jsp as long as your session is still active.

   int userid = session.getAttribute("userId"); 

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This error occurs when you are sending JSON data to server. Maybe in your string you are trying to add new line character by using /n.

If you add / before /n, it should work, you need to escape new line character.

"Hello there //n start coding"

The result should be as following

Hello there
start coding

How to set top position using jquery

And with Prototype:

$('yourDivId').setStyle({top: '100px', left:'80px'});

What are examples of TCP and UDP in real life?

  • TCP: will get there in meaningful order
  • UDP: god knows (maybe)

SVN icon overlays not showing properly

Tortoise SVN on Windows happens to lose sync quite often with the real file status. In that case try doing an svn cleanup.

Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.

Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types

Using env variable in Spring Boot's application.properties

This is in response to a number of comments as my reputation isn't high enough to comment directly.

You can specify the profile at runtime as long as the application context has not yet been loaded.

// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.

System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");

dropdownlist set selected value in MVC3 Razor

just in case someone comes with this question, this is how I do it, please forget about the repository object, I'm using the Repository Pattern, you can use your object context to retrieve the entities. And also don't pay attention to my entity names, my entity type Action has nothing to do with an MVC Action.

Controller:

ViewBag.ActionStatusId = new SelectList(repository.GetAll<ActionStatus>(), "ActionStatusId", "Name", myAction.ActionStatusId);

Pay attention that the last variable of the SelectList constructor is the selected value (object selectedValue)

Then this is my view to render it:

<div class="editor-label">
   @Html.LabelFor(model => model.ActionStatusId, "ActionStatus")
</div>
<div class="editor-field">
   @Html.DropDownList("ActionStatusId")
   @Html.ValidationMessageFor(model => model.ActionStatusId)
</div> 

I think it is pretty simple, I hope this helps! :)

Maximum number of threads in a .NET app?

i did a test on a 64bit system with c# console, the exception is type of out of memory, using 2949 threads.

I realize we should be using threading pool, which I do, but this answer is in response to the main question ;)

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

How can I convert ticks to a date format?

A DateTime object can be constructed with a specific value of ticks. Once you have determined the ticks value, you can do the following:

DateTime myDate = new DateTime(numberOfTicks);
String test = myDate.ToString("MMMM dd, yyyy");

Convert boolean result into number/integer

Imho the best solution is:

fooBar | 0

This is used in asm.js to force integer type.

Simple PowerShell LastWriteTime compare

Slightly easier - use the new-timespan cmdlet, which creates a time interval from the current time.

ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1}

shows all files not written to today.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

Get latest from Git branch

Although git pull origin yourbranch works, it's not really a good idea

You can alternatively do the following:

git fetch origin
git merge origin/yourbranch

The first line fetches all the branches from origin, but doesn't merge with your branches. This simply completes your copy of the repository.

The second line merges your current branch with that of yourbranch that you fetched from origin (which is one of your remotes).

This is assuming origin points to the repository at address ssh://11.21.3.12:23211/dir1/dir2

How can I select the first day of a month in SQL?

If you are looking at this today, and using SQL server 2012 or newer you have the EOMONTH function which makes things easier:

SELECT DATEADD(day, 1, EOMONTH(DATEADD(month, -1, GETDATE()))) as firstdateofmonth

You can change GETDATE() with whatever date variable you want.

How can I convert a char to int in Java?

I you have the char '9', it will store its ASCII code, so to get the int value, you have 2 ways

char x = '9';
int y = Character.getNumericValue(x);   //use a existing function
System.out.println(y + " " + (y + 1));  // 9  10

or

char x = '9';
int y = x - '0';                        // substract '0' code to get the difference
System.out.println(y + " " + (y + 1));  // 9  10

And it fact, this works also :

char x = 9;
System.out.println(">" + x + "<");     //>  < prints a horizontal tab
int y = (int) x;
System.out.println(y + " " + (y + 1)); //9 10

You store the 9 code, which corresponds to a horizontal tab (you can see when print as String, bu you can also use it as int as you see above

Git: How do I list only local branches?

Here's how to list local branches that do not have a remote branch in origin with the same name:

git branch | sed 's|* |  |' | sort > local
git branch -r | sed 's|origin/||' | sort > remote
comm -23 local remote

How do I login and authenticate to Postgresql after a fresh install?

by default you would need to use the postgres user:

sudo -u postgres psql postgres

Number of processors/cores in command line

The lscpu(1) command provided by the util-linux project might also be useful:

$ lscpu
Architecture:          x86_64
CPU op-mode(s):        32-bit, 64-bit
Byte Order:            Little Endian
CPU(s):                4
On-line CPU(s) list:   0-3
Thread(s) per core:    2
Core(s) per socket:    2
Socket(s):             1
NUMA node(s):          1
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 58
Model name:            Intel(R) Core(TM) i7-3520M CPU @ 2.90GHz
Stepping:              9
CPU MHz:               3406.253
CPU max MHz:           3600.0000
CPU min MHz:           1200.0000
BogoMIPS:              5787.10
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              256K
L3 cache:              4096K
NUMA node0 CPU(s):     0-3

Reload an iframe with jQuery

If you are cross-domain, simply setting the src back to the same url will not always trigger a reload, even if the location hash changes.

Ran into this problem while manually constructing Twitter button iframes, which wouldn't refresh when I updated the urls.

Twitter like buttons have the form: .../tweet_button.html#&_version=2&count=none&etc=...

Since Twitter uses the document fragment for the url, changing the hash/fragment didn't reload the source, and the button targets didn't reflect my new ajax-loaded content.

You can append a query string parameter for force the reload (eg: "?_=" + Math.random() but that will waste bandwidth, especially in this example where Twitter's approach was specifically trying to enable caching.

To reload something which only changes with hash tags, you need to remove the element, or change the src, wait for the thread to exit, then assign it back. If the page is still cached, this shouldn't require a network hit, but does trigger the frame reload.

 var old = iframe.src;
 iframe.src = '';
 setTimeout( function () {
    iframe.src = old;
 }, 0);

Update: Using this approach creates unwanted history items. Instead, remove and recreate the iframe element each time, which keeps this back() button working as expected. Also nice not to have the timer.

bash, extract string before a colon

cut -d: -f1

or

awk -F: '{print $1}'

or

sed 's/:.*//'

C programming: Dereferencing pointer to incomplete type error

You are using the pointer newFile without allocating space for it.

struct stasher_file *newFile = malloc(sizeof(stasher_file));

Also you should put the struct name at the top. Where you specified stasher_file is to create an instance of that struct.

struct stasher_file {
    char name[32];
    int  size;
    int  start;
    int  popularity;
};

Can't specify the 'async' modifier on the 'Main' method of a console app

As you discovered, in VS11 the compiler will disallow an async Main method. This was allowed (but never recommended) in VS2010 with the Async CTP.

I have recent blog posts about async/await and asynchronous console programs in particular. Here's some background info from the intro post:

If "await" sees that the awaitable has not completed, then it acts asynchronously. It tells the awaitable to run the remainder of the method when it completes, and then returns from the async method. Await will also capture the current context when it passes the remainder of the method to the awaitable.

Later on, when the awaitable completes, it will execute the remainder of the async method (within the captured context).

Here's why this is a problem in Console programs with an async Main:

Remember from our intro post that an async method will return to its caller before it is complete. This works perfectly in UI applications (the method just returns to the UI event loop) and ASP.NET applications (the method returns off the thread but keeps the request alive). It doesn't work out so well for Console programs: Main returns to the OS - so your program exits.

One solution is to provide your own context - a "main loop" for your console program that is async-compatible.

If you have a machine with the Async CTP, you can use GeneralThreadAffineContext from My Documents\Microsoft Visual Studio Async CTP\Samples(C# Testing) Unit Testing\AsyncTestUtilities. Alternatively, you can use AsyncContext from my Nito.AsyncEx NuGet package.

Here's an example using AsyncContext; GeneralThreadAffineContext has almost identical usage:

using Nito.AsyncEx;
class Program
{
    static void Main(string[] args)
    {
        AsyncContext.Run(() => MainAsync(args));
    }

    static async void MainAsync(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

Alternatively, you can just block the main Console thread until your asynchronous work has completed:

class Program
{
    static void Main(string[] args)
    {
        MainAsync(args).GetAwaiter().GetResult();
    }

    static async Task MainAsync(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

Note the use of GetAwaiter().GetResult(); this avoids the AggregateException wrapping that happens if you use Wait() or Result.

Update, 2017-11-30: As of Visual Studio 2017 Update 3 (15.3), the language now supports an async Main - as long as it returns Task or Task<T>. So you can now do this:

class Program
{
    static async Task Main(string[] args)
    {
        Bootstrapper bs = new Bootstrapper();
        var list = await bs.GetList();
    }
}

The semantics appear to be the same as the GetAwaiter().GetResult() style of blocking the main thread. However, there's no language spec for C# 7.1 yet, so this is only an assumption.

Dynamically set value of a file input

It is not possible to dynamically change the value of a file field, otherwise you could set it to "c:\yourfile" and steal files very easily.

However there are many solutions to a multi-upload system. I'm guessing that you're wanting to have a multi-select open dialog.

Perhaps have a look at http://www.plupload.com/ - it's a very flexible solution to multiple file uploads, and supports drop zones e.t.c.

MySQL "ERROR 1005 (HY000): Can't create table 'foo.#sql-12c_4' (errno: 150)"

Also both the tables need to have same character set.

for e.g.

CREATE TABLE1 (
  FIELD1 VARCHAR(100) NOT NULL PRIMARY KEY,
  FIELD2 VARCHAR(100) NOT NULL
)ENGINE=INNODB CHARACTER SET utf8 COLLATE utf8_bin;

to

CREATE TABLE2 (
  Field3 varchar(64) NOT NULL PRIMARY KEY,
  Field4 varchar(64) NOT NULL,
  CONSTRAINT FORIGEN KEY (Field3) REFERENCES TABLE1(FIELD1)
) ENGINE=InnoDB;

Will fail because they have different charsets. This is another subtle failure where mysql returns same error.

What is the difference between an int and a long in C++?

When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.

GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.

MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.

Equivalent of "continue" in Ruby

Use next, it will bypass that condition and rest of the code will work. Below i have provided the Full script and out put

class TestBreak
  puts " Enter the nmber"
  no= gets.to_i
  for i in 1..no
    if(i==5)
      next
    else 
      puts i
    end
  end
end

obj=TestBreak.new()

Output: Enter the nmber 10

1 2 3 4 6 7 8 9 10

Remove CSS class from element with JavaScript (no jQuery)

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

React component initialize state from props

you could use key value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled read this https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key

How can I view the contents of an ElasticSearch index?

If you didn't index too much data into the index yet, you can use term facet query on the field that you would like to debug to see the tokens and their frequencies:

curl -XDELETE 'http://localhost:9200/test-idx'
echo
curl -XPUT 'http://localhost:9200/test-idx' -d '
{
    "settings": {
        "index.number_of_shards" : 1,
        "index.number_of_replicas": 0
    },
    "mappings": {            
        "doc": {
            "properties": {
                "message": {"type": "string", "analyzer": "snowball"}
            }
        }
    }

}'
echo
curl -XPUT 'http://localhost:9200/test-idx/doc/1' -d '
{
  "message": "How is this going to be indexed?"
}
'
echo
curl -XPOST 'http://localhost:9200/test-idx/_refresh'
echo
curl -XGET 'http://localhost:9200/test-idx/doc/_search?pretty=true&search_type=count' -d '{
    "query": {
        "match": {
            "_id": "1"
        }
    },
    "facets": {
        "tokens": {
            "terms": {
                "field": "message"
            }
        }
    }
}
'
echo

How to add Active Directory user group as login in SQL Server

You can use T-SQL:

use master
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName

I use this as a part of restore from production server to testing machine:

USE master
GO
ALTER DATABASE yourDbName SET OFFLINE WITH ROLLBACK IMMEDIATE
RESTORE DATABASE yourDbName FROM DISK = 'd:\DropBox\backup\myDB.bak'
ALTER DATABASE yourDbName SET ONLINE
GO
CREATE LOGIN [NT AUTHORITY\LOCALSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO
CREATE LOGIN [NT AUTHORITY\NETWORKSERVICE] FROM WINDOWS WITH
DEFAULT_DATABASE=yourDbName
GO

You will need to use localized name of services in case of German or French Windows, see How to create a SQL Server login for a service account on a non-English Windows?

JWT refresh token flow

Assuming that this is about OAuth 2.0 since it is about JWTs and refresh tokens...:

  1. just like an access token, in principle a refresh token can be anything including all of the options you describe; a JWT could be used when the Authorization Server wants to be stateless or wants to enforce some sort of "proof-of-possession" semantics on to the client presenting it; note that a refresh token differs from an access token in that it is not presented to a Resource Server but only to the Authorization Server that issued it in the first place, so the self-contained validation optimization for JWTs-as-access-tokens does not hold for refresh tokens

  2. that depends on the security/access of the database; if the database can be accessed by other parties/servers/applications/users, then yes (but your mileage may vary with where and how you store the encryption key...)

  3. an Authorization Server may issue both access tokens and refresh tokens at the same time, depending on the grant that is used by the client to obtain them; the spec contains the details and options on each of the standardized grants

How do I set the default locale in the JVM?

You can enforce VM arguments for a JAR file with the following code:

import java.io.File;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

public class JVMArgumentEnforcer
{
    private String argument;

    public JVMArgumentEnforcer(String argument)
    {
        this.argument = argument;
    }

    public static long getTotalPhysicalMemory()
    {
        com.sun.management.OperatingSystemMXBean bean =
                (com.sun.management.OperatingSystemMXBean)
                        java.lang.management.ManagementFactory.getOperatingSystemMXBean();
        return bean.getTotalPhysicalMemorySize();
    }

    public static boolean isUsing64BitJavaInstallation()
    {
        String bitVersion = System.getProperty("sun.arch.data.model");

        return bitVersion.equals("64");
    }

    private boolean hasTargetArgument()
    {
        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
        List<String> inputArguments = runtimeMXBean.getInputArguments();

        return inputArguments.contains(argument);
    }

    public void forceArgument() throws Exception
    {
        if (!hasTargetArgument())
        {
            // This won't work from IDEs
            if (JARUtilities.isRunningFromJARFile())
            {
                // Supply the desired argument
                restartApplication();
            } else
            {
                throw new IllegalStateException("Please supply the VM argument with your IDE: " + argument);
            }
        }
    }

    private void restartApplication() throws Exception
    {
        String javaBinary = getJavaBinaryPath();
        ArrayList<String> command = new ArrayList<>();
        command.add(javaBinary);
        command.add("-jar");
        command.add(argument);
        String currentJARFilePath = JARUtilities.getCurrentJARFilePath();
        command.add(currentJARFilePath);

        ProcessBuilder processBuilder = new ProcessBuilder(command);
        processBuilder.start();

        // Kill the current process
        System.exit(0);
    }

    private String getJavaBinaryPath()
    {
        return System.getProperty("java.home")
                + File.separator + "bin"
                + File.separator + "java";
    }

    public static class JARUtilities
    {
        static boolean isRunningFromJARFile() throws URISyntaxException
        {
            File currentJarFile = getCurrentJARFile();

            return currentJarFile.getName().endsWith(".jar");
        }

        static String getCurrentJARFilePath() throws URISyntaxException
        {
            File currentJarFile = getCurrentJARFile();

            return currentJarFile.getPath();
        }

        private static File getCurrentJARFile() throws URISyntaxException
        {
            return new File(JVMArgumentEnforcer.class.getProtectionDomain().getCodeSource().getLocation().toURI());
        }
    }
}

It is used as follows:

JVMArgumentEnforcer jvmArgumentEnforcer = new JVMArgumentEnforcer("-Duser.language=pt-BR"); // For example
jvmArgumentEnforcer.forceArgument();

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here
    </div>

How to move screen without moving cursor in Vim?

I wrote a plugin which enables me to navigate the file without moving the cursor position. It's based on folding the lines between your position and your target position and then jumping over the fold, or abort it and don't move at all.

It's also easy to fast-switch between the cursor on the first line, the last line and cursor in the middle by just clicking j, k or l when you are in the mode of the plugin.

I guess it would be a good fit here.

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

How to wait until WebBrowser is completely loaded in VB.NET?

Salvete! I needed, simply, a function I could call to make the code wait for the page to load before it continued. After scouring the web for answers, and fiddling around for several hours, I came up with this to solve for myself, the exact dilemma you present. I know I am late in the game with an answer, but I wish to post this for anyone else who comes along.

usage: just call WaitForPageLoad() just after a call to navigation:

whatbrowser.Navigate("http://www.google.com")
WaitForPageLoad()

another example we don't combine the navigate feature with the page load, because sometimes you need to wait for a load without also navigating, for example, you might need to wait for a page to load that was started with an invokemember event:

whatbrowser.Document.GetElementById("UserName").InnerText = whatusername
whatbrowser.Document.GetElementById("Password").InnerText = whatpassword
whatbrowser.Document.GetElementById("LoginButton").InvokeMember("click")
WaitForPageLoad()

Here is the code: You need both subs plus the accessible variable, pageready. First, make sure to fix the variable called whatbrowser to be your webbrowser control

Now, somewhere in your module or class, place this:

Private Property pageready As Boolean = False

#Region "Page Loading Functions"
    Private Sub WaitForPageLoad()
        AddHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        While Not pageready
            Application.DoEvents()
        End While
        pageready = False
    End Sub

    Private Sub PageWaiter(ByVal sender As Object, ByVal e As WebBrowserDocumentCompletedEventArgs)
        If whatbrowser.ReadyState = WebBrowserReadyState.Complete Then
            pageready = True
            RemoveHandler whatbrowser.DocumentCompleted, New WebBrowserDocumentCompletedEventHandler(AddressOf PageWaiter)
        End If
    End Sub

#End Region

How to pass List from Controller to View in MVC 3

  1. Create a model which contains your list and other things you need for the view.

    For example:

    public class MyModel
    {
        public List<string> _MyList { get; set; }
    }
    
  2. From the action method put your desired list to the Model, _MyList property, like:

    public ActionResult ArticleList(MyModel model)
    {
        model._MyList = new List<string>{"item1","item2","item3"};
        return PartialView(@"~/Views/Home/MyView.cshtml", model);
    }
    
  3. In your view access the model as follows

    @model MyModel
    foreach (var item in Model)
    {
       <div>@item</div>
    }
    

I think it will help for start.

Concatenate String in String Objective-c

Iam amazed that none of the top answers pointed out that under recent Objective-C versions (after they added literals), you can concatenate just like this:

@"first" @"second"

And it will result in:

@"firstsecond"

You can not use it with NSString objects, only with literals, but it can be useful in some cases.

How to correctly display .csv files within Excel 2013?

The problem is from regional Options . The decimal separator in win 7 for european countries is coma . You have to open Control Panel -> Regional and Language Options -> Aditional Settings -> Decimal Separator : click to enter a dot (.) and to List Separator enter a coma (,) . This is !

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

Are there any free Xml Diff/Merge tools available?

I recommend you to use CodeCompare tool. It supports native highlighting of XML-data and it can be a good solution for your task.

How to merge lists into a list of tuples?

I know this is an old question and was already answered, but for some reason, I still wanna post this alternative solution. I know it's easy to just find out which built-in function does the "magic" you need, but it doesn't hurt to know you can do it by yourself.

>>> list_1 = ['Ace', 'King']
>>> list_2 = ['Spades', 'Clubs', 'Diamonds']
>>> deck = []
>>> for i in range(max((len(list_1),len(list_2)))):
        while True:
            try:
                card = (list_1[i],list_2[i])
            except IndexError:
                if len(list_1)>len(list_2):
                    list_2.append('')
                    card = (list_1[i],list_2[i])
                elif len(list_1)<len(list_2):
                    list_1.append('')
                    card = (list_1[i], list_2[i])
                continue
            deck.append(card)
            break
>>>
>>> #and the result should be:
>>> print deck
>>> [('Ace', 'Spades'), ('King', 'Clubs'), ('', 'Diamonds')]

Adding an assets folder in Android Studio

An image of how to in Android Studio 1.5.1.

Within the "Android" project (see the drop-down in the topleft of my image), Right-click on the app...

enter image description here

How to fetch the row count for all tables in a SQL SERVER database

SELECT 
    sc.name +'.'+ ta.name TableName, SUM(pa.rows) RowCnt
FROM 
    sys.tables ta
INNER JOIN sys.partitions pa
    ON pa.OBJECT_ID = ta.OBJECT_ID
INNER JOIN sys.schemas sc
    ON ta.schema_id = sc.schema_id
WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
GROUP BY sc.name,ta.name
ORDER BY SUM(pa.rows) DESC

pandas: best way to select all columns whose names start with X

My solution. It may be slower on performance:

a = pd.concat(df[df[c] == 1] for c in df.columns if c.startswith('foo'))
a.sort_index()


   bar.baz  foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu nas.foo
0      5.0     1.0         0             0        2         NA      NA
1      5.0     2.1         0             1        4          0       0
2      6.0     NaN         0           NaN        1          0       1
5      6.8     6.8         1             0        5          0       0

Adding and removing extensionattribute to AD object

Extension attributes are added by Exchange. According to this Technet article something like this should work:

Set-Mailbox -Identity "anyUser" -ExtensionCustomAttribute4 @{Remove="myString"}

for loop in Python

Try using this:

for k in range(1,c+1,2):

Difference between "enqueue" and "dequeue"

In my opinion one of the worst chosen word's to describe the process, as it is not related to anything in real-life or similar. In general the word "queue" is very bad as if pronounced, it sounds like the English character "q". See the inefficiency here?

enqueue: to place something into a queue; to add an element to the tail of a queue;

dequeue to take something out of a queue; to remove the first available element from the head of a queue

source: https://www.thefreedictionary.com

What is the difference between exit(0) and exit(1) in C?

exit(0) is equivalent to exit(EXIT_SUCCESS).

exit(1) is equivalent to exit(EXIT_FAILURE).

On failure normally any positive value get returned to exit the process, that you can find on shell by using $?.

Value more than 128 that is caused the termination by signal. So if any shell command terminated by signal the return status must be (128+signal number).

For example:

If any shell command is terminated by SIGINT then $? will give 130 ( 128+2) (Here 2 is signal number for SIGINT, check by using kill -l )

Relative instead of Absolute paths in Excel VBA

i think this may help. Below Macro checks if folder exists, if does not then create the folder and save in both xls and pdf formats in such folder. It happens that the folder is shared with the involved people so everybody is updated.

Sub PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco()
'
' PDF_laudo_e_Prod_SP_Sem_Ajuste_Preco Macro
'

'


Dim MyFolder As String
Dim LaudoName As String
Dim NF1Name As String
Dim OrigFolder As String

MyFolder = ThisWorkbook.path & "\" & Sheets("Laudo").Range("C9")
LaudoName = Sheets("Laudo").Range("K27")
NF1Name = Sheets("PROD SP sem ajuste").Range("Q3")
OrigFolder = ThisWorkbook.path

Sheets("Laudo").Select
Columns("D:P").Select
Selection.EntireColumn.Hidden = True

If Dir(MyFolder, vbDirectory) <> "" Then
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False

Sheets("PROD SP sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False

ThisWorkbook.SaveAs filename:=MyFolder & "\" & LaudoName

Application.DisplayAlerts = False

ThisWorkbook.SaveAs filename:=OrigFolder & "\" & "Entregas e Instrucao Barter 2015 - beta"

Application.DisplayAlerts = True

Else
MkDir MyFolder
Sheets("Laudo").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & LaudoName & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False

Sheets("PROD SP sem ajuste").ExportAsFixedFormat Type:=xlTypePDF, filename:=MyFolder & "\" & NF1Name & ".pdf", Quality:=xlQualityMinimum, _
IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
False

ThisWorkbook.SaveAs filename:=MyFolder & "\" & LaudoName

Application.DisplayAlerts = False

ThisWorkbook.SaveAs filename:=OrigFolder & "\" & "Entregas e Instrucao Barter 2015 - beta"

Application.DisplayAlerts = True

End If

Sheets("Laudo").Select
Columns("C:Q").Select
Selection.EntireColumn.Hidden = False
Range("A1").Select

End Sub

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

For this you have to use HtmlAttributes, but there is a catch: HtmlAttributes and css class .

you can define it like this:

new { Attrubute="Value", AttributeTwo = IntegerValue, @class="className" };

and here is a more realistic example:

new { style="width:50px" };
new { style="width:50px", maxsize = 50 };
new {size=30, @class="required"}

and finally in:

MVC 1

<%= Html.TextBox("test", new { style="width:50px" }) %> 

MVC 2

<%= Html.TextBox("test", null, new { style="width:50px" }) %> 

MVC 3

@Html.TextBox("test", null, new { style="width:50px" })

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How to call gesture tap on UIView programmatically in swift

    let tap = UITapGestureRecognizer(target: self, action: Selector("handleFrontTap:"))
    frontView.addGestureRecognizer(tap)

// Make sure this is not private
func handleFrontTap(gestureRecognizer: UITapGestureRecognizer) {
    print("tap working")
}

What does iterator->second mean?

The type of the elements of an std::map (which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K and value is V is std::pair<const K, V> - the key is const to prevent you from interfering with the internal sorting of map values.

std::pair<> has two members named first and second (see here), with quite an intuitive meaning. Thus, given an iterator i to a certain map, the expression:

i->first

Which is equivalent to:

(*i).first

Refers to the first (const) element of the pair object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:

i->second

Which is equivalent to:

(*i).second

Refers to the second element of the pair - i.e. to the corresponding value in the map.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Jquery $(this) Child Selector

http://jqapi.com/ Traversing--> Tree Traversal --> Children

Using an index to get an item, Python

values = ['A', 'B', 'C', 'D', 'E']
values[0] # returns 'A'
values[2] # returns 'C'
# etc.

How do you create different variable names while in a loop?

It's simply pointless to create variable variable names. Why?

  • They are unnecessary: You can store everything in lists, dictionarys and so on
  • They are hard to create: You have to use exec or globals()
  • You can't use them: How do you write code that uses these variables? You have to use exec/globals() again

Using a list is much easier:

# 8 strings: `Hello String 0, .. ,Hello String 8`
strings = ["Hello String %d" % x for x in range(9)]
for string in strings: # you can loop over them
    print string
print string[6] # or pick any of them

How to check for an empty object in an AngularJS view

You can use plain javascript Object class to achieve it, Object class has keys function which takes 1 argument as input as follows,

Object.keys(obj).length === 0

You can achieve it in 3 ways, 1) Current controller scope 2) Filter 3) $rootScope

1) First way is current controller scope,

$scope.isObjEmpty = function(obj){ return Object.keys(obj).length === 0; }

Then you can call the function from the view:

ng-show="!isObjEmpty(obj)" if you want to show and hide dom dynamically & ng-if="!isObjEmpty(obj)" if you want to remove or add dom dynamically.

2) The second way is a custom filter. Following code should work for the object & Array,

angular.module('angularApp')
    .filter('isEmpty', [function () {
        return function (obj) {
            if (obj == undefined || obj == null || obj == '')
                return true;
            if (angular.isObject(obj))
                return Object.keys(obj).length != 0;

            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return false;
                }
            }
            return true;
        };
    }]);

    <div ng-hide="items | isEmpty"> Your content's goes here </div>

3) The third way is $rootScope, create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.

function isObjEmpty (obj){ return Object.keys(obj).length === 0; }

$rootScope.isObjEmpty = isObjEmpty ;

How to access site running apache server over lan without internet connection

* Don't change anything to Listen : keep it as it is..

1) Open httpd.conf of Apache server (backup first) Look for the the following :

<Directory />
    Options FollowSymLinks
    AllowOverride None
    Order deny,allow
    Allow from all
    #Deny from all
</Directory>

and also this

<Directory "cgi-bin">
    AllowOverride None
    Options None
    Order allow,deny
    Allow from all
</Directory>

2) Now From taskbar :

Click on wamp icon > Apache > Apache modules > apache_rewrite (enable this module)

And Ya Also Activate "Put Online" From same taskbar icon

You need to allow port request from windows firewall setting.

(Windows 7)

Go to control panel > windows firewall > advance setting (on left sidebar)

then

Right click on inbound rules -> add new rule -> port -> TCP (Specific port 80 - if your localhost wok on this port) -> Allow the connections -> Give a profile name -> ok

Now Restart all the services of Apache server & you are done..

How to reset Django admin password?

You may also have answered a setup question wrong and have zero staff members. In which case head to postgres:

obvioustest=# \c [yourdatabasename]
obvioustest=# \x
obvioustest=# select * from auth_user;
-[ RECORD 1 ]+-------------
id           | 1
is_superuser | f
is_staff     | f
...

To fix, edit directly:

update auth_user set is_staff='true' where id=1;

CSS Calc Viewport Units Workaround?

Doing this with a CSS Grid is pretty easy. The trick is to set the grid's height to 100vw, then assign one of the rows to 75vw, and the remaining one (optional) to 1fr. This gives you, from what I assume is what you're after, a ratio-locked resizing container.

Example here: https://codesandbox.io/s/21r4z95p7j

You can even utilize the bottom gutter space if you so choose, simply by adding another "item".

Edit: StackOverflow's built-in code runner has some side effects. Pop over to the codesandbox link and you'll see the ratio in action.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  background-color: #334;_x000D_
  color: #eee;_x000D_
}_x000D_
_x000D_
.main {_x000D_
  min-height: 100vh;_x000D_
  min-width: 100vw;_x000D_
  display: grid;_x000D_
  grid-template-columns: 100%;_x000D_
  grid-template-rows: 75vw 1fr;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  background-color: #558;_x000D_
  padding: 2px;_x000D_
  margin: 1px;_x000D_
}_x000D_
_x000D_
.item.dead {_x000D_
  background-color: transparent;_x000D_
}
_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Parcel Sandbox</title>_x000D_
    <meta charset="UTF-8" />_x000D_
    <link rel="stylesheet" href="src/index.css" />_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <div id="app">_x000D_
      <div class="main">_x000D_
        <div class="item">Item 1</div>_x000D_
        <!-- <div class="item dead">Item 2 (dead area)</div> -->_x000D_
      </div>_x000D_
    </div>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

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

Our version of Oracle is running on Red Hat Enterprise Linux. We experimented with several different types of group permissions to no avail. The /defaultdir directory had a group that was a secondary group for the oracle user. When we updated the /defaultdir directory to have a group of "oinstall" (oracle's primary group), I was able to select from the external tables underneath that directory with no problem.

So, for others that come along and might have this issue, make the directory have oracle's primary group as the group and it might resolve it for you as it did us. We were able to set the permissions to 770 on the directory and files and selecting on the external tables works fine now.

Disable firefox same origin policy

As of September 2016 this addon is the best to disable CORS: https://github.com/fredericlb/Force-CORS/releases

In the options panel you can configure which header to inject and specific website to have it enabled automatically.

enter image description here

Remove #N/A in vlookup result

if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.

How to determine whether a year is a leap year?

The logic in the "one-liner" works fine. From personal experience, what has helped me is to assign the statements to variables (in their "True" form) and then use logical operators for the result:

A = year % 4 == 0
B = year % 100 == 0
C = year % 400 == 0

I used '==' in the B statement instead of "!=" and applied 'not' logical operator in the calculation:

leap = A and (not B or C)

This comes in handy with a larger set of conditions, and to simplify the boolean operation where applicable before writing a whole bunch of if statements.

How to parse a JSON object to a TypeScript Object

let employee = <Employee>JSON.parse(employeeString);

Remember: Strong typings is compile time only since javascript doesn't support it.

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

SQL Statement using Where clause with multiple values

SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

If you are using parametrized Stored procedure:

  1. Pass in comma separated string
  2. Use special function to split comma separated string into table value variable
  3. Use INNER JOIN ON t.PersonName = newTable.PersonName using a table variable which contains passed in names

How to generate XML from an Excel VBA macro?

This one more version - this will help in generic

Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer

Sub Create()
Dim strFilePath As String
Dim strFileName As String

'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value

Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName

End Sub


Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
    Dim Q As String
    Dim sOutputFileNamewithPath As String
    Q = Chr$(34)

    Dim sXML As String


    'sXML = sXML & "<rows>"

'    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1

    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend


    Dim iRow As Integer
    Dim iCount  As Integer
    iRow = iDataStartRow
    iCount = 1
    While Cells(iRow, 1) > ""
        'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
        sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
        For iCOl = 1 To iColCount - 1
          If (iStartCol = iCOl) Then
               sXML = sXML & "<" & strSubTag & ">"
          End If
          If (iEndCol = iCOl) Then
               sXML = sXML & "</" & strSubTag & ">"
          End If
         If (iStartCol2 = iCOl) Then
               sXML = sXML & "<" & strSubTag2 & ">"
          End If
          If (iEndCol2 = iCOl) Then
               sXML = sXML & "</" & strSubTag2 & ">"
          End If
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
           sXML = sXML & Trim$(Cells(iRow, iCOl))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
        Next

        'sXML = sXML & "</row>"
        Dim nDestFile As Integer, sText As String

    ''Close any open text files
        Close

    ''Get the number of the next free text file
        nDestFile = FreeFile
        sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
    ''Write the entire file to sText
        Open sOutputFileNamewithPath For Output As #nDestFile
        Print #nDestFile, sXML

        iRow = iRow + 1
        sXML = ""
        iCount = iCount + 1
    Wend
    'sXML = sXML & "</rows>"

    Close
End Sub

Test if a property is available on a dynamic variable

Here is the other way:

using Newtonsoft.Json.Linq;

internal class DymanicTest
{
    public static string Json = @"{
            ""AED"": 3.672825,
            ""AFN"": 56.982875,
            ""ALL"": 110.252599,
            ""AMD"": 408.222002,
            ""ANG"": 1.78704,
            ""AOA"": 98.192249,
            ""ARS"": 8.44469
}";

    public static void Run()
    {
        dynamic dynamicObject = JObject.Parse(Json);

        foreach (JProperty variable in dynamicObject)
        {
            if (variable.Name == "AMD")
            {
                var value = variable.Value;
            }
        }
    }
}

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

Disable browsers vertical and horizontal scrollbars

Try CSS

<body style="overflow: hidden">

Create SQL script that create database and tables

Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.

For unordered scripts generated by SSMS you can go following

a) Execute script (some objects will be inserted some wont, there will be some errors)

b) Remove all objects from the script that have been added to database

c) Go back to a) until everything is eventually executed

Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).

All of these will take care of the dependencies for you and save you even more time.

Android: adb: Permission Denied

The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $ after you started adb shell? If you correctly rooted your machine, you would have seen # instead.

If you see the $, try entering Super User mode by typing su. If Root is enabled, you will see the # - without asking for password.

How to convert int to QString?

I always use QString::setNum().

int i = 10;
double d = 10.75;
QString str;
str.setNum(i);
str.setNum(d);

setNum() is overloaded in many ways. See QString class reference.

How to get image height and width using java?

I tried to test performance using some of the various approaches listed. It's hard to make a rigorous test as many factors affect the result. I prepared two folders, one with 330 jpg files and another one with 330 png files. The average file size was 4Mb in both cases. Then I called getDimension for each file. Each implementation of getDimension method and each image type was tested separately (separate run). Here is the execution times that I got (first number for jpg, second number for png):

1(Apurv) - 101454ms, 84611ms
2(joinJpegs) - 471ms, N/A
3(Andrew Taylor) - 707ms, 68ms
4(Karussell, ImageIcon) - 106655ms, 100898ms
5(user350756) - 2649ms, 68ms

It's obvious that some methods load the whole file in order to get dimensions while others get by just reading some header information from the image. I think these numbers may be useful when application performance is critical.

Thank you everyone for the contribution to this thread - very helpful.

A keyboard shortcut to comment/uncomment the select text in Android Studio

Windows 10 and Android Studio: Ctrl + / (on small num pad), don't use Ctrl + Shift-7!

Javascript add method to object

you need to add it to Foo's prototype:

function Foo(){}
Foo.prototype.bar = function(){}
var x = new Foo()
x.bar()

java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

I have solved this problem by importing the following dependency. you must manually import httpclient

<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
    <exclusions>
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>*</artifactId>
        </exclusion>
    </exclusions>
</dependency>

How to make a view with rounded corners?

public class RoundedCornerLayout extends FrameLayout {
    private double mCornerRadius;

    public RoundedCornerLayout(Context context) {
        this(context, null, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RoundedCornerLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    public double getCornerRadius() {
        return mCornerRadius;
    }

    public void setCornerRadius(double cornerRadius) {
        mCornerRadius = cornerRadius;
    }

    @Override
    public void draw(Canvas canvas) {
        int count = canvas.save();

        final Path path = new Path();
        path.addRoundRect(new RectF(0, 0, canvas.getWidth(), canvas.getHeight()), (float) mCornerRadius, (float) mCornerRadius, Path.Direction.CW);
        canvas.clipPath(path, Region.Op.REPLACE);

        canvas.clipPath(path);
        super.draw(canvas);
        canvas.restoreToCount(count);
    }
}

List of remotes for a Git repository?

None of those methods work the way the questioner is asking for and which I've often had a need for as well. eg:

$ git remote
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@bserver
fatal: Not a git repository (or any of the parent directories): .git
$ git remote user@server:/home/user
fatal: Not a git repository (or any of the parent directories): .git
$ git ls-remote
fatal: No remote configured to list refs from.
$ git ls-remote user@server:/home/user
fatal: '/home/user' does not appear to be a git repository
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

The whole point of doing this is that you do not have any information except the remote user and server and want to find out what you have access to.

The majority of the answers assume you are querying from within a git working set. The questioner is assuming you are not.

As a practical example, assume there was a repository foo.git on the server. Someone in their wisdom decides they need to change it to foo2.git. It would really be nice to do a list of a git directory on the server. And yes, I see the problems for git. It would still be nice to have though.

Sorting a list using Lambda/Linq to objects

This is how I solved my problem:

List<User> list = GetAllUsers();  //Private Method

if (!sortAscending)
{
    list = list
           .OrderBy(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}
else
{
    list = list
           .OrderByDescending(r => r.GetType().GetProperty(sortBy).GetValue(r,null))
           .ToList();
}

How can I include null values in a MIN or MAX?

Use the analytic function :

select case when 
    max(field) keep (dense_rank first order by datfin desc nulls first) is null then 1 
    else 0 end as flag 
from MYTABLE;

getResourceAsStream() is always returning null

A call to Class#getResourceAsStream(String) delegates to the class loader and the resource is searched in the class path. In other words, you current code won't work and you should put abc.txt in WEB-INF/classes, or in WEB-INF/lib if packaged in a jar file.

Or use ServletContext.getResourceAsStream(String) which allows servlet containers to make a resource available to a servlet from any location, without using a class loader. So use this from a Servlet:

this.getServletContext().getResourceAsStream("/WEB-INF/abc.txt") ;

But is there a way I can call getServletContext from my Web Service?

If you are using JAX-WS, then you can get a WebServiceContext injected:

@Resource
private WebServiceContext wsContext;

And then get the ServletContext from it:

ServletContext sContext= wsContext.getMessageContext()
                             .get(MessageContext.SERVLET_CONTEXT));

Easy way to write contents of a Java InputStream to an OutputStream

PipedInputStream and PipedOutputStream should only be used when you have multiple threads, as noted by the Javadoc.

Also, note that input streams and output streams do not wrap any thread interruptions with IOExceptions... So, you should consider incorporating an interruption policy to your code:

byte[] buffer = new byte[1024];
int len = in.read(buffer);
while (len != -1) {
    out.write(buffer, 0, len);
    len = in.read(buffer);
    if (Thread.interrupted()) {
        throw new InterruptedException();
    }
}

This would be an useful addition if you expect to use this API for copying large volumes of data, or data from streams that get stuck for an intolerably long time.

How to prevent a background process from being stopped after closing SSH client in Linux

When the session is closed the process receives the SIGHUP signal which it is apparently not catching. You can use the nohup command when launching the process or the bash built-in command disown -h after starting the process to prevent this from happening:

> help disown
disown: disown [-h] [-ar] [jobspec ...]
     By default, removes each JOBSPEC argument from the table of active jobs.
    If the -h option is given, the job is not removed from the table, but is
    marked so that SIGHUP is not sent to the job if the shell receives a
    SIGHUP.  The -a option, when JOBSPEC is not supplied, means to remove all
    jobs from the job table; the -r option means to remove only running jobs.

Where are the recorded macros stored in Notepad++?

If you install Notepad++ on Linux system by wine (In my case desktop Ubuntu 14.04-LTS_X64) the file "shortcuts.xml" is under :

$/home/[USER-NAME]/.wine/drive_c/users/[USER-NAME]/My Documents/.wine/drive_c/Program Files (x86)/Notepad++/shortcuts.xml

Thanks to Harrison and all that have suggestions for that isssue.

Using cURL with a username and password?

You can use command like,

curl -u user-name -p http://www.example.com/path-to-file/file-name.ext > new-file-name.ext

Then HTTP password will be triggered.

Reference: http://www.asempt.com/article/how-use-curl-http-password-protected-site

How can I check if a key exists in a dictionary?

If you want to retrieve the key's value if it exists, you can also use

try:
    value = a[key]
except KeyError:
    # Key is not present
    pass

If you want to retrieve a default value when the key does not exist, use value = a.get(key, default_value). If you want to set the default value at the same time in case the key does not exist, use value = a.setdefault(key, default_value).

SQL Server 2008 - Case / If statements in SELECT Clause

You are looking for the CASE statement

http://msdn.microsoft.com/en-us/library/ms181765.aspx

Example copied from MSDN:

USE AdventureWorks;
GO
SELECT   ProductNumber, Category =
      CASE ProductLine
         WHEN 'R' THEN 'Road'
         WHEN 'M' THEN 'Mountain'
         WHEN 'T' THEN 'Touring'
         WHEN 'S' THEN 'Other sale items'
         ELSE 'Not for sale'
      END,
   Name
FROM Production.Product
ORDER BY ProductNumber;
GO

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

Angular directives - when and how to use compile, controller, pre-link and post-link

Compile function

Each directive's compile function is only called once, when Angular bootstraps.

Officially, this is the place to perform (source) template manipulations that do not involve scope or data binding.

Primarily, this is done for optimisation purposes; consider the following markup:

<tr ng-repeat="raw in raws">
    <my-raw></my-raw>
</tr>

The <my-raw> directive will render a particular set of DOM markup. So we can either:

  • Allow ng-repeat to duplicate the source template (<my-raw>), and then modify the markup of each instance template (outside the compile function).
  • Modify the source template to involve the desired markup (in the compile function), and then allow ng-repeat to duplicate it.

If there are 1000 items in the raws collection, the latter option may be faster than the former one.

Do:

  • Manipulate markup so it serves as a template to instances (clones).

Do not

  • Attach event handlers.
  • Inspect child elements.
  • Set up observations on attributes.
  • Set up watches on the scope.

Lightweight Javascript DB for use in Node.js

NeDB seems to be what you are looking for. From the blurb:

Embedded persistent database for Node.js, written in Javascript, with no dependency (except npm modules of course). You can think of it as a SQLite for Node.js projects, which can be used with a simple require statement. The API is a subset of MongoDB's. You can use it as a persistent or an in-memory only datastore.

Javascript require() function giving ReferenceError: require is not defined

Yes, require is a Node.JS function and doesn't work in client side scripting without certain requirements. If you're getting this error while writing electronJS code, try the following:

In your BrowserWindow declaration, add the following webPreferences field: i.e, instead of plain mainWindow = new BrowserWindow(), write

mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    });

Display A Popup Only Once Per User

You can use removeItem() class of localStorage to destroy that key on browser close with:

window.onbeforeunload = function{
    localStorage.removeItem('your key');
};

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

This work around will fix the issue found by @Cletus.

function submitForm(form) {
    //get the form element's document to create the input control with
    //(this way will work across windows in IE8)
    var button = form.ownerDocument.createElement('input');
    //make sure it can't be seen/disrupts layout (even momentarily)
    button.style.display = 'none';
    //make it such that it will invoke submit if clicked
    button.type = 'submit';
    //append it and click it
    form.appendChild(button).click();
    //if it was prevented, make sure we don't get a build up of buttons
    form.removeChild(button);
}

Will work on all modern browsers.
Will work across tabs/spawned child windows (yes, even in IE<9).
And is in vanilla!

Just pass it a DOM reference to a form element and it'll make sure all the attached listeners, the onsubmit, and (if its not prevented by then) finally, submit the form.

Read lines from a file into a Bash array

Latest revision based on comment from BinaryZebra's comment and tested here. The addition of command eval allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.

Use $IFS that has no spaces\tabs, just newlines/CR

$ IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync

Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes "" and braces {} as in the example above


Edit:

Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around

With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)

Other notes:

Can also follow drizzt's suggestion below and replace a forked subshell+cat with

$(</etc/passwd)

The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this

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

The answer from ks1322 helped me to identify the issue while using docker-compose exec:

If you omit the -T flag, docker-compose exec add a special character that break output, we see b instead of 1b:

$ test=$(/usr/local/bin/docker-compose exec db bash -c "echo 1")
$ echo "${test}b"
b
echo "${test}" | cat -vte
1^M$

With -T flag, docker-compose exec works as expected:

$ test=$(/usr/local/bin/docker-compose exec -T db bash -c "echo 1")
$ echo "${test}b"
1b

Differences between SP initiated SSO and IDP initiated SSO

IDP Initiated SSO

From PingFederate documentation :- https://docs.pingidentity.com/bundle/pf_sm_supportedStandards_pf82/page/task/idpInitiatedSsoPOST.html

In this scenario, a user is logged on to the IdP and attempts to access a resource on a remote SP server. The SAML assertion is transported to the SP via HTTP POST.

Processing Steps:

  1. A user has logged on to the IdP.
  2. The user requests access to a protected SP resource. The user is not logged on to the SP site.
  3. Optionally, the IdP retrieves attributes from the user data store.
  4. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP.

SP Initiated SSO

From PingFederate documentation:- http://documentation.pingidentity.com/display/PF610/SP-Initiated+SSO--POST-POST

In this scenario a user attempts to access a protected resource directly on an SP Web site without being logged on. The user does not have an account on the SP site, but does have a federated account managed by a third-party IdP. The SP sends an authentication request to the IdP. Both the request and the returned SAML assertion are sent through the user’s browser via HTTP POST.

Processing Steps:

  1. The user requests access to a protected SP resource. The request is redirected to the federation server to handle authentication.
  2. The federation server sends an HTML form back to the browser with a SAML request for authentication from the IdP. The HTML form is automatically posted to the IdP’s SSO service.
  3. If the user is not already logged on to the IdP site or if re-authentication is required, the IdP asks for credentials (e.g., ID and password) and the user logs on.
  4. Additional information about the user may be retrieved from the user data store for inclusion in the SAML response. (These attributes are predetermined as part of the federation agreement between the IdP and the SP)

  5. The IdP’s SSO service returns an HTML form to the browser with a SAML response containing the authentication assertion and any additional attributes. The browser automatically posts the HTML form back to the SP. NOTE: SAML specifications require that POST responses be digitally signed.

  6. (Not shown) If the signature and assertion are valid, the SP establishes a session for the user and redirects the browser to the target resource.

Excel VBA - Range.Copy transpose paste

WorksheetFunction Transpose()

Instead of copying, pasting via PasteSpecial, and using the Transpose option you can simply type a formula

    =TRANSPOSE(Sheet1!A1:A5)

or if you prefer VBA:

    Dim v
    v = WorksheetFunction.Transpose(Sheet1.Range("A1:A5"))
    Sheet2.Range("A1").Resize(1, UBound(v)) = v

Note: alternatively you could use late-bound Application.Transpose instead.

MS help reference states that having a current version of Microsoft 365, one can simply input the formula in the top-left-cell of the target range, otherwise the formula must be entered as a legacy array formula via Ctrl+Shift+Enter to confirm it.

Versions Excel vers. 2007+, Mac since 2011, Excel for Microsoft 365

jQuery has deprecated synchronous XMLHTTPRequest

To avoid this warning, do not use:

async: false

in any of your $.ajax() calls. This is the only feature of XMLHttpRequest that's deprecated.

The default is async: true, so if you never use this option at all, your code should be safe if the feature is ever really removed.

However, it probably won't be -- it may be removed from the standards, but I'll bet browsers will continue to support it for many years. So if you really need synchronous AJAX for some reason, you can use async: false and just ignore the warnings. But there are good reasons why synchronous AJAX is considered poor style, so you should probably try to find a way to avoid it. And the people who wrote Flash applications probably never thought it would go away, either, but it's in the process of being phased out now.

Notice that the Fetch API that's replacing XMLHttpRequest does not even offer a synchronous option.

MySQL "incorrect string value" error when save unicode string in Django

Improvement to @madprops answer - solution as a django management command:

import MySQLdb
from django.conf import settings

from django.core.management.base import BaseCommand


class Command(BaseCommand):

    def handle(self, *args, **options):
        host = settings.DATABASES['default']['HOST']
        password = settings.DATABASES['default']['PASSWORD']
        user = settings.DATABASES['default']['USER']
        dbname = settings.DATABASES['default']['NAME']

        db = MySQLdb.connect(host=host, user=user, passwd=password, db=dbname)
        cursor = db.cursor()

        cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

        sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
        cursor.execute(sql)

        results = cursor.fetchall()
        for row in results:
            print(f'Changing table "{row[0]}"...')
            sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
            cursor.execute(sql)
        db.close()

Hope this helps anybody but me :)

Global variables in Java

There is no such thing as a truly global variable in Java. Every static variable must belong to some class (like System.out), but when you have decided which class it will go in, you can refer to it from everywhere loaded by the same classloader.

Note that static variables should always be protected when updating to avoid race conditions.

Android EditText view Floating Hint in Material Design

Use the TextInputLayout provided by the Material Components Library:

    <com.google.android.material.textfield.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Label">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

    </com.google.android.material.textfield.TextInputLayout>

enter image description here

How to count check-boxes using jQuery?

Assume that you have a tr row with multiple checkboxes in it, and you want to count only if the first checkbox is checked.

You can do that by giving a class to the first checkbox

For example class='mycxk' and you can count that using the filter, like this

$('.mycxk').filter(':checked').length

Wait for all promises to resolve

Recently had this problem but with unkown number of promises.Solved using jQuery.map().

function methodThatChainsPromises(args) {

    //var args = [
    //    'myArg1',
    //    'myArg2',
    //    'myArg3',
    //];

    var deferred = $q.defer();
    var chain = args.map(methodThatTakeArgAndReturnsPromise);

    $q.all(chain)
    .then(function () {
        $log.debug('All promises have been resolved.');
        deferred.resolve();
    })
    .catch(function () {
        $log.debug('One or more promises failed.');
        deferred.reject();
    });

    return deferred.promise;
}

How do I uniquely identify computers visiting my web site?

Assuming you don't want the user to be in control, you can't. The web doesn't work like that, the best you can hope for is some heuristics.

If it is an option to force your visitor to install some software and use TCPA you may be able to pull something off.

Setting the MySQL root user password on OS X

macOS 10.14+ with 5.7.26 installed from Mac OSX DMG installer.

When attempting to use the UPDATE command posted by other users results in the following error:

ERROR 1820 (HY000): You must reset your password using ALTER USER statement before executing this statement.

Copy the password that was presented to you by the Installer open terminal and do the following:

mysql -uroot -p
ALTER USER 'root'@'localhost' IDENTIFIED BY 'YOURPASSWORDHERE';

How to pass a parameter like title, summary and image in a Facebook sharer URL

I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.

The following JavaScript function grabs the location.href & document.title for the sharer, and you can ultimately change these.

function fbs_click() {
        u=location.href;
        t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436');

            return false;
        }

Usage:

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
    Share on Facebook
</a>

It looks like this is what you could possibly be looking for: Facebook sharer title / desc....

Cast from VARCHAR to INT - MySQL

For casting varchar fields/values to number format can be little hack used:

SELECT (`PROD_CODE` * 1) AS `PROD_CODE` FROM PRODUCT`

How to calculate the width of a text string of a specific font and font-size?

For Swift 3.0+

extension String {
    func SizeOf_String( font: UIFont) -> CGSize {
        let fontAttribute = [NSFontAttributeName: font]
        let size = self.size(attributes: fontAttribute)  // for Single Line
       return size;
   }
}

Use it like...

        let Str = "ABCDEF"
        let Font =  UIFont.systemFontOfSize(19.0)
        let SizeOfString = Str.SizeOfString(font: Font!)

How to empty/destroy a session in rails?

To clear only certain parameters, you can use:

[:param1, :param2, :param3].each { |k| session.delete(k) }

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

How to keep environment variables when using sudo

A simple wrapper function (or in-line for loop)

I came up with a unique solution because:

  • sudo -E "$@" was leaking variables that was causing problems for my command
  • sudo VAR1="$VAR1" ... VAR42="$VAR42" "$@" was long and ugly in my case

demo.sh

#!/bin/bash

function sudo_exports(){
    eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) "$@"
}

# create a test script to call as sudo
echo 'echo Forty-Two is $VAR42' > sudo_test.sh
chmod +x sudo_test.sh

export VAR42="The Answer to the Ultimate Question of Life, The Universe, and Everything."

export _EXPORTS="_EXPORTS VAR1 VAR2 VAR3 VAR4 VAR5 VAR6 VAR7 VAR8 VAR9 VAR10 VAR11 VAR12 VAR13 VAR14 VAR15 VAR16 VAR17 VAR18 VAR19 VAR20 VAR21 VAR22 VAR23 VAR24 VAR25 VAR26 VAR27 VAR28 VAR29 VAR30 VAR31 VAR32 VAR33 VAR34 VAR35 VAR36 VAR37 VAR38 VAR39 VAR40 VAR41 VAR42"

# clean function style
sudo_exports ./sudo_test.sh

# or just use the content of the function
eval sudo $(for x in $_EXPORTS; do printf '%q=%q ' "$x" "${!x}"; done;) ./sudo_test.sh

Result

$ ./demo.sh
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.
Forty-Two is The Answer to the Ultimate Question of Life, The Universe, and Everything.

How?

This is made possible by a feature of the bash builtin printf. The %q produces a shell quoted string. Unlike the parameter expansion in bash 4.4, this works in bash versions < 4.0

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Abort a Git Merge

Truth be told there are many, many resources explaining how to do this already out on the web:

Git: how to reverse-merge a commit?

Git: how to reverse-merge a commit?

Undoing Merges, from Git's blog (retrieved from archive.org's Wayback Machine)

So I guess I'll just summarize some of these:

  1. git revert <merge commit hash>
    This creates an extra "revert" commit saying you undid a merge

  2. git reset --hard <commit hash *before* the merge>
    This reset history to before you did the merge. If you have commits after the merge you will need to cherry-pick them on to afterwards.

But honestly this guide here is better than anything I can explain, with diagrams! :)

How to manage a redirect request after a jQuery Ajax call

The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actual callback function.

For example, our wrapper function was something like:

function cbWrapper(data, funct){
    if($("#myForm", data).length > 0)
        top.location.href="login.htm";//redirection
    else
        funct(data);
}

Then, when making the Ajax call we used something like:

$.post("myAjaxHandler", 
       {
        param1: foo,
        param2: bar
       },
       function(data){
           cbWrapper(data, myActualCB);
       }, 
       "html"
);

This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)

What is the Windows equivalent of the diff command?

Well, on Windows I happily run diff and many other of the GNU tools. You can do it with cygwin, but I personally prefer GnuWin32 because it is a much lighter installation experience.

So, my answer is that the Windows equivalent of diff, is none other than diff itself!

What is the fastest way to send 100,000 HTTP requests in Python?

Create epoll object,
open many client TCP sockets,
adjust their send buffers to be a bit more than request header,
send a request header — it should be immediate, just placing into a buffer, register socket in epoll object,
do .poll on epoll obect,
read first 3 bytes from each socket from .poll,
write them to sys.stdout followed by \n (don't flush), close the client socket.

Limit number of sockets opened simultaneously — handle errors when sockets are created. Create a new socket only if another is closed.
Adjust OS limits.
Try forking into a few (not many) processes: this may help to use CPU a bit more effectively.

specifying goal in pom.xml

I stumbled upon this exception, and found out that I forgot to add a Main.
Check out if you have public static void main(String[] args) correctly.

Good luck!

LINQ Using Max() to select a single row

You can also do:

(from u in table
orderby u.Status descending
select u).Take(1);

No 'Access-Control-Allow-Origin' header is present on the requested resource error

If you use Google Chrome browser you can hack with an extension.

You can find a Chrome extension that will modify CORS headers on the fly in your application. Obviously, this is Chrome only, but I like that it works with zero changes anywhere at all.

You can use it for debugging your app on a local machine (if everything works in production).

Notice: If URL becomes broken the extension name is Access-Control-Allow-Origin: *. I recommend you to disable this extension when you not working on your stuff, because, for example, youtube does not work with this extension.

How to force delete a file?

You have to close that application first. There is no way to delete it, if it's used by some application.

UnLock IT is a neat utility that helps you to take control of any file or folder when it is locked by some application or system. For every locked resource, you get a list of locking processes and can unlock it by terminating those processes. EMCO Unlock IT offers Windows Explorer integration that allows unlocking files and folders by one click in the context menu.

There's also Unlocker (not recommended, see Warning below), which is a free tool which helps locate any file locking handles running, and give you the option to turn it off. Then you can go ahead and do anything you want with those files.

Warning: The installer includes a lot of undesirable stuff. You're almost certainly better off with UnLock IT.

ASP.NET Web API application gives 404 when deployed at IIS 7

You may need to install Hotfix KB980368.

This article describes a update that enables certain Internet Information Services (IIS) 7.0 or IIS 7.5 handlers to handle requests whose URLs do not end with a period. Specifically, these handlers are mapped to "." request paths. Currently, a handler that is mapped to a "." request path handles only requests whose URLs end with a period. For example, the handler handles only requests whose URLs resemble the following URL:

http://www.example.com/ExampleSite/ExampleFile.

After you apply this update, handlers that are mapped to a "*." request path can handle requests whose URLs end with a period and requests whose URLs do not end with a period. For example, the handler can now handle requests that resemble the following URLs:

http://www.example.com/ExampleSite/ExampleFile

http://www.example.com/ExampleSite/ExampleFile.

After this patch is applied, ASP.NET 4 applications can handle requests for extensionless URLs. Therefore, managed HttpModules that run prior to handler execution will run. In some cases, the HttpModules can return errors for extensionless URLs. For example, an HttpModule that was written to expect only .aspx requests may now return errors when it tries to access the HttpContext.Session property.

How to execute an SSIS package from .NET?

You can use this Function if you have some variable in the SSIS.

    Package pkg;

    Microsoft.SqlServer.Dts.Runtime.Application app;
    DTSExecResult pkgResults;
    Variables vars;

    app = new Microsoft.SqlServer.Dts.Runtime.Application();
    pkg = app.LoadPackage(" Location of your SSIS package", null);

    vars = pkg.Variables;

    // your variables
    vars["somevariable1"].Value = "yourvariable1";
    vars["somevariable2"].Value = "yourvariable2";

    pkgResults = pkg.Execute(null, vars, null, null, null);

    if (pkgResults == DTSExecResult.Success)
    {
        Console.WriteLine("Package ran successfully");
    }
    else
    {

        Console.WriteLine("Package failed");
    }

How do I remove the passphrase for the SSH key without having to create a new key?

On windows, you can use PuttyGen to load the private key file, remove the passphrase and then overwrite the existing private key file.

dyld: Library not loaded: @rpath/libswiftCore.dylib

For the device, you also need to add the dynamic framework to the Embedded binaries section in the General tab of the project.
enter image description here

Excel VBA Open workbook, perform actions, save as, close

I'll try and answer several different things, however my contribution may not cover all of your questions. Maybe several of us can take different chunks out of this. However, this info should be helpful for you. Here we go..

Opening A Seperate File:

ChDir "[Path here]"                          'get into the right folder here
Workbooks.Open Filename:= "[Path here]"      'include the filename in this path

'copy data into current workbook or whatever you want here

ActiveWindow.Close                          'closes out the file

Opening A File With Specified Date If It Exists:

I'm not sure how to search your directory to see if a file exists, but in my case I wouldn't bother to search for it, I'd just try to open it and put in some error checking so that if it doesn't exist then display this message or do xyz.

Some common error checking statements:

On Error Resume Next   'if error occurs continues on to the next line (ignores it)

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

Or (better option):

if one doesn't exist then bring up either a message box or dialogue box to say "the file does not exist, would you like to create a new one?

you would most likely want to use the GoTo ErrorHandler shown below to achieve this

On Error GoTo ErrorHandler:

ChDir "[Path here]"                         
Workbooks.Open Filename:= "[Path here]"      'try to open file here

ErrorHandler:
'Display error message or any code you want to run on error here

Much more info on Error handling here: http://www.cpearson.com/excel/errorhandling.htm


Also if you want to learn more or need to know more generally in VBA I would recommend Siddharth Rout's site, he has lots of tutorials and example code here: http://www.siddharthrout.com/vb-dot-net-and-excel/

Hope this helps!


Example on how to ensure error code doesn't run EVERYtime:

if you debug through the code without the Exit Sub BEFORE the error handler you'll soon realize the error handler will be run everytime regarldess of if there is an error or not. The link below the code example shows a previous answer to this question.

  Sub Macro

    On Error GoTo ErrorHandler:

    ChDir "[Path here]"                         
    Workbooks.Open Filename:= "[Path here]"      'try to open file here

    Exit Sub      'Code will exit BEFORE ErrorHandler if everything goes smoothly
                  'Otherwise, on error, ErrorHandler will be run

    ErrorHandler:
    'Display error message or any code you want to run on error here

  End Sub

Also, look at this other question in you need more reference to how this works: goto block not working VBA


Update multiple values in a single statement

In Oracle the solution would be:

UPDATE
    MasterTbl
SET
    (TotalX,TotalY,TotalZ) =
      (SELECT SUM(X),SUM(Y),SUM(Z)
         from DetailTbl where DetailTbl.MasterID = MasterTbl.ID)

Don't know if your system allows the same.

SELECT * FROM in MySQLi

You can still use it (mysqli is just another way of communicating with the server, the SQL language itself is expanded, not changed). Prepared statements are safer, though - since you don't need to go through the trouble of properly escaping your values each time. You can leave them as they were, if you want to but the risk of sql piggybacking is reduced if you switch.

Classes residing in App_Code is not accessible

I found it easier to move the files into a separate Class Library project and then reference that project in the web project and apply the namespace in the using section of the file. For some reason the other solutions were not working for me, but this work around did.

python setup.py uninstall

I had run python setup.py install once in my PyCharm, it installs all the packages into my conda base environment. Later when I want to remove all these packages, pip uninstall does not work. I had to delete them from /anaconda3/lib/python3.7/site-packages manually :(

So I don't see the reason why they use setup.py instead of writing requirements.txt file. The requirement file can be used to install packages in virtual environment and won't mess with system python packages.

How do I use Node.js Crypto to create a HMAC-SHA1 hash?

Gwerder's solution wont work because hash = hmac.read(); happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write statement is un-necessary in this example.

Instead do this:

var crypto    = require('crypto');
var hmac;
var algorithm = 'sha1';
var key       = 'abcdeg';
var text      = 'I love cupcakes';
var hash;

hmac = crypto.createHmac(algorithm, key);

// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');

// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
    hash = hmac.read();
    //...do something with the hash...
});

More formally, if you wish, the line

hmac.end(text, function () {

could be written

hmac.end(text, 'utf8', function () {

because in this example text is a utf string

When do I use super()?

Calling exactly super() is always redundant. It's explicitly doing what would be implicitly done otherwise. That's because if you omit a call to the super constructor, the no-argument super constructor will be invoked automatically anyway. Not to say that it's bad style; some people like being explicit.

However, where it becomes useful is when the super constructor takes arguments that you want to pass in from the subclass.

public class Animal {
   private final String noise;
   protected Animal(String noise) {
      this.noise = noise;
   }

   public void makeNoise() {
      System.out.println(noise);
   }
}

public class Pig extends Animal {
    public Pig() {
       super("Oink");
    }
}

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

In my case, simply giving the user permissions on the database fixed it.

So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Getting the encoding of a Postgres database

If you want to get database encodings:

psql  -U postgres -h somehost --list

You'll see something like:

List of databases
           Name         |  Owner   | Encoding
------------------------+----------+----------
db1                     | postgres | UTF8

Jquery Smooth Scroll To DIV - Using ID value from Link

You can do this:

$('.searchbychar').click(function () {
    var divID = '#' + this.id;
    $('html, body').animate({
        scrollTop: $(divID).offset().top
    }, 2000);
});

F.Y.I.

  • You need to prefix a class name with a . (dot) like in your first line of code.
  • $( 'searchbychar' ).click(function() {
  • Also, your code $('.searchbychar').attr('id') will return a string ID not a jQuery object. Hence, you can not apply .offset() method to it.

How to use double or single brackets, parentheses, curly braces

The difference between test, [ and [[ is explained in great details in the BashFAQ.

To cut a long story short: test implements the old, portable syntax of the command. In almost all shells (the oldest Bourne shells are the exception), [ is a synonym for test (but requires a final argument of ]). Although all modern shells have built-in implementations of [, there usually still is an external executable of that name, e.g. /bin/[.

[[ is a new improved version of it, which is a keyword, not a program. This has beneficial effects on the ease of use, as shown below. [[ is understood by KornShell and BASH (e.g. 2.03), but not by the older POSIX or BourneShell.

And the conclusion:

When should the new test command [[ be used, and when the old one [? If portability to the BourneShell is a concern, the old syntax should be used. If on the other hand the script requires BASH or KornShell, the new syntax is much more flexible.

Convert string to title case with JavaScript

Simpler more performant version, with simple caching.

_x000D_
_x000D_
  var TITLE_CASE_LOWER_MAP = {_x000D_
    'a': 1, 'an': 1, 'and': 1, 'as': 1, 'at': 1, 'but': 1, 'by': 1, 'en':1, 'with': 1,_x000D_
    'for': 1, 'if': 1, 'in': 1, 'of': 1, 'on': 1, 'the': 1, 'to': 1, 'via': 1_x000D_
  };_x000D_
_x000D_
  // LEAK/CACHE TODO: evaluate using LRU._x000D_
  var TITLE_CASE_CACHE = new Object();_x000D_
_x000D_
  toTitleCase: function (title) {_x000D_
    if (!title) return null;_x000D_
_x000D_
    var result = TITLE_CASE_CACHE[title];_x000D_
    if (result) {_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    result = "";_x000D_
    var split = title.toLowerCase().split(" ");_x000D_
    for (var i=0; i < split.length; i++) {_x000D_
_x000D_
      if (i > 0) {_x000D_
        result += " ";_x000D_
      }_x000D_
_x000D_
      var word = split[i];_x000D_
      if (i == 0 || TITLE_CASE_LOWER_MAP[word] != 1) {_x000D_
        word = word.substr(0,1).toUpperCase() + word.substr(1);_x000D_
      }_x000D_
_x000D_
      result += word;_x000D_
    }_x000D_
_x000D_
    TITLE_CASE_CACHE[title] = result;_x000D_
_x000D_
    return result;_x000D_
  },
_x000D_
_x000D_
_x000D_

How to cut first n and last n columns?

Cut can take several ranges in -f:

Columns up to 4 and from 7 onwards:

cut -f -4,7-

or for fields 1,2,5,6 and from 10 onwards:

cut -f 1,2,5,6,10-

etc

REST HTTP status codes for failed validation or invalid duplicate

406 - Not Acceptable

Which means this response is sent when the web server, after performing server-driven content negotiation, doesn't find any content that conforms to the criteria given by the user agent.

Replace NA with 0 in a data frame column

First, here's some sample data:

set.seed(1)
dat <- data.frame(one = rnorm(15),
                 two = sample(LETTERS, 15),
                 three = rnorm(15),
                 four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677        NA
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA        NA
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Here's our replacement:

dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
#          one  two       three      four
# 1         NA    M  0.80418951 0.8921983
# 2  0.1836433    O -0.05710677 0.0000000
# 3 -0.8356286    L  0.50360797 0.3899895
# 4         NA    E          NA 0.0000000
# 5  0.3295078    S          NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595

Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0

Crop image in PHP

You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)

Example:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

String contains another two strings

If you have a list of words you can do a method like this:

public bool ContainWords(List<string> wordList, string text)
{
   foreach(string currentWord in wordList)
      if(!text.Contains(currentWord))
         return false;
   return true;
}

How to create a directory and give permission in single command

install -d -m 0777 /your/dir

should give you what you want. Be aware that every user has the right to write add and delete files in that directory.

XAMPP on Windows - Apache not starting

I was able to fix this!

Had the same problems as stated above, made sure nothing was using port 80 and still not working and getting the message that Apache and Mysql were detected with the wrong path.

I did install XAMPP once before, uninstalled and reinstalled. I even manually uninstalled but still had issues.

The fix. Make sure you backup your system first!

  1. Start Services via Control Panel>Admin Tools (also with Ctrl+R and services.msc)

  2. Look for Apache and MySQL services. Look at the patch indicated in the description (right click on service then click on properties). Chances are that you have Apache listed twice, one from your correct install and one from a previous install. Even if you only see one, look at the path, chances are it's from a previous install and causing your install not to work. In either case, you need to delete those incorrect services.

    a. Got to command prompt (run as administrator): Start > all programs > Accessories > right click on Command Prompt > Select 'run as administrator'

    b. on command prompt type sc delete service, where service is the service you're wanting to delete, such as apache2.1 (or sc delete Apache2.4). It should be exactly as it appears in your services. If the service has spaces such as Apache 2.1 then enter it in quotes, i.e. sc delete "Apache 2.1"

    c. press enter. Now refresh or close/open your services window and you'll see it`s gone.

DO THIS for all services that XAMPP finds as running with an incorrect path.

Once you do this, go ahead and restart the XAMPP control panel (as administrator) and voila! all works. No conflicts

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

I was having the same question. Here is a working solution which is similar to eglasius's. I am using postgresql.

UPDATE QuestionTrackings
SET QuestionID = a.QuestionID
FROM QuestionTrackings q, QuestionAnswers a
WHERE q.QuestionID IS NULL

It complains if q was used in place of table name in line 1, and nothing should precede QuestionID in line 2.

Static Initialization Blocks

If your static variables need to be set at runtime then a static {...} block is very helpful.

For example, if you need to set the static member to a value which is stored in a config file or database.

Also useful when you want to add values to a static Map member as you can't add these values in the initial member declaration.

Token based authentication in Web API without any user interface

ASP.Net Web API has Authorization Server build-in already. You can see it inside Startup.cs when you create a new ASP.Net Web Application with Web API template.

OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
    // In production mode set AllowInsecureHttp = false
    AllowInsecureHttp = true
};

All you have to do is to post URL encoded username and password inside query string.

/Token/userName=johndoe%40example.com&password=1234&grant_type=password

If you want to know more detail, you can watch User Registration and Login - Angular Front to Back with Web API by Deborah Kurata.

How do you use math.random to generate random ints?

For your code to compile you need to cast the result to an int.

int abc = (int) (Math.random() * 100);

However, if you instead use the java.util.Random class it has built in method for you

Random random = new Random();
int abc = random.nextInt(100);

TSQL Pivot without aggregate function

yes, but why !!??

   Select CustomerID,
     Min(Case DBColumnName When 'FirstName' Then Data End) FirstName,
     Min(Case DBColumnName When 'MiddleName' Then Data End) MiddleName,
     Min(Case DBColumnName When 'LastName' Then Data End) LastName,
     Min(Case DBColumnName When 'Date' Then Data End) Date
   From table
   Group By CustomerId

Redirect parent window from an iframe action

If you'd like to redirect to another domain without the user having to do anything you can use a link with the property:

target="_parent"

as said previously, and then use:

document.getElementById('link').click();

to have it automatically redirect.

Example:

<!DOCTYPE HTML>

<html>

<head>

</head>

<body>

<a id="link" target="_parent" href="outsideDomain.html"></a>

<script type="text/javascript">
    document.getElementById('link').click();
</script>

</body>

</html>

Note: The javascript click() command must come after you declare the link.

Clear the form field after successful submission of php form

They remain in the fields because you are explicitly telling PHP to fill the form with the submitted data.

<input name="firstname" type="text" placeholder="First Name" required="required" 
value="<?php echo $_POST['firstname'];?>">
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ HERE

Just remove this, or if you want a condition to not do so make a if statement to that echo or just cleanup the $_POST fields.

$_POST = array(); // lets pretend nothing was posted

Or, if successful, redirect the user to another page:

header("Location: success.html");
exit; // Location header is set, pointless to send HTML, stop the script

Which by the way is the prefered method. If you keep the user in a page that was reached through a POST method, if he refreshes the page the form will be submitted again.

std::vector versus std::array in C++

std::vector is a template class that encapsulate a dynamic array1, stored in the heap, that grows and shrinks automatically if elements are added or removed. It provides all the hooks (begin(), end(), iterators, etc) that make it work fine with the rest of the STL. It also has several useful methods that let you perform operations that on a normal array would be cumbersome, like e.g. inserting elements in the middle of a vector (it handles all the work of moving the following elements behind the scenes).

Since it stores the elements in memory allocated on the heap, it has some overhead in respect to static arrays.

std::array is a template class that encapsulate a statically-sized array, stored inside the object itself, which means that, if you instantiate the class on the stack, the array itself will be on the stack. Its size has to be known at compile time (it's passed as a template parameter), and it cannot grow or shrink.

It's more limited than std::vector, but it's often more efficient, especially for small sizes, because in practice it's mostly a lightweight wrapper around a C-style array. However, it's more secure, since the implicit conversion to pointer is disabled, and it provides much of the STL-related functionality of std::vector and of the other containers, so you can use it easily with STL algorithms & co. Anyhow, for the very limitation of fixed size it's much less flexible than std::vector.

For an introduction to std::array, have a look at this article; for a quick introduction to std::vector and to the the operations that are possible on it, you may want to look at its documentation.


  1. Actually, I think that in the standard they are described in terms of maximum complexity of the different operations (e.g. random access in constant time, iteration over all the elements in linear time, add and removal of elements at the end in constant amortized time, etc), but AFAIK there's no other method of fulfilling such requirements other than using a dynamic array. As stated by @Lucretiel, the standard actually requires that the elements are stored contiguously, so it is a dynamic array, stored where the associated allocator puts it.

Pandas: convert dtype 'object' to int

It's simple

pd.factorize(df.purchase)[0]

Example:

labels, uniques = pd.factorize(['b', 'b', 'a', 'c', 'b'])`
labels
# array([0, 0, 1, 2, 0])
uniques
# array(['b', 'a', 'c'], dtype=object)

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

CharSequence VS String in Java?

An issue that DO arise in practical Android code is that comparing them with CharSequence.equals is valid but does not necessarily work as intended.

EditText t = (EditText )getView(R.id.myEditText); // Contains "OK"
Boolean isFalse = t.getText().equals("OK"); // will always return false.

Comparison should be made by

("OK").contentEquals(t.GetText()); 

What are .tpl files? PHP, web design

You have to learn Smarty syntax. That's a template system.

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

jQuery - adding elements into an array

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

Get Cell Value from Excel Sheet with Apache Poi

You have to use the FormulaEvaluator, as shown here. This will return a value that is either the value present in the cell or the result of the formula if the cell contains such a formula :

FileInputStream fis = new FileInputStream("/somepath/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("/somepath/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

// suppose your formula is in B3
CellReference cellReference = new CellReference("B3"); 
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol()); 

if (cell!=null) {
    switch (evaluator.evaluateFormulaCell(cell)) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cell.getBooleanCellValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println(cell.getNumericCellValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println(cell.getStringCellValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_ERROR:
            System.out.println(cell.getErrorCellValue());
            break;

        // CELL_TYPE_FORMULA will never occur
        case Cell.CELL_TYPE_FORMULA: 
            break;
    }
}

if you need the exact contant (ie the formla if the cell contains a formula), then this is shown here.

Edit : Added a few example to help you.

first you get the cell (just an example)

Row row = sheet.getRow(rowIndex+2);    
Cell cell = row.getCell(1);   

If you just want to set the value into the cell using the formula (without knowing the result) :

 String formula ="ABS((1-E"+(rowIndex + 2)+"/D"+(rowIndex + 2)+")*100)";    
 cell.setCellFormula(formula);    
 cell.setCellStyle(this.valueRightAlignStyleLightBlueBackground);

if you want to change the message if there is an error in the cell, you have to change the formula to do so, something like

IF(ISERR(ABS((1-E3/D3)*100));"N/A"; ABS((1-E3/D3)*100))

(this formula check if the evaluation return an error and then display the string "N/A", or the evaluation if this is not an error).

if you want to get the value corresponding to the formula, then you have to use the evaluator.

Hope this help,
Guillaume

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

Make an image responsive - the simplest way

Use Bootstrap to have a hustle free with your images as shown. Use class img-responsive and you are done:

<img src="cinqueterre.jpg" class="img-responsive" alt="Cinque Terre" width="304" height="236">