Programs & Examples On #Easyphp

EasyPHP is an integrated installer for an Apache, PHP, MySQL stack on Windows

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

You might also want to check your server configuration - sometimes the default for development type servers is to only accept connections from localhost.

How to find the php.ini file used by the command line?

Just run php --ini and look for Loaded Configuration File in output for the location of php.ini used by your CLI

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Just do one thing

open skype > tools > advance or advance settings Change port 80 to something else 7395

Restart your system then start Apache

How to find out what the date was 5 days ago?

General algorithms for date manipulation convert dates to and from Julian Day Numbers. Here is a link to a description of such algorithms, a description of the best algorithms currently known, and the mathematical proofs of each of them: http://web.archive.org/web/20140910060704/http://mysite.verizon.net/aesir_research/date/date0.htm

Pad a string with leading zeros so it's 3 characters long in SQL Server 2008

For those wanting to update their existing data here is the query:

update SomeEventTable set eventTime=RIGHT('00000'+ISNULL(eventTime, ''),5)

How to multiply values using SQL

You don't need to use GROUP BY but using it won't change the outcome. Just add an ORDER BY line at the end to sort your results.

SELECT player_name, player_salary, SUM(player_salary*1.1) AS NewSalary
FROM players
GROUP BY player_salary, player_name;
ORDER BY SUM(player_salary*1.1) DESC

How to capture the "virtual keyboard show/hide" event in Android?

Not sure if anyone post this. Found this solution simple to use!. The SoftKeyboard class is on gist.github.com. But while keyboard popup/hide event callback we need a handler to properly do things on UI:

/*
Somewhere else in your code
*/
RelativeLayout mainLayout = findViewById(R.layout.main_layout); // You must use your root layout
InputMethodManager im = (InputMethodManager) getSystemService(Service.INPUT_METHOD_SERVICE);

/*
Instantiate and pass a callback
*/
SoftKeyboard softKeyboard;
softKeyboard = new SoftKeyboard(mainLayout, im);
softKeyboard.setSoftKeyboardCallback(new SoftKeyboard.SoftKeyboardChanged()
{

    @Override
    public void onSoftKeyboardHide() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });
    }

    @Override
    public void onSoftKeyboardShow() 
    {
        // Code here
        new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    // Code here will run in UI thread
                    ...
                }
            });

    }   
});

What is N-Tier architecture?

It's my understanding that N-Tier separates business logic, client access and data from each other using separate physical machines. The theory is that one of them can be updated independently of the others.

What is the boundary in multipart/form-data?

Is the ??? free to be defined by the user?

Yes.

or is it supplied by the HTML?

No. HTML has nothing to do with that. Read below.

Is it possible for me to define the ??? as abcdefg?

Yes.

If you want to send the following data to the web server:

name = John
age = 12

using application/x-www-form-urlencoded would be like this:

name=John&age=12

As you can see, the server knows that parameters are separated by an ampersand &. If & is required for a parameter value then it must be encoded.

So how does the server know where a parameter value starts and ends when it receives an HTTP request using multipart/form-data?

Using the boundary, similar to &.

For example:

--XXX
Content-Disposition: form-data; name="name"

John
--XXX
Content-Disposition: form-data; name="age"

12
--XXX--

In that case, the boundary value is XXX. You specify it in the Content-Type header so that the server knows how to split the data it receives.

So you need to:

  • Use a value that won't appear in the HTTP data sent to the server.

  • Be consistent and use the same value everywhere in the request message.

python : list index out of range error while iteratively popping elements

List comprehension will lead you to a solution.

But the right way to copy a object in python is using python module copy - Shallow and deep copy operations.

l=[1,2,3,0,0,1]
for i in range(0,len(l)):
   if l[i]==0:
       l.pop(i)

If instead of this,

import copy
l=[1,2,3,0,0,1]
duplicate_l = copy.copy(l)
for i in range(0,len(l)):
   if l[i]==0:
       m.remove(i)
l = m

Then, your own code would have worked. But for optimization, list comprehension is a good solution.

Create or update mapping in elasticsearch

In later Elasticsearch versions (7.x), types were removed. Updating a mapping can becomes:

curl -XPUT "http://localhost:9200/test/_mapping" -H 'Content-Type: application/json' -d'{
  "properties": {
    "new_geo_field": {
      "type": "geo_point"
    }
  }
}'

As others have pointed out, if the field exists, you typically have to reindex. There are exceptions, such as adding a new sub-field or changing analysis settings.

You can't "create a mapping", as the mapping is created with the index. Typically, you'd define the mapping when creating the index (or via index templates):

curl -XPUT "http://localhost:9200/test" -H 'Content-Type: application/json' -d'{
  "mappings": {
    "properties": {
      "foo_field": {
        "type": "text"
      }
    }
  }
}'

That's because, in production at least, you'd want to avoid letting Elasticsearch "guess" new fields. Which is what generated this question: geo data was read as an array of long values.

How to check if a file is empty in Bash?

[ -s file.name ] || echo "file is empty"

What's the difference between unit, functional, acceptance, and integration tests?

This is very simple.

  1. Unit testing: This is the testing actually done by developers that have coding knowledge. This testing is done at the coding phase and it is a part of white box testing. When a software comes for development, it is developed into the piece of code or slices of code known as a unit. And individual testing of these units called unit testing done by developers to find out some kind of human mistakes like missing of statement coverage etc..

  2. Functional testing: This testing is done at testing (QA) phase and it is a part of black box testing. The actual execution of the previously written test cases. This testing is actually done by testers, they find the actual result of any functionality in the site and compare this result to the expected result. If they found any disparity then this is a bug.

  3. Acceptance testing: know as UAT. And this actually done by the tester as well as developers, management team, author, writers, and all who are involved in this project. To ensure the project is finally ready to be delivered with bugs free.

  4. Integration testing: The units of code (explained in point 1) are integrated with each other to complete the project. These units of codes may be written in different coding technology or may these are of different version so this testing is done by developers to ensure that all units of the code are compatible with other and there is no any issue of integration.

How to check if a given directory exists in Ruby

File.exist?("directory")

Dir[] returns an array, so it will never be nil. If you want to do it your way, you could do

Dir["directory"].empty?

which will return true if it wasn't found.

How do I uninstall a package installed using npm link?

npm link pain:

-Module name gulp-task

-Project name project-x


You want to link gulp-task:

1: Go to the gulp-task directory then do npm link this will symlink the project to your global modules

2: Go to your project project-x then do npm install make sure to remove the current node_modules directory


Now you want to remove this madness and use the real gulp-task, we have two options:

Option 1: Unlink via npm:

1: Go to your project and do npm unlink gulp-task this will remove the linked installed module

2: Go to the gulp-task directory and do npm unlink to remove symlink. Notice we didn't use the name of the module

3: celebrate


What if this didn't work, verify by locating your global installed module. My are location ls -la /usr/local/lib/node_modules/ if you are using nvm it will be a different path


Option 2: Remove the symlink like a normal linux guru

1: locate your global dependencies cd /usr/local/lib/node_modules/

2: removing symlink is simply using the rm command

rm gulp-task make sure you don't have / at the end

rm gulp-task/ is wrong

rm gulp-task ??

Maven version with a property

I have two recommendation for you

  1. Use CI Friendly Revision for all your artifacts. You can add -Drevision=2.0.1 in .mvn/maven.config file. So basically you define your version only at one location.
  2. For all external dependency create a property in parent file. You can use Apache Camel Parent Pom as reference

Check file extension in upload form in PHP

Not sure if this would have a faster computational time, but another option...

$acceptedFormats = array('gif', 'png', 'jpg');

if(!in_array(pathinfo($filename, PATHINFO_EXTENSION), $acceptedFormats))) {
    echo 'error';
}

Convert character to Date in R

You may be overcomplicating things, is there any reason you need the stringr package?

 df <- data.frame(Date = c("10/9/2009 0:00:00", "10/15/2009 0:00:00"))
 as.Date(df$Date, "%m/%d/%Y %H:%M:%S")

[1] "2009-10-09" "2009-10-15"

More generally and if you need the time component as well, use strptime:

strptime(df$Date, "%m/%d/%Y %H:%M:%S")

I'm guessing at what your actual data might look at from the partial results you give.

What's the difference between window.location and document.location in JavaScript?

document.location.constructor === window.location.constructor is true.

It's because it's exactly the same object as you can see from document.location===window.location.

So there's no need to compare the constructor or any other property.

Can a java lambda have more than 1 parameter?

It's possible if you define such a functional interface with multiple type parameters. There is no such built in type. (There are a few limited types with multiple parameters.)

@FunctionalInterface
interface Function6<One, Two, Three, Four, Five, Six> {
    public Six apply(One one, Two two, Three three, Four four, Five five);
}

public static void main(String[] args) throws Exception {
    Function6<String, Integer, Double, Void, List<Float>, Character> func = (a, b, c, d, e) -> 'z';
}

I've called it Function6 here. The name is at your discretion, just try not to clash with existing names in the Java libraries.


There's also no way to define a variable number of type parameters, if that's what you were asking about.


Some languages, like Scala, define a number of built in such types, with 1, 2, 3, 4, 5, 6, etc. type parameters.

How to open .SQLite files

SQLite is database engine, .sqlite or .db should be a database. If you don't need to program anything, you can use a GUI like sqlitebrowser or anything like that to view the database contents.

There is also spatialite, https://www.gaia-gis.it/fossil/spatialite_gui/index

Is an anchor tag without the href attribute safe?

It is OK, but at the same time can cause some browsers to become slow.

http://webdesignfan.com/yslow-tutorial-part-2-of-3-reducing-server-calls/

My advice is use <a href="#"></a>

If you're using JQuery remember to also use:

.click(function(event){
    event.preventDefault();
    // Click code here...
});

How do I print output in new line in PL/SQL?

In PL/SQL code, you can use: DBMS_OUTPUT.NEW_LINE;

Cocoa: What's the difference between the frame and the bounds?

The frame is the rectangle that defines the UIView with respect to its superview.

The bounds rect is the range of values that define that NSView's coordinate system.

i.e. anything in this rectangle will actually display in the UIView.

How to call execl() in C with the proper arguments?

execl("/home/vlc", 
  "/home/vlc", "/home/my movies/the movie i want to see.mkv", 
  (char*) NULL);

You need to specify all arguments, included argv[0] which isn't taken from the executable.

Also make sure the final NULL gets cast to char*.

Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html

How do I make a simple makefile for gcc on Linux?

For example this simple Makefile should be sufficient:

CC=gcc 
CFLAGS=-Wall

all: program
program: program.o
program.o: program.c program.h headers.h

clean:
    rm -f program program.o
run: program
    ./program

Note there must be <tab> on the next line after clean and run, not spaces.

UPDATE Comments below applied

Returning a pointer to a vector element in c++

Refer to dirkgently's and anon's answers, you can call the front function instead of begin function, so you do not have to write the *, but only the &.

Code Example:

vector<myObject> vec; //You have a vector of your objects
myObject first = vec.front(); //returns reference, not iterator, to the first object in the vector so you had only to write the data type in the generic of your vector, i.e. myObject, and not all the iterator stuff and the vector again and :: of course
myObject* pointer_to_first_object = &first; //* between & and first is not there anymore, first is already the first object, not iterator to it.

How to print the contents of RDD?

You can convert your RDD to a DataFrame then show() it.

// For implicit conversion from RDD to DataFrame
import spark.implicits._

fruits = sc.parallelize([("apple", 1), ("banana", 2), ("orange", 17)])

// convert to DF then show it
fruits.toDF().show()

This will show the top 20 lines of your data, so the size of your data should not be an issue.

+------+---+                                                                    
|    _1| _2|
+------+---+
| apple|  1|
|banana|  2|
|orange| 17|
+------+---+

Python list iterator behavior and next(iterator)

What is happening is that next(a) returns the next value of a, which is printed to the console because it is not affected.

What you can do is affect a variable with this value:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    b=next(a)
...
0
2
4
6
8

SQL Count for each date

It is most efficient to do your aggregation by integer and then convert back to datetime for presentation.

select 
    cast(daybucket - 1 as datetime) as count_date,
    counted_leads
from 
    (select 
         cast(created_date as int) as DayBucket,
         count(*) as counted_leads
     from mytable
     group by cast(created_date as int) ) as countByDay

message box in jquery

If you don't wont use jquery.ui(that is highly recommended), you can take a look at Block.UI plugin.

Alternate background colors for list items

If you want to do this purely in CSS then you'd have a class that you'd assign to each alternate list item. E.g.

<ul>
    <li class="alternate"><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li class="alternate"><a href="link">Link 3</a></li>
    <li><a href="link">Link 4</a></li>
    <li class="alternate"><a href="link">Link 5</a></li>
</ul>

If your list is dynamically generated, this task would be much easier.

If you don't want to have to manually update this content each time, you could use the jQuery library and apply a style alternately to each <li> item in your list:

<ul id="myList">
    <li><a href="link">Link 1</a></li>
    <li><a href="link">Link 2</a></li>
    <li><a href="link">Link 3</a></li>
    <li><a href="link">Link 4</a></li>
    <li><a href="link">Link 5</a></li>
</ul>

And your jQuery code:

$(document).ready(function(){
  $('#myList li:nth-child(odd)').addClass('alternate');
});

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

Change size of axes title and labels in ggplot2

I think a better way to do this is to change the base_size argument. It will increase the text sizes consistently.

g + theme_grey(base_size = 22)

As seen here.

How to put scroll bar only for modal-body?

What worked for me is setting the height to 100% the having the overflow on auto hope this will help

   <div style="height: 100%;overflow-y: auto;"> Some text o othre div scroll </div>

'router-outlet' is not a known element

If you are doing unit testing and get this error then Import RouterTestingModule into your app.component.spec.ts or inside your featured components' spec.ts:

import { RouterTestingModule } from '@angular/router/testing';

Add RouterTestingModule into your imports: [] like

describe('AppComponent', () => {

  beforeEach(async(() => {    
    TestBed.configureTestingModule({    
      imports: [    
        RouterTestingModule    
      ],
      declarations: [    
        AppComponent    
      ],    
    }).compileComponents();    
  }));

Trying to create a file in Android: open failed: EROFS (Read-only file system)

Adding

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

in manifest and using same as Martin:

path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES); 
File file = new File(path, "/" + fname);

It worked.

Ruby String to Date Conversion

str = "Tue, 10 Aug 2010 01:20:19 -0400 (EDT)"
str.to_date
=> Tue, 10 Aug 2010

How to remove the Flutter debug banner?

Well this is simple answer you want.

MaterialApp(
 debugShowCheckedModeBanner: false
)

But if you want to go deep with app (Want a release apk (which don't have debug banner) and if you are using android studio then go to

Run -> Flutter Run 'main.dart' in Relese mode

How can I print out C++ map values?

for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
    it != myMap.end(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator. You can use auto

for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
    std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}

Note the use of cbegin() and cend() functions.

Easier still, you can use the range-based for loop:

for(auto elem : myMap)
{
   std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}

Stretch Image to Fit 100% of Div Height and Width

Instead of setting absolute widths and heights, you can use percentages:

#mydiv img {
    height: 100%;
    width: 100%;
}

Undo working copy modifications of one file in Git?

If you have not yet pushed or otherwise shared your commit:

git diff --stat HEAD^...HEAD | \
fgrep filename_snippet_to_revert | cut -d' ' -f2 | xargs git checkout HEAD^ --
git commit -a --amend

How can I select checkboxes using the Selenium Java WebDriver?

The below code will first get all the checkboxes present on the page, and then deselect all the checked boxes.

List<WebElement> allCheckbox = driver.findElements(By
    .xpath("//input[@type='checkbox']"));

for (WebElement ele : allCheckbox) {
    if (ele.isSelected()) {
        ele.click();
    }
}

How to drop column with constraint?

Find the default constraint with this query here:

SELECT
    df.name 'Constraint Name' ,
    t.name 'Table Name',
    c.NAME 'Column Name'
FROM sys.default_constraints df
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id

This gives you the name of the default constraint, as well as the table and column name.

When you have that information you need to first drop the default constraint:

ALTER TABLE dbo.YourTable
DROP CONSTRAINT name-of-the-default-constraint-here

and then you can drop the column

ALTER TABLE dbo.YourTable DROP COLUMN YourColumn

Get root password for Google Cloud Engine VM

I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.

So here are steps.

  1. Go to IAM & Admin
  2. Select IAM
  3. Find your user name service account (basically your google account) and click Edit-member
  4. Add another role --> select 'Compute Engine' - 'Compute Admin'
  5. Restart your Compute VM
  6. open SSH shell and run the command 'sudo passwd'
  7. enter a brand new password. Voilà!

Concatenating string and integer in python

Modern string formatting:

"{} and {}".format("string", 1)

How do I check for vowels in JavaScript?

This is a rough RegExp function I would have come up with (it's untested)

function isVowel(char) {
    return /^[aeiou]$/.test(char.toLowerCase());
}

Which means, if (char.length == 1 && 'aeiou' is contained in char.toLowerCase()) then return true.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

There is another option not mentioned previously:

  • Pieceable Viewer has unfortunately stopped its service at December 31, 2012 but open-sourced its software. You need to compile your iOS application for the emulator and Pieceable's software will embed it in a webpage which hosts the application. This webpage can be used to run the iOS application. See Pieceable's for more details.

How to enable assembly bind failure logging (Fusion) in .NET

The Fusion Log Settings Viewer changer script is bar none the best way to do this.

In ASP.NET, it has been tricky at times to get this to work correctly. This script works great and was listed on Scott Hanselman's Power Tool list as well. I've personally used it for years and its never let me down.

Text-align class for inside a table

The following lines of code are working properly. You can assign the classes like text-center, left or right, The text will align accordingly.

<p class="text-center">Day 1</p> 
<p class="text-left">Day 2</p> 
<p class="text-right">Day 3</p>

Here there isn't any need to create any external class. These are the Bootstrap classes and have their own property.

The Role Manager feature has not been enabled

I found this question due the exception mentioned in it. My Web.Config didn't have any <roleManager> tag. I realized that even if I added it (as Infotekka suggested), it ended up in a Database exception. After following the suggestions in the other answers in here, none fully solved the problem.

Since these Web.Config tags can be automatically generated, it felt wrong to solve it by manually adding them. If you are in a similar case, undo all the changes you made to Web.Config and in Visual Studio:

  1. Press Ctrl+Q, type nuget and click on "Manage NuGet Packages";
  2. Press Ctrl+E, type providers and in the list it should show up "Microsoft ASP.NET Universal Providers Core Libraries" and "Microsoft ASP.NET Universal Providers for LocalDB" (both created by Microsoft);
  3. Click on the Install button in both of them and close the NuGet window;
  4. Check your Web.config and now you should have at least one <providers> tag inside Profile, Membership, SessionState tags and also inside the new RoleManager tag, like this:

    <roleManager defaultProvider="DefaultRoleProvider">
        <providers>
           <add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=NUMBER" connectionStringName="DefaultConnection" applicationName="/" />
        </providers>
    </roleManager>
    
  5. Add enabled="true" like so:

    <roleManager defaultProvider="DefaultRoleProvider" enabled="true">
    
  6. Press F6 to Build and now it should be OK to proceed to a database update without having that exception:

    1. Press Ctrl+Q, type manager, click on "Package Manager Console";
    2. Type update-database -verbose and the Seed method will run just fine (if you haven't messed elsewhere) and create a few tables in your Database;
    3. Press Ctrl+W+L to open the Server Explorer and you should be able to check in Data Connections > DefaultConnection > Tables the Roles and UsersInRoles tables among the newly created tables!

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

Open System Preference > MySQL > Initialize Database > Use Legacy Password Encription

Mockito : doAnswer Vs thenReturn

You should use thenReturn or doReturn when you know the return value at the time you mock a method call. This defined value is returned when you invoke the mocked method.

thenReturn(T value) Sets a return value to be returned when the method is called.

@Test
public void test_return() throws Exception {
    Dummy dummy = mock(Dummy.class);
    int returnValue = 5;

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenReturn(returnValue);
    doReturn(returnValue).when(dummy).stringLength("dummy");
}

Answer is used when you need to do additional actions when a mocked method is invoked, e.g. when you need to compute the return value based on the parameters of this method call.

Use doAnswer() when you want to stub a void method with generic Answer.

Answer specifies an action that is executed and a return value that is returned when you interact with the mock.

@Test
public void test_answer() throws Exception {
    Dummy dummy = mock(Dummy.class);
    Answer<Integer> answer = new Answer<Integer>() {
        public Integer answer(InvocationOnMock invocation) throws Throwable {
            String string = invocation.getArgumentAt(0, String.class);
            return string.length() * 2;
        }
    };

    // choose your preferred way
    when(dummy.stringLength("dummy")).thenAnswer(answer);
    doAnswer(answer).when(dummy).stringLength("dummy");
}

Line Break in XML?

In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

phpmyadmin "no data received to import" error, how to fix?

If you are using xampp you can find php.ini file by going into xampp control panel and and clicking config button in front of Apache.

How to get the unix timestamp in C#

You get a unix timestamp in C# by using DateTime.UtcNow and subtracting the epoch time of 1970-01-01.

e.g.

Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;

DateTime.UtcNow can be replaced with any DateTime object that you would like to get the unix timestamp for.

There is also a field, DateTime.UnixEpoch, which is very poorly documented by MSFT, but may be a substitute for new DateTime(1970, 1, 1)

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

Getting rid of bullet points from <ul>

your code:

ul#otis {
    list-style-type: none;
}

my suggestion:

#otis {
    list-style-type: none;

}

in css you need only use the #id not element#id. more helpful hints are provided here: w3schools

Error in spring application context schema

I also faced this problem and fixed it by removing version part from the XSD name.

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd to http://www.springframework.org/schema/beans/spring-beans.xsd

Versions less XSD's are mapped to the current version of the framework used in the application.

How to set app icon for Electron / Atom Shell App

If you want to update the app icon in the taskbar, then Update following in main.js (if using typescript then main.ts)

win.setIcon(path.join(__dirname, '/src/assets/logo-small.png'));

__dirname points to the root directory (same directory as package.json) of your application.

How to subtract X days from a date using Java calendar?

tl;dr

LocalDate.now().minusDays( 10 )

Better to specify time zone.

LocalDate.now( ZoneId.of( "America/Montreal" ) ).minusDays( 10 )

Details

The old date-time classes bundled with early versions of Java, such as java.util.Date/.Calendar, have proven to be troublesome, confusing, and flawed. Avoid them.

java.time

Java 8 and later supplants those old classes with the new java.time framework. See Tutorial. Defined by JSR 310, inspired by Joda-Time, and extended by theThreeTen-Extra project. The ThreeTen-Backport project back-ports the classes to Java 6 & 7; the ThreeTenABP project to Android.

The Question is vague, not clear if it asks for a date-only or a date-time.

LocalDate

For a date-only, without time-of-day, use the LocalDate class. Note that a time zone in crucial in determining a date such as "today".

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
LocalDate tenDaysAgo = today.minusDays( 10 );

ZonedDateTime

If you meant a date-time, then use the Instant class to get a moment on the timeline in UTC. From there, adjust to a time zone to get a ZonedDateTime object.

Instant now = Instant.now();  // UTC.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
ZonedDateTime tenDaysAgo = zdt.minusDays( 10 );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Why is it OK to return a 'vector' from a function?

Pre C++11:

The function will not return the local variable, but rather a copy of it. Your compiler might however perform an optimization where no actual copy action is made.

See this question & answer for further details.

C++11:

The function will move the value. See this answer for further details.

JDK on OSX 10.7 Lion

On newer versions of OS X you should find ALL JREs (and JDKs) under

/Library/Java/JavaVirtualMachines/

/System/Library/Java/JavaVirtualMachines/

the old path

/System/Library/Frameworks/JavaVM.framework/

has been deprecated.

Here is the official deprecation note:

http://developer.apple.com/library/mac/#releasenotes/Java/JavaSnowLeopardUpdate3LeopardUpdate8RN/NewandNoteworthy/NewandNoteworthy.html#//apple_ref/doc/uid/TP40010380-CH4-SW1

Get selected row item in DataGrid WPF

You can use the SelectedItem property to get the currently selected object, which you can then cast into the correct type. For instance, if your DataGrid is bound to a collection of Customer objects you could do this:

Customer customer = (Customer)myDataGrid.SelectedItem;

Alternatively you can bind SelectedItem to your source class or ViewModel.

<Grid DataContext="MyViewModel">
    <DataGrid ItemsSource="{Binding Path=Customers}"
              SelectedItem="{Binding Path=SelectedCustomer, Mode=TwoWay}"/>
</Grid>    

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

How do I check if the mouse is over an element in jQuery?

JUST FYI for future finders of this.

I made a jQuery plugin that can do this and a lot more. In my plugin, to get all elements the cursor is currently hovered over, simply do the following:

$.cursor("isHover"); // will return jQ object of all elements the cursor is 
                     // currently over & doesn't require timer

As I mentioned, it also has alot of other uses as you can see in the

jsFiddle found here

Maven project version inheritance - do I have to specify the parent version?

As Yanflea mentioned, there is a way to go around this.

In Maven 3.5.0 you can use the following way of transferring the version down from the parent project:

Parent POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mydomain</groupId>
    <artifactId>myprojectparent</artifactId>
    <packaging>pom</packaging>
    <version>${myversion}</version>
    <name>MyProjectParent</name>

    <properties>
        <myversion>0.1-SNAPSHOT</myversion>
    </properties>

    <modules>
        <module>modulefolder</module>
    </modules>
    ...
</project>

Module POM.xml

<project ...>
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.mydomain</groupId>
        <artifactId>myprojectmodule</artifactId>
        <version>${myversion}</version> <!-- This still needs to be set, but you can use properties from parent -->
    </parent>

    <groupId>se.car_o_liner</groupId>
    <artifactId>vinno</artifactId>
    <packaging>war</packaging>
    <name>Vinno</name>
    <!-- Note that there's no version specified; it's inherited from parent -->
    ...
</project>

You are free to change myversion to whatever you want that isn't a reserved property.

JUnit: how to avoid "no runnable methods" in test utils classes

In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.

Php artisan make:auth command is not defined

In short and precise, all you need to do is

composer require laravel/ui --dev

php artisan ui vue --auth and then the migrate php artisan migrate.

Just for an overview of Laravel Authentication

Laravel Authentication facilities comes with Guard and Providers, Guards define how users are authenticated for each request whereas Providers define how users are retrieved from you persistent storage.

Database Consideration - By default Laravel includes an App\User Eloquent Model in your app directory.

Auth Namespace - App\Http\Controllers\Auth

Controllers - RegisterController, LoginController, ForgotPasswordController and ResetPasswordController, all names are meaningful and easy to understand!

Routing - Laravel/ui package provides a quick way to scaffold all the routes and views you need for authentication using a few simple commands (as mentioned in the start instead of make:auth).

You can disable any newly created controller, e. g. RegisterController and modify your route declaration like, Auth::routes(['register' => false]); For further detail please look into the Laravel Documentation.

C++ variable has initializer but incomplete type?

I got a similar error and hit this page while searching the solution.

With Qt this error can happen if you forget to add the QT_WRAP_CPP( ... ) step in your build to run meta object compiler (moc). Including the Qt header is not sufficient.

fetch from origin with deleted remote branches?

You need to do the following

git fetch -p

in order to synchronize your branch list. The git manual says

-p, --prune
After fetching, remove any remote-tracking references that no longer exist on the remote. Tags are not subject to pruning if they are fetched only because of the default tag auto-following or due to a --tags option. However, if tags are fetched due to an explicit refspec (either on the command line or in the remote configuration, for example if the remote was cloned with the --mirror option), then they are also subject to pruning.

I personally like to use git fetch origin -p --progress because it shows a progress indicator.

Delete a row in DataGridView Control in VB.NET

If dgv(11, dgv.CurrentRow.Index).Selected = True Then
    dgv.Rows.RemoveAt(dgv.CurrentRow.Index)
Else
    Exit Sub
End If

Android studio Gradle build speed up

Acording to this page of the Android Team of Wikimedia Apps, a good way of optimize Gradle builds is adding this lines to your ~/.gradle/gradle.properties

org.gradle.daemon=true                                                          
org.gradle.parallel=true
org.gradle.configureondemand=true
org.gradle.jvmargs=-Xmx2048M

For those who do not have the file there are two ways to do it:

  1. Add the file locally in your project by creating a file called gradle.properties in the project root or,

  2. You can set them globally for all your projects by creating the same file in your home directory (%UserProfile%.gradle on Windows, ~/.gradle on Linux and Mac OS X)

    It is a good practice to set the properties in your home directory, rather than on a project level.

Is mongodb running?

You can use the below command, to check MongoDB status, e.g: sudo service MongoDB status which displays the status of MongoDB service as like the screenshot:

MongoDB status

Adb over wireless without usb cable at all for not rooted phones

The question is about a non rooted device but if it is rooted the simplest way would be to:

From the terminal on your phone, do this:

su
setprop service.adb.tcp.port 5555
stop adbd
start adbd

See this answer for full details.

How do I name the "row names" column in r

It sounds like you want to convert the rownames to a proper column of the data.frame. eg:

# add the rownames as a proper column
myDF <- cbind(Row.Names = rownames(myDF), myDF)
myDF

#           Row.Names id val vr2
# row_one     row_one  A   1  23
# row_two     row_two  A   2  24
# row_three row_three  B   3  25
# row_four   row_four  C   4  26

If you want to then remove the original rownames:

rownames(myDF) <- NULL
myDF
#   Row.Names id val vr2
# 1   row_one  A   1  23
# 2   row_two  A   2  24
# 3 row_three  B   3  25
# 4  row_four  C   4  26


Alternatively, if all of your data is of the same class (ie, all numeric, or all string), you can convert to Matrix and name the dimnames

myMat <- as.matrix(myDF)
names(dimnames(myMat)) <- c("Names.of.Rows", "")
myMat

# Names.of.Rows id  val vr2 
#   row_one   "A" "1" "23"
#   row_two   "A" "2" "24"
#   row_three "B" "3" "25"
#   row_four  "C" "4" "26"

How to close existing connections to a DB

Perfect solution provided by Stev.org: http://www.stev.org/post/2011/03/01/MS-SQL-Kill-connections-by-host.aspx

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[KillConnectionsHost]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[KillConnectionsHost]
GO


/****** Object:  StoredProcedure [dbo].[KillConnectionsHost]    Script Date: 10/26/2012 13:59:39 ******/

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[KillConnectionsHost] @hostname varchar(MAX)
AS
    DECLARE @spid int
    DECLARE @sql varchar(MAX)

    DECLARE cur CURSOR FOR
        SELECT spid FROM sys.sysprocesses P
            JOIN sys.sysdatabases D ON (D.dbid = P.dbid)
            JOIN sys.sysusers U ON (P.uid = U.uid)
            WHERE hostname = @hostname AND hostname != ''
            AND P.spid != @@SPID

    OPEN cur

    FETCH NEXT FROM cur
        INTO @spid

    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT CONVERT(varchar, @spid)

        SET @sql = 'KILL ' + RTRIM(@spid)
        PRINT @sql
        EXEC(@sql)

        FETCH NEXT FROM cur
            INTO @spid
    END

    CLOSE cur
    DEALLOCATE cur
GO

Datagridview full row selection but get single cell value

this get me the text value of exact cell in data grid view

private void dataGridView_SelectionChanged(object sender, EventArgs e)
    {
        label1.Text = dataGridView.CurrentRow.Cells[#].Value.ToString();
    }

you can see it in label and change # wih the index of the exact cell you want

How to read line by line of a text area HTML tag

This would give you all valid numeric values in lines. You can change the loop to validate, strip out invalid characters, etc - whichever you want.

var lines = [];
$('#my_textarea_selector').val().split("\n").each(function ()
{
    if (parseInt($(this) != 'NaN')
        lines[] = parseInt($(this));
}

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

concat.js is being included in the concat task's source files public/js/*.js. You could have a task that removes concat.js (if the file exists) before concatenating again, pass an array to explicitly define which files you want to concatenate and their order, or change the structure of your project.

If doing the latter, you could put all your sources under ./src and your built files under ./dest

src
+-- css
¦   +-- 1.css
¦   +-- 2.css
¦   +-- 3.css
+-- js
    +-- 1.js
    +-- 2.js
    +-- 3.js

Then set up your concat task

concat: {
  js: {
    src: 'src/js/*.js',
    dest: 'dest/js/concat.js'
  },
  css: {
    src: 'src/css/*.css',
    dest: 'dest/css/concat.css'
  }
},

Your min task

min: {
  js: {
    src: 'dest/js/concat.js',
    dest: 'dest/js/concat.min.js'
  }
},

The build-in min task uses UglifyJS, so you need a replacement. I found grunt-css to be pretty good. After installing it, load it into your grunt file

grunt.loadNpmTasks('grunt-css');

And then set it up

cssmin: {
  css:{
    src: 'dest/css/concat.css',
    dest: 'dest/css/concat.min.css'
  }
}

Notice that the usage is similar to the built-in min.

Change your default task to

grunt.registerTask('default', 'concat min cssmin');

Now, running grunt will produce the results you want.

dest
+-- css
¦   +-- concat.css
¦   +-- concat.min.css
+-- js
    +-- concat.js
    +-- concat.min.js

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

SQL Query to fetch data from the last 30 days?

Pay attention to one aspect when doing "purchase_date>(sysdate-30)": "sysdate" is the current date, hour, minute and second. So "sysdate-30" is not exactly "30 days ago", but "30 days ago at this exact hour".

If your purchase dates have 00.00.00 in hours, minutes, seconds, better doing:

where trunc(purchase_date)>trunc(sysdate-30)

(this doesn't take hours, minutes and seconds into account).

How can I check if an element exists in the visible DOM?

Try the following. It is the most reliable solution:

window.getComputedStyle(x).display == ""

For example,

var x = document.createElement("html")
var y = document.createElement("body")
var z = document.createElement("div")
x.appendChild(y);
y.appendChild(z);

z.style.display = "block";

console.log(z.closest("html") == null); // 'false'
console.log(z.style.display); // 'block'
console.log(window.getComputedStyle(z).display == ""); // 'true'

How do I determine if a checkbox is checked?

You can use this code, it can return true or false:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  _x000D_
  //add selector of your checkbox_x000D_
_x000D_
  var status=$('#IdSelector')[0].checked;_x000D_
  _x000D_
  console.log(status);_x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

How I can delete in VIM all text from current line to end of file?

Just add another way , in normal mode , type ctrl+v then G, select the rest, then D, I don't think it is effective , you should do like @Ed Guiness, head -n 20 > filename in linux.

PHP random string generator

This creates a 20 character long hexadecimal string:

$string = bin2hex(openssl_random_pseudo_bytes(10)); // 20 chars

In PHP 7 (random_bytes()):

$string = base64_encode(random_bytes(10)); // ~14 characters, includes /=+
// or
$string = substr(str_replace(['+', '/', '='], '', base64_encode(random_bytes(32))), 0, 32); // 32 characters, without /=+
// or
$string = bin2hex(random_bytes(10)); // 20 characters, only 0-9a-f

Undefined symbols for architecture armv7

rename your m file (which includes methods funcs) to mm or vice versa will fix your problem. mine solved renaming mm to m or m to mm.

Get item in the list in Scala?

Safer is to use lift so you can extract the value if it exists and fail gracefully if it does not.

data.lift(2)

This will return None if the list isn't long enough to provide that element, and Some(value) if it is.

scala> val l = List("a", "b", "c")
scala> l.lift(1)
Some("b")
scala> l.lift(5)
None

Whenever you're performing an operation that may fail in this way it's great to use an Option and get the type system to help make sure you are handling the case where the element doesn't exist.

Explanation:

This works because List's apply (which sugars to just parentheses, e.g. l(index)) is like a partial function that is defined wherever the list has an element. The List.lift method turns the partial apply function (a function that is only defined for some inputs) into a normal function (defined for any input) by basically wrapping the result in an Option.

How to find sum of multiple columns in a table in SQL Server 2005?

You must also be aware of null records:

SELECT  (ISNULL(Val1,0) + ISNULL(Val2,0) + ISNULL(Val3,0)) as 'Total'
FROM Emp

Usage of ISNULL:

ISNULL(col_Name, replace value)

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression

Change it like this and it should work:

var key = item.Key.ToString();
IQueryable<entity> pages = from p in context.pages
                           where  p.Serial == key
                           select p;

The reason why the exception is not thrown in the line the LINQ query is declared but in the line of the foreach is the deferred execution feature, i.e. the LINQ query is not executed until you try to access the result. And this happens in the foreach and not earlier.

Sql Server string to date conversion

If you want SQL Server to try and figure it out, just use CAST CAST('whatever' AS datetime) However that is a bad idea in general. There are issues with international dates that would come up. So as you've found, to avoid those issues, you want to use the ODBC canonical format of the date. That is format number 120, 20 is the format for just two digit years. I don't think SQL Server has a built-in function that allows you to provide a user given format. You can write your own and might even find one if you search online.

Return sql rows where field contains ONLY non-alphanumeric characters

This will not work correctly, e.g. abcÑxyz will pass thru this as it has a,b,c... you need to work with Collate or check each byte.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

In postgres simply : TO_CHAR(timestamp_column, 'DD/MM/YYYY') as submission_date

Where can I find "make" program for Mac OS X Lion?

Have you installed Xcode and the developer tools? I think make, along with gcc and friends, is installed with that and not before. Xcode 4.1 for Lion is free.

SQL Inner Join On Null Values

If you want null values to be included from Y.QID then Fastest way is

SELECT * FROM Y LEFT JOIN X ON y.QID = X.QID

Note: this solution is applicable only if you need null values from Left table i.e. Y (in above case).

Otherwise INNER JOIN x ON x.qid IS NOT DISTINCT FROM y.qid is right way to do

How do I list all tables in a schema in Oracle SQL?

If you need to get the size of the table as well, this will be handy:

select SEGMENT_NAME, PARTITION_NAME, BYTES from user_segments where SEGMENT_TYPE='TABLE' order by 1

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

How to get the <html> tag HTML with JavaScript / jQuery?

In addition to some of the other answers, you could also access the HTML element via:

var htmlEl = document.body.parentNode;

Then you could get the inner HTML content:

var inner = htmlEl.innerHTML;

Doing so this way seems to be marginally faster. If you are just obtaining the HTML element, however, document.body.parentNode seems to be quite a bit faster.

After you have the HTML element, you can mess with the attributes with the getAttribute and setAttribute methods.

For the DOCTYPE, you could use document.doctype, which was elaborated upon in this question.

Javascript parse float is ignoring the decimals after my comma

It is better to use this syntax to replace all the commas in a case of a million 1,234,567

var string = "1,234,567";
string = string.replace(/[^\d\.\-]/g, ""); 
var number = parseFloat(string);
console.log(number)

The g means to remove all commas.

Check the Jsfiddle demo here.

How to calculate moving average without keeping the count and data-total?

New average = old average * (n-1)/n + new value /n

This is assuming the count only changed by one value. In case it is changed by M values then:

new average = old average * (n-len(M))/n + (sum of values in M)/n).

This is the mathematical formula (I believe the most efficient one), believe you can do further code by yourselves

What represents a double in sql server?

float in SQL Server actually has [edit:almost] the precision of a "double" (in a C# sense).

float is a synonym for float(53). 53 is the bits of the mantissa.

.NET double uses 54 bits for the mantissa.

Real differences between "java -server" and "java -client"?

I've not noticed any difference in startup time between the 2, but clocked a very minimal improvement in application performance with "-server" (Solaris server, everyone using SunRays to run the app). That was under 1.5.

AngularJS HTTP post to PHP and undefined

It's an old question but it worth to mention that in Angular 1.4 $httpParamSerializer is added and when using $http.post, if we use $httpParamSerializer(params) to pass the parameters, everything works like a regular post request and no JSON deserializing is needed on server side.

https://docs.angularjs.org/api/ng/service/$httpParamSerializer

Angular: 'Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays'

Remember to pipe Observables to async, like *ngFor item of items$ | async, where you are trying to *ngFor item of items$ where items$ is obviously an Observable because you notated it with the $ similar to items$: Observable<IValuePair>, and your assignment may be something like this.items$ = this.someDataService.someMethod<IValuePair>() which returns an Observable of type T.

Adding to this... I believe I have used notation like *ngFor item of (items$ | async)?.someProperty

delete vs delete[] operators in C++

The delete operator deallocates memory and calls the destructor for a single object created with new.

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].

Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.

How do you cache an image in Javascript

as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.

var images = [
'/path/to/image1.png',
'/path/to/image2.png'
];

$(images).each(function() {
var image = $('<img />').attr('src', this);
});

CSS Input with width: 100% goes outside parent's bound

If all above fail, try setting the following properties for your input, to have it take max space but not overflow:

input {
    min-width: 100%;
    max-width: 100%;
}

How to solve "Connection reset by peer: socket write error"?

The socket has been closed by the client (browser).

A bug in your code:

byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:

byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

Sorting a vector of custom objects

Below is the code using lambdas

#include "stdafx.h"
#include <vector>
#include <algorithm>

using namespace std;

struct MyStruct
{
    int key;
    std::string stringValue;

    MyStruct(int k, const std::string& s) : key(k), stringValue(s) {}
};

int main()
{
    std::vector < MyStruct > vec;

    vec.push_back(MyStruct(4, "test"));
    vec.push_back(MyStruct(3, "a"));
    vec.push_back(MyStruct(2, "is"));
    vec.push_back(MyStruct(1, "this"));

    std::sort(vec.begin(), vec.end(), 
        [] (const MyStruct& struct1, const MyStruct& struct2)
        {
            return (struct1.key < struct2.key);
        }
    );
    return 0;
}

Jackson overcoming underscores in favor of camel-case

The current best practice is to configure Jackson within the application.yml (or properties) file.

Example:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE

If you have more complex configuration requirements, you can also configure Jackson programmatically.

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        // insert other configurations
    }

} 

How do I tell Matplotlib to create a second (new) plot, then later plot on the old one?

One way I found after some struggling is creating a function which gets data_plot matrix, file name and order as parameter to create boxplots from the given data in the ordered figure (different orders = different figures) and save it under the given file_name.

def plotFigure(data_plot,file_name,order):
    fig = plt.figure(order, figsize=(9, 6))
    ax = fig.add_subplot(111)
    bp = ax.boxplot(data_plot)
    fig.savefig(file_name, bbox_inches='tight')
    plt.close()

How to connect to remote Redis server?

There are two ways to connect remote redis server using redis-cli:

1. Using host & port individually as options in command

redis-cli -h host -p port

If your instance is password protected

redis-cli -h host -p port -a password

e.g. if my-web.cache.amazonaws.com is the host url and 6379 is the port

Then this will be the command:

redis-cli -h my-web.cache.amazonaws.com -p 6379

if 92.101.91.8 is the host IP address and 6379 is the port:

redis-cli -h 92.101.91.8 -p 6379

command if the instance is protected with password pass123:

redis-cli -h my-web.cache.amazonaws.com -p 6379 -a pass123

2. Using single uri option in command

redis-cli -u redis://password@host:port

command in a single uri form with username & password

redis-cli -u redis://username:password@host:port

e.g. for the same above host - port configuration command would be

redis-cli -u redis://[email protected]:6379

command if username is also provided user123

redis-cli -u redis://user123:[email protected]:6379

This detailed answer was for those who wants to check all options. For more information check documentation: Redis command line usage

Switch case on type c#

The following code works more or less as one would expect a type-switch that only looks at the actual type (e.g. what is returned by GetType()).

public static void TestTypeSwitch()
{
    var ts = new TypeSwitch()
        .Case((int x) => Console.WriteLine("int"))
        .Case((bool x) => Console.WriteLine("bool"))
        .Case((string x) => Console.WriteLine("string"));

    ts.Switch(42);     
    ts.Switch(false);  
    ts.Switch("hello"); 
}

Here is the machinery required to make it work.

public class TypeSwitch
{
    Dictionary<Type, Action<object>> matches = new Dictionary<Type, Action<object>>();
    public TypeSwitch Case<T>(Action<T> action) { matches.Add(typeof(T), (x) => action((T)x)); return this; } 
    public void Switch(object x) { matches[x.GetType()](x); }
}

Streaming Audio from A URL in Android using MediaPlayer?

Looking my projects:

  1. https://github.com/master255/ImmortalPlayer http/FTP support, One thread to read, send and save to cache data. Most simplest way and most fastest work. Complex logic - best way!
  2. https://github.com/master255/VideoViewCache Simple Videoview with cache. Two threads for play and save data. Bad logic, but if you need then use this.

What does asterisk * mean in Python?

See Function Definitions in the Language Reference.

If the form *identifier is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form **identifier is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.

Also, see Function Calls.

Assuming that one knows what positional and keyword arguments are, here are some examples:

Example 1:

# Excess keyword argument (python 2) example:
def foo(a, b, c, **args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo(a="testa", d="excess", c="testc", b="testb", k="another_excess")

As you can see in the above example, we only have parameters a, b, c in the signature of the foo function. Since d and k are not present, they are put into the args dictionary. The output of the program is:

a = testa
b = testb
c = testc
{'k': 'another_excess', 'd': 'excess'}

Example 2:

# Excess positional argument (python 2) example:
def foo(a, b, c, *args):
    print "a = %s" % (a,)
    print "b = %s" % (b,)
    print "c = %s" % (c,)
    print args

foo("testa", "testb", "testc", "excess", "another_excess")

Here, since we're testing positional arguments, the excess ones have to be on the end, and *args packs them into a tuple, so the output of this program is:

a = testa
b = testb
c = testc
('excess', 'another_excess')

You can also unpack a dictionary or a tuple into arguments of a function:

def foo(a,b,c,**args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argdict = dict(a="testa", b="testb", c="testc", excessarg="string")
foo(**argdict)

Prints:

a=testa
b=testb
c=testc
args={'excessarg': 'string'}

And

def foo(a,b,c,*args):
    print "a=%s" % (a,)
    print "b=%s" % (b,)
    print "c=%s" % (c,)
    print "args=%s" % (args,)

argtuple = ("testa","testb","testc","excess")
foo(*argtuple)

Prints:

a=testa
b=testb
c=testc
args=('excess',)

Does a "Find in project..." feature exist in Eclipse IDE?

Ctrl + Alt + G can be used to find selected text across a workspace in eclipse.

OSX: ? Option + ? Command + G

Android Volley - BasicNetwork.performRequest: Unexpected response code 400

Me too got the same error but in my case I was calling url with blank spaces.

Then, I fixed it by parsing like below.

String url = "Your URL Link";

url = url.replaceAll(" ", "%20");

StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                            new com.android.volley.Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                ...
                                ...
                                ...

Link to the issue number on GitHub within a commit message

If you want to link to a GitHub issue and close the issue, you can provide the following lines in your Git commit message:

Closes #1.
Closes GH-1.
Closes gh-1.

(Any of the three will work.) Note that this will link to the issue and also close it. You can find out more in this blog post (start watching the embedded video at about 1:40).

I'm not sure if a similar syntax will simply link to an issue without closing it.

Formatting Phone Numbers in PHP

Check Phone number

$phone = '+385 99 1234 1234'

$str = preg_match('/^\+?\d{1,3}[\s-]?\d{1,3}[\s-]?\d{1,4}[\s-]?\d{1,4}$/', $phone);

if($str){
return true;
}else{
return false;
}

Bootstrap datetimepicker is not a function

Try to use datepicker/ timepicker instead of datetimepicker like:

replace:

$('#datetimepicker1').datetimepicker();

with:

$('#datetimepicker1').datepicker(); // or timepicker for time picker

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

How can I determine the direction of a jQuery scroll event?

var tempScrollTop, currentScrollTop = 0; 

$(window).scroll(function(){ 

   currentScrollTop = $("#div").scrollTop(); 

   if (tempScrollTop > currentScrollTop ) {
       // upscroll code
   }
  else if (tempScrollTop < currentScrollTop ){
      // downscroll code
  }

  tempScrollTop = currentScrollTop; 
} 

or use the mousewheel extension, see here.

IP to Location using Javascript

You can submit the IP you receive to an online geolocation service, such as http://www.geoplugin.net/json.gp?ip=<your ip here>&jsoncallback=<suitable javascript function in your source>, then including the source it returns which will run the function you specify in jsoncallback with the geolocation information.

Alternatively, you may want to look into HTML5's geolocation features -- you can see a demo of it in action here. The advantage of this is that you do not need to make requests to foreign servers, but it may not work on browsers that do not support HTML5.

How to get Time from DateTime format in SQL?

I often use this script to get Time from DateTime:

SELECT CONVERT(VARCHAR(9),RIGHT(YOURCOLUMN_DATETIME,9),108) FROM YOURTABLE

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.

You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

class MObject {        
        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };

OR by parameterized constructor

class MObject {
        public MObject(int code, string org)
        {
            Code = code;
            Org = org;
        }

        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};


        

How can I represent 'Authorization: Bearer <token>' in a Swagger Spec (swagger.json)

My Hackie way to solve this was by modifying the swagger.go file in the echo-swagger package in my case:

At the bottom of the file update the window.onload function to include a requestInterceptor which correctly formats the token.

window.onload = function() {
  // Build a system
  const ui = SwaggerUIBundle({
  url: "{{.URL}}",
  dom_id: '#swagger-ui',
  validatorUrl: null,
  presets: [
    SwaggerUIBundle.presets.apis,
    SwaggerUIStandalonePreset
  ],
  plugins: [
    SwaggerUIBundle.plugins.DownloadUrl
  ,
  layout: "StandaloneLayout",
  requestInterceptor: (req) => {
    req.headers.Authorization = "Bearer " + req.headers.Authorization
  return req
  }
})

window.ui = ui

}

How to find a Java Memory Leak

NetBeans has a built-in profiler.

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

Create a basic matrix in C (input by user !)

//R stands for ROW and C stands for COLUMN:

//i stands for ROW and j stands for COLUMN:

#include<stdio.h>

int main(){

    int M[100][100];

    int R,C,i,j;

    printf("Please enter how many rows you want:\n");

    scanf("%d",& R);

    printf("Please enter how column you want:\n");

    scanf("%d",& C);

    printf("Please enter your matrix:\n");

    for(i = 0; i < R; i++){

        for(j = 0; j < C; j++){

            scanf("%d", &M[i][j]);

        }

        printf("\n");

    }
    for(i = 0; i < R; i++){

        for(j = 0; j < C; j++){

            printf("%d\t", M[i][j]);

        }
        printf("\n");

   }

   getch();

   return 0;
}

Using the GET parameter of a URL in JavaScript

This looked ok:

function gup( name ){
   name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
   var regexS = "[\\?&]"+name+"=([^&#]*)";
   var regex = new RegExp( regexS );
   var results = regex.exec( window.location.href );
   if( results == null )
      return "";
   else
      return results[1];
}

From http://www.netlobo.com/url_query_string_javascript.html

How do I perform the SQL Join equivalent in MongoDB?

We can merge two collection by using mongoDB sub query. Here is example, Commentss--

`db.commentss.insert([
  { uid:12345, pid:444, comment:"blah" },
  { uid:12345, pid:888, comment:"asdf" },
  { uid:99999, pid:444, comment:"qwer" }])`

Userss--

db.userss.insert([
  { uid:12345, name:"john" },
  { uid:99999, name:"mia"  }])

MongoDB sub query for JOIN--

`db.commentss.find().forEach(
    function (newComments) {
        newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
        db.newCommentUsers.insert(newComments);
    }
);`

Get result from newly generated Collection--

db.newCommentUsers.find().pretty()

Result--

`{
    "_id" : ObjectId("5511236e29709afa03f226ef"),
    "uid" : 12345,
    "pid" : 444,
    "comment" : "blah",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f0"),
    "uid" : 12345,
    "pid" : 888,
    "comment" : "asdf",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f1"),
    "uid" : 99999,
    "pid" : 444,
    "comment" : "qwer",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f3"),
            "uid" : 99999,
            "name" : "mia"
        }
    ]
}`

Hope so this will help.

TestNG ERROR Cannot find class in classpath

I was facing the same issue and what I tried is as below.

  1. Clean the project (Right click on pom.xml and clean)
  2. And update the maven project (Project > Maven > Update Maven Project)

This solved the issue.

C# - Create SQL Server table programmatically

For managing DataBase Objects in SQL Server i would suggest using Server Management Objects

What is a deadlock?

Deadlocks will only occur when you have two or more locks that can be aquired at the same time and they are grabbed in different order.

Ways to avoid having deadlocks are:

  • avoid having locks (if possible),
  • avoid having more than one lock
  • always take the locks in the same order.

Call a python function from jinja2

Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:

# jinja2.__version__ == 2.8
from jinja2 import Template

def calcName(n, i):
    return ' '.join([n] * i)

template = Template("Hello {{ calcName('Gandalf', 2) }}")

template.render(calcName=calcName)
# or
template.render({'calcName': calcName})

How to determine if a String has non-alphanumeric characters?

string.matches("^\\W*$"); should do what you want, but it does not include whitespace. string.matches("^(?:\\W|\\s)*$"); does match whitespace as well.

How do I get the "id" after INSERT into MySQL database with Python?

Use cursor.lastrowid to get the last row ID inserted on the cursor object, or connection.insert_id() to get the ID from the last insert on that connection.

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

Others have noted the correct answer, but have not clearly explained the all-important reason:

  • why do we need this?

What do < and > stand for?

  • &lt; stands for the < sign. Just remember: lt == less than
  • &gt; stands for the > Just remember: gt == greater than

Why can’t we simply use the < and > characters in HTML?

  • This is because the > and < characters are ‘reserved’ characters in HTML.
  • HTML is a mark up language: The < and > are used to denote the starting and ending of different elements: e.g. <h1> and not for the displaying of the greater than or less than symbols. But what if you wanted to actually display those symbols? You would simply use &lt; and &gt; and the browser will know exactly how to display it.

Getting byte array through input type = file

_x000D_
_x000D_
document.querySelector('input').addEventListener('change', function(){_x000D_
    var reader = new FileReader();_x000D_
    reader.onload = function(){_x000D_
        var arrayBuffer = this.result,_x000D_
array = new Uint8Array(arrayBuffer),_x000D_
  binaryString = String.fromCharCode.apply(null, array);_x000D_
_x000D_
console.log(binaryString);_x000D_
      console.log(arrayBuffer);_x000D_
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;_x000D_
        }_x000D_
    reader.readAsArrayBuffer(this.files[0]);_x000D_
  }, false);
_x000D_
<input type="file"/>_x000D_
<div id="result"></div>
_x000D_
_x000D_
_x000D_

Effective swapping of elements of an array in Java

Solution for object and primitive types:

public static final <T> void swap(final T[] arr, final int i, final int j) {
    T tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final boolean[] arr, final int i, final int j) {
    boolean tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final byte[] arr, final int i, final int j) {
    byte tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final short[] arr, final int i, final int j) {
    short tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final int[] arr, final int i, final int j) {
    int tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final long[] arr, final int i, final int j) {
    long tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final char[] arr, final int i, final int j) {
    char tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final float[] arr, final int i, final int j) {
    float tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}
public static final void swap(final double[] arr, final int i, final int j) {
    double tmp = arr[i];
    arr[i] = arr[j];
    arr[j] = tmp;
}

How to use onClick() or onSelect() on option tag in a JSP page?

Even more simplified: You can pass the value attribute directly!

<html>
 <head>
  <script type="text/javascript">

   function changeFunc($i) {
    alert($i);
   }

  </script>
 </head>
 <body>
  <select id="selectBox" onchange="changeFunc(value);">
   <option value="1">Option #1</option>
   <option value="2">Option #2</option>
  </select>
 </body>
</html>

The alert will either return 1 or 2.

How to set image to fit width of the page using jsPDF?

You can get the width and height of PDF document like below,

var doc = new jsPDF("p", "mm", "a4");

var width = doc.internal.pageSize.getWidth();
var height = doc.internal.pageSize.getHeight();

Then you can use this width and height for your image to fit the entire PDF document.

var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJ......';

doc.addImage(imgData, 'JPEG', 0, 0, width, height);

Make sure that your image has the same size (resolution) of the PDF document. Otherwise it will look distorted (stretched).

If you want convert px to mm use this link http://www.endmemo.com/sconvert/millimeterpixel.php

How can I add some small utility functions to my AngularJS application?

The easiest way to add utility functions is to leave them at the global level:

function myUtilityFunction(x) { return "do something with "+x; }

Then, the simplest way to add a utility function (to a controller) is to assign it to $scope, like this:

$scope.doSomething = myUtilityFunction;

Then you can call it like this:

{{ doSomething(x) }}

or like this:

ng-click="doSomething(x)"

EDIT:

The original question is if the best way to add a utility function is through a service. I say no, if the function is simple enough (like the isNotString() example provided by the OP).

The benefit of writing a service is to replace it with another (via injection) for the purpose of testing. Taken to an extreme, do you need to inject every single utility function into your controller?

The documentation says to simply define behavior in the controller (like $scope.double): http://docs.angularjs.org/guide/controller

How to get some values from a JSON string in C#?

Your strings are JSON formatted, so you will need to parse it into a object. For that you can use JSON.NET.

Here is an example on how to parse a JSON string into a dynamic object:

string source = "{\r\n   \"id\": \"100000280905615\", \r\n \"name\": \"Jerard Jones\",  \r\n   \"first_name\": \"Jerard\", \r\n   \"last_name\": \"Jones\", \r\n   \"link\": \"https://www.facebook.com/Jerard.Jones\", \r\n   \"username\": \"Jerard.Jones\", \r\n   \"gender\": \"female\", \r\n   \"locale\": \"en_US\"\r\n}";
dynamic data = JObject.Parse(source);
Console.WriteLine(data.id);
Console.WriteLine(data.first_name);
Console.WriteLine(data.last_name);
Console.WriteLine(data.gender);
Console.WriteLine(data.locale);

Happy coding!

Convert string to hex-string in C#

In .NET 5.0 and later you can use the Convert.ToHexString() method.

using System;
using System.Text;

string value = "Hello world";

byte[] bytes = Encoding.UTF8.GetBytes(value);

string hexString = Convert.ToHexString(bytes);

Console.WriteLine($"String value: \"{value}\"");
Console.WriteLine($"   Hex value: \"{hexString}\"");

Running the above example code, you would get the following output:

String value: "Hello world"
   Hex value: "48656C6C6F20776F726C64"

How to disable PHP Error reporting in CodeIgniter?

Change CI index.php file to:

if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

if (defined('ENVIRONMENT')){
    switch (ENVIRONMENT){
        case 'development':
            error_reporting(E_ALL);
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

IF PHP errors are off, but any MySQL errors are still going to show, turn these off in the /config/database.php file. Set the db_debug option to false:

$db['default']['db_debug'] = FALSE; 

Also, you can use active_group as development and production to match the environment https://www.codeigniter.com/user_guide/database/configuration.html

$active_group = 'development';


$db['development']['hostname'] = 'localhost';
$db['development']['username'] = '---';
$db['development']['password'] = '---';
$db['development']['database'] = '---';
$db['development']['dbdriver'] = 'mysql';
$db['development']['dbprefix'] = '';
$db['development']['pconnect'] = TRUE;

$db['development']['db_debug'] = TRUE;

$db['development']['cache_on'] = FALSE;
$db['development']['cachedir'] = '';
$db['development']['char_set'] = 'utf8';
$db['development']['dbcollat'] = 'utf8_general_ci';
$db['development']['swap_pre'] = '';
$db['development']['autoinit'] = TRUE;
$db['development']['stricton'] = FALSE;



$db['production']['hostname'] = 'localhost';
$db['production']['username'] = '---';
$db['production']['password'] = '---';
$db['production']['database'] = '---';
$db['production']['dbdriver'] = 'mysql';
$db['production']['dbprefix'] = '';
$db['production']['pconnect'] = TRUE;

$db['production']['db_debug'] = FALSE;

$db['production']['cache_on'] = FALSE;
$db['production']['cachedir'] = '';
$db['production']['char_set'] = 'utf8';
$db['production']['dbcollat'] = 'utf8_general_ci';
$db['production']['swap_pre'] = '';
$db['production']['autoinit'] = TRUE;
$db['production']['stricton'] = FALSE;

Android, How to create option Menu

Change your onCreateOptionsMenu method to return true. To quote the docs:

You must return true for the menu to be displayed; if you return false it will not be shown.

Eclipse projects not showing up after placing project files in workspace/projects

I have tried many of the option suggested but at last importing project in new workspace solved my problem.

I think there is some problem in metadata files in old workspace.

jquery clone div and append it after specific div

You can use clone, and then since each div has a class of car_well you can use insertAfter to insert after the last div.

$("#car2").clone().insertAfter("div.car_well:last");

Export Postgresql table data using pgAdmin

  1. Right-click on your table and pick option Backup..
  2. On File Options, set Filepath/Filename and pick PLAIN for Format
  3. Ignore Dump Options #1 tab
  4. In Dump Options #2 tab, check USE INSERT COMMANDS
  5. In Dump Options #2 tab, check Use Column Inserts if you want column names in your inserts.
  6. Hit Backup button

How do I insert a JPEG image into a python Tkinter window?

Try this:

import tkinter as tk
from PIL import ImageTk, Image

#This creates the main window of an application
window = tk.Tk()
window.title("Join")
window.geometry("300x300")
window.configure(background='grey')

path = "Aaron.jpg"

#Creates a Tkinter-compatible photo image, which can be used everywhere Tkinter expects an image object.
img = ImageTk.PhotoImage(Image.open(path))

#The Label widget is a standard Tkinter widget used to display a text or image on the screen.
panel = tk.Label(window, image = img)

#The Pack geometry manager packs widgets in rows or columns.
panel.pack(side = "bottom", fill = "both", expand = "yes")

#Start the GUI
window.mainloop()

Related docs: ImageTk Module, Tkinter Label Widget, Tkinter Pack Geometry Manager

How to convert a String to a Date using SimpleDateFormat?

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

django no such table:

You can try this!

python manage.py migrate --run-syncdb

I have the same problem with Django 1.9 and 1.10. This code works!

Deleting queues in RabbitMQ

In RabbitMQ versions > 3.0, you can also utilize the HTTP API if the rabbitmq_management plugin is enabled. Just be sure to set the content-type to 'application/json' and provide the vhost and queue name:

I.E. Using curl with a vhost 'test' and queue name 'testqueue':

$ curl -i -u guest:guest -H "content-type:application/json" -XDELETE http://localhost:15672/api/queues/test/testqueue
HTTP/1.1 204 No Content
Server: MochiWeb/1.1 WebMachine/1.9.0 (someone had painted it blue)
Date: Tue, 16 Apr 2013 10:37:48 GMT
Content-Type: application/json
Content-Length: 0

Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null

Had the same error in my functional Component as

function ShopCard(props) {
const { shops = {} } = useContext(ContextProvider);
return(
    shops.map((shop)=>{
    <div></div>     
})
)
}

Instead of

function ShopCard(props) {
  const { shops = {} } = useContext(ContextProvider);
  shops.map((shop)=>{
    return(
   <div></div>

   )            
    })

}

Reading json files in C++

Essentially javascript and C++ work on two different principles. Javascript creates an "associative array" or hash table, which matches a string key, which is the field name, to a value. C++ lays out structures in memory, so the first 4 bytes are an integer, which is an age, then maybe we have a fixed-wth 32 byte string which represents the "profession".

So javascript will handle things like "age" being 18 in one record and "nineteen" in another. C++ can't. (However C++ is much faster).

So if we want to handle JSON in C++, we have to build the associative array from the ground up. Then we have to tag the values with their types. Is it an integer, a real value (probably return as "double"), boolean, a string? It follows that a JSON C++ class is quite a large chunk of code. Effectively what we are doing is implementing a bit of the javascript engine in C++. We then pass our JSON parser the JSON as a string, and it tokenises it, and gives us functions to query the JSON from C++.

Drawing an SVG file on a HTML5 canvas

Mozilla has a simple way for drawing SVG on canvas called "Drawing DOM objects into a canvas"

PHP - SSL certificate error: unable to get local issuer certificate

When you view the http://curl.haxx.se/docs/caextract.html page, you will notice in big letters a section called:

RSA-1024 removed

Read it, then download the version of the certificates that includes the 'RSA-1024' certificates. https://github.com/bagder/ca-bundle/blob/e9175fec5d0c4d42de24ed6d84a06d504d5e5a09/ca-bundle.crt

Those will work with Mandrill.

Disabling SSL is a bad idea.

Sending multipart/formdata with jQuery.ajax

Nowadays you don't even need jQuery:) fetch API support table

let result = fetch('url', {method: 'POST', body: new FormData(document.querySelector("#form"))})

Entity Framework select distinct name

Entity-Framework Select Distinct Name:

Suppose if you are want every first data of particular column of each group ;

 var data = objDb.TableName.GroupBy(dt => dt.ColumnName).Select(dt => new { dt.Key }).ToList();

            foreach (var item in data)
            {
                var data2= objDb.TableName.Where(dt=>dt.ColumnName==item.Key).Select(dt=>new {dt.SelectYourColumn}).Distinct().FirstOrDefault();

               //Eg.
                {
                       ListBox1.Items.Add(data2.ColumnName);                    
                }

            }

How can I open a website in my web browser using Python?

As the instructions state, using the open() function does work, and opens the default web browser - usually I would say: "why wouldn't I want to use Firefox?!" (my default and favorite browser)

import webbrowser as wb
wb.open_new_tab('http://www.google.com')

The above should work for the computer's default browser. However, what if you want to to open in Google Chrome?

The proper way to do this is:

import webbrowser as wb
wb.get('chrome %s').open_new_tab('http://www.google.com')

To be honest, I'm not really sure that I know the difference between 'chrome' and 'google-chrome', but apparently there is some since they've made the two different type names in the webbrowser documentation.

However, doing this didn't work right off the bat for me. Every time, I would get the error:

Traceback (most recent call last):
File "C:\Python34\programs\a_temp_testing.py", line 3, in <module>
wb.get('google-chrome')
File "C:\Python34\lib\webbrowser.py", line 51, in get
raise Error("could not locate runnable browser")
webbrowser.Error: could not locate runnable browser

To solve this, I had to add the folder for chrome.exe to System PATH. My chrome.exe executable file is found at:

C:\Program Files (x86)\Google\Chrome\Application

You should check whether it is here or not for yourself.

To add this to your Environment Variables System PATH, right click on your Windows icon and go to System. System Control Panel applet (Start - Settings - Control Panel - System). Change advanced settings, or the advanced tab, and select the button there called Environment Varaibles.

Once you click on Environment Variables here, another window will pop up. Scroll through the items, select PATH, and click edit.

Once you're in here, click New to add the folder path to your chrome.exe file. Like I said above, mine was found at:

C:\Program Files (x86)\Google\Chrome\Application

Click save and exit out of there. Then make sure you reboot your computer.

Hope this helps!

How to insert a line break <br> in markdown

Try adding 2 spaces (or a backslash \) after the first line:

[Name of link](url)
My line of text\

Visually:

[Name of link](url)<space><space>
My line of text\

Output:

<p><a href="url">Name of link</a><br>
My line of text<br></p>

7-Zip command to create and extract a password-protected ZIP file on Windows?

General Syntax:

7z a archive_name target parameters

Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.

Parameters:

  • -p encrypt and prompt for PW.
  • -pPUT_PASSWORD_HERE (this replaces -p) if you want to preset the PW with no prompt.
  • -mhe=on to hide file structure, otherwise file structure and names will be visible by default.

Eg. This will prompt for a PW and hide file structures:

7z a archive_name target -p -mhe=on

Eg. No prompt, visible file structure:

7z a archive_name target -pPUT_PASSWORD_HERE

And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.

Going through a text file line by line in C

Say you're dealing with some other delimiter, such as a \t tab, instead of a \n newline.

A more general approach to delimiters is the use of getc(), which grabs one character at a time.

Note that getc() returns an int, so that we can test for equality with EOF.

Secondly, we define an array line[BUFFER_MAX_LENGTH] of type char, in order to store up to BUFFER_MAX_LENGTH-1 characters on the stack (we have to save that last character for a \0 terminator character).

Use of an array avoids the need to use malloc and free to create a character pointer of the right length on the heap.

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    /* get a character from the file pointer */
    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            fprintf(stdout, "%s\n", line);
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            fprintf(stdout, "%s\n", line);
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

If you must use a char *, then you can still use this code, but you strdup() the line[] array, once it is filled up with a line's worth of input. You must free this duplicated string once you're done with it, or you'll get a memory leak:

#define BUFFER_MAX_LENGTH 1024

int main(int argc, char* argv[])
{
    FILE *file = NULL;
    char line[BUFFER_MAX_LENGTH];
    int tempChar;
    unsigned int tempCharIdx = 0U;
    char *dynamicLine = NULL;

    if (argc == 2)
         file = fopen(argv[1], "r");
    else {
         fprintf(stderr, "error: wrong number of arguments\n"
                         "usage: %s textfile\n", argv[0]);
         return EXIT_FAILURE;
    }

    if (!file) {
         fprintf(stderr, "error: could not open textfile: %s\n", argv[1]);
         return EXIT_FAILURE;
    }

    while(tempChar = fgetc(file))
    {
        /* avoid buffer overflow error */
        if (tempCharIdx == BUFFER_MAX_LENGTH) {
            fprintf(stderr, "error: line is too long. increase BUFFER_MAX_LENGTH.\n");
            return EXIT_FAILURE;
        }

        /* test character value */
        if (tempChar == EOF) {
            line[tempCharIdx] = '\0';
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            break;
        }
        else if (tempChar == '\n') {
            line[tempCharIdx] = '\0';
            tempCharIdx = 0U;
            dynamicLine = strdup(line);
            fprintf(stdout, "%s\n", dynamicLine);
            free(dynamicLine);
            dynamicLine = NULL;
            continue;
        }
        else
            line[tempCharIdx++] = (char)tempChar;
    }

    return EXIT_SUCCESS;
}

Move SQL data from one table to another

You could try this:

SELECT * INTO tbl_NewTableName 
FROM tbl_OldTableName
WHERE Condition1=@Condition1Value

Then run a simple delete:

DELETE FROM tbl_OldTableName
WHERE Condition1=@Condition1Value

JavaScript function to add X months to a date

The following function adds months to a date in JavaScript (source). It takes into account year roll-overs and varying month lengths:

_x000D_
_x000D_
function addMonths(date, months) {_x000D_
    var d = date.getDate();_x000D_
    date.setMonth(date.getMonth() + +months);_x000D_
    if (date.getDate() != d) {_x000D_
      date.setDate(0);_x000D_
    }_x000D_
    return date;_x000D_
}_x000D_
_x000D_
// Add 12 months to 29 Feb 2016 -> 28 Feb 2017_x000D_
console.log(addMonths(new Date(2016,1,29),12).toString());_x000D_
_x000D_
// Subtract 1 month from 1 Jan 2017 -> 1 Dec 2016_x000D_
console.log(addMonths(new Date(2017,0,1),-1).toString());_x000D_
_x000D_
// Subtract 2 months from 31 Jan 2017 -> 30 Nov 2016_x000D_
console.log(addMonths(new Date(2017,0,31),-2).toString());_x000D_
_x000D_
// Add 2 months to 31 Dec 2016 -> 28 Feb 2017_x000D_
console.log(addMonths(new Date(2016,11,31),2).toString());
_x000D_
_x000D_
_x000D_

The above solution covers the edge case of moving from a month with a greater number of days than the destination month. eg.

  • Add twelve months to February 29th 2020 (should be February 28th 2021)
  • Add one month to August 31st 2020 (should be September 30th 2020)

If the day of the month changes when applying setMonth, then we know we have overflowed into the following month due to a difference in month length. In this case, we use setDate(0) to move back to the last day of the previous month.

Note: this version of this answer replaces an earlier version (below) that did not gracefully handle different month lengths.

var x = 12; //or whatever offset
var CurrentDate = new Date();
console.log("Current date:", CurrentDate);
CurrentDate.setMonth(CurrentDate.getMonth() + x);
console.log("Date after " + x + " months:", CurrentDate);

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Lea's converter is no longer available. I just used this converter

Steps:

  1. Enter the Unicode decimal version such as 8226 in the tool's green input field.
  2. Press Dec code points
  3. See the result in the box Unicode U+hex notation (eg U+2022)
  4. Use it in your CSS. Eg content: '\2022'

ps. I have no connection with the web site.

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

What is the difference between sscanf or atoi to convert a string to an integer?

When there is no concern about invalid string input or range issues, use the simplest: atoi()

Otherwise, the method with best error/range detection is neither atoi(), nor sscanf(). This good answer all ready details the lack of error checking with atoi() and some error checking with sscanf().

strtol() is the most stringent function in converting a string to int. Yet it is only a start. Below are detailed examples to show proper usage and so the reason for this answer after the accepted one.

// Over-simplified use
int strtoi(const char *nptr) {
  int i = (int) strtol(nptr, (char **)NULL, 10);
  return i; 
}

This is the like atoi() and neglects to use the error detection features of strtol().

To fully use strtol(), there are various features to consider:

  1. Detection of no conversion: Examples: "xyz", or "" or "--0"? In these cases, endptr will match nptr.

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (nptr == endptr) return FAIL_NO_CONVERT;
    
  2. Should the whole string convert or just the leading portion: Is "123xyz" OK?

    char *endptr;
    int i = (int)strtol(nptr, &endptr, 10);
    if (*endptr != '\0') return FAIL_EXTRA_JUNK;
    
  3. Detect if value was so big, the the result is not representable as a long like "999999999999999999999999999999".

    errno = 0;
    long L = strtol(nptr, &endptr, 10);
    if (errno == ERANGE) return FAIL_OVERFLOW;
    
  4. Detect if the value was outside the range of than int, but not long. If int and long have the same range, this test is not needed.

    long L = strtol(nptr, &endptr, 10);
    if (L < INT_MIN || L > INT_MAX) return FAIL_INT_OVERFLOW;
    
  5. Some implementations go beyond the C standard and set errno for additional reasons such as errno to EINVAL in case no conversion was performed or EINVAL The value of the Base parameter is not valid.. The best time to test for these errno values is implementation dependent.

Putting this all together: (Adjust to your needs)

#include <errno.h>
#include <stdlib.h>

int strtoi(const char *nptr, int *error_code) {
  char *endptr;
  errno = 0;
  long i = strtol(nptr, &endptr, 10);

  #if LONG_MIN < INT_MIN || LONG_MAX > INT_MAX
  if (errno == ERANGE || i > INT_MAX || i < INT_MIN) {
    errno = ERANGE;
    i = i > 0 : INT_MAX : INT_MIN;
    *error_code = FAIL_INT_OVERFLOW;
  }
  #else
  if (errno == ERANGE) {
    *error_code = FAIL_OVERFLOW;
  }
  #endif

  else if (endptr == nptr) {
    *error_code = FAIL_NO_CONVERT;
  } else if (*endptr != '\0') {
    *error_code = FAIL_EXTRA_JUNK;
  } else if (errno) {
    *error_code = FAIL_IMPLEMENTATION_REASON;
  }
  return (int) i;
}

Note: All functions mentioned allow leading spaces, an optional leading sign character and are affected by locale change. Additional code is required for a more restrictive conversion.


Note: Non-OP title change skewed emphasis. This answer applies better to original title "convert string to integer sscanf or atoi"

java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver

I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)

unix diff side-to-side results?

Use the -y option:

diff -y file1 file2

How to load all modules in a folder?

I've created a module for that, which doesn't rely on __init__.py (or any other auxiliary file) and makes me type only the following two lines:

import importdir
importdir.do("Foo", globals())

Feel free to re-use or contribute: http://gitlab.com/aurelien-lourot/importdir

How do I plot only a table in Matplotlib?

Not sure if this is already answered, but if you want only a table in a figure window, then you can hide the axes:

fig, ax = plt.subplots()

# Hide axes
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False)

# Table from Ed Smith answer
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
ax.table(cellText=clust_data,colLabels=collabel,loc='center')

Scala vs. Groovy vs. Clojure

I never had time to play with clojure. But for scala vs groovy, this is words from James Strachan - Groovy creator

"Though my tip though for the long term replacement of javac is Scala. I'm very impressed with it! I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy."

You can read the whole story here

Renaming Column Names in Pandas Groupby function

The current (as of version 0.20) method for changing column names after a groupby operation is to chain the rename method. See this deprecation note in the documentation for more detail.

Deprecated Answer as of pandas version 0.20

This is the first result in google and although the top answer works it does not really answer the question. There is a better answer here and a long discussion on github about the full functionality of passing dictionaries to the agg method.

These answers unfortunately do not exist in the documentation but the general format for grouping, aggregating and then renaming columns uses a dictionary of dictionaries. The keys to the outer dictionary are column names that are to be aggregated. The inner dictionaries have keys that the new column names with values as the aggregating function.

Before we get there, let's create a four column DataFrame.

df = pd.DataFrame({'A' : list('wwwwxxxx'), 
                   'B':list('yyzzyyzz'), 
                   'C':np.random.rand(8), 
                   'D':np.random.rand(8)})

   A  B         C         D
0  w  y  0.643784  0.828486
1  w  y  0.308682  0.994078
2  w  z  0.518000  0.725663
3  w  z  0.486656  0.259547
4  x  y  0.089913  0.238452
5  x  y  0.688177  0.753107
6  x  z  0.955035  0.462677
7  x  z  0.892066  0.368850

Let's say we want to group by columns A, B and aggregate column C with mean and median and aggregate column D with max. The following code would do this.

df.groupby(['A', 'B']).agg({'C':['mean', 'median'], 'D':'max'})

            D         C          
          max      mean    median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This returns a DataFrame with a hierarchical index. The original question asked about renaming the columns in the same step. This is possible using a dictionary of dictionaries:

df.groupby(['A', 'B']).agg({'C':{'C_mean': 'mean', 'C_median': 'median'}, 
                            'D':{'D_max': 'max'}})

            D         C          
        D_max    C_mean  C_median
A B                              
w y  0.994078  0.476233  0.476233
  z  0.725663  0.502328  0.502328
x y  0.753107  0.389045  0.389045
  z  0.462677  0.923551  0.923551

This renames the columns all in one go but still leaves the hierarchical index which the top level can be dropped with df.columns = df.columns.droplevel(0).

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

The ContentList's Set method will not get called when you change a value inside the collection, instead you should be looking out for the CollectionChanged event firing.

public class CollectionViewModel : ViewModelBase
{          
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
    }

    public CollectionViewModel()
    {
         _contentList = new ObservableCollection<EntityViewModel>();
         _contentList.CollectionChanged += ContentCollectionChanged;
    }

    public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //This will get called when the collection is changed
    }
}

Okay, that's twice today I've been bitten by the MSDN documentation being wrong. In the link I gave you it says:

Occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

But it actually doesn't fire when an item is changed. I guess you'll need a more bruteforce method then:

public class CollectionViewModel : ViewModelBase
{          
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
    }

    public CollectionViewModel()
    {
         _contentList = new ObservableCollection<EntityViewModel>();
         _contentList.CollectionChanged += ContentCollectionChanged;
    }

    public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            foreach(EntityViewModel item in e.OldItems)
            {
                //Removed items
                item.PropertyChanged -= EntityViewModelPropertyChanged;
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach(EntityViewModel item in e.NewItems)
            {
                //Added items
                item.PropertyChanged += EntityViewModelPropertyChanged;
            }     
        }       
    }

    public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        //This will get called when the property of an object inside the collection changes
    }
}

If you are going to need this a lot you may want to subclass your own ObservableCollection that triggers the CollectionChanged event when a member triggers its PropertyChanged event automatically (like it says it should in the documentation...)

Install specific version using laravel installer

From Laravel 6, Now It's working with the following command:

composer create-project --prefer-dist laravel/laravel:^7.0 blog

Can PHP cURL retrieve response headers AND body in a single request?

The problem with many answers here is that "\r\n\r\n" can legitimately appear in the body of the html, so you can't be sure that you're splitting headers correctly.

It seems that the only way to store headers separately with one call to curl_exec is to use a callback as is suggested above in https://stackoverflow.com/a/25118032/3326494

And then to (reliably) get just the body of the request, you would need to pass the value of the Content-Length header to substr() as a negative start value.

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

What is the purpose of the HTML "no-js" class?

When Modernizr runs, it removes the "no-js" class and replaces it with "js". This is a way to apply different CSS rules depending on whether or not Javascript support is enabled.

See Modernizer's source code.

How to execute UNION without sorting? (SQL)

1,1: select 1 from dual union all select 1 from dual 1: select 1 from dual union select 1 from dual

Putting HTML inside Html.ActionLink(), plus No Link Text?

It's very simple.

If you want to have something like a glyphicon icon and then "Wish List",

<span class="glyphicon-heart"></span> @Html.ActionLink("Wish List (0)", "Index", "Home")

In Java what is the syntax for commenting out multiple lines?

/* 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
*/

Can I do a max(count(*)) in SQL?

This question is old, but was referenced in a new question on dba.SE. I feel the best solutions haven't been provided, yet, so I am adding another one.

First off, assuming referential integrity (typically enforced with foreign key constraints) you do not need to join to the table movie at all. That's dead freight in your query. All answers so far fail to point that out.


Can I do a max(count(*)) in SQL?

To answer the question in the title: Yes, in Postgres 8.4 (released 2009-07-01, before this question was asked) or later you can achieve that by nesting an aggregate function in a window function:

SELECT c.yr, count(*) AS ct, max(count(*)) OVER () AS max_ct
FROM   actor   a
JOIN   casting c ON c.actorid = a.id
WHERE  a.name = 'John Travolta'
GROUP  BY c.yr;

Consider the sequence of events in a SELECT query:

The (possible) downside: window functions do not aggregate rows. You get all rows left after the aggregate step. Useful in some queries, but not ideal for this one.


To get one row with the highest count, you can use ORDER BY ct LIMIT 1 like @wolph hinted:

SELECT c.yr, count(*) AS ct
FROM   actor   a
JOIN   casting c ON c.actorid = a.id
WHERE  a.name = 'John Travolta'
GROUP  BY c.yr
ORDER  BY ct DESC
LIMIT  1;

Using only basic SQL features available in any halfway decent RDBMS - the LIMIT implementation varies:

Or you can get one row per group with the highest count with DISTINCT ON (only Postgres):


Answer

But you asked for:

... rows for which count(*) is max.

Possibly more than one. The most elegant solution is with the window function rank() in a subquery. Ryan provided a query but it can be simpler (details in my answer above):

SELECT yr, ct
FROM  (
   SELECT c.yr, count(*) AS ct, rank() OVER (ORDER BY count(*) DESC) AS rnk
   FROM   actor   a
   JOIN   casting c ON c.actorid = a.id
   WHERE  a.name = 'John Travolta'
   GROUP  BY c.yr
   ) sub
WHERE  rnk = 1;

All major RDBMS support window functions nowadays. Except MySQL and forks (MariaDB seems to have implemented them at last in version 10.2).

How schedule build in Jenkins?

Jenkins uses Cron Expressions.

You can simply schedule hourly builds by just typing@hourly.

Validate a username and password against Active Directory?

Probably easiest way is to PInvoke LogonUser Win32 API.e.g.

http://www.pinvoke.net/default.aspx/advapi32/LogonUser.html

MSDN Reference here...

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

Definitely want to use logon type

LOGON32_LOGON_NETWORK (3)

This creates a lightweight token only - perfect for AuthN checks. (other types can be used to build interactive sessions etc.)

What type of hash does WordPress use?

include_once('../../../wp-config.php');

global $wpdb;

$password = wp_hash_password("your password");

What does "yield break;" do in C#?

yield break is just a way of saying return for the last time and don't return any value

e.g

// returns 1,2,3,4,5
IEnumerable<int> CountToFive()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
    yield return 5;
    yield break;
    yield return 6;
    yield return 7;
    yield return 8;
    yield return 9;
 }

Check if a String contains numbers Java

The solution I went with looks like this:

Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);

Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);

if (matcher1.find() && matcher2.find())
{
    int number = Integer.parseInt(matcher1.group());                    
    pw.println(number + " squared = " + (number * number));
}

I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)

Updates were rejected because the tip of your current branch is behind hint: its remote counterpart. Integrate the remote changes (e.g

You need to merge the remote branch into your current branch by running git pull.

If your local branch is already up-to-date, you may also need to run git pull --rebase.

A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.

JQuery: How to get selected radio button value?

To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.

$('input[name=radioName]:checked', '#myForm').val()

OR by only

$('form input[type=radio]:checked').val();

Domain Account keeping locking out with correct password every few minutes

May be the virus by name CONFLICKER try d.exe tool from symantec on the machine hope your problem will be resolved. Check the security logs in domain controller and scan those machines because of this virus it creates bad passwords and lock the users.

Show message box in case of exception

        try
        {
           // your code
        }
        catch (Exception w)
        {
            MessageDialog msgDialog = new MessageDialog(w.ToString());
        }

How to remove specific substrings from a set of strings in Python?

Strings are immutable. string.replace (python 2.x) or str.replace (python 3.x) creates a new string. This is stated in the documentation:

Return a copy of string s with all occurrences of substring old replaced by new. ...

This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):

new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}