Programs & Examples On #Ripple

Ripple is a Chrome plugin that emulates the PhoneGap APIs. It enables testing of applications that target mobile devices.

How to add icon to mat-icon-button

Just add the <mat-icon> inside mat-button or mat-raised-button. See the example below. Note that I am using material icon instead of your svg for demo purpose:

<button mat-button>
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

OR

<button mat-raised-button color="accent">
    <mat-icon>mic</mat-icon>
    Start Recording
</button>

Here is a link to stackblitz demo.

'mat-form-field' is not a known element - Angular 5 & Material2

When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

Please import below:

import { MatInputModule } from '@angular/material';

mat-form-field must contain a MatFormFieldControl

If anyone got stuck with this error after attempting to nest a <mat-checkbox>, be of good cheer! It doesn't work inside a <mat-form-field> tag.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

Add ripple effect to my button with button background color?

Add Ripple Effect/Animation to a Android Button

Just replace your button background attribute with android:background="?attr/selectableItemBackground" and your code looks like this.

      <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/selectableItemBackground"
        android:text="New Button" />

Another Way to Add Ripple Effect/Animation to an Android Button

Using this method, you can customize ripple effect color. First, you have to create a xml file in your drawable resource directory. Create a ripple_effect.xml file and add following code. res/drawable/ripple_effect.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:color="#f816a463"
    tools:targetApi="lollipop">
    <item android:id="@android:id/mask">
        <shape android:shape="rectangle">
            <solid android:color="#f816a463" />
        </shape>
    </item>
</ripple>

And set background of button to above drawable resource file

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/ripple_effect"
    android:padding="16dp"
    android:text="New Button" />

Angular2 get clicked element id

For nested html, use closest

<button (click)="toggle($event)" class="someclass" id="btn1">
    <i class="fa fa-user"></i>
</button>

toggle(event) {
   (event.target.closest('button') as Element).id; 
}

MySQL Incorrect datetime value: '0000-00-00 00:00:00'

I have this error as well after upgrading MySQL from 5.6 to 5.7

I figured out that the best solution for me was to combine some of the solutions here and make something of it that worked with the minimum of input.

I use MyPHPAdmin for the simplicity of sending the queries through the interface because then I can check the structure and all that easily. You might use ssh directly or some other interface. The method should be similar or same anyway.

...

1.

First check out the actual error when trying to repair the db:

joomla.jos_menu Note : TIME/TIMESTAMP/DATETIME columns of old format have been upgraded to the new format.

Warning : Incorrect datetime value: '0000-00-00 00:00:00' for column 'checked_out_time' at row 1

Error : Invalid default value for 'checked_out_time'

status : Operation failed

This tells me the column checked_out_time in the table jos_menu needs to have all bad dates fixed as well as the "default" changed.

...

2.

I run the SQL query based on the info in the error message:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE checked_out_time = 0

If you get an error you can use the below query instead that seems to always work:

UPDATE jos_menu SET checked_out_time = '1970-01-01 08:00:00' WHERE CAST(checked_out_time AS CHAR(20)) = '0000-00-00 00:00:00'

...

3.

Then once that is done I run the second SQL query:

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT CURRENT_TIMESTAMP;

Or in the case it is a date that has to be NULL

ALTER TABLE `jos_menu` CHANGE `checked_out_time` `checked_out_time` DATETIME NULL DEFAULT NULL;

...

If I run repair database now I get:

joomla.jos_menu OK

...

Works just fine :)

How to set a ripple effect on textview or imageview on Android?

android:background="?android:selectableItemBackground"
android:focusable="true"
android:clickable="true"

How to update RecyclerView Adapter Data?

I've solved the same problem in a different way. I don't have data I waiting for it from the background thread so start with an emty list.

        mAdapter = new ModelAdapter(getContext(),new ArrayList<Model>());
   // then when i get data

        mAdapter.update(response.getModelList());
  //  and update is in my adapter

        public void update(ArrayList<Model> modelList){
            adapterModelList.clear(); 
            for (Product model: modelList) {
                adapterModelList.add(model); 
            }
           mAdapter.notifyDataSetChanged();
        }

That's it.

Android changing Floating Action Button color

Vijet Badigannavar's answer is correct but using ColorStateList is usually complicated and he didn't tell us how to do it. Since we often focus on changing View's color in normal and pressed state, I'm going to add more details:

  1. If you want to change FAB's color in normal state, you can just write

    mFab.setBackgroundTintList(ColorStateList.valueOf(your color in int));
    
  2. If you want to change FAB's color in pressed state, thanks for Design Support Library 22.2.1, you can just write

    mFab.setRippleColor(your color in int);
    

    By setting this attribute, when you long-pressed the FAB, a ripple with your color will appear at your touch point and reveal into whole surface of FAB. Please notice that it won't change FAB's color in normal state. Below API 21(Lollipop), there is no ripple effect but FAB's color will still change when you're pressing it.

Finally, if you want to implement more complex effect for states, then you should dig deeply into ColorStateList, here is a SO question discussing it: How do I create ColorStateList programmatically?.

UPDATE: Thanks for @Kaitlyn's comment. To remove stroke of FAB using backgroundTint as its color, you can set app:borderWidth="0dp" in your xml.

Adjust icon size of Floating action button (fab)

You can use iconSize like this:

    floatingActionButton: FloatingActionButton(
      onPressed: () {
        // Add your onPressed code here
      },
      child: IconButton(
        icon: isPlaying
            ? Icon(
                Icons.pause_circle_outline,
              )
            : Icon(
                Icons.play_circle_outline,
              ),
              iconSize: 40,
              
        onPressed: () {
          setState(() {
            isPlaying = !isPlaying;
          });
        },
       
      ),
    ),

Ripple effect on Android Lollipop CardView

Add these two line code into your xml view to give ripple effect on your cardView.

android:clickable="true"
android:foreground="?android:attr/selectableItemBackground"

Material effect on button with background color

I ran into this problem today actually playing with the v22 library.

Assuming that you're using styles you can set the colorButtonNormal property and the buttons will use that color by default.

<style name="AppTheme" parent="BaseTheme">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/primaryColor</item>
    <item name="colorPrimaryDark">@color/primaryColorDark</item>
    <item name="colorAccent">@color/accentColor</item>
    <item name="colorButtonNormal">@color/primaryColor</item>
</style>

Outside of that you could still make a style for the button then use that per button if you needed an assortment of colors (haven't tested, just speculating).

Remember to add android: before the item names in your v21 style.

How to achieve ripple animation using support library?

Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"

Update

If you want ripple effect with rounded corners and custom background you can use this:

background_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
<item android:id="@android:id/mask">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

<item android:id="@android:id/background">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

layout.xml

<Button
    android:id="@+id/btn_play"
    android:background="@drawable/background_ripple"
    app:backgroundTint="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/play_now" />

I used this on API >= 21

Node.js: socket.io close client connection

try this to close the connection:

socket.close();

and if you want to open it again:

socket.connect();

invalid_grant trying to get oAuth token from google

We tried so many things, and in the end the issue was that the client had turned "Less Secure App Access" off in their Google Account settings.

To turn this on:

  1. Go to https://myaccount.google.com/ and manage account
  2. Go to the Security tab
  3. Turn Less secure app access on

enter image description here

I hope this saves someone some time!

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

Flash CS4 refuses to let go

Try deleting your ASO files.

ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.

This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.

Difference between Visual Basic 6.0 and VBA

VBA stands for Visual Basic for Applications and so is the small "for applications" scripting brother of VB. VBA is indeed available in Excel, but also in the other office applications.

With VB, one can create a stand-alone windows application, which is not possible with VBA.

It is possible for developers however to "embed" VBA in their own applications, as a scripting language to automate those applications.

Edit: From the VBA FAQ:

Q. What is Visual Basic for Applications?

A. Microsoft Visual Basic for Applications (VBA) is an embeddable programming environment designed to enable developers to build custom solutions using the full power of Microsoft Visual Basic. Developers using applications that host VBA can automate and extend the application functionality, shortening the development cycle of custom business solutions.

Note that VB.NET is even another language, which only shares syntax with VB.

Check that Field Exists with MongoDB

Suppose we have a collection like below:

{ 
  "_id":"1234"
  "open":"Yes"
  "things":{
             "paper":1234
             "bottle":"Available"
             "bottle_count":40
            } 
}

We want to know if the bottle field is present or not?

Ans:

db.products.find({"things.bottle":{"$exists":true}})

How to find memory leak in a C++ code/project?

AddressSanitizer (ASan) is a fast memory error detector. It finds use-after-free and {heap,stack,global}-buffer overflow bugs in C/C++ programs. It finds:

  • Use after free (dangling pointer dereference)
  • Heap buffer overflow
  • Stack buffer overflow
  • Global buffer overflow
  • Use after return
  • Initialization order bugs

This tool is very fast. The average slowdown of the instrumented program is ~2x.

What is the difference between the operating system and the kernel?

Basically the Kernel is the interface between hardware (devices which are available in Computer) and Application software is like MS Office, Visual Studio, etc.

If I answer "what is an OS?" then the answer could be the same. Hence the kernel is the part & core of the OS.

The very sensitive tasks of an OS like memory management, I/O management, process management are taken care of by the kernel only.

So the ultimate difference is:

  1. Kernel is responsible for Hardware level interactions at some specific range. But the OS is like hardware level interaction with full scope of computer.
  2. Kernel triggers SystemCalls to tell the OS that this resource is available at this point of time. The OS is responsible to handle those system calls in order to utilize the resource.

Update Git submodule to latest commit on origin

In your project parent directory, run:

git submodule update --init

Or if you have recursive submodules run:

git submodule update --init --recursive

Sometimes this still doesn't work, because somehow you have local changes in the local submodule directory while the submodule is being updated.

Most of the time the local change might not be the one you want to commit. It can happen due to a file deletion in your submodule, etc. If so, do a reset in your local submodule directory and in your project parent directory, run again:

git submodule update --init --recursive

How to use bluetooth to connect two iPhone?

If I remember correctly, Bluetooth defines certain roles that devices can take. Most cell phones only support a certain number of roles. For instance, I can have a Bluetooth stereo headset that connects to my phone to receive audio, but just because my cell phone has Bluetooth does mean that it supports BEING a speaker for a different device - it doesn't advertise its capabilities of having a speaker for use by other Bluetooth devices.

I assume you want to transfer files between two iPhones? Transferring files via Bluetooth does seem like functionality that I would put in the iPhone, but I'm not Apple so I don't know for sure. In fact, yes, it seems that file transfer is not supported except in jailbroken phones:

http://gizmodo.com/5138797/iphone-bluetooth-file-transfer-coming-soon-yes

You'll probably get similar answers for Bluetooth Dial-Up Networking. I'd imagine they kept the Bluetooth commands out of the SDK for various reasons and you'll have to jailbreak your phone to get the functionality back.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

List<Map<String, Object>> List = getJdbcTemplate().queryForList(SELECT_ALL_CONVERSATIONS_SQL_FULL, new Object[] {userId, dateFrom, dateTo});
for (Map<String, Object> rowMap : resultList) {
    DTO dTO = new DTO();
    dTO.setrarchyID((Long) (rowMap.get("ID")));
}

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

Should I use past or present tense in git commit messages?

The preference for present-tense, imperative-style commit messages comes from Git itself. From Documentation/SubmittingPatches in the Git repo:

Describe your changes in imperative mood, e.g. "make xyzzy do frotz" instead of "[This patch] makes xyzzy do frotz" or "[I] changed xyzzy to do frotz", as if you are giving orders to the codebase to change its behavior.

So you'll see a lot of Git commit messages written in that style. If you're working on a team or on open source software, it is helpful if everyone sticks to that style for consistency. Even if you're working on a private project, and you're the only one who will ever see your git history, it's helpful to use the imperative mood because it establishes good habits that will be appreciated when you're working with others.

lvalue required as left operand of assignment error when using C++

To assign, you should use p=p+1; instead of p+1=p;

int main()
{

   int x[3]={4,5,6};
   int *p=x;
   p=p+1; /*You just needed to switch the terms around*/
   cout<<p<<endl;
   getch();
}

How to hide the border for specified rows of a table?

Add programatically noborder class to specific row to hide it

<style>
     .noborder
      {
        border:none;
      }
    </style>

<table>

    <tr>
       <th>heading1</th>
       <th>heading2</th>
    </tr>


    <tr>
       <td>content1</td>
       <td>content2</td>
    </tr>
    /*no border for this row */
    <tr class="noborder">
       <td>content1</td>
       <td>content2</td>
    </tr>

</table>

Characters allowed in a URL

I tested it by requesting my website (apache) with all available chars on my german keyboard as URL parameter:

http://example.com/?^1234567890ß´qwertzuiopü+asdfghjklöä#<yxcvbnm,.-°!"§$%&/()=? `QWERTZUIOPÜ*ASDFGHJKLÖÄ\'>YXCVBNM;:_²³{[]}\|µ@€~

These were not encoded:

^0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.-!/()=?`*;:_{}[]\|~

Not encoded after urlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_

Not encoded after rawurlencode():

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~

Note: Before PHP 5.3.0 rawurlencode() encoded ~ because of RFC 1738. But this was replaced by RFC 3986 so its safe to use, now. But I do not understand why for example {} are encoded through rawurlencode() because they are not mentioned in RFC 3986.

An additional test I made was regarding auto-linking in mail texts. I tested Mozilla Thunderbird, aol.com, outlook.com, gmail.com, gmx.de and yahoo.de and they fully linked URLs containing these chars:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~+#,%&=*;:@

Of course the ? was linked, too, but only if it was used once.

Some people would now suggest to use only the rawurlencode() chars, but did you ever hear that someone had problems to open these websites?

Asterisk
http://wayback.archive.org/web/*/http://google.com

Colon
https://en.wikipedia.org/wiki/Wikipedia:About

Plus
https://plus.google.com/+google

At sign, Colon, Comma and Exclamation mark
https://www.google.com/maps/place/USA/@36.2218457,...

Because of that these chars should be usable unencoded without problems. Of course you should not use &; because of encoding sequences like &amp;. The same reason is valid for % as it used to encode chars in general. And = as it assigns a value to a parameter name.

Finally I would say its ok to use these unencoded:

0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_~!+,*:@

But if you expect randomly generated URLs you should not use .!, because those mark the end of a sentence and some mail apps will not auto-link the last char of the url. Example:

Visit http://example.com/foo=bar! !

Creating a list of objects in Python

If I understand correctly your question, you ask a way to execute a deep copy of an object. What about using copy.deepcopy?

import copy

x = SimpleClass()

for count in range(0,4):
  y = copy.deepcopy(x)
  (...)
  y.attr1= '*Bob* '* count

A deepcopy is a recursive copy of the entire object. For more reference, you can have a look at the python documentation: https://docs.python.org/2/library/copy.html

How set background drawable programmatically in Android

setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

Convert java.util.date default format to Timestamp in Java

You can use DateFormat(java.text.*) to parse the date:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")

You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.

CSS 100% height with padding/margin

The solution is to NOT use height and width at all! Attach the inner box using top, left, right, bottom and then add margin.

_x000D_
_x000D_
.box {margin:8px; position:absolute; top:0; left:0; right:0; bottom:0}
_x000D_
<div class="box" style="background:black">_x000D_
  <div class="box" style="background:green">_x000D_
    <div class="box" style="background:lightblue">_x000D_
      This will show three nested boxes. Try resizing browser to see they remain nested properly._x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is a tracking branch?

tracking branch is nothing but a way to save us some typing.

If we track a branch, we do not have to always type git push origin <branch-name> or git pull origin <branch-name> or git fetch origin <branch-name> or git merge origin <branch-name>. given we named our remote origin, we can just use git push, git pull, git fetch,git merge, respectively.

We track a branch when we:

  1. clone a repository using git clone
  2. When we use git push -u origin <branch-name>. This -u make it a tracking branch.
  3. When we use git branch -u origin/branch_name branch_name

ld.exe: cannot open output file ... : Permission denied

Your program is still running. You have to kill it by closing the command line window. If you press control alt delete, task manager, process`s (kill the ones that match your filename).

Should __init__() call the parent class's __init__()?

If you need something from super's __init__ to be done in addition to what is being done in the current class's __init__, you must call it yourself, since that will not happen automatically. But if you don't need anything from super's __init__, no need to call it. Example:

>>> class C(object):
        def __init__(self):
            self.b = 1


>>> class D(C):
        def __init__(self):
            super().__init__() # in Python 2 use super(D, self).__init__()
            self.a = 1


>>> class E(C):
        def __init__(self):
            self.a = 1


>>> d = D()
>>> d.a
1
>>> d.b  # This works because of the call to super's init
1
>>> e = E()
>>> e.a
1
>>> e.b  # This is going to fail since nothing in E initializes b...
Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    e.b  # This is going to fail since nothing in E initializes b...
AttributeError: 'E' object has no attribute 'b'

__del__ is the same way, (but be wary of relying on __del__ for finalization - consider doing it via the with statement instead).

I rarely use __new__. I do all the initialization in __init__.

Disable time in bootstrap date time picker

 $("#datetimepicker4").datepicker({
    dateFormat: 'mm/dd/yy',
    changeMonth: true,
    changeYear: true,
    showOtherMonths: true,
    selectOtherMonths: true,
    pickTime: false,
    format: 'YYYY-MM-DD'
});

What is IPV6 for localhost and 0.0.0.0?

IPv6 localhost

::1 is the loopback address in IPv6.

Within URLs

Within a URL, use square brackets []:

  • http://[::1]/
    Defaults to port 80.
  • http://[::1]:80/
    Specify port.

Enclosing the IPv6 literal in square brackets for use in a URL is defined in RFC 2732 – Format for Literal IPv6 Addresses in URL's.

How do I find the parent directory in C#?

To avoid issues with trailing \, call it this way:

  string ParentFolder =  Directory.GetParent( folder.Trim('\\')).FullName;

default select option as blank

You could use Javascript to achieve this. Try the following code:

HTML

<select id="myDropdown">      
    <option>Option 1</option>     
    <option>Option 2</option>     
    <option>Option 3</option>     
</select> 

JS

document.getElementById("myDropdown").selectedIndex = -1;

or JQuery

$("#myDropdown").prop("selectedIndex", -1);

XPath query to get nth instance of an element

This seems to work:

/descendant::input[@id="search_query"][2]

I go this from "XSLT 2.0 and XPath 2.0 Programmer's Reference, 4th Edition" by Michael Kay.

There is also a note in the "Abbreviated Syntax" section of the XML Path Language specification http://www.w3.org/TR/xpath/#path-abbrev that provided a clue.

How can I change NULL to 0 when getting a single value from a SQL function?

ORACLE/PLSQL:

NVL FUNCTION

SELECT NVL(SUM(Price), 0) AS TotalPrice 
FROM Inventory
WHERE (DateAdded BETWEEN @StartDate AND @EndDate)

This SQL statement would return 0 if the SUM(Price) returned a null value. Otherwise, it would return the SUM(Price) value.

Deleting a SQL row ignoring all foreign keys and constraints

On all tables with foreign keys pointing to this one, use:

ALTER TABLE MyOtherTable NOCHECK CONSTRAINT fk_name

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

How to get the HTML's input element of "file" type to only accept pdf files?

No way to do that other than validate file extension with JavaScript when input path is populated by the file picker. To implement anything fancier you need to write your own component for whichever browser you want (activeX or XUL)

There's an "accept" attribute in HTML4.01 but I'm not aware of any browser supporting it - e.g. accept="image/gif,image/jpeg - so it's a neat but impractical spec

Group by in LINQ

Absolutely - you basically want:

var results = from p in persons
              group p.car by p.PersonId into g
              select new { PersonId = g.Key, Cars = g.ToList() };

Or as a non-query expression:

var results = persons.GroupBy(
    p => p.PersonId, 
    p => p.car,
    (key, g) => new { PersonId = key, Cars = g.ToList() });

Basically the contents of the group (when viewed as an IEnumerable<T>) is a sequence of whatever values were in the projection (p.car in this case) present for the given key.

For more on how GroupBy works, see my Edulinq post on the topic.

(I've renamed PersonID to PersonId in the above, to follow .NET naming conventions.)

Alternatively, you could use a Lookup:

var carsByPersonId = persons.ToLookup(p => p.PersonId, p => p.car);

You can then get the cars for each person very easily:

// This will be an empty sequence for any personId not in the lookup
var carsForPerson = carsByPersonId[personId];

Extract column values of Dataframe as List in Apache Spark

In Scala and Spark 2+, try this (assuming your column name is "s"): df.select('s).as[String].collect

Is there any "font smoothing" in Google Chrome?

Chrome doesn't render the fonts like Firefox or any other browser does. This is generally a problem in Chrome running on Windows only. If you want to make the fonts smooth, use the -webkit-font-smoothing property on yer h4 tags like this.

h4 {
    -webkit-font-smoothing: antialiased;
}

You can also use subpixel-antialiased, this will give you different type of smoothing (making the text a little blurry/shadowed). However, you will need a nightly version to see the effects. You can learn more about font smoothing here.

How to convert a char to a String?

As @WarFox stated - there are 6 methods to convert char to string. However, the fastest one would be via concatenation, despite answers above stating that it is String.valueOf. Here is benchmark that proves that:

@BenchmarkMode(Mode.Throughput)
@Fork(1)
@State(Scope.Thread)
@Warmup(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, batchSize = 1000, timeUnit = TimeUnit.SECONDS)
public class CharToStringConversion {

    private char c = 'c';

    @Benchmark
    public String stringValueOf() {
        return String.valueOf(c);
    }

    @Benchmark
    public String stringValueOfCharArray() {
        return String.valueOf(new char[]{c});
    }

    @Benchmark
    public String characterToString() {
        return Character.toString(c);
    }

    @Benchmark
    public String characterObjectToString() {
        return new Character(c).toString();
    }

    @Benchmark
    public String concatBlankStringPre() {
        return c + "";
    }

    @Benchmark
    public String concatBlankStringPost() {
        return "" + c;
    }

    @Benchmark
    public String fromCharArray() {
        return new String(new char[]{c});
    }
}

And result:

Benchmark                                        Mode  Cnt       Score      Error  Units
CharToStringConversion.characterObjectToString  thrpt   10   82132.021 ± 6841.497  ops/s
CharToStringConversion.characterToString        thrpt   10  118232.069 ± 8242.847  ops/s
CharToStringConversion.concatBlankStringPost    thrpt   10  136960.733 ± 9779.938  ops/s
CharToStringConversion.concatBlankStringPre     thrpt   10  137244.446 ± 9113.373  ops/s
CharToStringConversion.fromCharArray            thrpt   10   85464.842 ± 3127.211  ops/s
CharToStringConversion.stringValueOf            thrpt   10  119281.976 ± 7053.832  ops/s
CharToStringConversion.stringValueOfCharArray   thrpt   10   86563.837 ± 6436.527  ops/s

As you can see, the fastest one would be c + "" or "" + c;

VM version: JDK 1.8.0_131, VM 25.131-b11

This performance difference is due to -XX:+OptimizeStringConcat optimization. You can read about it here.

How to find out the location of currently used MySQL configuration file in linux

The information you want can be found by running

mysql --help

or

mysqld --help --verbose

I tried this command on my machine:

mysql --help | grep "Default options" -A 1

And it printed out:

Default options are read from the following files in the given order:
/etc/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

See if that works for you.

Group by with multiple columns using lambda

var query = source.GroupBy(x => new { x.Column1, x.Column2 });

JavaScript: changing the value of onclick with or without jQuery

Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>

Hope this helps

Adjust UILabel height depending on the text

Thanks for this post. It helped me a great deal. In my case I am also editing the text in a separate view controller. I noticed that when I use:

[cell.contentView addSubview:cellLabel];

in the tableView:cellForRowAtIndexPath: method that the label view was continually rendered over the top of the previous view each time I edited the cell. The text became pixelated, and when something was deleted or changed, the previous version was visible under the new version. Here's how I solved the problem:

if ([[cell.contentView subviews] count] > 0) {
    UIView *test = [[cell.contentView subviews] objectAtIndex:0];
    [test removeFromSuperview];
}
[cell.contentView insertSubview:cellLabel atIndex:0];

No more weird layering. If there is a better way to handle this, Please let me know.

Set max-height on inner div so scroll bars appear, but not on parent div

This would work just fine, set the height to desired pixel

#inner-right{
            height: 100px;
            overflow:auto;
            }

IF EXISTS before INSERT, UPDATE, DELETE for optimization

Yes this will affect performance (the degree to which performance will be affected will be affected by a number of factors). Effectively you are doing the same query "twice" (in your example). Ask yourself whether or not you need to be this defensive in your query and in what situations would the row not be there? Also, with an update statement the rows affected is probably a better way to determine if anything has been updated.

What is the difference between an expression and a statement in Python?

Statements represent an action or command e.g print statements, assignment statements.

print 'hello', x = 1

Expression is a combination of variables, operations and values that yields a result value.

5 * 5 # yields 25

Lastly, expression statements

print 5*5

jQuery select option elements by value

You can use .val() to select the value, like the following:

function select_option(i) {
    $("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

Core dumped, but core file is not in the current directory?

With the launch of systemd, there's another scenario aswell. By default systemd will store core dumps in its journal, being accessible with the systemd-coredumpctl command. Defined in the core_pattern-file:

$ cat /proc/sys/kernel/core_pattern 
|/usr/lib/systemd/systemd-coredump %p %u %g %s %t %e

This behaviour can be disabled with a simple "hack":

$ ln -s /dev/null /etc/sysctl.d/50-coredump.conf
$ sysctl -w kernel.core_pattern=core      # or just reboot

As always, the size of core dumps has to be equal or higher than the size of the core that is being dumped, as done by for example ulimit -c unlimited.

How do you allow spaces to be entered using scanf?

People (and especially beginners) should never use scanf("%s") or gets() or any other functions that do not have buffer overflow protection, unless you know for certain that the input will always be of a specific format (and perhaps not even then).

Remember than scanf stands for "scan formatted" and there's precious little less formatted than user-entered data. It's ideal if you have total control of the input data format but generally unsuitable for user input.

Use fgets() (which has buffer overflow protection) to get your input into a string and sscanf() to evaluate it. Since you just want what the user entered without parsing, you don't really need sscanf() in this case anyway:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* Maximum name size + 1. */

#define MAX_NAME_SZ 256

int main(int argC, char *argV[]) {
    /* Allocate memory and check if okay. */

    char *name = malloc(MAX_NAME_SZ);
    if (name == NULL) {
        printf("No memory\n");
        return 1;
    }

    /* Ask user for name. */

    printf("What is your name? ");

    /* Get the name, with size limit. */

    fgets(name, MAX_NAME_SZ, stdin);

    /* Remove trailing newline, if there. */

    if ((strlen(name) > 0) && (name[strlen (name) - 1] == '\n'))
        name[strlen (name) - 1] = '\0';

    /* Say hello. */

    printf("Hello %s. Nice to meet you.\n", name);

    /* Free memory and exit. */

    free (name);
    return 0;
}

Difference in days between two dates in Java?

I did it this way. it's easy :)

Date d1 = jDateChooserFrom.getDate();
Date d2 = jDateChooserTo.getDate();

Calendar day1 = Calendar.getInstance();
day1.setTime(d1);

Calendar day2 = Calendar.getInstance();
day2.setTime(d2);

int from = day1.get(Calendar.DAY_OF_YEAR);
int to = day2.get(Calendar.DAY_OF_YEAR);

int difference = to-from;

"Are you missing an assembly reference?" compile error - Visual Studio

Right-click the assembly reference in the solution explorer, properties, disable the "Specific Version" option.

Find TODO tags in Eclipse

  1. Push Ctrl+H
  2. Got to File Search tab
  3. Enter "// TODO Auto-generated method stub" in Containing Text field
  4. Enter "*.java" in Filename patterns field
  5. Select proper scope

How to use ArrayList's get() method

ArrayList get(int index) method is used for fetching an element from the list. We need to specify the index while calling get method and it returns the value present at the specified index.

public Element get(int index)

Example : In below example we are getting few elements of an arraylist by using get method.

package beginnersbook.com;
import java.util.ArrayList;
public class GetMethodExample {
   public static void main(String[] args) {
       ArrayList<String> al = new ArrayList<String>();
       al.add("pen");
       al.add("pencil");
       al.add("ink");
       al.add("notebook");
       al.add("book");
       al.add("books");
       al.add("paper");
       al.add("white board");

       System.out.println("First element of the ArrayList: "+al.get(0));
       System.out.println("Third element of the ArrayList: "+al.get(2));
       System.out.println("Sixth element of the ArrayList: "+al.get(5));
       System.out.println("Fourth element of the ArrayList: "+al.get(3));
   }
}

Output:

First element of the ArrayList: pen
Third element of the ArrayList: ink
Sixth element of the ArrayList: books
Fourth element of the ArrayList: notebook

How to [recursively] Zip a directory in PHP?

Here is a simple function that can compress any file or directory recursively, only needs the zip extension to be loaded.

function Zip($source, $destination)
{
    if (!extension_loaded('zip') || !file_exists($source)) {
        return false;
    }

    $zip = new ZipArchive();
    if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
        return false;
    }

    $source = str_replace('\\', '/', realpath($source));

    if (is_dir($source) === true)
    {
        $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

        foreach ($files as $file)
        {
            $file = str_replace('\\', '/', $file);

            // Ignore "." and ".." folders
            if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
                continue;

            $file = realpath($file);

            if (is_dir($file) === true)
            {
                $zip->addEmptyDir(str_replace($source . '/', '', $file . '/'));
            }
            else if (is_file($file) === true)
            {
                $zip->addFromString(str_replace($source . '/', '', $file), file_get_contents($file));
            }
        }
    }
    else if (is_file($source) === true)
    {
        $zip->addFromString(basename($source), file_get_contents($source));
    }

    return $zip->close();
}

Call it like this:

Zip('/folder/to/compress/', './compressed.zip');

What is the suggested way to install brew, node.js, io.js, nvm, npm on OS X?

For install with zsh and Homebrew:

brew install nvm

Then Add the following to ~/.zshrc or your desired shell configuration file:

export NVM_DIR="$HOME/.nvm"
. "/usr/local/opt/nvm/nvm.sh"

Then install a node version and use it.

nvm install 7.10.1
nvm use 7.10.1

"Port 4200 is already in use" when running the ng serve command

I am sharing this as the fowling two commands did not do the job on my mac:

sudo kill $(sudo lsof -t -i:4200)

sudo kill `sudo lsof -t -i:4200`

The following one did, but if you were using the integrated terminal in Visual Code, try to use your machine terminal and add the fowling command:

lsof -t -i tcp:4200 | xargs kill -9

shuffling/permutating a DataFrame in pandas

Here is a work around I found if you want to only shuffle a subset of the DataFrame:

shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])

MySQL: determine which database is selected?

slightly off-topic (using the CLI instead of PHP), but still worth knowing: You can set the prompt to display the default database by using any of the following

mysql --prompt='\d> '
export MYSQL_PS1='\d> '

or once inside

prompt \d>\_
\R \d>\_

Update Multiple Rows in Entity Framework from a list of ids

something like below

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
    friends.ForEach(a=>a.msgSentBy='1234');
    db.SaveChanges();
}

UPDATE:

you can update multiple fields as below

friends.ForEach(a =>
                      {
                         a.property1 = value1;
                         a.property2 = value2;
                      });

Running multiple AsyncTasks at the same time -- not possible?

Just to include the latest update (UPDATE 4) in @Arhimed 's immaculate answer in the very good summary of @sulai:

void doTheTask(AsyncTask task) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { // Android 4.4 (API 19) and above
        // Parallel AsyncTasks are possible, with the thread-pool size dependent on device
        // hardware
        task.execute(params);
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { // Android 3.0 to
        // Android 4.3
        // Parallel AsyncTasks are not possible unless using executeOnExecutor
        task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
    } else { // Below Android 3.0
        // Parallel AsyncTasks are possible, with fixed thread-pool size
        task.execute(params);
    }
}

What does LPCWSTR stand for and how should it be handled with?

LPCWSTR is equivalent to wchar_t const *. It's a pointer to a wide character string that won't be modified by the function call.

You can assign to LPCWSTRs by prepending a L to a string literal: LPCWSTR *myStr = L"Hello World";

LPCTSTR and any other T types, take a string type depending on the Unicode settings for your project. If _UNICODE is defined for your project, the use of T types is the same as the wide character forms, otherwise the Ansi forms. The appropriate function will also be called this way: FindWindowEx is defined as FindWindowExA or FindWindowExW depending on this definition.

Move UIView up when the keyboard appears in iOS

Here you go. I have used this code with UIView, though. You should be able to make those adjustments for scrollview.

    func addKeyboardNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillHide(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// if using constraints            
// bottomViewBottomSpaceConstraint.constant = keyboardSize.height
self.view.frame.origin.y -= keyboardSize.height
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    func keyboardWillHide(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
//if using constraint
//        bottomViewBottomSpaceConstraint.constant = 0
self.view.frame.origin.y = 0
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }

Don't forget to remove notifications at right place.

func removeKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

How can I rename column in laravel using migration?

Renaming Columns (Laravel 5.x)

To rename a column, you may use the renameColumn method on the Schema builder. *Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file.*

Or you can simply required the package using composer...

composer require doctrine/dbal

Source: https://laravel.com/docs/5.0/schema#renaming-columns

Note: Use make:migration and not migrate:make for Laravel 5.x

HTTP status code for update and delete?

{
    "VALIDATON_ERROR": {
        "code": 512,
        "message": "Validation error"
    },
    "CONTINUE": {
        "code": 100,
        "message": "Continue"
    },
    "SWITCHING_PROTOCOLS": {
        "code": 101,
        "message": "Switching Protocols"
    },
    "PROCESSING": {
        "code": 102,
        "message": "Processing"
    },
    "OK": {
        "code": 200,
        "message": "OK"
    },
    "CREATED": {
        "code": 201,
        "message": "Created"
    },
    "ACCEPTED": {
        "code": 202,
        "message": "Accepted"
    },
    "NON_AUTHORITATIVE_INFORMATION": {
        "code": 203,
        "message": "Non Authoritative Information"
    },
    "NO_CONTENT": {
        "code": 204,
        "message": "No Content"
    },
    "RESET_CONTENT": {
        "code": 205,
        "message": "Reset Content"
    },
    "PARTIAL_CONTENT": {
        "code": 206,
        "message": "Partial Content"
    },
    "MULTI_STATUS": {
        "code": 207,
        "message": "Multi-Status"
    },
    "MULTIPLE_CHOICES": {
        "code": 300,
        "message": "Multiple Choices"
    },
    "MOVED_PERMANENTLY": {
        "code": 301,
        "message": "Moved Permanently"
    },
    "MOVED_TEMPORARILY": {
        "code": 302,
        "message": "Moved Temporarily"
    },
    "SEE_OTHER": {
        "code": 303,
        "message": "See Other"
    },
    "NOT_MODIFIED": {
        "code": 304,
        "message": "Not Modified"
    },
    "USE_PROXY": {
        "code": 305,
        "message": "Use Proxy"
    },
    "TEMPORARY_REDIRECT": {
        "code": 307,
        "message": "Temporary Redirect"
    },
    "PERMANENT_REDIRECT": {
        "code": 308,
        "message": "Permanent Redirect"
    },
    "BAD_REQUEST": {
        "code": 400,
        "message": "Bad Request"
    },
    "UNAUTHORIZED": {
        "code": 401,
        "message": "Unauthorized"
    },
    "PAYMENT_REQUIRED": {
        "code": 402,
        "message": "Payment Required"
    },
    "FORBIDDEN": {
        "code": 403,
        "message": "Forbidden"
    },
    "NOT_FOUND": {
        "code": 404,
        "message": "Not Found"
    },
    "METHOD_NOT_ALLOWED": {
        "code": 405,
        "message": "Method Not Allowed"
    },
    "NOT_ACCEPTABLE": {
        "code": 406,
        "message": "Not Acceptable"
    },
    "PROXY_AUTHENTICATION_REQUIRED": {
        "code": 407,
        "message": "Proxy Authentication Required"
    },
    "REQUEST_TIMEOUT": {
        "code": 408,
        "message": "Request Timeout"
    },
    "CONFLICT": {
        "code": 409,
        "message": "Conflict"
    },
    "GONE": {
        "code": 410,
        "message": "Gone"
    },
    "LENGTH_REQUIRED": {
        "code": 411,
        "message": "Length Required"
    },
    "PRECONDITION_FAILED": {
        "code": 412,
        "message": "Precondition Failed"
    },
    "REQUEST_TOO_LONG": {
        "code": 413,
        "message": "Request Entity Too Large"
    },
    "REQUEST_URI_TOO_LONG": {
        "code": 414,
        "message": "Request-URI Too Long"
    },
    "UNSUPPORTED_MEDIA_TYPE": {
        "code": 415,
        "message": "Unsupported Media Type"
    },
    "REQUESTED_RANGE_NOT_SATISFIABLE": {
        "code": 416,
        "message": "Requested Range Not Satisfiable"
    },
    "EXPECTATION_FAILED": {
        "code": 417,
        "message": "Expectation Failed"
    },
    "IM_A_TEAPOT": {
        "code": 418,
        "message": "I'm a teapot"
    },
    "INSUFFICIENT_SPACE_ON_RESOURCE": {
        "code": 419,
        "message": "Insufficient Space on Resource"
    },
    "METHOD_FAILURE": {
        "code": 420,
        "message": "Method Failure"
    },
    "UNPROCESSABLE_ENTITY": {
        "code": 422,
        "message": "Unprocessable Entity"
    },
    "LOCKED": {
        "code": 423,
        "message": "Locked"
    },
    "FAILED_DEPENDENCY": {
        "code": 424,
        "message": "Failed Dependency"
    },
    "PRECONDITION_REQUIRED": {
        "code": 428,
        "message": "Precondition Required"
    },
    "TOO_MANY_REQUESTS": {
        "code": 429,
        "message": "Too Many Requests"
    },
    "REQUEST_HEADER_FIELDS_TOO_LARGE": {
        "code": 431,
        "message": "Request Header Fields Too"
    },
    "UNAVAILABLE_FOR_LEGAL_REASONS": {
        "code": 451,
        "message": "Unavailable For Legal Reasons"
    },
    "INTERNAL_SERVER_ERROR": {
        "code": 500,
        "message": "Internal Server Error"
    },
    "NOT_IMPLEMENTED": {
        "code": 501,
        "message": "Not Implemented"
    },
    "BAD_GATEWAY": {
        "code": 502,
        "message": "Bad Gateway"
    },
    "SERVICE_UNAVAILABLE": {
        "code": 503,
        "message": "Service Unavailable"
    },
    "GATEWAY_TIMEOUT": {
        "code": 504,
        "message": "Gateway Timeout"
    },
    "HTTP_VERSION_NOT_SUPPORTED": {
        "code": 505,
        "message": "HTTP Version Not Supported"
    },
    "INSUFFICIENT_STORAGE": {
        "code": 507,
        "message": "Insufficient Storage"
    },
    "NETWORK_AUTHENTICATION_REQUIRED": {
        "code": 511,
        "message": "Network Authentication Required"
    }
}

How to enable explicit_defaults_for_timestamp?

On a Windows platform,

  1. Find your my.ini configuration file.
  2. In my.ini go to the [mysqld] section.
  3. Add explicit_defaults_for_timestamp=true without quotes and save the change.
  4. Start mysqld

This worked for me (windows 7 Ultimate 32bit)

Link error "undefined reference to `__gxx_personality_v0'" and g++

If g++ still gives error Try using:

g++ file.c -lstdc++

Look at this post: What is __gxx_personality_v0 for?

Make sure -lstdc++ is at the end of the command. If you place it at the beginning (i.e. before file.c), you still can get this same error.

Suppress/ print without b' prefix for bytes in Python 3

If the data is in an UTF-8 compatible format, you can convert the bytes to a string.

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337

compilation error: identifier expected

You also will have to catch or throw the IOException. See below. Not always the best way, but it will get you a result:

public class details {
    public static void main( String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Twitter Bootstrap scrollable table rows and fixed header

Here is a jQuery plugin that does exactly that: http://fixedheadertable.com/

Usage:

$('selector').fixedHeaderTable({ fixedColumn: 1 });

Set the fixedColumn option if you want any number of columns to be also fixed for horizontal scrolling.

EDIT: This example http://www.datatables.net/examples/basic_init/scroll_y.html is much better in my opinion, although with DataTables you'll need to get a better understanding of how it works in general.

EDIT2: For Bootstrap to work with DataTables you need to follow the instructions here: http://datatables.net/blog/Twitter_Bootstrap_2 (I have tested this and it works)- For Bootstrap 3 there's a discussion here: http://datatables.net/forums/discussion/comment/53462 - (I haven't tested this)

Daylight saving time and time zone best practices

This is an important and surprisingly tough issue. The truth is that there is no completely satisfying standard for persisting time. For example, the SQL standard and the ISO format (ISO 8601) are clearly not enough.

From the conceptual point of view, one usually deals with two types of time-date data, and it's convenient to distinguish them (the above standards do not) : "physical time" and "civil time".

A "physical" instant of time is a point in the continuous universal timeline that physics deal with (ignoring relativity, of course). This concept can be adequately coded-persisted in UTC, for example (if you can ignore leap seconds).

A "civil" time is a datetime specification that follows civil norms: a point of time here is fully specified by a set of datetime fields (Y,M,D,H,MM,S,FS) plus a TZ (timezone specification) (also a "calendar", actually; but lets assume we restrict the discussion to Gregorian calendar). A timezone and a calendar jointly allow (in principle) to map from one representation to another. But civil and physical time instants are fundamentally different types of magnitudes, and they should be kept conceptually separated and treated differently (an analogy: arrays of bytes and character strings).

The issue is confusing because we speak of these types events interchangeably, and because the civil times are subject to political changes. The problem (and the need to distinguish these concepts) becomes more evident for events in the future. Example (taken from my discussion here.

John records in his calendar a reminder for some event at datetime 2019-Jul-27, 10:30:00, TZ=Chile/Santiago, (which has offset GMT-4, hence it corresponds to UTC 2019-Jul-27 14:30:00). But some day in the future, the country decides to change the TZ offset to GMT-5.

Now, when the day comes... should that reminder trigger at

A) 2019-Jul-27 10:30:00 Chile/Santiago = UTC time 2019-Jul-27 15:30:00 ?

or

B) 2019-Jul-27 9:30:00 Chile/Santiago = UTC time 2019-Jul-27 14:30:00 ?

There is no correct answer, unless one knows what John conceptually meant when he told the calendar "Please ring me at 2019-Jul-27, 10:30:00 TZ=Chile/Santiago".

Did he mean a "civil date-time" ("when the clocks in my city tell 10:30")? In that case, A) is the correct answer.

Or did he mean a "physical instant of time", a point in the continuus line of time of our universe, say, "when the next solar eclipse happens". In that case, answer B) is the correct one.

A few Date/Time APIs get this distinction right: among them, Jodatime, which is the foundation of the next (third!) Java DateTime API (JSR 310).

fork() child and parent processes

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

Join vs. sub-query

I just thinking about the same problem, but I am using subquery in the FROM part. I need connect and query from large tables, the "slave" table have 28 million record but the result is only 128 so small result big data! I am using MAX() function on it.

First I am using LEFT JOIN because I think that is the correct way, the mysql can optimalize etc. Second time just for testing, I rewrite to sub-select against the JOIN.

LEFT JOIN runtime: 1.12s SUB-SELECT runtime: 0.06s

18 times faster the subselect than the join! Just in the chokito adv. The subselect looks terrible but the result ...

How to update a git clone --mirror?

Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update).

But unfortunately there is no way to clone / mirror / update the hooks, as I wanted...

I have found this very interesting thread about cloning/mirroring the hooks:

http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread

I learned:

  • The hooks are not considered part of the repository contents.

  • There is more data, like the .git/description folder, which does not get cloned, just as the hooks.

  • The default hooks that appear in the hooks dir comes from the TEMPLATE_DIR

  • There is this interesting template feature on git.

So, I may either ignore this "clone the hooks thing", or go for a rsync strategy, given the purposes of my mirror (backup + source for other clones, only).

Well... I will just forget about hooks cloning, and stick to the git remote update way.

  • Sehe has just pointed out that not only "hooks" aren't managed by the clone / update process, but also stashes, rerere, etc... So, for a strict backup, rsync or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update.

Thanks! Improved a bit of my own "git-fu"... :-)

Convert a RGB Color Value to a Hexadecimal String

Random ra = new Random();
int r, g, b;
r=ra.nextInt(255);
g=ra.nextInt(255);
b=ra.nextInt(255);
Color color = new Color(r,g,b);
String hex = Integer.toHexString(color.getRGB() & 0xffffff);
if (hex.length() < 6) {
    hex = "0" + hex;
}
hex = "#" + hex;

How to debug external class library projects in visual studio?

I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:

Build Events:

  • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

  • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

Debug:

  • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

  • Working Directory C:\<path-to-main>\bin\debug

This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

How do I get only directories using Get-ChildItem?

From PowerShell v2 and newer (k represents the folder you are beginning your search at):

Get-ChildItem $Path -attributes D -Recurse

If you just want folder names only, and nothing else, use this:

Get-ChildItem $Path -Name -attributes D -Recurse

If you are looking for a specific folder, you could use the following. In this case, I am looking for a folder called myFolder:

Get-ChildItem $Path -attributes D -Recurse -include "myFolder"

Read entire file in Scala?

Just like in Java, using CommonsIO library:

FileUtils.readFileToString(file, StandardCharsets.UTF_8)

Also, many answers here forget Charset. It's better to always provide it explicitly, or it will hit one day.

Objective-C: Reading a file line by line

I see a lot of these answers rely on reading the whole text file into memory instead of taking it one chunk at a time. Here's my solution in nice modern Swift, using FileHandle to keep memory impact low:

enum MyError {
    case invalidTextFormat
}

extension FileHandle {

    func readLine(maxLength: Int) throws -> String {

        // Read in a string of up to the maximum length
        let offset = offsetInFile
        let data = readData(ofLength: maxLength)
        guard let string = String(data: data, encoding: .utf8) else {
            throw MyError.invalidTextFormat
        }

        // Check for carriage returns; if none, this is the whole string
        let substring: String
        if let subindex = string.firstIndex(of: "\n") {
            substring = String(string[string.startIndex ... subindex])
        } else {
            substring = string
        }

        // Wind back to the correct offset so that we don't miss any lines
        guard let dataCount = substring.data(using: .utf8, allowLossyConversion: false)?.count else {
            throw MyError.invalidTextFormat
        }
        try seek(toOffset: offset + UInt64(dataCount))
        return substring
    }

}

Note that this preserves the carriage return at the end of the line, so depending on your needs you may want to adjust the code to remove it.

Usage: simply open a file handle to your target text file and call readLine with a suitable maximum length - 1024 is standard for plain text, but I left it open in case you know it will be shorter. Note that the command will not overflow the end of the file, so you may have to check manually that you've not reached it if you intend to parse the entire thing. Here's some sample code that shows how to open a file at myFileURL and read it line-by-line until the end.

do {
    let handle = try FileHandle(forReadingFrom: myFileURL)
    try handle.seekToEndOfFile()
    let eof = handle.offsetInFile
    try handle.seek(toFileOffset: 0)

    while handle.offsetInFile < eof {
        let line = try handle.readLine(maxLength: 1024)
        // Do something with the string here
    }
    try handle.close()
catch let error {
    print("Error reading file: \(error.localizedDescription)"
}

The ScriptManager must appear before any controls that need it

There many cases where script Manager may give problem like that. you Try This First add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.

  1. We need to add ScriptManager while using any AJAX Control not only update Panel. <asp:ScriptManager ID="ScriptManger1" runat="Server" />

  2. If you are using Latest Ajax Control Toolkit (I am not sure about version 4.0 or 4.5) you need to use that Particular ToolkitScriptManager and not ScriptManager from default Ajax Extensions.

  3. You can use only one ScriptManager or ToolKitScriptManager on page, If you have added it on Master Page you no need to add it again on Web Page.

  4. The problem mentioned here may because of ContentPlaceHolder Please Check how many content place holders you have on your master page. Lets take an example if you have 2 content Placeholders "Head" and "ContentPlaceHolder1" on Master Page and ContentPlaceHolder1 is your Content Page.please check below code I added here my ScriptManager on Second Placeholder just below there is update panel.

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <asp:ContentPlaceHolder id="head" runat="server">
    </asp:ContentPlaceHolder>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:ContentPlaceHolder id="MainContent" runat="server">
        <asp:ScriptManager ID="ScriptManger1" runat="Server" />
          <asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
    </ContentTemplate>
</asp:UpdatePanel>
        </asp:ContentPlaceHolder>
    </div>
    </form>
</body>
</html> 

Most of us make mistake while designing web form when we choose masterpage by default on web page there are equal number of placeholders as of MasterPage.

<%@ Page Title="" Language="C#" MasterPageFile="~/Master Pages/Home.master" AutoEventWireup="true" CodeFile="frmCompanyLogin.aspx.cs" Inherits="Authentication_frmCompanyLogin" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" Runat="Server">
</asp:Content>

We no need to remove any PlaceHolder it is guiding structure but you must have to add the web form Contents in Same PlaceHolder where you added your ScriptManager(on Master Page) or add Script Manager in appropriate Placeholder or any place Holder which appears before the content in which Ajax Control is used.

Android ADB doesn't see device

On Windows it is most probably that the device drivers are not installed properly.

First, install Google USB Driver from Android SDK Manager.

Then, go to Start, right-click on My Computer, select Properties and go to Device Manager on the left. Locate you device under Other Devices (Unknown devices, USB Devices). Right-click on it and select Properties. Navigate to Driver tab. Select Update Driver and then Browse my computer for driver software. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver directory. Windows should find and install drivers there. Then run adb kill-server. Next time you do adb devices the device should be in the list.

Where does linux store my syslog?

In addition to the accepted answer, it is useful to know the following ...

Each of those functions should have manual pages associated with them.

If you run man -k syslog (a keyword search of man pages) you will get a list of man pages that refer to, or are about syslog

$ man -k syslog
logger (1)           - a shell command interface to the syslog(3) system l...
rsyslog.conf (5)     - rsyslogd(8) configuration file
rsyslogd (8)         - reliable and extended syslogd
syslog (2)           - read and/or clear kernel message ring buffer; set c...
syslog (3)           - send messages to the system logger
vsyslog (3)          - send messages to the system logger

You need to understand the manual sections in order to delve further.

Here's an excerpt from the man page for man, that explains man page sections :

The table below shows the section numbers of the manual followed  by
the types of pages they contain.

   1   Executable programs or shell commands
   2   System calls (functions provided by the kernel)
   3   Library calls (functions within program libraries)
   4   Special files (usually found in /dev)
   5   File formats and conventions eg /etc/passwd
   6   Games
   7   Miscellaneous  (including  macro  packages and conven-
       tions), e.g. man(7), groff(7)
   8   System administration commands (usually only for root)
   9   Kernel routines [Non standard]

To read the above run

$man man 

So, if you run man 3 syslog you get a full manual page for the syslog function that you called in your code.

SYSLOG(3)                Linux Programmer's Manual                SYSLOG(3)

NAME
   closelog,  openlog,  syslog,  vsyslog  - send messages to the system
   logger

SYNOPSIS
   #include <syslog.h>

   void openlog(const char *ident, int option, int facility);
   void syslog(int priority, const char *format, ...);
   void closelog(void);

   #include <stdarg.h>

   void vsyslog(int priority, const char *format, va_list ap);

Not a direct answer but hopefully you will find this useful.

How to get JQuery.trigger('click'); to initiate a mouse click

I have tried top two answers, it doesn't worked for me until I removed "display:none" from my file input elements. Then I reverted back to .trigger() it also worked at safari for windows.

So conclusion, Don't use display:none; to hide your file input , you may use opacity:0 instead.

How to remove blank lines from a Unix file

sed -i '/^$/d' foo

This tells sed to delete every line matching the regex ^$ i.e. every empty line. The -i flag edits the file in-place, if your sed doesn't support that you can write the output to a temporary file and replace the original:

sed '/^$/d' foo > foo.tmp
mv foo.tmp foo

If you also want to remove lines consisting only of whitespace (not just empty lines) then use:

sed -i '/^[[:space:]]*$/d' foo

Edit: also remove whitespace at the end of lines, because apparently you've decided you need that too:

sed -i '/^[[:space:]]*$/d;s/[[:space:]]*$//' foo

failed to load ad : 3

There could be one of the reasons that You might have created your advertise from adMob console by clicking yes that your app is already in playstore and giving url of your live app.Now in that case you wont able to run your ads in any other projects which is having diff package id then the live one(not even test advertise).You have to implement the ads in live project containing same package id and in other case will be getting ad failed to load ad : 3.

Thanks! Happy coding!

Android Notification Sound

On Oreo (Android 8) and above it should be done for custom sound in this way (notification channels):

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);

@UniqueConstraint and @Column(unique = true) in hibernate annotation

In addition to @Boaz's and @vegemite4me's answers....

By implementing ImplicitNamingStrategy you may create rules for automatically naming the constraints. Note you add your naming strategy to the metadataBuilder during Hibernate's initialization:

metadataBuilder.applyImplicitNamingStrategy(new MyImplicitNamingStrategy());

It works for @UniqueConstraint, but not for @Column(unique = true), which always generates a random name (e.g. UK_3u5h7y36qqa13y3mauc5xxayq).

There is a bug report to solve this issue, so if you can, please vote there to have this implemented. Here: https://hibernate.atlassian.net/browse/HHH-11586

Thanks.

How to reset db in Django? I get a command 'reset' not found error

if you are using Django 2.0 Then

python manage.py flush 

will work

Fully custom validation error message with Rails

In your view

object.errors.each do |attr,msg|
  if msg.is_a? String
    if attr == :base
      content_tag :li, msg
    elsif msg[0] == "^"
      content_tag :li, msg[1..-1]
    else
      content_tag :li, "#{object.class.human_attribute_name(attr)} #{msg}"
    end
  end
end

When you want to override the error message without the attribute name, simply prepend the message with ^ like so:

validates :last_name,
  uniqueness: {
    scope: [:first_name, :course_id, :user_id],
    case_sensitive: false,
    message: "^This student has already been registered."
  }

Getting Raw XML From SOAPMessage in Java

If you need formatting the xml string to xml, try this:

String xmlStr = "your-xml-string";
Source xmlInput = new StreamSource(new StringReader(xmlStr));
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput,
        new StreamResult(new FileOutputStream("response.xml")));

Generate GUID in MySQL for existing Data?

MYsql

UPDATE tablename   SET columnName = UUID()

oracle

UPDATE tablename   SET columnName = SYS_GUID();

SQLSERVER

UPDATE tablename   SET columnName = NEWID();;

convert '1' to '0001' in JavaScript

String.prototype.padZero= function(len, c){
    var s= this, c= c || '0';
    while(s.length< len) s= c+ s;
    return s;
}

dispite the name, you can left-pad with any character, including a space. I never had a use for right side padding, but that would be easy enough.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Just click red button to stop all services on eclipse than re- run application as Spring Boot Application - This worked for me.

How to write loop in a Makefile?

THE major reason to use make IMHO is the -j flag. make -j5 will run 5 shell commands at once. This is good if you have 4 CPUs say, and a good test of any makefile.

Basically, you want make to see something like:

.PHONY: all
all: job1 job2 job3

.PHONY: job1
job1: ; ./a.out 1

.PHONY: job2
job2: ; ./a.out 2

.PHONY: job3
job3: ; ./a.out 3

This is -j friendly (a good sign). Can you spot the boiler-plate? We could write:

.PHONY: all job1 job2 job3
all: job1 job2 job3
job1 job2 job3: job%:
    ./a.out $*

for the same effect (yes, this is the same as the previous formulation as far as make is concerned, just a bit more compact).

A further bit of parameterisation so that you can specify a limit on the command-line (tedious as make does not have any good arithmetic macros, so I'll cheat here and use $(shell ...))

LAST := 1000
NUMBERS := $(shell seq 1 ${LAST})
JOBS := $(addprefix job,${NUMBERS})
.PHONY: all ${JOBS}
all: ${JOBS} ; echo "$@ success"
${JOBS}: job%: ; ./a.out $*

You run this with make -j5 LAST=550, with LAST defaulting to 1000.

Validate that a string is a positive integer

Looks like a regular expression is the way to go:

var isInt = /^\+?\d+$/.test('the string');

Laravel Eloquent inner join with multiple conditions

Because you did it in such a way that it thinks both are join conditions in your code given below:

public function scopeShops($query) {
    return $query->join('kg_shops', function($join)
    {
        $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
        $join->on('kg_shops.active', '=', "1");
    });
}

So,you should remove the second line:

return $query->join('kg_shops', function($join)
{
    $join->on('kg_shops.id', '=', 'kg_feeds.shop_id');
});

Now, you should add a where clause and it should be like this:

return $query->join('kg_shops', function($join)
{
  $join->on('kg_shops.id', '=', 'kg_feeds.shop_id')->where('kg_shops.active', 1);
})->get();

"google is not defined" when using Google Maps V3 in Firefox remotely

Try using this:

<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script> 

Cause of a process being a deadlock victim

Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.

No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:

By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the SET DEADLOCK_PRIORITY statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).

Q2. If I execute the select with a NOLOCK hint, will this remove the problem?

No. For several reasons:

Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?

Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.

With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.

Is it possible to use 'else' in a list comprehension?

If you want an else you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value as the statement instead, and remove the filter from the end:

table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))

Android: How can I pass parameters to AsyncTask's onPreExecute()?

1) For me that's the most simple way passing parameters to async task is like this

// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);

Declare and use the async task like here

private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {

    @Override
    protected Void doInBackground(Boolean...pParams) 
    {
        Boolean param1, param2, param3;

        //

          param1=pParams[0];    
          param2=pParams[1];
          param3=pParams[2];    
      ....
}                           

2) Passing methods to async-task In order to avoid coding the async-Task infrastructure (thread, messagenhandler, ...) multiple times you might consider to pass the methods which should be executed in your async-task as a parameter. Following example outlines this approach. In addition you might have the need to subclass the async-task to pass initialization parameters in the constructor.

 /* Generic Async Task    */
interface MyGenericMethod {
    int execute(String param);
}

protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
    public String mParam;                           // member variable to parameterize the function
    @Override
    protected Void doInBackground(MyGenericMethod... params) {
        //  do something here
        params[0].execute("Myparameter");
        return null;
    }       
}

// to start the asynctask do something like that
public void startAsyncTask()
{
    // 
    AsyncTask<MyGenericMethod, Void, Void>  mytest = new testtask().execute(new MyGenericMethod() {
        public int execute(String param) {
            //body
            return 1;
        }
    });     
}

How do I see which checkbox is checked?

If the checkbox is checked, then the checkbox's value will be passed. Otherwise, the field is not passed in the HTTP post.

if (isset($_POST['mycheckbox'])) {
    echo "checked!";
}

double free or corruption (!prev) error in c program

1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory

Here is the program with all the changes needed. I compiled and ran... no errors or warnings.

#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h>  //sine
#include <string.h>

#define TIME 255
#define HARM 32

int main (void) {
    double sineRads;
    double sine;
    int tcount = 0;
    int hcount = 0;
    /* allocate some heap memory for the large array of waveform data */
    double *ptr = malloc(sizeof(double) * TIME);
     //memset( ptr, 0x00, sizeof(double) * TIME);  may not always set double to 0
    for( tcount = 0; tcount < TIME; tcount++ )
    {
         ptr[tcount] = 0; 
    }

    tcount = 0;
    if (NULL == ptr) {
        printf("ERROR: couldn't allocate waveform memory!\n");
    } else {
        /*evaluate and add harmonic amplitudes for each time step */
        for(tcount = 0; tcount < TIME; tcount++){
            for(hcount = 0; hcount <= HARM; hcount++){
                sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
                sineRads *= (hcount + 1); //scale frequency by harmonic number
                sine = sin(sineRads); 
                ptr[tcount] += sine; //add to other results for this time step
            }
        }
        free(ptr);
        ptr = NULL;     
    }
    return 0;
}

How to bind Close command to a button

Actually, it is possible without C# code. The key is to use interactions:

<Button Content="Close">
  <i:Interaction.Triggers>
    <i:EventTrigger EventName="Click">
      <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
  </i:Interaction.Triggers>
</Button>

In order for this to work, just set the x:Name of your window to "window", and add these two namespaces:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"

This requires that you add the Expression Blend SDK DLL to your project, specifically Microsoft.Expression.Interactions.

In case you don't have Blend, the SDK can be downloaded here.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

if your application accepts errors raise from Oracle, then you can use it. we have an application, each time when an error happens, we call raise_application_error, the application will popup a red box to show the error message we provide through this method.

When using dotnet code, I just use "raise", dotnet exception mechanisim will automatically capture the error passed by Oracle ODP and shown inside my catch exception code.

Count number of rows within each group

library(tidyverse)

df_1 %>%
  group_by(Year, Month) %>%
  summarise(count= n()) 

css absolute position won't work with margin-left:auto margin-right: auto

I've used this trick to center an absolutely positioned element. Though, you have to know the element's width.

.divtagABS {
    width: 100px;
    position: absolute;
    left: 50%;
    margin-left: -50px;
  }

Basically, you use left: 50%, then back it out half of it's width with a negative margin.

HTML Button : Navigate to Other Page - Different Approaches

I make a link. A link is a link. A link navigates to another page. That is what links are for and everybody understands that. So Method 3 is the only correct method in my book.

I wouldn't want my link to look like a button at all, and when I do, I still think functionality is more important than looks.

Buttons are less accessible, not only due to the need of Javascript, but also because tools for the visually impaired may not understand this Javascript enhanced button well.

Method 4 would work as well, but it is more a trick than a real functionality. You abuse a form to post 'nothing' to this other page. It's not clean.

m2e lifecycle-mapping not found

this step works on me : 1. Remove your project on eclipse 2. Re import project 3. Delete target folder on your project 4. mvn or mvnw install

Structure of a PDF file?

Extracting text from PDF is a hard problem because PDF has such a layout-oriented structure. You can see the docs and source code of my barely-successful attempt on CPAN (my implementation is in Perl). The PDF data structure is very cool and well designed, but it's easier to write than read.

rbenv not changing ruby version

Linux / Ubuntu Users Step 1:

$ rbenv versions
  system
  2.6.0
* 2.7.0 (set by /home/User/Documents/sample-app/.ruby-version) #Yours will be different
  2.7.2

Step 2:

$ nano /home/User/Documents/sample-app/.ruby-version

Step 3:

$ ruby -v
ruby 2.7.2p137 (2020-10-01 revision 5445e04352) [x86_64-linux]

C++ IDE for Linux?

I recommend you read The Art Of UNIX Progranmming. It will frame your mind into using the environment as your IDE.

Convert SVG image to PNG with PHP

You can use Raphaël—JavaScript Library and achieve it easily. It will work in IE also.

How to convert a string from uppercase to lowercase in Bash?

Why not execute in backticks ?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

Git cli: get user info from username

git config --list

git config -l

will display your username and email together, along with other info

Laravel 5: Display HTML with Blade

Use {!! $text !!}to display data without escaping it. Just be sure that you don’t do this with data that came from the user and has not been cleaned.

how to re-format datetime string in php?

You can use date_parse_from_format() function ...

Check this link..you will get clear idea

How do I initialize a byte array in Java?

Smallest internal type, which at compile time can be assigned by hex numbers is char, as

private static final char[] CDRIVES_char = new char[] {0xe0, 0xf4, ...};

In order to have an equivalent byte array one might deploy conversions as

public static byte[] charToByteArray(char[] x)
{
    final byte[] res = new byte[x.length];
    for (int i = 0; i < x.length; i++)
    {
        res[i] = (byte) x[i];
    }
    return res;
}

public static byte[][] charToByteArray(char[][] x)
{
    final byte[][] res = new byte[x.length][];
    for (int i = 0; i < x.length; i++)
    {
        res[i] = charToByteArray(x[i]);
    }
    return res;
}

How can I increment a date by one day in Java?

Construct a Calendar object and use the method add(Calendar.DATE, 1);

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

Make an image width 100% of parent div, but not bigger than its own width

You should set the max width and if you want you can also set some padding on one of the sides. In my case the max-width: 100% was good but the image was right next to the end of the screen.

  max-width: 100%;
  padding-right: 30px;
  /*add more paddings if needed*/

How can I remove a key from a Python dictionary?

We can delete a key from a Python dictionary by the some of the following approaches.

Using the del keyword; it's almost the same approach like you did though -

 myDict = {'one': 100, 'two': 200, 'three': 300 }
 print(myDict)  # {'one': 100, 'two': 200, 'three': 300}
 if myDict.get('one') : del myDict['one']
 print(myDict)  # {'two': 200, 'three': 300}

Or

We can do like the following:

But one should keep in mind that, in this process actually it won't delete any key from the dictionary rather than making a specific key excluded from that dictionary. In addition, I observed that it returned a dictionary which was not ordered the same as myDict.

myDict = {'one': 100, 'two': 200, 'three': 300, 'four': 400, 'five': 500}
{key:value for key, value in myDict.items() if key != 'one'}

If we run it in the shell, it'll execute something like {'five': 500, 'four': 400, 'three': 300, 'two': 200} - notice that it's not the same ordered as myDict. Again if we try to print myDict, then we can see all keys including which we excluded from the dictionary by this approach. However, we can make a new dictionary by assigning the following statement into a variable:

var = {key:value for key, value in myDict.items() if key != 'one'}

Now if we try to print it, then it'll follow the parent order:

print(var) # {'two': 200, 'three': 300, 'four': 400, 'five': 500}

Or

Using the pop() method.

myDict = {'one': 100, 'two': 200, 'three': 300}
print(myDict)

if myDict.get('one') : myDict.pop('one')
print(myDict)  # {'two': 200, 'three': 300}

The difference between del and pop is that, using pop() method, we can actually store the key's value if needed, like the following:

myDict = {'one': 100, 'two': 200, 'three': 300}
if myDict.get('one') : var = myDict.pop('one')
print(myDict) # {'two': 200, 'three': 300}
print(var)    # 100

Fork this gist for future reference, if you find this useful.

Sorting Python list based on the length of the string

def lensort(list_1):
    list_2=[];list_3=[]
for i in list_1:
    list_2.append([i,len(i)])
list_2.sort(key = lambda x : x[1])
for i in list_2:
    list_3.append(i[0])
return list_3

This works for me!

Example on ToggleButton

Just remove the line toggle.toggle(); from your click listener toggle() method will always reset your toggle button value.

And as you are trying to take the value of EditText in string variable which always remains same as you are getting value in onCreate() so better directly use the EditText to get the value of it in your onClick listener.

Just change your code as below its working fine now.

  btn.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
                       //toggle.toggle();
            if ( ed.getText().toString().equalsIgnoreCase("1")) {

                toggle.setTextOff("TOGGLE ON");
                toggle.setChecked(true);
            } else if ( ed.getText().toString().equalsIgnoreCase("0")) {

                toggle.setTextOn("TOGGLE OFF");
                toggle.setChecked(false);

            }
        }
    });

How to set editor theme in IntelliJ Idea

If you are using a Windows System. You can press Ctrl + Alt + S, and select Appearance.

Average of multiple columns

You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(R1),
                      (R2),
                      (R3),
                      (R4),
                      (R5)) T (c)) AS [Average]
FROM   Request  

The 2005 version is a bit more tedious

SELECT *,
       (SELECT AVG(c)
        FROM   (SELECT R1
                UNION ALL
                SELECT R2
                UNION ALL
                SELECT R3
                UNION ALL
                SELECT R4
                UNION ALL
                SELECT R5) T (c)) AS [Average]
FROM   Request

How to convert text column to datetime in SQL

This works:

SELECT STR_TO_DATE(dateColumn, '%c/%e/%Y %r') FROM tabbleName WHERE 1

Hadoop: «ERROR : JAVA_HOME is not set»

You can add in your .bashrc file:

export JAVA_HOME=$(readlink -f /usr/bin/java | sed "s:bin/java::")

and it will dynamically change when you update your packages.

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++ is the lingua franca of the console game industry. For better or worse, you must know it to be a professional console game programmer.

How to delete row based on cell value

The easiest way to do this would be to use a filter.

You can either filter for any cells in column A that don't have a "-" and copy / paste, or (my more preferred method) filter for all cells that do have a "-" and then select all and delete - Once you remove the filter, you're left with what you need.

Hope this helps.

Can't access to HttpContext.Current

Adding a bit to mitigate the confusion here. Even though Darren Davies' (accepted) answer is more straight forward, I think Andrei's answer is a better approach for MVC applications.

The answer from Andrei means that you can use HttpContext just as you would use System.Web.HttpContext.Current. For example, if you want to do this:

System.Web.HttpContext.Current.User.Identity.Name

you should instead do this:

HttpContext.User.Identity.Name

Both achieve the same result, but (again) in terms of MVC, the latter is more recommended.

Another good and also straight forward information regarding this matter can be found here: Difference between HttpContext.Current and Controller.Context in MVC ASP.NET.

PowerShell script to return members of multiple security groups

Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv

I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:

Get-Module -ListAvailable | Import-Module

Correct format specifier for double in printf

Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

Here are relevant parts extracted:

Foreword

This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

  • %lf conversion specifier allowed in printf

7.19.6.1 The fprintf function

7 The length modifiers and their meanings are:

l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

The same rules specified for fprintf apply for printf, sprintf and similar functions.

7.19.6.2 The fscanf function

11 The length modifiers and their meanings are:

l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

The long story short, for fprintf the following specifiers and corresponding types are specified:

  • %f -> double
  • %Lf -> long double.

and for fscanf it is:

  • %f -> float
  • %lf -> double
  • %Lf -> long double.

How do I express "if value is not empty" in the VBA language?

It depends on what you want to test:

  • for a string, you can use If strName = vbNullString or IF strName = "" or Len(strName) = 0 (last one being supposedly faster)
  • for an object, you can use If myObject is Nothing
  • for a recordset field, you could use If isnull(rs!myField)
  • for an Excel cell, you could use If range("B3") = "" or IsEmpty(myRange)

Extended discussion available here (for Access, but most of it works for Excel as well).

Reverse HashMap keys and values in Java

Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)

Sample code

HashMap<String, Character> reversedHashMap = MapUtils.invertMap(myHashMap) 

Android: Reverse geocoding - getFromLocation

Here is a full example code using a Thread and a Handler to get the Geocoder answer without blocking the UI.

Geocoder call procedure, can be located in a Helper class

public static void getAddressFromLocation(
        final Location location, final Context context, final Handler handler) {
    Thread thread = new Thread() {
        @Override public void run() {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());   
            String result = null;
            try {
                List<Address> list = geocoder.getFromLocation(
                        location.getLatitude(), location.getLongitude(), 1);
                if (list != null && list.size() > 0) {
                    Address address = list.get(0);
                    // sending back first address line and locality
                    result = address.getAddressLine(0) + ", " + address.getLocality();
                }
            } catch (IOException e) {
                Log.e(TAG, "Impossible to connect to Geocoder", e);
            } finally {
                Message msg = Message.obtain();
                msg.setTarget(handler);
                if (result != null) {
                    msg.what = 1;
                    Bundle bundle = new Bundle();
                    bundle.putString("address", result);
                    msg.setData(bundle);
                } else 
                    msg.what = 0;
                msg.sendToTarget();
            }
        }
    };
    thread.start();
}

Here is the call to this Geocoder procedure in your UI Activity:

getAddressFromLocation(mLastKownLocation, this, new GeocoderHandler());

And the handler to show the results in your UI:

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String result;
        switch (message.what) {
        case 1:
            Bundle bundle = message.getData();
            result = bundle.getString("address");
            break;
        default:
            result = null;
        }
        // replace by what you need to do
        myLabel.setText(result);
    }   
}

Don't forget to put the following permission in your Manifest.xml

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

How to SHUTDOWN Tomcat in Ubuntu?

None of the suggested solutions worked for me.

I had run tomcat restart before completing the deployment which messed up my web app.

EC2 ran tomcat automatically and tomcat was stuck trying to connect to a database connection which was not configured properly.

I just needed to remove my customized context in server.xml, restart tomcat and add the context back in.

Iterating through a range of dates in Python

I have a similar problem, but I need to iterate monthly instead of daily.

This is my solution

import calendar
from datetime import datetime, timedelta

def days_in_month(dt):
    return calendar.monthrange(dt.year, dt.month)[1]

def monthly_range(dt_start, dt_end):
    forward = dt_end >= dt_start
    finish = False
    dt = dt_start

    while not finish:
        yield dt.date()
        if forward:
            days = days_in_month(dt)
            dt = dt + timedelta(days=days)            
            finish = dt > dt_end
        else:
            _tmp_dt = dt.replace(day=1) - timedelta(days=1)
            dt = (_tmp_dt.replace(day=dt.day))
            finish = dt < dt_end

Example #1

date_start = datetime(2016, 6, 1)
date_end = datetime(2017, 1, 1)

for p in monthly_range(date_start, date_end):
    print(p)

Output

2016-06-01
2016-07-01
2016-08-01
2016-09-01
2016-10-01
2016-11-01
2016-12-01
2017-01-01

Example #2

date_start = datetime(2017, 1, 1)
date_end = datetime(2016, 6, 1)

for p in monthly_range(date_start, date_end):
    print(p)

Output

2017-01-01
2016-12-01
2016-11-01
2016-10-01
2016-09-01
2016-08-01
2016-07-01
2016-06-01

Excel VBA calling sub from another sub with multiple inputs, outputs of different sizes

These are really two questions.

The first one is answered here: Calling a Sub in VBA

To the second one, protip: there is no main subroutine in VBA. Forget procedural, general-purpose languages. VBA subs are "macros" - you can run them by hitting Alt+F8 or by adding a button to your worksheet and calling up the sub you want from the automatically generated "ButtonX_Click" sub.

How to access POST form fields

Use express-fileupload package:

var app = require('express')();
var http = require('http').Server(app);
const fileUpload = require('express-fileupload')

app.use(fileUpload());

app.post('/', function(req, res) {
  var email = req.body.email;
  res.send('<h1>Email :</h1> '+email);
});

http.listen(3000, function(){
  console.log('Running Port:3000');
});

How to uninstall a windows service and delete its files without rebooting

If in .net ( I'm not sure if it works for all windows services)

  • Stop the service (THis may be why you're having a problem.)
  • InstallUtil -u [name of executable]
  • Installutil -i [name of executable]
  • Start the service again...

Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...

Python None comparison: should I use "is" or ==?

PEP 8 defines that it is better to use the is operator when comparing singletons.

Automated Python to Java translation

to clarify your question:

From Python Source code to Java source code? (I don't think so)

.. or from Python source code to Java Bytecode? (Jython does this under the hood)

How to resolve git's "not something we can merge" error

I had this issue as well. The branch looked like 'username/master' which seemed to confuse git as it looked like a remote address I defined. For me using this

git merge origin/username/master

worked perfectly fine.

Spring MVC 4: "application/json" Content Type is not being set correctly

First thing to understand is that the RequestMapping#produces() element in

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")

serves only to restrict the mapping for your request handlers. It does nothing else.

Then, given that your method has a return type of String and is annotated with @ResponseBody, the return value will be handled by StringHttpMessageConverter which sets the Content-type header to text/plain. If you want to return a JSON string yourself and set the header to application/json, use a return type of ResponseEntity (get rid of @ResponseBody) and add appropriate headers to it.

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<String> bar() {
    final HttpHeaders httpHeaders= new HttpHeaders();
    httpHeaders.setContentType(MediaType.APPLICATION_JSON);
    return new ResponseEntity<String>("{\"test\": \"jsonResponseExample\"}", httpHeaders, HttpStatus.OK);
}

Note that you should probably have

<mvc:annotation-driven /> 

in your servlet context configuration to set up your MVC configuration with the most suitable defaults.

How to include duplicate keys in HashMap?

Use Map<Integer, List<String>>:

Map<Integer, List<String>> map = new LinkedHashMap< Integer, List<String>>();

map.put(-1505711364, new ArrayList<>(Arrays.asList("4")));
map.put(294357273, new ArrayList<>(Arrays.asList("15", "71")));
//...

To add a new key/value pair in this map:

public void add(Integer key, String newValue) {
    List<String> currentValue = map.get(key);
    if (currentValue == null) {
        currentValue = new ArrayList<String>();
        map.put(key, currentValue);
    }
    currentValue.add(newValue);
}

Count number of iterations in a foreach loop

count($Contents);

or

sizeof($Contents);

Integrating MySQL with Python in Windows

The precompiled binaries on http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python is just worked for me.

  1. Open MySQL_python-1.2.5-cp27-none-win_amd64.whl file with zip extractor program.
  2. Copy the contents to C:\Python27\Lib\site-packages\

detect key press in python?

So I made this ..kind of game.. based on this post (using msvcr library and Python 3.7).

The following is the "main function" of the game, that is detecting the keys pressed:

# Requiered libraries - - - -
import msvcrt
# - - - - - - - - - - - - - -


def _secret_key(self):
    # Get the key pressed by the user and check if he/she wins.

    bk = chr(10) + "-"*25 + chr(10)

    while True:

        print(bk + "Press any key(s)" + bk)
        #asks the user to type any key(s)

        kp = str(msvcrt.getch()).replace("b'", "").replace("'", "")
        # Store key's value.

        if r'\xe0' in kp:
            kp += str(msvcrt.getch()).replace("b'", "").replace("'", "")
            # Refactor the variable in case of multi press.

        if kp == r'\xe0\x8a':
            # If user pressed the secret key, the game ends.
            # \x8a is CTRL+F12, that's the secret key.

            print(bk + "CONGRATULATIONS YOU PRESSED THE SECRET KEYS!\a" + bk)
            print("Press any key to exit the game")
            msvcrt.getch()
            break
        else:
            print("    You pressed:'", kp + "', that's not the secret key(s)\n")
            if self.select_continue() == "n":
                if self.secondary_options():
                    self._main_menu()
                break

If you want the full source code of the porgram you can see it or download it from here:

The Secret Key Game (GitHub)

(note: the secret keypress is: Ctrl+F12)

I hope you can serve as an example and help for those who come to consult this information.

How to escape comma and double quote at same time for CSV file?

There are several libraries. Here are two examples:


❐ Apache Commons Lang

Apache Commons Lang includes a special class to escape or unescape strings (CSV, EcmaScript, HTML, Java, Json, XML): org.apache.commons.lang3.StringEscapeUtils.

  • Escape to CSV

    String escaped = StringEscapeUtils
        .escapeCsv("I said \"Hey, I am 5'10\".\""); // I said "Hey, I am 5'10"."
    
    System.out.println(escaped); // "I said ""Hey, I am 5'10""."""
    
  • Unescape from CSV

    String unescaped = StringEscapeUtils
        .unescapeCsv("\"I said \"\"Hey, I am 5'10\"\".\"\"\""); // "I said ""Hey, I am 5'10""."""
    
    System.out.println(unescaped); // I said "Hey, I am 5'10"."
    

* You can download it from here.


❐ OpenCSV

If you use OpenCSV, you will not need to worry about escape or unescape, only for write or read the content.

  • Writing file:

    FileOutputStream fos = new FileOutputStream("awesomefile.csv"); 
    OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
    CSVWriter writer = new CSVWriter(osw);
    ...
    String[] row = {
        "123", 
        "John", 
        "Smith", 
        "39", 
        "I said \"Hey, I am 5'10\".\""
    };
    writer.writeNext(row);
    ...
    writer.close();
    osw.close();
    os.close();
    
  • Reading file:

    FileInputStream fis = new FileInputStream("awesomefile.csv"); 
    InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
    CSVReader reader = new CSVReader(isr);
    
    for (String[] row; (row = reader.readNext()) != null;) {
        System.out.println(Arrays.toString(row));
    }
    
    reader.close();
    isr.close();
    fis.close();
    

* You can download it from here.

How to disable an Android button?

If you need to disable button add this line of code.

Button button = findViewById(R.id.button)
button.setEnabled(false);

And enable button , just add this line

 button.setEnabled(true);

Happy coding :D

How can I create a war file of my project in NetBeans?

Simplest way is to Check the Output - Build tab: It would display the location of war file.
It will have something like:

Installing D:\Project\target\Tool.war to C:\Users\myname.m2\repository\com\tool\1.0\Tool-1.0.war

How to disable Hyper-V in command line?

you can use my script. paste code lines to notepad and save as vbs(for example switch_hypervisor.vbs)

Option Explicit

Dim backupfile
Dim record
Dim myshell
Dim appmyshell
Dim myresult
Dim myline
Dim makeactive
Dim makepassive
Dim reboot
record=""
Set myshell = WScript.CreateObject("WScript.Shell")

If WScript.Arguments.Length = 0 Then
    Set appmyshell  = CreateObject("Shell.Application")
    appmyshell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
    WScript.Quit
End if




Set backupfile = CreateObject("Scripting.FileSystemObject")
If Not (backupfile.FileExists("C:\bcdedit.bak")) Then
    Set myresult = myshell.Exec("cmd /c bcdedit /export c:\bcdedit.bak")
End If

Set myresult = myshell.Exec("cmd /c bcdedit")
Do While Not myresult.StdOut.AtEndOfStream
    myline = myresult.StdOut.ReadLine()

    If myline="The boot configuration data store could not be opened." Then
        record=""
        exit do
    End If
    If Instr(myline, "identifier") > 0 Then
        record=""
        If Instr(myline, "{current}") > 0 Then
            record="current"
        End If
    End If
    If Instr(myline, "hypervisorlaunchtype") > 0 And record = "current" Then
        If Instr(myline, "Auto") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "On") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "Off") > 0 Then
            record="0"
            Exit Do
        End If
    End If
Loop

If record="1" Then
    makepassive = MsgBox ("Hypervisor status is active, do you want set to passive? ", vbYesNo, "Hypervisor")
    Select Case makepassive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype off"
        reboot = MsgBox ("Hypervisor chenged to passive; Computer must reboot. Reboot now? ", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="0" Then
    makeactive = MsgBox ("Hypervisor status is passive, do you want set active? ", vbYesNo, "Hypervisor")
    Select Case makeactive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype auto"
        reboot = MsgBox ("Hypervisor changed to active;  Computer must reboot. Reboot now?", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="" Then
        MsgBox("Error: record can't find")
End If

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);

How to get the number of days of difference between two dates on mysql?

What about the DATEDIFF function ?

Quoting the manual's page :

DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation


In your case, you'd use :

mysql> select datediff('2010-04-15', '2010-04-12');
+--------------------------------------+
| datediff('2010-04-15', '2010-04-12') |
+--------------------------------------+
|                                    3 | 
+--------------------------------------+
1 row in set (0,00 sec)

But note the dates should be written as YYYY-MM-DD, and not DD-MM-YYYY like you posted.

Trying to get property of non-object MySQLi result

$sql = "SELECT * FROM table";
$result = $conn->query($sql);

if (!$result) {
    trigger_error('Invalid query: ' . $conn->error);
}

check the error with mysqli_error() function

probably your query has some faults.

How to get the last char of a string in PHP?

I'd advise to go for Gordon's solution as it is more performant than substr():

<?php 

$string = 'abcdef';
$repetitions = 10000000;

echo "\n\n";
echo "----------------------------------\n";
echo $repetitions . " repetitions...\n";
echo "----------------------------------\n";
echo "\n\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = substr($string, -1);

echo "substr() took " . (microtime(true) - $start) . "seconds\n";

$start = microtime(true);
for($i=0; $i<$repetitions; $i++)
    $x = $string[strlen($string)-1];

echo "array access took " . (microtime(true) - $start) . "seconds\n";

die();

outputs something like

 ---------------------------------- 
 10000000 repetitions...
 ----------------------------------

 substr() took 2.0285921096802seconds 
 array access took 1.7474739551544seconds

How can I switch to another branch in git?

Check remote branch list:

git branch -a

Switch to another Branch:

git checkout -b <local branch name> <Remote branch name>
Example: git checkout -b Dev_8.4 remotes/gerrit/Dev_8.4

Check local Branch list:

git branch

Update everything:

git pull

requestFeature() must be called before adding content

I know it's over a year old, but calling requestFeature() never solved my problem. In fact I don't call it at all.

It was an issue with inflating the view I suppose. Despite all my searching, I never found a suitable solution until I played around with the different methods of inflating a view.

AlertDialog.Builder is the easy solution but requires a lot of work if you use the onPrepareDialog() to update that view.

Another alternative is to leverage AsyncTask for dialogs.

A final solution that I used is below:

public class CustomDialog extends AlertDialog {

   private View content;

   public CustomDialog(Context context) {
       super(context);

       LayoutInflater li = LayoutInflater.from(context);
       content = li.inflate(R.layout.custom_view, null);

       setUpAdditionalStuff(); // do more view cleanup
       setView(content);           
   }

   private void setUpAdditionalStuff() {
       // ...
   }

   // Call ((CustomDialog) dialog).prepare() in the onPrepareDialog() method  
   public void prepare() {
       setTitle(R.string.custom_title);
       setIcon( getIcon() );
       // ...
   }
}

* Some Additional notes:

  1. Don't rely on hiding the title. There is often an empty space despite the title not being set.
  2. Don't try to build your own View with header footer and middle view. The header, as stated above, may not be entirely hidden despite requesting FEATURE_NO_TITLE.
  3. Don't heavily style your content view with color attributes or text size. Let the dialog handle that, other wise you risk putting black text on a dark blue dialog because the vendor inverted the colors.

get size of json object

use this one

//for getting length of object
 int length = jsonObject.length();

or

//for getting length of array
 int length = jsonArray.length();

How do I get the AM/PM value from a DateTime?

string.Format("{0:hh:mm:ss tt}", DateTime.Now)

This should give you the string value of the time. tt should append the am/pm.

You can also look at the related topic:

How do you get the current time of day?

How does database indexing work?

Just think of Database Index as Index of a book.

If you have a book about dogs and you want to find an information about let's say, German Shepherds, you could of course flip through all the pages of the book and find what you are looking for - but this of course is time consuming and not very fast.

Another option is that, you could just go to the Index section of the book and then find what you are looking for by using the Name of the entity you are looking ( in this instance, German Shepherds) and also looking at the page number to quickly find what you are looking for.

In Database, the page number is referred to as a pointer which directs the database to the address on the disk where entity is located. Using the same German Shepherd analogy, we could have something like this (“German Shepherd”, 0x77129) where 0x77129 is the address on the disk where the row data for German Shepherd is stored.

In short, an index is a data structure that stores the values for a specific column in a table so as to speed up query search.

Tomcat view catalina.out log file

locate catalina.out and find out where is your catalina out. Because it depends.

If there is several, look at their sizes: that with size 0 are not what you want.

Loop through all the rows of a temp table and call a stored procedure for each row

You can do something like this

    Declare @min int=0, @max int =0 --Initialize variable here which will be use in loop 
    Declare @Recordid int,@TO nvarchar(30),@Subject nvarchar(250),@Body nvarchar(max)  --Initialize variable here which are useful for your

    select ROW_NUMBER() OVER(ORDER BY [Recordid] )  AS Rownumber, Recordid, [To], [Subject], [Body], [Flag]
            into #temp_Mail_Mstr FROM Mail_Mstr where Flag='1'  --select your condition with row number & get into a temp table

    set @min = (select MIN(Rownumber) from #temp_Mail_Mstr); --Get minimum row number from temp table
    set @max = (select Max(Rownumber) from #temp_Mail_Mstr);  --Get maximum row number from temp table

   while(@min <= @max)
   BEGIN
        select @Recordid=Recordid, @To=[To], @Subject=[Subject], @Body=Body from #temp_Mail_Mstr where Rownumber=@min

        -- You can use your variables (like @Recordid,@To,@Subject,@Body) here  
        -- Do your work here 

        set @min=@min+1 --Increment of current row number
    END

(Built-in) way in JavaScript to check if a string is a valid number

Save yourself the headache of trying to find a "built-in" solution.

There isn't a good answer, and the hugely upvoted answer in this thread is wrong.

npm install is-number

In JavaScript, it's not always as straightforward as it should be to reliably check if a value is a number. It's common for devs to use +, -, or Number() to cast a string value to a number (for example, when values are returned from user input, regex matches, parsers, etc). But there are many non-intuitive edge cases that yield unexpected results:

console.log(+[]); //=> 0
console.log(+''); //=> 0
console.log(+'   '); //=> 0
console.log(typeof NaN); //=> 'number'

JQuery: dynamic height() with window resize()

To see the window height while (or after) it is resized, try it:

$(window).resize(function() {
$('body').prepend('<div>' + $(window).height() - 46 + '</div>');
});

How can I start an Activity from a non-Activity class?

Once you have obtained the context in your onTap() you can also do:

Intent myIntent = new Intent(mContext, theNewActivity.class);
mContext.startActivity(myIntent);

adding .css file to ejs

In order to serve up a static CSS file in express app (i.e. use a css style file to style ejs "templates" files in express app). Here are the simple 3 steps that need to happen:

  1. Place your css file called "styles.css" in a folder called "assets" and the assets folder in a folder called "public". Thus the relative path to the css file should be "/public/assets/styles.css"

  2. In the head of each of your ejs files you would simply call the css file (like you do in a regular html file) with a <link href=… /> as shown in the code below. Make sure you copy and paste the code below directly into your ejs file <head> section

    <link href= "/public/assets/styles.css" rel="stylesheet" type="text/css" />
    
  3. In your server.js file, you need to use the app.use() middleware. Note that a middleware is nothing but a term that refers to those operations or code that is run between the request and the response operations. By putting a method in middleware, that method will automatically be called everytime between the request and response methods. To serve up static files (such as a css file) in the app.use() middleware there is already a function/method provided by express called express.static(). Lastly, you also need to specify a request route that the program will respond to and serve up the files from the static folder everytime the middleware is called. Since you will be placing the css files in your public folder. In the server.js file, make sure you have the following code:

    // using app.use to serve up static CSS files in public/assets/ folder when /public link is called in ejs files
    // app.use("/route", express.static("foldername"));
    app.use('/public', express.static('public'));
    

After following these simple 3 steps, every time you res.render('ejsfile') in your app.get() methods you will automatically see the css styling being called. You can test by accessing your routes in the browser.

How to run a hello.js file in Node.js on windows?

For all stuck on how to start!

https://github.com/sethvincent/javascripting

Copy here incase link dies:

  1. Open node.js command prompt
  2. Make directory called javascripting by typing "mkdir javascripting"
  3. Change directory into the javascripting folder by typing "cd javascripting"
  4. Create a file named introduction.js by typing "touch introduction.js" OR FOR WINDOWS: "NUL > introduction.js"
  5. Open the file and type some javascript e.g. "Console.log('hello');"
  6. Save the file and check it runs by typing "javascripting verify introduction.js"

What does java.lang.Thread.interrupt() do?

If the targeted thread has been waiting (by calling wait(), or some other related methods that essentially do the same thing, such as sleep()), it will be interrupted, meaning that it stops waiting for what it was waiting for and receive an InterruptedException instead.

It is completely up to the thread itself (the code that called wait()) to decide what to do in this situation. It does not automatically terminate the thread.

It is sometimes used in combination with a termination flag. When interrupted, the thread could check this flag, and then shut itself down. But again, this is just a convention.

Is it possible to return empty in react render function?

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

Switch between two frames in tkinter

One way is to stack the frames on top of each other, then you can simply raise one above the other in the stacking order. The one on top will be the one that is visible. This works best if all the frames are the same size, but with a little work you can get it to work with any sized frames.

Note: for this to work, all of the widgets for a page must have that page (ie: self) or a descendant as a parent (or master, depending on the terminology you prefer).

Here's a bit of a contrived example to show you the general concept:

try:
    import tkinter as tk                # python 3
    from tkinter import font as tkfont  # python 3
except ImportError:
    import Tkinter as tk     # python 2
    import tkFont as tkfont  # python 2

class SampleApp(tk.Tk):

    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)

        self.title_font = tkfont.Font(family='Helvetica', size=18, weight="bold", slant="italic")

        # the container is where we'll stack a bunch of frames
        # on top of each other, then the one we want visible
        # will be raised above the others
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand=True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}
        for F in (StartPage, PageOne, PageTwo):
            page_name = F.__name__
            frame = F(parent=container, controller=self)
            self.frames[page_name] = frame

            # put all of the pages in the same location;
            # the one on the top of the stacking order
            # will be the one that is visible.
            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame("StartPage")

    def show_frame(self, page_name):
        '''Show a frame for the given page name'''
        frame = self.frames[page_name]
        frame.tkraise()


class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is the start page", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)

        button1 = tk.Button(self, text="Go to Page One",
                            command=lambda: controller.show_frame("PageOne"))
        button2 = tk.Button(self, text="Go to Page Two",
                            command=lambda: controller.show_frame("PageTwo"))
        button1.pack()
        button2.pack()


class PageOne(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 1", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        label = tk.Label(self, text="This is page 2", font=controller.title_font)
        label.pack(side="top", fill="x", pady=10)
        button = tk.Button(self, text="Go to the start page",
                           command=lambda: controller.show_frame("StartPage"))
        button.pack()


if __name__ == "__main__":
    app = SampleApp()
    app.mainloop()

start page page 1 page 2

If you find the concept of creating instance in a class confusing, or if different pages need different arguments during construction, you can explicitly call each class separately. The loop serves mainly to illustrate the point that each class is identical.

For example, to create the classes individually you can remove the loop (for F in (StartPage, ...) with this:

self.frames["StartPage"] = StartPage(parent=container, controller=self)
self.frames["PageOne"] = PageOne(parent=container, controller=self)
self.frames["PageTwo"] = PageTwo(parent=container, controller=self)

self.frames["StartPage"].grid(row=0, column=0, sticky="nsew")
self.frames["PageOne"].grid(row=0, column=0, sticky="nsew")
self.frames["PageTwo"].grid(row=0, column=0, sticky="nsew")

Over time people have asked other questions using this code (or an online tutorial that copied this code) as a starting point. You might want to read the answers to these questions:

Check if cookie exists else set cookie to Expire in 10 days

if (/(^|;)\s*visited=/.test(document.cookie)) {
    alert("Hello again!");
} else {
    document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
    alert("This is your first time!");
}

is one way to do it. Note that document.cookie is a magic property, so you don't have to worry about overwriting anything, either.

There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage and friends are convenient and useful.

Facebook Javascript SDK Problem: "FB is not defined"

Try to load your scripts in Head section. Moreover, it will be better if you define your scripts under some call like: document.ready, if you defined these scripts in body section

Multiple queries executed in java in single statement

I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:

String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{  
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);  
    theStatement = theConnection.prepareStatement(str1);
    ResultSet theResult = theStatement.executeQuery();
    int count8 = theStatement.executeUpdate(str9);
    theStatement.close();
    theConnection.close();
    theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
    theStatement = theConnection.prepareStatement(str2);
    theResult = theStatement.executeQuery();

    ArrayList<Port> portList = new ArrayList<Port>();
    while (theResult.next()) {
        Port port = new Port();
        port.setPort_id(theResult.getInt("port_id"));

        portList.add(port);
    }

I hope it helps

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

Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data

curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);

// $output contains the output string
$output = curl_exec($ch);

$lines = explode("\n",$output);

$out = array();
$headers = true;

foreach ($lines as $l){
    $l = trim($l);

    if ($headers && !empty($l)){
        if (strpos($l,'HTTP') !== false){
            $p = explode(' ',$l);
            $out['Headers']['Status'] = trim($p[1]);
        } else {
            $p = explode(':',$l);
            $out['Headers'][$p[0]] = trim($p[1]);
        }
    } elseif (!empty($l)) {
        $out['Data'] = $l;
    }

    if (empty($l)){
        $headers = false;
    }
}

Update Item to Revision vs Revert to Revision

To understand how the state of your working copy is different in both scenarios, you must understand the concept of the BASE revision:

BASE

The revision number of an item in a working copy. If the item has been locally modified, this refers to the way the item appears without those local modifications.

Your working copy contains a snapshot of each file (hidden in a .svn folder) in this BASE revision, meaning as it was when last retrieved from the repository. This explains why working copies take 2x the space and how it is possible that you can examine and even revert local modifications without a network connection.

Update item to Revision changes this base revision, making BASE out of date. When you try to commit local modifications, SVN will notice that your BASE does not match the repository HEAD. The commit will be refused until you do an update (and possibly a merge) to fix this.

Revert to revision does not change BASE. It is conceptually almost the same as manually editing the file to match an earlier revision.

How to pass optional arguments to a method in C++?

With commas separating them, just like parameters without default values.

int func( int x = 0, int y = 0 );

func(); // doesn't pass optional parameters, defaults are used, x = 0 and y = 0

func(1, 2); // provides optional parameters, x = 1 and y = 2

How can I remove the decimal part from JavaScript number?

You can also use bitwise operators to truncate the decimal.

e.g.

var x = 9 / 2;
console.log(x); // 4.5

x = ~~x;
console.log(x); // 4

x = -3.7
console.log(~~x) // -3
console.log(x | 0) // -3
console.log(x << 0) // -3

Bitwise operations are considerably more efficient than the Math functions. The double not bitwise operator also seems to slightly outperform the x | 0 and x << 0 bitwise operations by a negligible amount.

// 952 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) | 0;
}

// 1150 milliseconds
for (var i = 0; i < 1000000; i++) {
    (i * 0.5) << 0;
}

// 1284 milliseconds
for (var i = 0; i < 1000000; i++) {
    Math.trunc(i * 0.5);
}

// 939 milliseconds
for (var i = 0; i < 1000000; i++) {
    ~~(i * 0.5);
}

Also worth noting is that the bitwise not operator takes precedence over arithmetic operations, so you may need to surround calculations with parentheses to have the intended result:

x = -3.7

console.log(~~x * 2) // -6
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

console.log(~~(x * 2)) // -7
console.log(x * 2 | 0) // -7
console.log(x * 2 << 0) // -7

More info about the double bitwise not operator can be found at Double bitwise NOT (~~)

Hibernate-sequence doesn't exist

Working with Spring Boot

Solution

Put the string below in .application.properties

spring.jpa.properties.hibernate.id.new_generator_mappings=false

Explanation

On Hibernate 4.X this attribute defaults to true.

How remove border around image in css?

I do believe you need to add the border: none style to your icon element as well.

How to write macro for Notepad++?

Actually, the shortcuts.xml file does not store user-generated macros and no obvious candidates contain this info. These instructions are out of date.

Contrary to various websites' tips, storing user-generated macros isn't enabled for v.5.4.2. That XML file is there, but your macro does not get stored it in.

I'm guessing it's a bug that'll be fixed by the next version.

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Double brackets accesses a list element, while a single bracket gives you back a list with a single element.

lst <- list('one','two','three')

a <- lst[1]
class(a)
## returns "list"

a <- lst[[1]]
class(a)
## returns "character"

add allow_url_fopen to my php.ini using .htaccess

If your host is using suPHP, you can try creating a php.ini file in the same folder as the script and adding:

allow_url_fopen = On

(you can determine this by creating a file and checking which user it was created under: if you, it's suPHP, if "apache/nobody" or not you, then it's a normal PHP mode. You can also make a script

<?php
echo `id`;
?>

To give the same information, assuming shell_exec is not a disabled function)

How to test my servlet using JUnit

First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.

There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mock/web/package-summary.html

Using these mocks, you could test things like

What happens if username is not in the request?

What happens if username is in the request?

etc

You could then do stuff like:

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class MyServletTest {
    private MyServlet servlet;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        servlet = new MyServlet();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void correctUsernameInRequest() throws ServletException, IOException {
        request.addParameter("username", "scott");
        request.addParameter("password", "tiger");

        servlet.doPost(request, response);

        assertEquals("text/html", response.getContentType());

        // ... etc
    }
}

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

Angular pass callback function to child component as @Input similar to AngularJS way

As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.

The parent modal contains the function to close the modal. This parent passes the close function to the login child component.

import { Component} from '@angular/core';
import { LoginFormComponent } from './login-form.component'

@Component({
  selector: 'my-modal',
  template: `<modal #modal>
      <login-form (onClose)="onClose($event)" ></login-form>
    </modal>`
})
export class ParentModalComponent {
  modal: {...};

  onClose() {
    this.modal.close();
  }
}

After the child login component submits the login form, it closes the parent modal using the parent's callback function

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'login-form',
  template: `<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
      <button type="submit">Submit</button>
    </form>`
})
export class ChildLoginComponent {
  @Output() onClose = new EventEmitter();
  submitted = false;

  onSubmit() {
    this.onClose.emit();
    this.submitted = true;
  }
}

Thread pooling in C++11

You can use thread_pool from boost library:

void my_task(){...}

int main(){
    int threadNumbers = thread::hardware_concurrency();
    boost::asio::thread_pool pool(threadNumbers);

    // Submit a function to the pool.
    boost::asio::post(pool, my_task);

    // Submit a lambda object to the pool.
    boost::asio::post(pool, []() {
      ...
    });
}

You also can use threadpool from open source community:

void first_task() {...}    
void second_task() {...}

int main(){
    int threadNumbers = thread::hardware_concurrency();
    pool tp(threadNumbers);

    // Add some tasks to the pool.
    tp.schedule(&first_task);
    tp.schedule(&second_task);
}

CSS3 transform not working

Since nobody referenced relevant documentation:

CSS Transforms Module Level 1 - Terminology - Transformable Element

A transformable element is an element in one of these categories:

  • an element whose layout is governed by the CSS box model which is either a block-level or atomic inline-level element, or whose display property computes to table-row, table-row-group, table-header-group, table-footer-group, table-cell, or table-caption
  • an element in the SVG namespace and not governed by the CSS box model which has the attributes transform, ‘patternTransform‘ or gradientTransform.

In your case, the <a> elements are inline by default.

Changing the display property's value to inline-block renders the elements as atomic inline-level elements, and therefore the elements become "transformable" by definition.

li a {
   display: inline-block;
   -webkit-transform: rotate(10deg);
   -moz-transform: rotate(10deg);
   -o-transform: rotate(10deg); 
   transform: rotate(10deg);
}

As mentioned above, this only seems to applicable in -webkit based browsers since it appears to work in IE/FF regardless.

Can I target all <H> tags with a single selector?

No, a comma-separated list is what you want in this case.

Choosing the default value of an Enum type without having to change values

One more way that might be helpful - to use some kind of "alias". For example:

public enum Status
{
    New = 10,
    Old = 20,
    Actual = 30,

    // Use Status.Default to specify default status in your code. 
    Default = New 
}

Change the selected value of a drop-down list with jQuery

Pure JS

For modern browsers using CSS selectors is not a problem for pure JS

document.querySelector('._statusDDL').value = 2;

_x000D_
_x000D_
function change() {
  document.querySelector('._statusDDL').value = 2;
}
_x000D_
<select class="_statusDDL">
  <option value="1" selected>A</option>
  <option value="2">B</option>
  <option value="3">C</option>
</select>

<button onclick="change()">Change</button>
_x000D_
_x000D_
_x000D_

Finding absolute value of a number without using Math.abs()

Here is a one-line solution that will return the absolute value of a number:

abs_number = (num < 0) ? -num : num;

How to draw a path on a map using kml file?

Thank Mathias Lin, tested and it works!

In addition, sample implementation of Mathias's method in activity can be as follows.

public class DirectionMapActivity extends MapActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.directionmap);

        MapView mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);

        // Acquire a reference to the system Location Manager
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

        String locationProvider = LocationManager.NETWORK_PROVIDER;
        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

        StringBuilder urlString = new StringBuilder();
        urlString.append("http://maps.google.com/maps?f=d&hl=en");
        urlString.append("&saddr=");//from
        urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
        urlString.append(",");
        urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
        urlString.append("&daddr=");//to
        urlString.append( Double.toString((double)dest[0]/1.0E6 ));
        urlString.append(",");
        urlString.append( Double.toString((double)dest[1]/1.0E6 ));
        urlString.append("&ie=UTF8&0&om=0&output=kml");

        try{
            // setup the url
            URL url = new URL(urlString.toString());
            // create the factory
            SAXParserFactory factory = SAXParserFactory.newInstance();
            // create a parser
            SAXParser parser = factory.newSAXParser();
            // create the reader (scanner)
            XMLReader xmlreader = parser.getXMLReader();
            // instantiate our handler
            NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
            // assign our handler
            xmlreader.setContentHandler(navSaxHandler);
            // get our data via the url class
            InputSource is = new InputSource(url.openStream());
            // perform the synchronous parse           
            xmlreader.parse(is);
            // get the results - should be a fully populated RSSFeed instance, or null on error
            NavigationDataSet ds = navSaxHandler.getParsedData();

            // draw path
            drawPath(ds, Color.parseColor("#add331"), mapView );

            // find boundary by using itemized overlay
            GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
            GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
                                                ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );

            Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
            MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
            OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
            OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
            bgItemizedOverlay.addOverlay(currentPixel);
            bgItemizedOverlay.addOverlay(destPixel);

            // center and zoom in the map
            MapController mc = mapView.getController();
            mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
            mc.animateTo(new GeoPoint(
                    (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
                    , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

        } catch(Exception e) {
            Log.d("DirectionMap","Exception parsing kml.");
        }

    }
    // and the rest of the methods in activity, e.g. drawPath() etc...

MapItemizedOverlay.java

public class MapItemizedOverlay extends ItemizedOverlay{
    private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
    private Context mContext;

    public MapItemizedOverlay(Drawable defaultMarker, Context context) {
          super(boundCenterBottom(defaultMarker));
          mContext = context;
    }

    public void addOverlay(OverlayItem overlay) {
        mOverlays.add(overlay);
        populate();
    }

    @Override
    protected OverlayItem createItem(int i) {
      return mOverlays.get(i);
    }

    @Override
    public int size() {
      return mOverlays.size();
    }

}

Firebug-like debugger for Google Chrome

Firebug Lite supports to inspect HTML elements, computed CSS style, and a lot more. Since it's pure JavaScript, it works in many different browsers. Just include the script in your source, or add the bookmarklet to your bookmark bar to include it on any page with a single click.

http://getfirebug.com/lite.html

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Create Pandas DataFrame from a string

A quick and easy solution for interactive work is to copy-and-paste the text by loading the data from the clipboard.

Select the content of the string with your mouse:

Copy data for pasting into a Pandas dataframe

In the Python shell use read_clipboard()

>>> pd.read_clipboard()
  col1;col2;col3
0       1;4.4;99
1      2;4.5;200
2       3;4.7;65
3      4;3.2;140

Use the appropriate separator:

>>> pd.read_clipboard(sep=';')
   col1  col2  col3
0     1   4.4    99
1     2   4.5   200
2     3   4.7    65
3     4   3.2   140

>>> df = pd.read_clipboard(sep=';') # save to dataframe

How can I tell gcc not to inline a function?

static __attribute__ ((noinline))  void foo()
{

}

This is what worked for me.

Searching word in vim?

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press 'SHIFT' key with * key
  3. To search in backward press 'SHIFT' key with # key

Getting time difference between two times in PHP

You can use strtotime() for time calculation. Here is an example:

$checkTime = strtotime('09:00:59');
echo 'Check Time : '.date('H:i:s', $checkTime);
echo '<hr>';

$loginTime = strtotime('09:01:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!'; echo '<br>';
echo 'Time diff in sec: '.abs($diff);

echo '<hr>';

$loginTime = strtotime('09:00:59');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';

echo '<hr>';

$loginTime = strtotime('09:00:00');
$diff = $checkTime - $loginTime;
echo 'Login Time : '.date('H:i:s', $loginTime).'<br>';
echo ($diff < 0)? 'Late!' : 'Right time!';

Demo

Check the already-asked question - how to get time difference in minutes:

Subtract the past-most one from the future-most one and divide by 60.

Times are done in unix format so they're just a big number showing the number of seconds from January 1 1970 00:00:00 GMT

How should I choose an authentication library for CodeIgniter?

Tank Auth looks good but the documentation is just a one-page explanation of how to install, plus a quick run-down of each PHP file. At least that's all I found after lots of Googling. Maybe what people mean above when they say that Tank Auth is well-documented is that the code is well-commented. That's a good thing, but different than documentation. It would have been nice to have some documentation about how to integrate Tank Auth's features with your existing code.

JPanel vs JFrame in Java

You should not extend the JFrame class unnecessarily (only if you are adding extra functionality to the JFrame class)

JFrame:

JFrame extends Component and Container.

It is a top level container used to represent the minimum requirements for a window. This includes Borders, resizability (is the JFrame resizeable?), title bar, controls (minimize/maximize allowed?), and event handlers for various Events like windowClose, windowOpened etc.

JPanel:

JPanel extends Component, Container and JComponent

It is a generic class used to group other Components together.

  • It is useful when working with LayoutManagers e.g. GridLayout f.i adding components to different JPanels which will then be added to the JFrame to create the gui. It will be more manageable in terms of Layout and re-usability.

  • It is also useful for when painting/drawing in Swing, you would override paintComponent(..) and of course have the full joys of double buffering.

A Swing GUI cannot exist without a top level container like (JWindow, Window, JFrame Frame or Applet), while it may exist without JPanels.

Volatile Vs Atomic

Volatile and Atomic are two different concepts. Volatile ensures, that a certain, expected (memory) state is true across different threads, while Atomics ensure that operation on variables are performed atomically.

Take the following example of two threads in Java:

Thread A:

value = 1;
done = true;

Thread B:

if (done)
  System.out.println(value);

Starting with value = 0 and done = false the rule of threading tells us, that it is undefined whether or not Thread B will print value. Furthermore value is undefined at that point as well! To explain this you need to know a bit about Java memory management (which can be complex), in short: Threads may create local copies of variables, and the JVM can reorder code to optimize it, therefore there is no guarantee that the above code is run in exactly that order. Setting done to true and then setting value to 1 could be a possible outcome of the JIT optimizations.

volatile only ensures, that at the moment of access of such a variable, the new value will be immediately visible to all other threads and the order of execution ensures, that the code is at the state you would expect it to be. So in case of the code above, defining done as volatile will ensure that whenever Thread B checks the variable, it is either false, or true, and if it is true, then value has been set to 1 as well.

As a side-effect of volatile, the value of such a variable is set thread-wide atomically (at a very minor cost of execution speed). This is however only important on 32-bit systems that i.E. use long (64-bit) variables (or similar), in most other cases setting/reading a variable is atomic anyways. But there is an important difference between an atomic access and an atomic operation. Volatile only ensures that the access is atomically, while Atomics ensure that the operation is atomically.

Take the following example:

i = i + 1;

No matter how you define i, a different Thread reading the value just when the above line is executed might get i, or i + 1, because the operation is not atomically. If the other thread sets i to a different value, in worst case i could be set back to whatever it was before by thread A, because it was just in the middle of calculating i + 1 based on the old value, and then set i again to that old value + 1. Explanation:

Assume i = 0
Thread A reads i, calculates i+1, which is 1
Thread B sets i to 1000 and returns
Thread A now sets i to the result of the operation, which is i = 1

Atomics like AtomicInteger ensure, that such operations happen atomically. So the above issue cannot happen, i would either be 1000 or 1001 once both threads are finished.

HTML5 Form Input Pattern Currency Format

I like to give the users a bit of flexibility and trust, that they will get the format right, but I do want to enforce only digits and two decimals for currency

^[$\-\s]*[\d\,]*?([\.]\d{0,2})?\s*$

Takes care of:

$ 1.
-$ 1.00
$ -1.0
.1
.10
-$ 1,000,000.0

Of course it will also match:

$$--$1,92,9,29.1 => anyway after cleanup => -192,929.10

align right in a table cell with CSS

What worked for me now is:

CSS:

.right {
  text-align: right;
  margin-right: 1em;
}

.left {
  text-align: left;
  margin-left: 1em;
}

HTML:

<table width="100%">
  <tbody>
    <tr>
      <td class="left">
        <input id="abort" type="submit" name="abort" value="Back">
        <input id="save" type="submit" name="save" value="Save">
      </td>
      <td class="right">
        <input id="delegate" type="submit" name="delegate" value="Delegate">
        <input id="unassign" type="submit" name="unassign" value="Unassign">
        <input id="complete" type="submit" name="complete" value="Complete">
      </td>
    </tr>
  </tbody>
</table>

See the following fiddle:

http://jsfiddle.net/Joysn/3u3SD/

Maximum and minimum values in a textbox

Its quite simple dear you can use range validator

<asp:TextBox ID="TextBox2" runat="server" TextMode="Number"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"   
    ControlToValidate="TextBox2"   
    ErrorMessage="Invalid number. Please enter the number between 0 to 20."   
    MaximumValue="20" MinimumValue="0" Type="Integer"></asp:RangeValidator>   
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"   
    ControlToValidate="TextBox2" ErrorMessage="This is required field, can not be blank."></asp:RequiredFieldValidator>

otherwise you can use javascript

<script>
function minmax(value, min, max) 
{
    if(parseInt(value) < min || isNaN(parseInt(value))) 
        return 0; 
    else if(parseInt(value) > max) 
        return 20; 
    else return value;
}
</script>                        
<input type="text" name="TextBox1" id="TextBox1" maxlength="5"
onkeyup="this.value = minmax(this.value, 0, 20)" />

Generating random number between 1 and 10 in Bash Shell Script

Simplest solution would be to use tool which allows you to directly specify ranges, like shuf

shuf -i1-10 -n1

If you want to use $RANDOM, it would be more precise to throw out the last 8 numbers in 0...32767, and just treat it as 0...32759, since taking 0...32767 mod 10 you get the following distribution

0-8 each: 3277 
8-9 each: 3276

So, slightly slower but more precise would be

while :; do ran=$RANDOM; ((ran < 32760)) && echo $(((ran%10)+1)) && break; done 

Docker command can't connect to Docker daemon

note to self: I get the error from the question's title when I forget to run docker command with sudo:

sudo docker run ...

[Ubuntu 15.10]