Programs & Examples On #Kernighan and ritchie

Questions about or related to the book "The C Programming Language" (which is also known as K&R) by Brian Kernighan and Dennis Ritchie.

change PATH permanently on Ubuntu

Add

export PATH=$PATH:/home/me/play

to your ~/.profile and execute

source ~/.profile 

in order to immediately reflect changes to your current terminal instance.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

Question still relevant as of Android Studio 3.5.2 for Windows.

In my specific use case, I was trying to add Gander (https://github.com/Ashok-Varma/Gander) to my list of dependencies when I keep getting this particular headache.

It turns out that I have yet to get JCenter Certificate approved in my cacerts file. I'm going through a company firewall and i had to do this with dependencies that I attempt to import. Thus, to do so:

  1. Ensure that your Android Studio does not need to go through any proxy.

  2. Export the certificate where you get your dependency (usually just JCenter)

  3. Add the certificate to your cacerts file:

    keytool -import -alias [your-certificate-name] -keystore 'C:\Program Files\Java\jdk[version]\jre\lib\security\cacerts' -file [absolute\path\to\your\certificate].cer

  4. Restart Android Studio

  5. Try syncing again.

Answer is based on this one: https://stackoverflow.com/a/26183328/4972380

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

How can one create an overlay in css?

Here is an overlay using a pseudo-element (eg: no need to add more markup to do it)

_x000D_
_x000D_
.box {_x000D_
  background: 0 0 url(http://ianfarb.com/wp-content/uploads/2013/10/nicholas-hodag.jpg);_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
.box:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background: rgba(0, 0, 0, 0.4);_x000D_
}
_x000D_
  <div class="box"></div>
_x000D_
_x000D_
_x000D_

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

You'll get this error as well if you are verifying that an extension method of an interface is called.

For example if you are mocking:

var mockValidator = new Mock<IValidator<Foo>>();
mockValidator
  .Verify(validator => validator.ValidateAndThrow(foo, null));

You will get the same exception because .ValidateAndThrow() is an extension on the IValidator<T> interface.

public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet = null)...

Jenkins - passing variables between jobs?

You can use Hudson Groovy builder to do this.

First Job in pipeline

enter image description here

Second job in pipeline

enter image description here

Spark - repartition() vs coalesce()

I would like to add to Justin and Power's answer that -

repartition will ignore existing partitions and create new ones. So you can use it to fix data skew. You can mention partition keys to define the distribution. Data skew is one of the biggest problems in the 'big data' problem space.

coalesce will work with existing partitions and shuffle a subset of them. It can't fix the data skew as much as repartition does. Therefore even if it is less expensive it might not be the thing you need.

How can I make a thumbnail <img> show a full size image when clicked?

Here is the Angular version of LightBox. Just Awesome :)

Note : I have put this answer hence No Js library has been mentioned under the Tags.

angular-bootstrap-lightbox

<ul ng-controller="GalleryCtrl">
  <li ng-repeat="image in images">
    <a ng-click="openLightboxModal($index)">
      <img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
    </a>
  </li>
</ul>

python: how to identify if a variable is an array or a scalar

preds_test[0] is of shape (128,128,1) Lets check its data type using isinstance() function isinstance takes 2 arguments. 1st argument is data 2nd argument is data type isinstance(preds_test[0], np.ndarray) gives Output as True. It means preds_test[0] is an array.

postgres: upgrade a user to be a superuser?

May be sometimes upgrading to a superuser might not be a good option. So apart from super user there are lot of other options which you can use. Open your terminal and type the following:

$ sudo su - postgres
[sudo] password for user: (type your password here)
$ psql
postgres@user:~$ psql
psql (10.5 (Ubuntu 10.5-1.pgdg18.04+1))
Type "help" for help.

postgres=# ALTER USER my_user WITH option

Also listing the list of options

SUPERUSER | NOSUPERUSER | CREATEDB | NOCREATEDB  | CREATEROLE | NOCREATEROLE |
CREATEUSER | NOCREATEUSER | INHERIT | NOINHERIT | LOGIN | NOLOGIN | REPLICATION|
NOREPLICATION | BYPASSRLS | NOBYPASSRLS | CONNECTION LIMIT connlimit | 
[ ENCRYPTED | UNENCRYPTED ] PASSWORD 'password' | VALID UNTIL 'timestamp'

So in command line it will look like

postgres=# ALTER USER my_user WITH  LOGIN

OR use an encrypted password.

postgres=# ALTER USER my_user  WITH ENCRYPTED PASSWORD '5d41402abc4b2a76b9719d911017c592';

OR revoke permissions after a specific time.

postgres=# ALTER USER my_user  WITH VALID UNTIL '2019-12-29 19:09:00';

C# delete a folder and all files and folders within that folder

Try:

System.IO.Directory.Delete(path,true)

This will recursively delete all files and folders underneath "path" assuming you have the permissions to do so.

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

A quick and easy way for Mac OS X 10.8 (Mountain Lion), 10.9 (Mavericks), 10.10 (Yosemite), and 10.11 (El Capitan):

I assume you have XCode, its command line tools, Python, and MySQL installed.

  1. Install PIP:

    sudo easy_install pip
    
  2. Edit ~/.profile: (Might not be necessary in Mac OS X 10.10)

    nano ~/.profile
    

    Copy and paste the following two line

    export PATH=/usr/local/mysql/bin:$PATH
    export DYLD_LIBRARY_PATH=/usr/local/mysql/lib/
    

    Save and exit. Afterwords execute the following command:

    source  ~/.profile
    
  3. Install MySQLdb

    sudo pip install MySQL-python
    

    To test if everything works fine just try

    python -c "import MySQLdb"
    

It worked like a charm for me. I hope it helps.

If you encounter an error regarding a missing library: Library not loaded: libmysqlclient.18.dylib then you have to symlink it to /usr/lib like so:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib 

Set NOW() as Default Value for datetime datatype?

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `dateCreated` datetime DEFAULT CURRENT_TIMESTAMP,
  `dateUpdated` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mobile_UNIQUE` (`mobile`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

How to export data from Spark SQL to CSV

The answer above with spark-csv is correct but there is an issue - the library creates several files based on the data frame partitioning. And this is not what we usually need. So, you can combine all partitions to one:

df.coalesce(1).
    write.
    format("com.databricks.spark.csv").
    option("header", "true").
    save("myfile.csv")

and rename the output of the lib (name "part-00000") to a desire filename.

This blog post provides more details: https://fullstackml.com/2015/12/21/how-to-export-data-frame-from-apache-spark/

IF a cell contains a string

SEARCH does not return 0 if there is no match, it returns #VALUE!. So you have to wrap calls to SEARCH with IFERROR.

For example...

=IF(IFERROR(SEARCH("cat", A1), 0), "cat", "none")

or

=IF(IFERROR(SEARCH("cat",A1),0),"cat",IF(IFERROR(SEARCH("22",A1),0),"22","none"))

Here, IFERROR returns the value from SEARCH when it works; the given value of 0 otherwise.

Filter Excel pivot table using VBA

I think i am understanding your question. This filters things that are in the column labels or the row labels. The last 2 sections of the code is what you want but im pasting everything so that you can see exactly how It runs start to finish with everything thats defined etc. I definitely took some of this code from other sites fyi.

Near the end of the code, the "WardClinic_Category" is a column of my data and in the column label of the pivot table. Same for the IVUDDCIndicator (its a column in my data but in the row label of the pivot table).

Hope this helps others...i found it very difficult to find code that did this the "proper way" rather than using code similar to the macro recorder.

Sub CreatingPivotTableNewData()


'Creating pivot table
Dim PvtTbl As PivotTable
Dim wsData As Worksheet
Dim rngData As Range
Dim PvtTblCache As PivotCache
Dim wsPvtTbl As Worksheet
Dim pvtFld As PivotField

'determine the worksheet which contains the source data
Set wsData = Worksheets("Raw_Data")

'determine the worksheet where the new PivotTable will be created
Set wsPvtTbl = Worksheets("3N3E")

'delete all existing Pivot Tables in the worksheet
'in the TableRange1 property, page fields are excluded; to select the entire PivotTable report, including the page fields, use the TableRange2 property.
For Each PvtTbl In wsPvtTbl.PivotTables
If MsgBox("Delete existing PivotTable!", vbYesNo) = vbYes Then
PvtTbl.TableRange2.Clear
End If
Next PvtTbl


'A Pivot Cache represents the memory cache for a PivotTable report. Each Pivot Table report has one cache only. Create a new PivotTable cache, and then create a new PivotTable report based on the cache.

'set source data range:
Worksheets("Raw_Data").Activate
Set rngData = wsData.Range(Range("A1"), Range("H1").End(xlDown))


'Creates Pivot Cache and PivotTable:
Worksheets("Raw_Data").Activate
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngData.Address, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTbl.Range("A1"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Set PvtTbl = wsPvtTbl.PivotTables("PivotTable1")

'Default value of ManualUpdate property is False so a PivotTable report is recalculated automatically on each change.
'Turn this off (turn to true) to speed up code.
PvtTbl.ManualUpdate = True


'Adds row and columns for pivot table
PvtTbl.AddFields RowFields:="VerifyHr", ColumnFields:=Array("WardClinic_Category", "IVUDDCIndicator")

'Add item to the Report Filter
PvtTbl.PivotFields("DayOfWeek").Orientation = xlPageField


'set data field - specifically change orientation to a data field and set its function property:
With PvtTbl.PivotFields("TotalVerified")
.Orientation = xlDataField
.Function = xlAverage
.NumberFormat = "0.0"
.Position = 1
End With

'Removes details in the pivot table for each item
Worksheets("3N3E").PivotTables("PivotTable1").PivotFields("WardClinic_Category").ShowDetail = False

'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("WardClinic_Category").PivotItems
    Select Case PivotItem.Name
        Case "3N3E"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem


'Removes pivot items from pivot table except those cases defined below (by looping through)
For Each PivotItem In PvtTbl.PivotFields("IVUDDCIndicator").PivotItems
    Select Case PivotItem.Name
        Case "UD", "IV"
            PivotItem.Visible = True
        Case Else
            PivotItem.Visible = False
        End Select
    Next PivotItem

'turn on automatic update / calculation in the Pivot Table
PvtTbl.ManualUpdate = False


End Sub

How to remove ASP.Net MVC Default HTTP Headers?

X-Powered-By is a custom header in IIS. Since IIS 7, you can remove it by adding the following to your web.config:

<system.webServer>
  <httpProtocol>
    <customHeaders>
      <remove name="X-Powered-By" />
    </customHeaders>
  </httpProtocol>
</system.webServer>

This header can also be modified to your needs, for more information refer to http://www.iis.net/ConfigReference/system.webServer/httpProtocol/customHeaders


Add this to web.config to get rid of the X-AspNet-Version header:

<system.web>
  <httpRuntime enableVersionHeader="false" />
</system.web>

Finally, to remove X-AspNetMvc-Version, edit Global.asax.cs and add the following in the Application_Start event:

protected void Application_Start()
{
    MvcHandler.DisableMvcResponseHeader = true;
}

You can also modify headers at runtime via the Application_PreSendRequestHeaders event in Global.asax.cs. This is useful if your header values are dynamic:

protected void Application_PreSendRequestHeaders(object source, EventArgs e)
{
      Response.Headers.Remove("foo");
      Response.Headers.Add("bar", "quux");
}

How can I disable an <option> in a <select> based on its value in JavaScript?

Pure Javascript

With pure Javascript, you'd have to cycle through each option, and check the value of it individually.

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  (op[i].value.toLowerCase() == "stackoverflow") 
    ? op[i].disabled = true 
    : op[i].disabled = false ;
}

Without enabling non-targeted elements:

// Get all options within <select id='foo'>...</select>
var op = document.getElementById("foo").getElementsByTagName("option");
for (var i = 0; i < op.length; i++) {
  // lowercase comparison for case-insensitivity
  if (op[i].value.toLowerCase() == "stackoverflow") {
    op[i].disabled = true;
  }
}

jQuery

With jQuery you can do this with a single line:

$("option[value='stackoverflow']")
  .attr("disabled", "disabled")
  .siblings().removeAttr("disabled");

Without enabling non-targeted elements:

$("option[value='stackoverflow']").attr("disabled", "disabled");

? Note that this is not case insensitive. "StackOverflow" will not equal "stackoverflow". To get a case-insensitive match, you'd have to cycle through each, converting the value to a lower case, and then check against that:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled").siblings().removeAttr("disabled");
  }
});

Without enabling non-targeted elements:

$("option").each(function(){
  if ($(this).val().toLowerCase() == "stackoverflow") {
    $(this).attr("disabled", "disabled");
  }
});

Laravel - Session store not set on request

I was getting this error with Laravel Sanctum. I fixed it by adding \Illuminate\Session\Middleware\StartSession::class, to the api middleware group in Kernel.php, but I later figured out this "worked" because my authentication routes were added in api.php instead of web.php, so Laravel was using the wrong auth guard.

I moved these routes here into web.php and then they started working properly with the AuthenticatesUsers.php trait:

Route::group(['middleware' => ['guest', 'throttle:10,5']], function () {
    Route::post('register', 'Auth\RegisterController@register')->name('register');
    Route::post('login', 'Auth\LoginController@login')->name('login');

    Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail');
    Route::post('password/reset', 'Auth\ResetPasswordController@reset');

    Route::post('email/verify/{user}', 'Auth\VerificationController@verify')->name('verification.verify');
    Route::post('email/resend', 'Auth\VerificationController@resend');

    Route::post('oauth/{driver}', 'Auth\OAuthController@redirectToProvider')->name('oauth.redirect');
    Route::get('oauth/{driver}/callback', 'Auth\OAuthController@handleProviderCallback')->name('oauth.callback');
});

Route::post('logout', 'Auth\LoginController@logout')->name('logout');

I figured out the problem after I got another weird error about RequestGuard::logout() does not exist.

It made me realize that my custom auth routes are calling methods from the AuthenticatesUsers trait, but I wasn't using Auth::routes() to accomplish it. Then I realized Laravel uses the web guard by default and that means routes should be in routes/web.php.

This is what my settings look like now with Sanctum and a decoupled Vue SPA app:

Kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        EnsureFrontendRequestsAreStateful::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'throttle:60,1',
    ],
];

Note: With Laravel Sanctum and same-domain Vue SPA, you use httpOnly cookies for session cookie, and remember me cookie, and unsecure cookie for CSRF, so you use the web guard for auth, and every other protected, JSON-returning route should use auth:sanctum middleware.

config/auth.php

'defaults' => [
    'guard' => 'web',
    'passwords' => 'users',
],

...

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
        'hash' => false,
    ],
],

Then you can have unit tests such as this, where critically, Auth::check(), Auth::user(), and Auth::logout() work as expected with minimal config and maximal usage of AuthenticatesUsers and RegistersUsers traits.

Here are a couple of my login unit tests:

TestCase.php

/**
 * Creates and/or returns the designated regular user for unit testing
 *
 * @return \App\User
 */
public function user() : User
{
    $user = User::query()->firstWhere('email', '[email protected]');

    if ($user) {
        return $user;
    }

    // User::generate() is just a wrapper around User::create()
    $user = User::generate('Test User', '[email protected]', self::AUTH_PASSWORD);

    return $user;
}

/**
 * Resets AuthManager state by logging out the user from all auth guards.
 * This is used between unit tests to wipe cached auth state.
 *
 * @param array $guards
 * @return void
 */
protected function resetAuth(array $guards = null) : void
{
    $guards = $guards ?: array_keys(config('auth.guards'));

    foreach ($guards as $guard) {
        $guard = $this->app['auth']->guard($guard);

        if ($guard instanceof SessionGuard) {
            $guard->logout();
        }
    }

    $protectedProperty = new \ReflectionProperty($this->app['auth'], 'guards');
    $protectedProperty->setAccessible(true);
    $protectedProperty->setValue($this->app['auth'], []);
}

LoginTest.php

protected $auth_guard = 'web';

/** @test */
public function it_can_login()
{
    $user = $this->user();

    $this->postJson(route('login'), ['email' => $user->email, 'password' => TestCase::AUTH_PASSWORD])
        ->assertStatus(200)
        ->assertJsonStructure([
            'user' => [
                ...expectedUserFields,
            ],
        ]);

    $this->assertEquals(Auth::check(), true);
    $this->assertEquals(Auth::user()->email, $user->email);
    $this->assertAuthenticated($this->auth_guard);
    $this->assertAuthenticatedAs($user, $this->auth_guard);

    $this->resetAuth();
}

/** @test */
public function it_can_logout()
{
    $this->actingAs($this->user())
        ->postJson(route('logout'))
        ->assertStatus(204);

    $this->assertGuest($this->auth_guard);

    $this->resetAuth();
}

I overrided the registered and authenticated methods in the Laravel auth traits so that they return the user object instead of just the 204 OPTIONS:

public function authenticated(Request $request, User $user)
{
    return response()->json([
        'user' => $user,
    ]);
}

protected function registered(Request $request, User $user)
{
    return response()->json([
        'user' => $user,
    ]);
}

Look at the vendor code for the auth traits. You can use them untouched, plus those two above methods.

  • vendor/laravel/ui/auth-backend/RegistersUsers.php
  • vendor/laravel/ui/auth-backend/AuthenticatesUsers.php

Here is my Vue SPA's Vuex actions for login:

async login({ commit }, credentials) {
    try {
        const { data } = await axios.post(route('login'), {
            ...credentials,
            remember: credentials.remember || undefined,
        });

        commit(FETCH_USER_SUCCESS, { user: data.user });
        commit(LOGIN);

        return commit(CLEAR_INTENDED_URL);
    } catch (err) {
        commit(LOGOUT);
        throw new Error(`auth/login# Problem logging user in: ${err}.`);
    }
},

async logout({ commit }) {
    try {
        await axios.post(route('logout'));

        return commit(LOGOUT);
    } catch (err) {
        commit(LOGOUT);

        throw new Error(`auth/logout# Problem logging user out: ${err}.`);
    }
},

It took me over a week to get Laravel Sanctum + same-domain Vue SPA + auth unit tests all working up to my standard, so hopefully my answer here can help save others time in the future.

How do I change Bootstrap 3 column order on mobile layout?

October 2017

I would like to add another Bootstrap 4 solution. One that worked for me.

The CSS "Order" property, combined with a media query, can be used to re-order columns when they get stacked in smaller screens.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Adjust the screen size and you'll see the columns get stacked in a different order.

I'll tie this in with the original poster's question. With CSS, the navbar, sidebar, and content can be targeted and then order properties applied within a media query.

Bootstrap 3 .col-xs-offset-* doesn't work?

The bootstrap css used in the jsfiddle link, dont have the css for col-xs-offset-*, thats why the css are not been applied. Refer the latest bootstrap css.

Global variables in header file

Dont define varibale in header file , do declaration in header file(good practice ) .. in your case it is working because multiple weak symbols .. Read about weak and strong symbol ....link :http://csapp.cs.cmu.edu/public/ch7-preview.pdf

This type of code create problem while porting.

How to disable registration new users in Laravel

As of Laravel 5.7 you can pass an array of options to Auth::routes(). You can then disable the register routes with:

Auth::routes(['register' => false]);

You can see how this works from the source code: src/Illuminate/Routing/Router.php.

How to install PostgreSQL's pg gem on Ubuntu?

apt-get install ruby-dev worked for me.

Lazy Loading vs Eager Loading

Consider the below situation

public class Person{
    public String Name{get; set;}
    public String Email {get; set;}
    public virtual Employer employer {get; set;}
}

public List<EF.Person> GetPerson(){
    using(EF.DbEntities db = new EF.DbEntities()){
       return db.Person.ToList();
    }
}

Now after this method is called, you cannot lazy load the Employer entity anymore. Why? because the db object is disposed. So you have to do Person.Include(x=> x.employer) to force that to be loaded.

How to find if an array contains a specific string in JavaScript/jQuery?

You really don't need jQuery for this.

var myarr = ["I", "like", "turtles"];
var arraycontainsturtles = (myarr.indexOf("turtles") > -1);

Hint: indexOf returns a number, representing the position where the specified searchvalue occurs for the first time, or -1 if it never occurs

or

function arrayContains(needle, arrhaystack)
{
    return (arrhaystack.indexOf(needle) > -1);
}

It's worth noting that array.indexOf(..) is not supported in IE < 9, but jQuery's indexOf(...) function will work even for those older versions.

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

How to create Java gradle project

Finally after comparing all solution, I think starting from build.gradle file can be convenient.

Gradle distribution has samples folder with a lot of examples, and there is gradle init --type basic comand see Chapter 47. Build Init Plugin. But they all needs some editing.

You can use template below as well, then run gradle initSourceFolders eclipse

/*
* Nodeclipse/Enide build.gradle template for basic Java project
*   https://github.com/Nodeclipse/nodeclipse-1/blob/master/org.nodeclipse.enide.editors.gradle/docs/java/basic/build.gradle
* Initially asked on
*   http://stackoverflow.com/questions/14017364/how-to-create-java-gradle-project
* Usage
*   1. create folder (or general Eclipse project) and put this file inside
*   2. run `gradle initSourceFolders eclipse` or `gradle initSourceFolders idea`
* @author Paul Verest; 
* based on `gradle init --type basic`, that does not create source folders 
*/

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'

task initSourceFolders { // add << before { to prevent executing during configuration phase
   sourceSets*.java.srcDirs*.each { it.mkdirs() }
   sourceSets*.resources.srcDirs*.each { it.mkdirs() }
}

task wrapper(type: Wrapper) {
    gradleVersion = '1.11'
}

// In this section you declare where to find the dependencies of your project
repositories {
    // Use Maven Central for resolving your dependencies.
    // You can declare any Maven/Ivy/file repository here.
    mavenCentral()
}

// In this section you declare the dependencies for your production and test code
dependencies {
    //compile fileTree(dir: 'libs', include: '*.jar')
    // The production code uses the SLF4J logging API at compile time
    //compile 'org.slf4j:slf4j-api:1.7.5'

    // Declare the dependency for your favourite test framework you want to use in your tests.
    // TestNG is also supported by the Gradle Test task. Just change the
    // testCompile dependency to testCompile 'org.testng:testng:6.8.1' and add
    // 'test.useTestNG()' to your build script.
    testCompile "junit:junit:4.11"
}

The result is like below.

overview

That can be used without any Gradle plugin for Eclipse,
or with (Enide) Gradle for Eclipse, Jetty, Android alternative to Gradle Integration for Eclipse

editbox

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

Based on your application type/size/load/no. of users ..etc - u can keep following as your production properties

spring.datasource.tomcat.initial-size=50
spring.datasource.tomcat.max-wait=20000
spring.datasource.tomcat.max-active=300
spring.datasource.tomcat.max-idle=150
spring.datasource.tomcat.min-idle=8
spring.datasource.tomcat.default-auto-commit=true

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.

SQL Server 2008 can't login with newly created user

SQL Server was not configured to allow mixed authentication.

Here are steps to fix:

  1. Right-click on SQL Server instance at root of Object Explorer, click on Properties
  2. Select Security from the left pane.
  3. Select the SQL Server and Windows Authentication mode radio button, and click OK.

    enter image description here

  4. Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

This is also incredibly helpful for IBM Connections users, my wizards were not able to connect until I fxed this setting.

How does bitshifting work in Java?

You can't write binary literals like 00101011 in Java so you can write it in hexadecimal instead:

byte x = 0x2b;

To calculate the result of x >> 2 you can then just write exactly that and print the result.

System.out.println(x >> 2);

Making RGB color in Xcode

The values are determined by the bit of the image. 8 bit 0 to 255

16 bit...some ridiculous number..0 to 65,000 approx.

32 bit are 0 to 1

I use .004 with 32 bit images...this gives 1.02 as a result when multiplied by 255

Replacing spaces with underscores in JavaScript?

I know this is old but I didn't see anyone mention extending the String prototype.

String.prototype.replaceAll = function(search, replace){
    if(!search || !replace){return this;} //if search entry or replace entry empty return the string
    return this.replace(new RegExp('[' + search + ']', 'g'), replace); //global RegEx search for all instances ("g") of your search entry and replace them all.
};

Spring Data JPA findOne() change to Optional how to use this?

I always write a default method "findByIdOrError" in widely used CrudRepository repos/interfaces.

@Repository 
public interface RequestRepository extends CrudRepository<Request, Integer> {

    default Request findByIdOrError(Integer id) {
        return findById(id).orElseThrow(EntityNotFoundException::new);
    } 
}

Open multiple Projects/Folders in Visual Studio Code

You can open any folder, so if your projects are in the same tree, just open the folder beneath them.

Otherwise you can open 2 instances of Code as another option

How to store custom objects in NSUserDefaults

If anybody is looking for a swift version:

1) Create a custom class for your data

class customData: NSObject, NSCoding {
let name : String
let url : String
let desc : String

init(tuple : (String,String,String)){
    self.name = tuple.0
    self.url = tuple.1
    self.desc = tuple.2
}
func getName() -> String {
    return name
}
func getURL() -> String{
    return url
}
func getDescription() -> String {
    return desc
}
func getTuple() -> (String,String,String) {
    return (self.name,self.url,self.desc)
}

required init(coder aDecoder: NSCoder) {
    self.name = aDecoder.decodeObjectForKey("name") as! String
    self.url = aDecoder.decodeObjectForKey("url") as! String
    self.desc = aDecoder.decodeObjectForKey("desc") as! String
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.name, forKey: "name")
    aCoder.encodeObject(self.url, forKey: "url")
    aCoder.encodeObject(self.desc, forKey: "desc")
} 
}

2) To save data use following function:

func saveData()
    {
        let data  = NSKeyedArchiver.archivedDataWithRootObject(custom)
        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(data, forKey:"customArray" )
    }

3) To retrieve:

if let data = NSUserDefaults.standardUserDefaults().objectForKey("customArray") as? NSData
        {
             custom = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! [customData]
        }

Note: Here I am saving and retrieving an array of the custom class objects.

How to get package name from anywhere?

If you use the gradle-android-plugin to build your app, then you can use

BuildConfig.APPLICATION_ID

to retrieve the package name from any scope, incl. a static one.

Returning string from C function

Easier still: return a pointer to a string that's been malloc'd with strdup.

#include <ncurses.h>

char * getStr(int length)
{   
    char word[length];

    for (int i = 0; i < length; i++)
    {
        word[i] = getch();
    }

    word[i] = '\0';
    return strdup(&word[0]);
}

int main()
{
    char wordd[10];
    initscr();
    *wordd = getStr(10);
    printw("The string is:\n");
    printw("%s\n",*wordd);
    getch();
    endwin();
    return 0;
}

jQuery + client-side template = "Syntax error, unrecognized expression"

Turns out string starting with a newline (or anything other than "<") is not considered HTML string in jQuery 1.9

http://stage.jquery.com/upgrade-guide/1.9/#jquery-htmlstring-versus-jquery-selectorstring

jQuery set checkbox checked

Set the check box after loading the modal window. I think you are setting the check box before loading the page.

$('#fModal').modal('show');
$("#estado_cat").attr("checked","checked");

How can I know if a process is running?

Synchronous solution :

void DisplayProcessStatus(Process process)
{
    process.Refresh();  // Important


    if(process.HasExited)
    {
        Console.WriteLine("Exited.");
    }
    else
    {
        Console.WriteLine("Running.");
    } 
}

Asynchronous solution:

void RegisterProcessExit(Process process)
{
    // NOTE there will be a race condition with the caller here
    //   how to fix it is left as an exercise
    process.Exited += process_Exited;
}

static void process_Exited(object sender, EventArgs e)
{
   Console.WriteLine("Process has exited.");
}

Python - How to cut a string in Python?

string = 'http://www.domain.com/?s=some&two=20'
cut_string = string.split('&')
new_string = cut_string[0]
print(new_string)

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

How to create a regex for accepting only alphanumeric characters?

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";

Blue and Purple Default links, how to remove?

<a href="https://www." style="color: inherit;"target="_blank">

For CSS inline style, this worked best for me.

Why and when to use angular.copy? (Deep Copy)

I am just sharing my experience here, I used angular.copy() for comparing two objects properties. I was working on a number of inputs without form element, I was wondering how to compare two objects properties and based on result I have to enable and disable the save button. So I used as below.

I assigned an original server object user values to my dummy object to say userCopy and used watch to check changes to the user object.

My server API which gets me data from the server:

var req = {
    method: 'GET',
    url: 'user/profile/' + id,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
    $scope.user = data;
    $scope.userCopy = angular.copy($scope.user);
    $scope.btnSts=true;
}).error(function(data) {
    $ionicLoading.hide();
});

//initially my save button is disabled because objects are same, once something 
//changes I am activating save button

$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
    console.log($scope.userCopy.name);

    if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
        console.log('Changed');
        $scope.btnSts = false;
    } else {
        console.log('Unchanged');
        $scope.btnSts = true;
    }    
}, true);

I am not sure but comparing two objects was really headache for me always but with angular.copy() it went smoothly.

What is the easiest way to parse an INI file in Java?

As mentioned, ini4j can be used to achieve this. Let me show one other example.

If we have an INI file like this:

[header]
key = value

The following should display value to STDOUT:

Ini ini = new Ini(new File("/path/to/file"));
System.out.println(ini.get("header", "key"));

Check the tutorials for more examples.

Why do you have to link the math library in C?

stdio is part of the standard C library which, by default, gcc will link against.

The math function implementations are in a separate libm file that is not linked to by default so you have to specify it -lm. By the way, there is no relation between those header files and library files.

How to remove array element in mongodb?

Try the following query:

collection.update(
  { _id: id },
  { $pull: { 'contact.phone': { number: '+1786543589455' } } }
);

It will find document with the given _id and remove the phone +1786543589455 from its contact.phone array.

You can use $unset to unset the value in the array (set it to null), but not to remove it completely.

How to call a Web Service Method?

The current way to do this is by using the "Add Service Reference" command. If you specify "TestUploaderWebService" as the service reference name, that will generate the type TestUploaderWebService.Service1. That class will have a method named GetFileListOnWebServer, which will return an array of strings (you can change that to be a list of strings if you like). You would use it like this:

string[] files = null;
TestUploaderWebService.Service1 proxy = null;
bool success = false;
try
{
    proxy = new TestUploaderWebService.Service1();
    files = proxy.GetFileListOnWebServer();
    proxy.Close();
    success = true;
}
finally
{
    if (!success)
    {
        proxy.Abort();
    }
}

P.S. Tell your instructor to look at "Microsoft: ASMX Web Services are a “Legacy Technology”", and ask why he's teaching out of date technology.

Add element to a JSON file?

alternatively you can do

iter(data).next()['f'] = var

SQL Server converting varbinary to string

If you want to convert a single VARBINARY value into VARCHAR (STRING) you can do by declaring a variable like this:

DECLARE @var VARBINARY(MAX)
SET @var = 0x21232F297A57A5A743894A0E4A801FC3
SELECT CAST(@var AS VARCHAR(MAX))

If you are trying to select from table column then you can do like this:

SELECT CAST(myBinaryCol AS VARCHAR(MAX))
FROM myTable

Looking for a short & simple example of getters/setters in C#

Internally, getters and setters are just methods. When C# compiles, it generates methods for your getters and setters like this, for example:

public int get_MyProperty() { ... }
public void set_MyProperty(int value) { ... }

C# allows you to declare these methods using a short-hand syntax. The line below will be compiled into the methods above when you build your application.

public int MyProperty { get; set; }

or

private int myProperty;
public int MyProperty 
{ 
    get { return myProperty; }
    set { myProperty = value; } // value is an implicit parameter containing the value being assigned to the property.
}

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

If you don't need to handle raster files and PDF/PS/EPS through the same tool, don't loosen ImageMagick's security.

Instead, keep your defense in depth for your web applications intact, check that your Ghostscript has been patched for all known -dSAFER vulnerabilities and then invoke it directly.

gs -dSAFER -r300 -sDEVICE=png16m -o document-%03d.png document.pdf
  • -dSAFER opts you out of the legacy-compatibility "run Postscript will full permission to interact with the outside world as a turing-complete programming language" mode.
  • -r300 sets the desired DPI to 300 (the default is 72)
  • -sDEVICE specifies the output format (See the Devices section of the manual for other choices.)
  • -o is a shorthand for -dBATCH -dNOPAUSE -sOutputFile=
  • This section of the Ghostscript manual gives some example formats for for multi-file filename output but, for the actual syntax definition, it points you at the documentation for the C printf(3) function.

If you're rendering EPS files, add -dEPSCrop so it won't pad your output to page size and use -sDEVICE=pngalpha to get transparent backgrounds.

How do you completely remove Ionic and Cordova installation from mac?

Command to remove Cordova and ionic

  • For Window system

    • npm uninstall -g ionic
    • npm uninstall -g cordova
  • For Mac system

    • sudo npm uninstall -g ionic
    • sudo npm uninstall -g cordova
  • For install cordova and ionic

    • npm install -g cordova
    • npm install -g ionic

Note:

  • If you want to install in MAC System use before npm use sudo only.
  • And plan to install specific version of ionic and cordova then use @(version no.).

eg.

sudo npm install -g [email protected]

sudo npm install -g [email protected]

Select entries between dates in doctrine 2

You can do either…

$qb->where('e.fecha BETWEEN :monday AND :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

or…

$qb->where('e.fecha > :monday')
   ->andWhere('e.fecha < :sunday')
   ->setParameter('monday', $monday->format('Y-m-d'))
   ->setParameter('sunday', $sunday->format('Y-m-d'));

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I update my Hibernate JPA to 2.1 and It works.

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <version>1.0.0.Final</version>
</dependency>

How do I convert a String object into a Hash object?

Please consider this solution. Library+spec:

File: lib/ext/hash/from_string.rb:

require "json"

module Ext
  module Hash
    module ClassMethods
      # Build a new object from string representation.
      #
      #   from_string('{"name"=>"Joe"}')
      #
      # @param s [String]
      # @return [Hash]
      def from_string(s)
        s.gsub!(/(?<!\\)"=>nil/, '":null')
        s.gsub!(/(?<!\\)"=>/, '":')
        JSON.parse(s)
      end
    end
  end
end

class Hash    #:nodoc:
  extend Ext::Hash::ClassMethods
end

File: spec/lib/ext/hash/from_string_spec.rb:

require "ext/hash/from_string"

describe "Hash.from_string" do
  it "generally works" do
    [
      # Basic cases.
      ['{"x"=>"y"}', {"x" => "y"}],
      ['{"is"=>true}', {"is" => true}],
      ['{"is"=>false}', {"is" => false}],
      ['{"is"=>nil}', {"is" => nil}],
      ['{"a"=>{"b"=>"c","ar":[1,2]}}', {"a" => {"b" => "c", "ar" => [1, 2]}}],
      ['{"id"=>34030, "users"=>[14105]}', {"id" => 34030, "users" => [14105]}],

      # Tricky cases.
      ['{"data"=>"{\"x\"=>\"y\"}"}', {"data" => "{\"x\"=>\"y\"}"}],   # Value is a `Hash#inspect` string which must be preserved.
    ].each do |input, expected|
      output = Hash.from_string(input)
      expect([input, output]).to eq [input, expected]
    end
  end # it
end

How do I display image in Alert/confirm box in Javascript?

Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?

This might be useful: http://jqueryui.com/dialog/

You can do it like this:

<!doctype html>

<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>jQuery UI Dialog - Default functionality</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <script>
  body {
    font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
    font-size: 62.5%;
}

  </script>
  <script>
  $(function() {
    $( "#dialog" ).dialog();
  });
  </script>
</head>
<body>

<div id="dialog" title="Basic dialog">
  <p>Image:</p>
  <img src="http://placehold.it/50x50" alt="Placeholder Image" />

</div>


</body>
</html>

Logger slf4j advantages of formatting with {} instead of string concatenation

Short version: Yes it is faster, with less code!

String concatenation does a lot of work without knowing if it is needed or not (the traditional "is debugging enabled" test known from log4j), and should be avoided if possible, as the {} allows delaying the toString() call and string construction to after it has been decided if the event needs capturing or not. By having the logger format a single string the code becomes cleaner in my opinion.

You can provide any number of arguments. Note that if you use an old version of sljf4j and you have more than two arguments to {}, you must use the new Object[]{a,b,c,d} syntax to pass an array instead. See e.g. http://slf4j.org/apidocs/org/slf4j/Logger.html#debug(java.lang.String, java.lang.Object[]).

Regarding the speed: Ceki posted a benchmark a while back on one of the lists.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

I encountered this error when the JDK that I compiled the app under was different from the tomcat JVM. I verified that the Tomcat manager was running jvm 1.6.0 but the app was compiled under java 1.7.0.

After upgrading Java and changing JAVA_HOME in our startup script (/etc/init.d/tomcat) the error went away.

Can you find all classes in a package using reflection?

You should probably take a look at the open source Reflections library. With it you can easily achieve what you want.

First, setup the reflections index (it's a bit messy since searching for all classes is disabled by default):

List<ClassLoader> classLoadersList = new LinkedList<ClassLoader>();
classLoadersList.add(ClasspathHelper.contextClassLoader());
classLoadersList.add(ClasspathHelper.staticClassLoader());

Reflections reflections = new Reflections(new ConfigurationBuilder()
    .setScanners(new SubTypesScanner(false /* don't exclude Object.class */), new ResourcesScanner())
    .setUrls(ClasspathHelper.forClassLoader(classLoadersList.toArray(new ClassLoader[0])))
    .filterInputsBy(new FilterBuilder().include(FilterBuilder.prefix("org.your.package"))));

Then you can query for all objects in a given package:

Set<Class<?>> classes = reflections.getSubTypesOf(Object.class);

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

Read input stream twice

You can wrap input stream with PushbackInputStream. PushbackInputStream allows to unread ("write back") bytes which were already read, so you can do like this:

public class StreamTest {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's wrap it with PushBackInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new PushbackInputStream(originalStream, 10); // 10 means that maximnum 10 characters can be "written back" to the stream

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    ((PushbackInputStream) wrappedStream).unread(readBytes, 0, readBytes.length);

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3


  }

  private static byte[] getBytes(InputStream is, int howManyBytes) throws IOException {
    System.out.print("Reading stream: ");

    byte[] buf = new byte[howManyBytes];

    int next = 0;
    for (int i = 0; i < howManyBytes; i++) {
      next = is.read();
      if (next > 0) {
        buf[i] = (byte) next;
      }
    }
    return buf;
  }

  private static void printBytes(byte[] buffer) throws IOException {
    System.out.print("Reading stream: ");

    for (int i = 0; i < buffer.length; i++) {
      System.out.print(buffer[i] + " ");
    }
    System.out.println();
  }


}

Please note that PushbackInputStream stores internal buffer of bytes so it really creates a buffer in memory which holds bytes "written back".

Knowing this approach we can go further and combine it with FilterInputStream. FilterInputStream stores original input stream as a delegate. This allows to create new class definition which allows to "unread" original data automatically. The definition of this class is following:

public class TryReadInputStream extends FilterInputStream {
  private final int maxPushbackBufferSize;

  /**
  * Creates a <code>FilterInputStream</code>
  * by assigning the  argument <code>in</code>
  * to the field <code>this.in</code> so as
  * to remember it for later use.
  *
  * @param in the underlying input stream, or <code>null</code> if
  *           this instance is to be created without an underlying stream.
  */
  public TryReadInputStream(InputStream in, int maxPushbackBufferSize) {
    super(new PushbackInputStream(in, maxPushbackBufferSize));
    this.maxPushbackBufferSize = maxPushbackBufferSize;
  }

  /**
   * Reads from input stream the <code>length</code> of bytes to given buffer. The read bytes are still avilable
   * in the stream
   *
   * @param buffer the destination buffer to which read the data
   * @param offset  the start offset in the destination <code>buffer</code>
   * @aram length how many bytes to read from the stream to buff. Length needs to be less than
   *        <code>maxPushbackBufferSize</code> or IOException will be thrown
   *
   * @return number of bytes read
   * @throws java.io.IOException in case length is
   */
  public int tryRead(byte[] buffer, int offset, int length) throws IOException {
    validateMaxLength(length);

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int bytesRead = 0;

    int nextByte = 0;

    for (int i = 0; (i < length) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        buffer[offset + bytesRead++] = (byte) nextByte;
      }
    }

    if (bytesRead > 0) {
      ((PushbackInputStream) in).unread(buffer, offset, bytesRead);
    }

    return bytesRead;

  }

  public byte[] tryRead(int maxBytesToRead) throws IOException {
    validateMaxLength(maxBytesToRead);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(); // as ByteArrayOutputStream to dynamically allocate internal bytes array instead of allocating possibly large buffer (if maxBytesToRead is large)

    // NOTE: below reading byte by byte instead of "int bytesRead = is.read(firstBytes, 0, maxBytesOfResponseToLog);"
    // because read() guarantees to read a byte

    int nextByte = 0;

    for (int i = 0; (i < maxBytesToRead) && (nextByte >= 0); i++) {
      nextByte = read();
      if (nextByte >= 0) {
        baos.write((byte) nextByte);
      }
    }

    byte[] buffer = baos.toByteArray();

    if (buffer.length > 0) {
      ((PushbackInputStream) in).unread(buffer, 0, buffer.length);
    }

    return buffer;

  }

  private void validateMaxLength(int length) throws IOException {
    if (length > maxPushbackBufferSize) {
      throw new IOException(
        "Trying to read more bytes than maxBytesToRead. Max bytes: " + maxPushbackBufferSize + ". Trying to read: " +
        length);
    }
  }

}

This class has two methods. One for reading into existing buffer (defintion is analogous to calling public int read(byte b[], int off, int len) of InputStream class). Second which returns new buffer (this may be more effective if the size of buffer to read is unknown).

Now let's see our class in action:

public class StreamTest2 {
  public static void main(String[] args) throws IOException {
    byte[] bytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

    InputStream originalStream = new ByteArrayInputStream(bytes);

    byte[] readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 1 2 3

    readBytes = getBytes(originalStream, 3);
    printBytes(readBytes); // prints: 4 5 6

    // now let's use our TryReadInputStream

    originalStream = new ByteArrayInputStream(bytes);

    InputStream wrappedStream = new TryReadInputStream(originalStream, 10);

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // NOTE: no manual call to "unread"(!) because TryReadInputStream handles this internally
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 1 2 3

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3);
    printBytes(readBytes); // prints 1 2 3

    // we can also call normal read which will actually read the bytes without "writing them back"
    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 1 2 3

    readBytes = getBytes(wrappedStream, 3);
    printBytes(readBytes); // prints 4 5 6

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); // now we can try read next bytes
    printBytes(readBytes); // prints 7 8 9

    readBytes = ((TryReadInputStream) wrappedStream).tryRead(3); 
    printBytes(readBytes); // prints 7 8 9


  }



}

Search for an item in a Lua list

You're seeing firsthand one of the cons of Lua having only one data structure---you have to roll your own. If you stick with Lua you will gradually accumulate a library of functions that manipulate tables in the way you like to do things. My library includes a list-to-set conversion and a higher-order list-searching function:

function table.set(t) -- set of list
  local u = { }
  for _, v in ipairs(t) do u[v] = true end
  return u
end

function table.find(f, l) -- find element v of l satisfying f(v)
  for _, v in ipairs(l) do
    if f(v) then
      return v
    end
  end
  return nil
end

Iterate through a HashMap

Extracted from the reference How to Iterate Over a Map in Java:

There are several ways of iterating over a Map in Java. Let's go over the most common methods and review their advantages and disadvantages. Since all maps in Java implement the Map interface, the following techniques will work for any map implementation (HashMap, TreeMap, LinkedHashMap, Hashtable, etc.)

Method #1: Iterating over entries using a For-Each loop.

This is the most common method and is preferable in most cases. It should be used if you need both map keys and values in the loop.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Note that the For-Each loop was introduced in Java 5, so this method is working only in newer versions of the language. Also a For-Each loop will throw NullPointerException if you try to iterate over a map that is null, so before iterating you should always check for null references.

Method #2: Iterating over keys or values using a For-Each loop.

If you need only keys or values from the map, you can iterate over keySet or values instead of entrySet.

Map<Integer, Integer> map = new HashMap<Integer, Integer>();

// Iterating over keys only
for (Integer key : map.keySet()) {
    System.out.println("Key = " + key);
}

// Iterating over values only
for (Integer value : map.values()) {
    System.out.println("Value = " + value);
}

This method gives a slight performance advantage over entrySet iteration (about 10% faster) and is more clean.

Method #3: Iterating using Iterator.

Using Generics:

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry<Integer, Integer> entry = entries.next();
    System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}

Without Generics:

Map map = new HashMap();
Iterator entries = map.entrySet().iterator();
while (entries.hasNext()) {
    Map.Entry entry = (Map.Entry) entries.next();
    Integer key = (Integer)entry.getKey();
    Integer value = (Integer)entry.getValue();
    System.out.println("Key = " + key + ", Value = " + value);
}

You can also use same technique to iterate over keySet or values.

This method might look redundant, but it has its own advantages. First of all, it is the only way to iterate over a map in older versions of Java. The other important feature is that it is the only method that allows you to remove entries from the map during iteration by calling iterator.remove(). If you try to do this during For-Each iteration you will get "unpredictable results" according to Javadoc.

From a performance point of view this method is equal to a For-Each iteration.

Method #4: Iterating over keys and searching for values (inefficient).

Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
    Integer value = map.get(key);
    System.out.println("Key = " + key + ", Value = " + value);
}

This might look like a cleaner alternative for method #1, but in practice it is pretty slow and inefficient as getting values by a key might be time-consuming (this method in different Map implementations is 20%-200% slower than method #1). If you have FindBugs installed, it will detect this and warn you about inefficient iteration. This method should be avoided.

Conclusion:

If you need only keys or values from the map, use method #2. If you are stuck with older version of Java (less than 5) or planning to remove entries during iteration, you have to use method #3. Otherwise use method #1.

Regular Expression: Any character that is NOT a letter or number

To match anything other than letter or number or letter with diacritics like é you could try this:

[^\wÀ-úÀ-ÿ]

And to replace:

var str = 'dfj,dsf7é@lfsd .sdklfàj1';
str = str.replace(/[^\wÀ-úÀ-ÿ]/g, '_');

Inspired by the top post with support for diacritics

source

TypeError: 'module' object is not callable

A simple way to solve this problem is export thePYTHONPATH variable enviroment. For example, for Python 2.6 in Debian/GNU Linux:

export PYTHONPATH=/usr/lib/python2.6`

In other operating systems, you would first find the location of this module or the socket.py file.

Set date input field's max date to today

JavaScript only simple solution

_x000D_
_x000D_
datePickerId.max = new Date().toISOString().split("T")[0];
_x000D_
<input type="date" id="datePickerId" />
_x000D_
_x000D_
_x000D_

Change Row background color based on cell value DataTable

The equivalent syntax since DataTables 1.10+ is rowCallback

"rowCallback": function( row, data, index ) {
    if ( data[2] == "5" )
    {
        $('td', row).css('background-color', 'Red');
    }
    else if ( data[2] == "4" )
    {
        $('td', row).css('background-color', 'Orange');
    }
}

One of the previous answers mentions createdRow. That may give similar results under some conditions, but it is not the same. For example, if you use draw() after updating a row's data, createdRow will not run. It only runs once. rowCallback will run again.

cor shows only NA or 1 for correlations - Why?

The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.

Get Current date in epoch from Unix shell script

Depending on the language you're using it's going to be something simple like

CInt(CDate("1970-1-1") - CDate(Today()))

Ironically enough, yesterday was day 40,000 if you use 1/1/1900 as "day zero" like many computer systems use.

Prevent typing non-numeric in input type number

Try preventing the default behaviour if you don't like the incoming key value:

document.querySelector("input").addEventListener("keypress", function (evt) {
    if (evt.which < 48 || evt.which > 57)
    {
        evt.preventDefault();
    }
});

Replace and overwrite instead of appending

file='path/test.xml' 
with open(file, 'w') as filetowrite:
    filetowrite.write('new content')

Open the file in 'w' mode, you will be able to replace its current text save the file with new contents.

PHP + curl, HTTP POST sample code?

A live example of using php curl_exec to do an HTTP post:

Put this in a file called foobar.php:

<?php
  $ch = curl_init();
  $skipper = "luxury assault recreational vehicle";
  $fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
  $postvars = '';
  foreach($fields as $key=>$value) {
    $postvars .= $key . "=" . $value . "&";
  }
  $url = "http://www.google.com";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
  curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  print "curl response is:" . $response;
  curl_close ($ch);
?>

Then run it with the command php foobar.php, it dumps this kind of output to screen:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
  A mountain of content...
</body>
</html>

So you did a PHP POST to www.google.com and sent it some data.

Had the server been programmed to read in the post variables, it could decide to do something different based upon that.

A project with an Output Type of Class Library cannot be started directly

    Right Click on "Solution Explorer" -> "Properties"
    Expand "Common Properties"
    Select "Start Up Project"
    click the radio button "Single Start_up Project"
    select your Project name from the drop down list.

If still not working after the above steps, then try this.

    Expand solutions explorer.
    Right click on project name -> "Properties"
    Go to "Application" tab
    Select "Output type" 
 From the drop down list select the appropriate type according to your application.
    "Windows application" or
    "Console application"

Then save (ctrl + S)

Try debugging (F5)

In Python, when to use a Dictionary, List or Set?

When use them, I make an exhaustive cheatsheet of their methods for your reference:

class ContainerMethods:
    def __init__(self):
        self.list_methods_11 = {
                    'Add':{'append','extend','insert'},
                    'Subtract':{'pop','remove'},
                    'Sort':{'reverse', 'sort'},
                    'Search':{'count', 'index'},
                    'Entire':{'clear','copy'},
                            }
        self.tuple_methods_2 = {'Search':'count','index'}

        self.dict_methods_11 = {
                    'Views':{'keys', 'values', 'items'},
                    'Add':{'update'},
                    'Subtract':{'pop', 'popitem',},
                    'Extract':{'get','setdefault',},
                    'Entire':{ 'clear', 'copy','fromkeys'},
                            }
        self.set_methods_17 ={
                    'Add':{['add', 'update'],['difference_update','symmetric_difference_update','intersection_update']},
                    'Subtract':{'pop', 'remove','discard'},
                    'Relation':{'isdisjoint', 'issubset', 'issuperset'},
                    'operation':{'union' 'intersection','difference', 'symmetric_difference'}
                    'Entire':{'clear', 'copy'}}

Reading Data From Database and storing in Array List object

Also If you want you result set data in list .please use below LOC:

public List<String> dbselect(String query)
  {
      List<String> dbdata=new ArrayList<String>();
      try {
        dbResult=statement.executeQuery(query);
        ResultSetMetaData metadata=dbResult.getMetaData();
        for(int i=0;i>=metadata.getColumnCount();i++)
        {
            dbdata.add(dbResult.getString(i));
        }
        return dbdata;
    } catch (SQLException e) {
        return null;
    }
      
      
  }

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

How to install CocoaPods?

1.First open your terminal

2.Then update your gem file with command

sudo gem install -n /usr/local/bin cocoapods

3.Then give your project path

cd /your project path 

4.Touch the podifle

touch podfile

5.Open your podfile

open -e podfile

6.It will open a podfile like a text edit. Then set your target. For example if you want to set up Google maps then your podfile should be like

use_frameworks!
target 'yourProjectName' do
    pod 'GoogleMaps'
end

7.Then install the pod

pod install

SQL Server Regular expressions in T-SQL

There is some basic pattern matching available through using LIKE, where % matches any number and combination of characters, _ matches any one character, and [abc] could match a, b, or c... There is more info on the MSDN site.

Change route params without reloading in Angular 2

For anyone like me finding this question the following might be useful.

I had a similar problem and initially tried using location.go and location.replaceState as suggested in other answers here. However I ran into problems when I had to navigate to another page on the app because the navigation was relative to the current route and the current route wasn't being updated by location.go or location.replaceState (the router doesn't know anything about what these do to the URL)

In essence I needed a solution that DIDN'T reload the page/component when the route parameter changed but DID update the route state internally.

I ended up using query parameters. You can find more about it here: https://angular-2-training-book.rangle.io/handout/routing/query_params.html

So if you need to do something like save an order and get an order ID you can update your page URL like shown below. Updating a centre location and related data on a map would be similar

// let's say we're saving an order. Initally the URL is just blah/orders
save(orderId) {
    // [Here we would call back-end to save the order in the database]

    this.router.navigate(['orders'], { queryParams: { id: orderId } });
    // now the URL is blah/orders?id:1234. We don't reload the orders
    // page or component so get desired behaviour of not seeing any 
    // flickers or resetting the page.
}

and you keep track of it within the ngOnInit method like:

ngOnInit() {
    this.orderId = this.route
        .queryParamMap
        .map(params => params.get('id') || null);
    // orderID is up-to-date with what is saved in database now, or if
    // nothing is saved and hence no id query paramter the orderId variable
    // is simply null.
    // [You can load the order here from its ID if this suits your design]
}

If you need to go direct to the order page with a new (unsaved) order you can do:

this.router.navigate(['orders']);

Or if you need to go direct to the order page for an existing (saved) order you can do:

this.router.navigate(['orders'], { queryParams: { id: '1234' } });

Parse JSON in TSQL

Update: As of SQL Server 2016 parsing JSON in TSQL is now possible.

Natively, there is no support. You'll have to use CLR. It is as simple as that, unless you have a huge masochistic streak and want to write a JSON parser in SQL

Normally, folk ask for JSON output from the DB and there are examples on the internet. But into a DB?

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

try this:

Using jQuery:

You can reset the entire form with:

$("#myform")[0].reset();

Or just the specific field with:

$('#form-id').children('input').val('')

Using JavaScript Without jQuery

<input type="button" value="Submit" id="btnsubmit" onclick="submitForm()">

function submitForm() {
   // Get the first form with the name
   // Hopefully there is only one, but there are more, select the correct index
   var frm = document.getElementsByName('contact-form')[0];
   frm.submit(); // Submit
   frm.reset();  // Reset
   return false; // Prevent page refresh
}

How to create a custom-shaped bitmap marker with Android map API v2

From lambda answer, I have made something closer to the requirements.

boolean imageCreated = false;

Bitmap bmp = null;
Marker currentLocationMarker;
private void doSomeCustomizationForMarker(LatLng currentLocation) {
    if (!imageCreated) {
        imageCreated = true;
        Bitmap.Config conf = Bitmap.Config.ARGB_8888;
        bmp = Bitmap.createBitmap(400, 400, conf);
        Canvas canvas1 = new Canvas(bmp);

        Paint color = new Paint();
        color.setTextSize(30);
        color.setColor(Color.WHITE);

        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inMutable = true;

        Bitmap imageBitmap=BitmapFactory.decodeResource(getResources(),
                R.drawable.messi,opt);
        Bitmap resized = Bitmap.createScaledBitmap(imageBitmap, 320, 320, true);
        canvas1.drawBitmap(resized, 40, 40, color);

        canvas1.drawText("Le Messi", 30, 40, color);

        currentLocationMarker = mMap.addMarker(new MarkerOptions().position(currentLocation)
                .icon(BitmapDescriptorFactory.fromBitmap(bmp))
                // Specifies the anchor to be at a particular point in the marker image.
                .anchor(0.5f, 1));
    } else {
        currentLocationMarker.setPosition(currentLocation);
    }

}

Get Hard disk serial Number

Hm, looking at your first set of code, I think you have retrieved (maybe?) the hard drive model. The serial # comes from Win32_PhysicalMedia.

Get Hard Drive model

    ManagementObjectSearcher searcher = new
    ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

   foreach(ManagementObject wmi_HD in searcher.Get())
   {
    HardDrive hd = new HardDrive();
    hd.Model = wmi_HD["Model"].ToString();
    hd.Type  = wmi_HD["InterfaceType"].ToString(); 
    hdCollection.Add(hd);
   }

Get the Serial Number

 searcher = new
    ManagementObjectSearcher("SELECT * FROM Win32_PhysicalMedia");

   int i = 0;
   foreach(ManagementObject wmi_HD in searcher.Get())
   {
    // get the hard drive from collection
    // using index
    HardDrive hd = (HardDrive)hdCollection[i];

    // get the hardware serial no.
    if (wmi_HD["SerialNumber"] == null)
     hd.SerialNo = "None";
    else
     hd.SerialNo = wmi_HD["SerialNumber"].ToString();

    ++i;
   }

Source

Hope this helps :)

MySQL Workbench Edit Table Data is read only

I was getting the read-only problem even when I was selecting the primary key. I eventually figured out it was a casing problem. Apparently the PK column must be cased the same as defined in the table. using: workbench 6.3 on windows

Read-Only

SELECT leadid,firstname,lastname,datecreated FROM lead;

Allowed edit

SELECT LeadID,firstname,lastname,datecreated FROM lead;

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

Parsing ISO 8601 date in Javascript

The Date object handles 8601 as it's first parameter:

_x000D_
_x000D_
var d = new Date("2014-04-07T13:58:10.104Z");_x000D_
console.log(d.toString());
_x000D_
_x000D_
_x000D_

How do I install and use curl on Windows?

  • Download curl for windows from the path : https://curl.haxx.se/windows/
  • Unzip and you will find the ..\bin\curl.exe
  • Add ...\bin\ to your path variable for easy global access

How to Logout of an Application Where I Used OAuth2 To Login With Google?

To logout from the app only but not the Gmail:

window.gapi.load('auth2', () => {
      window.gapi.auth2
        .init({
          client_id:
            '<Your client id configired on google console>'
        })
        .then(() => {
          window.gapi.auth2
            .getAuthInstance()
            .signOut()
            .then(function() {
              console.log('User signed out.');
            });
        });
    });

I'm using above in my ReactJs code.

phpMyAdmin allow remote users

Try this

Replace

<Directory /usr/share/phpMyAdmin/>
    <IfModule mod_authz_core.c>
        # Apache 2.4
        <RequireAny>
            Require ip 127.0.0.1
            Require ip ::1
        </RequireAny>
    </IfModule>
    <IfModule !mod_authz_core.c>
        # Apache 2.2
        Order Deny,Allow
        Deny from All
        Allow from 127.0.0.1
        Allow from ::1
    </IfModule>
</Directory>

With this:

<Directory "/usr/share/phpMyAdmin/">
    Options Indexes FollowSymLinks MultiViews
    AllowOverride all
        Order Allow,Deny 
    Allow from all
</Directory>

Add the following line for ease of access:

Alias /phpmyadmin /usr/share/phpMyAdmin

Getting DOM elements by classname

If you wish to get the innerhtml of the class without the zend you could use this:

$dom = new DomDocument();
$dom->load($filePath);
$classname = 'main-article';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument(); 
foreach ($nodes as $node) 
    {
    $tmp_dom->appendChild($tmp_dom->importNode($node,true));
    }
$innerHTML.=trim($tmp_dom->saveHTML()); 
echo $innerHTML;

Does Hive have a String split function?

Another interesting usecase for split in Hive is when, for example, a column ipname in the table has a value "abc11.def.ghft.com" and you want to pull "abc11" out:

SELECT split(ipname,'[\.]')[0] FROM tablename;

gitignore all files of extension in directory

Never tried it, but git help ignore suggests that if you put a .gitignore with *.js in /public/static, it will do what you want.

Note: make sure to also check out Joeys' answer below: if you want to ignore files in a specific subdirectory, then a local .gitignore is the right solution (locality is good). However if you need the same pattern to apply to your whole repo, then the ** solution is better.

NSDictionary to NSArray?

NSArray * values = [dictionary allValues];

Javascript counting number of objects in object

The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.

Then you can use either _.size(object) or _.keys(object).length

For your obj.Data, you could test this with:

console.log( _.size(obj.Data) );

or:

console.log( _.keys(obj.Data).length );

Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)

Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:

function ObjectLength( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
};

You can test this with:

console.log( ObjectLength(obj.Data) );

That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:

function ObjectLength_Modern( object ) {
    return Object.keys(object).length;
}

function ObjectLength_Legacy( object ) {
    var length = 0;
    for( var key in object ) {
        if( object.hasOwnProperty(key) ) {
            ++length;
        }
    }
    return length;
}

var ObjectLength =
    Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;

and as before, test it with:

console.log( ObjectLength(obj.Data) );

This code uses Object.keys(object).length in modern browsers and falls back to counting in a loop for old browsers.

But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.

I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.

Thanks to Barmar for suggesting Object.keys for newer browsers in his answer.

powershell - extract file name and extension

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

What does the Excel range.Rows property really do?

There is another way, take this as example

Dim sr As String    
sr = "6:10"
Rows(sr).Select

All you need to do is to convert your variables iStartRow, iEndRow to a string.

Shorthand if/else statement Javascript

y = (y != undefined) ? y : x;

The parenthesis are not necessary, I just add them because I think it's easier to read this way.

Specify a Root Path of your HTML directory for script links?

/ means the root of the current drive;

./ means the current directory;

../ means the parent of the current directory.

How to access my localhost from another PC in LAN?

You have to edit httpd.conf and find this line: Listen 127.0.0.1:80

Then write down your desired IP you set for LAN. Don't use automatic IP.
e.g.: Listen 192.168.137.1:80

I used 192.167.137.1 as my LAN IP of Windows 7. Restart Apache and enjoy sharing.

How does origin/HEAD get set?

What moves origin/HEAD "organically"?

  • git clone sets it once to the spot where HEAD is on origin
    • it serves as the default branch to checkout after cloning with git clone

What does HEAD on origin represent?

  • on bare repositories (often repositories “on servers”) it serves as a marker for the default branch, because git clone uses it in such a way
  • on non-bare repositories (local or remote), it reflects the repository’s current checkout

What sets origin/HEAD?

  • git clone fetches and sets it
  • it would make sense if git fetch updates it like any other reference, but it doesn’t
  • git remote set-head origin -a fetches and sets it
    • useful to update the local knowledge of what remote considers the “default branch”

Trivia

  • origin/HEAD can also be set to any other value without contacting the remote: git remote set-head origin <branch>
    • I see no use-case for this, except for testing
  • unfortunately nothing is able to set HEAD on the remote
  • older versions of git did not know which branch HEAD points to on the remote, only which commit hash it finally has: so it just hopefully picked a branch name pointing to the same hash

What is java pojo class, java bean, normal class?

POJO stands for Plain Old Java Object, and would be used to describe the same things as a "Normal Class" whereas a JavaBean follows a set of rules. Most commonly Beans use getters and setters to protect their member variables, which are typically set to private and have a no-argument public constructor. Wikipedia has a pretty good rundown of JavaBeans: http://en.wikipedia.org/wiki/JavaBeans

POJO is usually used to describe a class that doesn't need to be a subclass of anything, or implement specific interfaces, or follow a specific pattern.

How to Generate Unique ID in Java (Integer)?

int uniqueId = 0;

int getUniqueId()
{
    return uniqueId++;
}

Add synchronized if you want it to be thread safe.

Click a button programmatically

in c# this is working :D

protect void button1_Click(object sender, EventArgs e){
    button2_Click(button2, null);
}

protect void button2_Click(object sender, EventeArgs e){
    //some codes here
}

for vb.net

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button1.Click
    Button2_Click(Sender, e)
End Sub

Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs)   Handles Button2.Click
    //some codes here
End Sub

Convert pandas Series to DataFrame

probably graded as a non-pythonic way to do this but this'll give the result you want in a line:

new_df = pd.DataFrame(zip(email,list))

Result:

               email               list
0   [email protected]    [1.0, 0.0, 0.0]
1   [email protected]    [2.0, 0.0, 0.0]
2   [email protected]    [1.0, 0.0, 0.0]
3   [email protected]    [4.0, 0.0, 3.0]
4   [email protected]    [1.0, 5.0, 0.0]

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

You can have multiple <context:property-placeholder /> elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.

Increase max execution time for php

PHP file (for example, my_lengthy_script.php)

ini_set('max_execution_time', 300); //300 seconds = 5 minutes

.htaccess file

<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>

More configuration options

<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>

If wordpress, set this in the config.php file,

define('WP_MEMORY_LIMIT', '128M');

If drupal, sites/default/settings.php

ini_set('memory_limit', '128M');

If you are using other frameworks,

ini_set('memory_limit', '128M');

You can increase memory as gigabyte.

ini_set('memory_limit', '3G'); // 3 Gigabytes

259200 means:-

( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days

More details on my blog

what is the use of xsi:schemaLocation?

If you go into any of those locations, then you will find what is defined in those schema. For example, it tells you what is the data type of the ini-method key words value.

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

How do I install TensorFlow's tensorboard?

pip install tensorflow.tensorboard  # install tensorboard
pip show tensorflow.tensorboard
# Location: c:\users\<name>\appdata\roaming\python\python35\site-packages
# now just run tensorboard as:
python c:\users\<name>\appdata\roaming\python\python35\site-packages\tensorboard\main.py --logdir=<logidr>

Alternative to iFrames with HTML5

You can use an XMLHttpRequest to load a page into a div (or any other element of your page really). An exemple function would be:

function loadPage(){
if (window.XMLHttpRequest){
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}else{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200){
        document.getElementById("ID OF ELEMENT YOU WANT TO LOAD PAGE IN").innerHTML=xmlhttp.responseText;
    }
}

xmlhttp.open("POST","WEBPAGE YOU WANT TO LOAD",true);
xmlhttp.send();
}

If your sever is capable, you could also use PHP to do this, but since you're asking for an HTML5 method, this should be all you need.

What is the difference between synchronous and asynchronous programming (in node.js)

The difference between these two approaches is as follows:

Synchronous way: It waits for each operation to complete, after that only it executes the next operation. For your query: The console.log() command will not be executed until & unless the query has finished executing to get all the result from Database.

Asynchronous way: It never waits for each operation to complete, rather it executes all operations in the first GO only. The result of each operation will be handled once the result is available. For your query: The console.log() command will be executed soon after the Database.Query() method. While the Database query runs in the background and loads the result once it is finished retrieving the data.

Use cases

  1. If your operations are not doing very heavy lifting like querying huge data from DB then go ahead with Synchronous way otherwise Asynchronous way.

  2. In Asynchronous way you can show some Progress indicator to the user while in background you can continue with your heavy weight works. This is an ideal scenario for GUI apps.

Capturing URL parameters in request.GET

def some_view(request, *args, **kwargs):
    if kwargs.get('q', None):
        # Do something here ..

Concatenate text files with Windows command line, dropping leading lines

I know you said that you couldn't install any software, but I'm not sure how tight that restriction is. Anyway, I had the same issue (trying to concatenate two files with presumably the same headers) and I thought I'd provide an alternative answer for others who arrive at this page, since it worked just great for me.

After trying a whole bunch of commands in windows and being severely frustrated, and also trying all sorts of graphical editors that promised to be able to open large files, but then couldn't, I finally got back to my Linux roots and opened my Cygwin prompt. Two commands:

cp file1.csv out.csv
tail -n+2 file2.csv >> out.csv

For file1.csv 800MB and file2.csv 400MB, those two commands took under 5 seconds on my machine. In a Cygwin prompt, no less. I thought Linux commands were supposed to be slow in Cygwin but that approach took far less effort and was way easier than any windows approach I could find.

How do I set the default Java installation/runtime (Windows)?

This is a bit of a pain on Windows. Here's what I do.

Install latest Sun JDK, e.g. 6u11, in path like c:\install\jdk\sun\6u11, then let the installer install public JRE in the default place (c:\program files\blah). This will setup your default JRE for the majority of things.

Install older JDKs as necessary, like 5u18 in c:\install\jdk\sun\5u18, but don't install the public JREs.

When in development, I have a little batch file that I use to setup a command prompt for each JDK version. Essentially just set JAVA_HOME=c:\jdk\sun\JDK_DESIRED and then set PATH=%JAVA_HOME%\bin;%PATH%. This will put the desired JDK first in the path and any secondary tools like Ant or Maven can use the JAVA_HOME variable.

The path is important because most public JRE installs put a linked executable at c:\WINDOWS\System32\java.exe, which usually overrides most other settings.

Response to preflight request doesn't pass access control check

I have faced with this problem when DNS server was set to 8.8.8.8 (google's). Actually, the problem was in router, my application tried to connect with server through the google, not locally (for my particular case). I have removed 8.8.8.8 and this solved the issue. I know that this issues solved by CORS settings, but maybe someone will have the same trouble as me

What is the iPhone 4 user-agent?

  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Mobile/7D11
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A293 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_0_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8A306 Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_1 like Mac OS X; en-us) AppleWebKit/532.9 (KHTML, like Gecko) Version/4.0.5 Mobile/8B5097d Safari/6531.22.7
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2 like Mac OS X; en_us) AppleWebKit/525.18.1 (KHTML, like Gecko)
  • Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_2_1 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8C148 Safari/6533.18.5

...for now

Change Text Color of Selected Option in a Select Box

Try this:

_x000D_
_x000D_
.greenText{ background-color:green; }_x000D_
_x000D_
.blueText{ background-color:blue; }_x000D_
_x000D_
.redText{ background-color:red; }
_x000D_
<select_x000D_
    onchange="this.className=this.options[this.selectedIndex].className"_x000D_
    class="greenText">_x000D_
     <option class="greenText" value="apple" >Apple</option>_x000D_
    <option class="redText"   value="banana" >Banana</option>_x000D_
    <option class="blueText" value="grape" >Grape</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Inserting into Oracle and retrieving the generated sequence ID

Doing it as a stored procedure does have lot of advantages. You can get the sequence that is inserted into the table using syntax insert into table_name values returning.

Like:

declare
some_seq_val  number;
lv_seq        number;
begin
some_seq_val := your_seq.nextval;
insert into your_tab (col1, col2, col3) 
values (some_seq_val, val2, val3) returning some_seq_val into lv_seq;

dbms_output.put_line('The inserted sequence is: '||to_char(lv_seq));
end;
/

Or just return some_seq_val. In case you are not making use of SEQUENCE, and arriving the sequence on some calculation, you can make use of returning into effectively.

Align DIV's to bottom or baseline

_x000D_
_x000D_
td {_x000D_
  height: 150px;_x000D_
  width: 150px;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
b {_x000D_
  border: 1px solid black;_x000D_
}_x000D_
_x000D_
.child-2 {_x000D_
  vertical-align: bottom;_x000D_
}_x000D_
_x000D_
.child-3 {_x000D_
  vertical-align: top;_x000D_
}
_x000D_
<table border=1>_x000D_
  <tr>_x000D_
    <td class="child-1">_x000D_
      <b>child 1</b>_x000D_
    </td>_x000D_
    <td class="child-2">_x000D_
     <b>child 2</b>_x000D_
    </td>_x000D_
    <td class="child-3">_x000D_
      <b>child 3</b>_x000D_
    </td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

This is my solution

How to deal with certificates using Selenium?

For Firefox:

ProfilesIni profile = new ProfilesIni();
FirefoxProfile myprofile = profile.getProfile("default");
myprofile.setAcceptUntrustedCertificates(true);
myprofile.setAssumeUntrustedCertificateIssuer(true);
WebDriver driver = new FirefoxDriver(myprofile);

For Chrome we can use:

DesiredCapabilities capabilities = DesiredCapabilities.chrome();
capabilities.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));
driver = new ChromeDriver(capabilities);

For Internet Explorer we can use:

DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.ACCEPT_SSL_CERTS, true);      
Webdriver driver = new InternetExplorerDriver(capabilities);

Append file contents to the bottom of existing file in Bash

This should work:

 cat "$API" >> "$CONFIG"

You need to use the >> operator to append to a file. Redirecting with > causes the file to be overwritten. (truncated).

jQuery $("#radioButton").change(...) not firing during de-selection

<input id='r1' type='radio' class='rg' name="asdf"/>
<input id='r2' type='radio' class='rg' name="asdf"/>
<input id='r3' type='radio' class='rg' name="asdf"/>
<input id='r4' type='radio' class='rg' name="asdf"/><br/>
<input type='text' id='r1edit'/>                  

jquery part

$(".rg").change(function () {

if ($("#r1").attr("checked")) {
            $('#r1edit:input').removeAttr('disabled');
        }
        else {
            $('#r1edit:input').attr('disabled', 'disabled');
        }
                    });

here is the DEMO

How do I get a list of files in a directory in C++?

After combining a lot of snippets, I finally found a reuseable solution for Windows, that uses ATL Library, which comes with Visual Studio.

#include <atlstr.h>

void getFiles(CString directory) {
    HANDLE dir;
    WIN32_FIND_DATA file_data;
    CString  file_name, full_file_name;
    if ((dir = FindFirstFile((directory + "/*"), &file_data)) == INVALID_HANDLE_VALUE)
    {
        // Invalid directory
    }

    while (FindNextFile(dir, &file_data)) {
        file_name = file_data.cFileName;
        full_file_name = directory + file_name;
        if (strcmp(file_data.cFileName, ".") != 0 && strcmp(file_data.cFileName, "..") != 0)
        {
            std::string fileName = full_file_name.GetString();
            // Do stuff with fileName
        }
    }
}

To access the method, just call:

getFiles("i:\\Folder1");

Serializing class instance to JSON

This can be easily handled with pydantic, as it already has this functionality built-in.

Option 1: normal way

from pydantic import BaseModel

class testclass(BaseModel):
    value1: str = "a"
    value2: str = "b"

test = testclass()

>>> print(test.json(indent=4))
{
    "value1": "a",
    "value2": "b"
}

Option 2: using pydantic's dataclass

import json
from pydantic.dataclasses import dataclass
from pydantic.json import pydantic_encoder

@dataclass
class testclass:
    value1: str = "a"
    value2: str = "b"

test = testclass()
>>> print(json.dumps(test, indent=4, default=pydantic_encoder))
{
    "value1": "a",
    "value2": "b"
}

Alter column, add default constraint

you can wrap reserved words in square brackets to avoid these kinds of errors:

dbo.TableName.[Date]

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

I have the same issue with Entity Framework 6.1.3

But with different scenario. My model property is of type nullable DateTime

DateTime? CreatedDate { get; set; }

So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext:

Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);

jquery live hover

This code works:

    $(".ui-button-text").live(
        'hover',
        function (ev) {
            if (ev.type == 'mouseover') {
                $(this).addClass("ui-state-hover");
            }

            if (ev.type == 'mouseout') {
                $(this).removeClass("ui-state-hover");
            }
        });

Why does Java have an "unreachable statement" compiler error?

While I think this compiler error is a good thing, there is a way you can work around it. Use a condition you know will be true:

public void myMethod(){

    someCodeHere();

    if(1 < 2) return; // compiler isn't smart enough to complain about this

    moreCodeHere();

}

The compiler is not smart enough to complain about that.

copying all contents of folder to another folder using batch file?

If you have robocopy,

robocopy C:\Folder1 D:\Folder2 /COPYALL /E

otherwise,

xcopy /e /v C:\Folder1 D:\Folder2

Can I add an image to an ASP.NET button?

You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.

Style="background-image:url('Image/1.png');"

You can change image location with using

background-repeat

properties. So you can write a button like below:

<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

PHP has a built in function called bool chmod(string $filename, int $mode )

http://php.net/function.chmod

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);
    chmod($file, 0777);  //changed to add the zero
    return true;
}

c++ integer->std::string conversion. Simple function?

Now in c++11 we have

#include <string>
string s = std::to_string(123);

Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string

How to compare two object variables in EL expression language?

Not sure if I get you right, but the simplest way would be something like:

<c:if test="${languageBean.locale == 'en'">
  <f:selectItems value="#{customerBean.selectableCommands_limited_en}" />
</c:if>

Just a quick copy and paste from an app of mine...

HTH

Git undo changes in some files

Yes;

git commit FILE

will commit just FILE. Then you can use

git reset --hard

to undo local changes in other files.

There may be other ways too that I don't know about...

edit: or, as NicDumZ said, git-checkout just the files you want to undo the changes on (the best solution depends on wether there are more files to commit or more files to undo :-)

Android Error - Open Failed ENOENT

With sdk, you can't write to the root of internal storage. This cause your error.

Edit :

Based on your code, to use internal storage with sdk:

final File dir = new File(context.getFilesDir() + "/nfs/guille/groce/users/nicholsk/workspace3/SQLTest");
dir.mkdirs(); //create folders where write files
final File file = new File(dir, "BlockForTest.txt");

Getting windbg without the whole WDK?

The saga continues with the Windows 10 version. I had to install Win Debug Tools on clean Windows 10 OS with Visual Studio 2015.

To make a long story short, just follow the instructions in the link provided by David Black. After downloading the files, instead of running the SDK installer, browse to the installers directory and execute the msi files directly.

I wonder how many man hours have been lost through the last decade because of MS sloppiness in regards to WDK/SDK installation?

Dynamically create Bootstrap alerts box through JavaScript

You can also create a HTML alert template like this:

<div class="alert alert-info" id="alert_template" style="display: none;">
    <button type="button" class="close">×</button>
</div>

And so you can do in JavaScript this here:

$("#alert_template button").after('<span>Some text</span>');
$('#alert_template').fadeIn('slow');

Which is in my opinion cleaner and faster. In addition you stick to Twitter Bootstrap standards when calling fadeIn().

To guarantee that this alert template works also with multiple calls (so it doesn't add the new message to the old one), add this here to your JavaScript:

$('#alert_template .close').click(function(e) {
    $("#alert_template span").remove();
});

So this call removes the span element every time you close the alert via the x-button.

Using JavaMail with TLS

With Simple Java Mail 5.0.0 (simplejavamail.org) it is very straightforward and the library will take care of all the Session properties for you.

Here's an example using Google's SMTP servers:

Email email = EmailBuilder.startingBlank()
        .from("lollypop", "[email protected]")
        .to("C.Cane", "[email protected]")
        .withSubject("hey")
        .withPlainText("We should meet up!")
        .withHTMLText("<b>We should meet up!</b>")
        .buildEmail();

MailerBuilder.withSMTPServer("smtp.gmail.com", 25, "user", "pass", SMTP_TLS)
        .buildMailer()
        .sendMail(email);

MailerBuilder.withSMTPServer("smtp.gmail.com", 587, "user", "pass", SMTP_TLS)
        .buildMailer()
        .sendMail(email);

MailerBuilder.withSMTPServer("smtp.gmail.com", 465, "user", "pass", SMTP_SSL)
        .buildMailer()
        .sendMail(email);

If you have two-factor login turned on, you need to generate an application specific password from your Google account.

How can I count text lines inside an DOM element? Can I?

You should be able to split('\n').length and get the line breaks.

update: this works on FF/Chrome but not IE.

<html>
<head>
<script src="jquery-1.3.2.min.js"></script>
<script>
    $(document).ready(function() {
        var arr = $("div").text().split('\n');
        for (var i = 0; i < arr.length; i++)
            $("div").after(i + '=' + arr[i] + '<br/>');
    });
</script>
</head>
<body>
<div>One
Two
Three</div>
</body>
</html>

javascript jquery radio button click

it is always good to restrict the DOM search. so better to use a parent also, so that the entire DOM won't be traversed.

IT IS VERY FAST

<div id="radioBtnDiv">
  <input name="myButton" type="radio" class="radioClass" value="manual" checked="checked"/>
 <input name="myButton" type="radio" class="radioClass" value="auto" checked="checked"/>
</div>



 $("input[name='myButton']",$('#radioBtnDiv')).change(
    function(e)
    {
        // your stuffs go here
    });

Generate random numbers uniformly over an entire range

Of course, the following code won't give you random numbers but pseudo random number. Use the following code

#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )

For example:

int myRand = QUICK_RAND(10, 20);

You must call

srand(time(0));  // Initialize random number generator.

otherwise the numbers won't be near random.

Use of var keyword in C#

I split var all over the places, the only questionable places for me are internal short types, e.g. I prefer int i = 3; over var i = 3;

How to delete SQLite database from Android programmatically

Delete old Db when uninstall the app.

Setting android:allowBackup="false" in the application tag in AndroidManifest.xml fixed the problem. It seems that for some weird reason the Android OS was restoring from a backup every time I deployed the app.

How to load external webpage in WebView

Thanks to this post, I finally found the solution. Here is the code:

import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
import android.annotation.TargetApi;

public class Main extends Activity {

    private WebView mWebview ;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        mWebview  = new WebView(this);

        mWebview.getSettings().setJavaScriptEnabled(true); // enable javascript

        final Activity activity = this;

        mWebview.setWebViewClient(new WebViewClient() {
            @SuppressWarnings("deprecation")
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Toast.makeText(activity, description, Toast.LENGTH_SHORT).show();
            }
            @TargetApi(android.os.Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest req, WebResourceError rerr) {
                // Redirect to deprecated method, so you can use it in all SDK versions
                onReceivedError(view, rerr.getErrorCode(), rerr.getDescription().toString(), req.getUrl().toString());
            }
        });

        mWebview .loadUrl("http://www.google.com");
        setContentView(mWebview );

    }

}

DataTables fixed headers misaligned with columns in wide tables

Trigger DataTable search function after initializing DataTable with a blank string in it. It will automatically adjust misalignment of thead with tbody.

$( document ).ready(function()
{

    $('#monitor_data_voyage').DataTable( {
        scrollY:150,
        bSort:false,
        bPaginate:false,
        sScrollX: "100%",
        scrollX: true,
    } );

    setTimeout( function(){
       $('#monitor_data_voyage').DataTable().search( '' ).draw();
    }, 10 );

});

Reading Email using Pop3 in C#

I wouldn't recommend OpenPOP. I just spent a few hours debugging an issue - OpenPOP's POPClient.GetMessage() was mysteriously returning null. I debugged this and found it was a string index bug - see the patch I submitted here: http://sourceforge.net/tracker/?func=detail&aid=2833334&group_id=92166&atid=599778. It was difficult to find the cause since there are empty catch{} blocks that swallow exceptions.

Also, the project is mostly dormant... the last release was in 2004.

For now we're still using OpenPOP, but I'll take a look at some of the other projects people have recommended here.

Invalid length for a Base-64 char array

My initial guess without knowing the data would be that the UserNameToVerify is not a multiple of 4 in length. Check out the FromBase64String on msdn.

// Ok
byte[] b1 = Convert.FromBase64String("CoolDude");
// Exception
byte[] b2 = Convert.FromBase64String("MyMan");

Force browser to refresh css, javascript, etc

If you want to be sure that these files are properly refreshed by Chrome for all users, then you need to have must-revalidate in the Cache-Control header. This will make Chrome re-check files to see if they need to be re-fetched.

Recommend the following response header:

Cache-Control: must-validate

This tells Chrome to check with the server, and see if there is a newer file. If there is a newer file, it will receive it in the response. If not, it will receive a 304 response, and the assurance that the one in the cache is up to date.

If you do NOT set this header, then in the absence of any other setting that invalidates the file, Chrome will never check with the server to see if there is a newer version.

Here is a blog post that discusses the issue further.

How can I send an HTTP POST request to a server from Excel using VBA?

I did this before using the MSXML library and then using the XMLHttpRequest object, see here.

PHP Header redirect not working

Don't include header.php. You should not output HTML when you are going to redirect.

Make a new file, eg. "pre.php". Put this in it:

<?php
include('class.user.php');
include('class.Connection.php');
?>

Then in header.php, include that, in stead of including the two other files. In form.php, include pre.php in stead of header.php.

How do I get a human-readable file size in bytes abbreviation using .NET?

I assume you're looking for "1.4 MB" instead of "1468006 bytes"?

I don't think there is a built-in way to do that in .NET. You'll need to just figure out which unit is appropriate, and format it.

Edit: Here's some sample code to do just that:

http://www.codeproject.com/KB/cpp/formatsize.aspx

How do I deal with corrupted Git object files?

In general, fixing corrupt objects can be pretty difficult. However, in this case, we're confident that the problem is an aborted transfer, meaning that the object is in a remote repository, so we should be able to safely remove our copy and let git get it from the remote, correctly this time.

The temporary object file, with zero size, can obviously just be removed. It's not going to do us any good. The corrupt object which refers to it, d4a0e75..., is our real problem. It can be found in .git/objects/d4/a0e75.... As I said above, it's going to be safe to remove, but just in case, back it up first.

At this point, a fresh git pull should succeed.

...assuming it was going to succeed in the first place. In this case, it appears that some local modifications prevented the attempted merge, so a stash, pull, stash pop was in order. This could happen with any merge, though, and didn't have anything to do with the corrupted object. (Unless there was some index cleanup necessary, and the stash did that in the process... but I don't believe so.)

Increase permgen space

For tomcat you can increase the permGem space by using

 -XX:MaxPermSize=128m

For this you need to create (if not already exists) a file named setenv.sh in tomcat/bin folder and include following line in it

   export JAVA_OPTS="-XX:MaxPermSize=128m"

Reference : http://wiki.razuna.com/display/ecp/Adjusting+Memory+Settings+for+Tomcat

How to change visibility of layout programmatically

Use this Layout in your xml file

<LinearLayout
  android:id="@+id/contacts_type"
  android:orientation="horizontal"
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:visibility="gone">
</LinearLayout>

Define your layout in .class file

 LinearLayout linearLayout = (LinearLayout) findViewById(R.id.contacts_type);

Now if you want to display this layout just write

 linearLayout.setVisibility(View.VISIBLE);

and if you want to hide layout just write

 linearLayout.setVisibility(View.INVISIBLE);

How to use a typescript enum value in an Angular2 ngSwitch statement

This's simple and works like a charm :) just declare your enum like this and you can use it on HTML template

  statusEnum: typeof StatusEnum = StatusEnum;

Access the css ":after" selector with jQuery

You can add style for :after a like html code.
For example:

var value = 22;
body.append('<style>.wrapper:after{border-top-width: ' + value + 'px;}</style>');

Querying data by joining two tables in two database on different servers

If a linked server is not allowed by your dba, you can use OPENROWSET. Books Online will provide the syntax you need.

Write values in app.config file

If you are using App.Config to store values in <add Key="" Value="" /> or CustomSections section use ConfigurationManager class, else use XMLDocument class.

For example:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="server" value="192.168.0.1\xxx"/>
    <add key="database" value="DataXXX"/>
    <add key="username" value="userX"/>
    <add key="password" value="passX"/>
  </appSettings>
</configuration>

You could use the code posted on CodeProject

Formatting a Date String in React Native

The beauty of the React Native is that it supports lots of JS libraries like Moment.js. Using moment.js would be a better/easier way to handle date/time instead coding from scratch

just run this in the terminal (yarn add moment also works if using React's built-in package manager):

npm install moment --save

And in your React Native js page:

import Moment from 'moment';

render(){
    Moment.locale('en');
    var dt = '2016-05-02T00:00:00';
    return(<View> {Moment(dt).format('d MMM')} </View>) //basically you can do all sorts of the formatting and others
}

You may check the moment.js official docs here https://momentjs.com/docs/

int to string in MySQL

select t2.* 
from t1 join t2 on t2.url='site.com/path/%' + cast(t1.id as varchar)  + '%/more' 
where t1.id > 9000

Using concat like suggested is even better though

Multiple "order by" in LINQ

This should work for you:

var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)

How to tell git to use the correct identity (name and email) for a given project?

If you don't use the --global parameter it will set the variables for the current project only.

How do I exit a while loop in Java?

Take a look at the Java™ Tutorials by Oracle.

But basically, as dacwe said, use break.

If you can it is often clearer to avoid using break and put the check as a condition of the while loop, or using something like a do while loop. This isn't always possible though.

What is the difference between a generative and a discriminative algorithm?

My two cents: Discriminative approaches highlight differences Generative approaches do not focus on differences; they try to build a model that is representative of the class. There is an overlap between the two. Ideally both approaches should be used: one will be useful to find similarities and the other will be useful to find dis-similarities.

How can I convert a long to int in Java?

For small values, casting is enough:

long l = 42;
int i = (int) l;

However, a long can hold more information than an int, so it's not possible to perfectly convert from long to int, in the general case. If the long holds a number less than or equal to Integer.MAX_VALUE you can convert it by casting without losing any information.

For example, the following sample code:

System.out.println( "largest long is " + Long.MAX_VALUE );
System.out.println( "largest int is " + Integer.MAX_VALUE );

long x = (long)Integer.MAX_VALUE;
x++;
System.out.println("long x=" + x);

int y = (int) x;
System.out.println("int y=" + y);

produces the following output on my machine:

largest long is 9223372036854775807
largest int is 2147483647
long x=2147483648
int y=-2147483648

Notice the negative sign on y. Because x held a value one larger than Integer.MAX_VALUE, int y was unable to hold it. In this case, it wrapped around to the negative numbers.

If you wanted to handle this case yourself, you might do something like:

if ( x > (long)Integer.MAX_VALUE ) {
    // x is too big to convert, throw an exception or something useful
}
else {
    y = (int)x;
}

All of this assumes positive numbers. For negative numbers, use MIN_VALUE instead of MAX_VALUE.

Hibernate Criteria Restrictions AND / OR combination

For the new Criteria since version Hibernate 5.2:

CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<SomeClass> criteriaQuery = criteriaBuilder.createQuery(SomeClass.class);

Root<SomeClass> root = criteriaQuery.from(SomeClass.class);

Path<Object> expressionA = root.get("A");
Path<Object> expressionB = root.get("B");

Predicate predicateAEqualX = criteriaBuilder.equal(expressionA, "X");
Predicate predicateBInXY = expressionB.in("X",Y);
Predicate predicateLeft = criteriaBuilder.and(predicateAEqualX, predicateBInXY);

Predicate predicateAEqualY = criteriaBuilder.equal(expressionA, Y);
Predicate predicateBEqualZ = criteriaBuilder.equal(expressionB, "Z");
Predicate predicateRight = criteriaBuilder.and(predicateAEqualY, predicateBEqualZ);

Predicate predicateResult = criteriaBuilder.or(predicateLeft, predicateRight);

criteriaQuery
        .select(root)
        .where(predicateResult);

List<SomeClass> list = getSession()
        .createQuery(criteriaQuery)
        .getResultList();  

How to change the status bar color in Android?

Just create a new theme in res/values/styles.xml where you change the "colorPrimaryDark" which is the color of the status bar:

<style name="AppTheme.GrayStatusBar" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="colorPrimaryDark">@color/colorGray</item>
</style>

And modify the activity theme in AndroidManifest.xml to the one you want, on the next activity you can change the color back to the original one by selecting the original theme:

<activity
    android:name=".LoginActivity"
    android:theme="@style/AppTheme.GrayStatusBar" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

This is how your res/values/colors.xml should look like:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#c6d6f0</color>
    <color name="colorGray">#757575</color>
</resources>

Nested attributes unpermitted parameters

From the docs

To whitelist an entire hash of parameters, the permit! method can be used

params.require(:log_entry).permit!

Nested attributes are in the form of a hash. In my app, I have a Question.rb model accept nested attributes for an Answer.rb model (where the user creates answer choices for a question he creates). In the questions_controller, I do this

  def question_params

      params.require(:question).permit!

  end

Everything in the question hash is permitted, including the nested answer attributes. This also works if the nested attributes are in the form of an array.

Having said that, I wonder if there's a security concern with this approach because it basically permits anything that's inside the hash without specifying exactly what it is, which seems contrary to the purpose of strong parameters.

How do I vertically align text in a div?

<!DOCTYPE html>
<html>

  <head>
    <style>
      .container {
        height: 250px;
        background: #f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        align-items: center;
        -webkit-box-align: center;
        justify-content: center;
      }
      p{
        font-size: 24px;
      }
    </style>
  </head>

  <body>
    <div class="container">
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
    </div>
  </body>

</html>

Remove duplicates from an array of objects in JavaScript

What about this:

function dedupe(arr, compFn){
    let res = [];
    if (!compFn) compFn = (a, b) => { return a === b };
    arr.map(a => {if(!res.find(b => compFn(a, b))) res.push(a)});
    return res;
}

How to deselect all selected rows in a DataGridView control?

i found out why my first row was default selected and found out how to not select it by default.

By default my datagridview was the object with the first tab-stop on my windows form. Making the tab stop first on another object (maybe disabling tabstop for the datagrid at all will work to) disabled selecting the first row

What is the simplest way to swap each pair of adjoining chars in a string with Python?

To swap characters in a string a of position l and r

def swap(a, l, r):
    a = a[0:l] + a[r] + a[l+1:r] + a[l] + a[r+1:]
    return a

Example: swap("aaabcccdeee", 3, 7) returns "aaadcccbeee"

Default value of function parameter

The first way would be preferred to the second.

This is because the header file will show that the parameter is optional and what its default value will be. Additionally, this will ensure that the default value will be the same, no matter the implementation of the corresponding .cpp file.

In the second way, there is no guarantee of a default value for the second parameter. The default value could change, depending on how the corresponding .cpp file is implemented.

Getters \ setters for dummies

You can define instance method for js class, via prototype of the constructor.

Following is the sample code:

// BaseClass

var BaseClass = function(name) {
    // instance property
    this.name = name;
};

// instance method
BaseClass.prototype.getName = function() {
    return this.name;
};
BaseClass.prototype.setName = function(name) {
    return this.name = name;
};


// test - start
function test() {
    var b1 = new BaseClass("b1");
    var b2 = new BaseClass("b2");
    console.log(b1.getName());
    console.log(b2.getName());

    b1.setName("b1_new");
    console.log(b1.getName());
    console.log(b2.getName());
}

test();
// test - end

And, this should work for any browser, you can also simply use nodejs to run this code.

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

How can I uninstall Ruby on ubuntu?

Here is what sudo apt-get purge ruby* removed relating to GRUB for me:

grub-pc 
grub-gfxpayload-lists
grub2-common
grub-pc-bin 
grub-common 

How to add a vertical Separator?

I like to use the "Line" control. It gives you exact control over where the separator starts and ends. Although it isn't exactly a separator, it functions is the same way, especially in a StackPanel.

The line control works within a grid too. I prefer to use the StackPanel because you don't have to worry about different controls overlapping.

<StackPanel Orientation="Horizontal">
    <Button Content="Button 1" Height="20" Width="70"/>
    <Line X1="0" X2="0" Y1="0" Y2="20" Stroke="Black" StrokeThickness="0.5" Margin="5,0,10,0"/>
    <Button Content="Button 2" Height="20" Width="70"/>
</StackPanel>

X1 = x starting position (should be 0 for a vertical line)

X2 = x ending position (X1 = X2 for a vertical line)

Y1 = y starting position (should be 0 for a vertical line)

Y2 = y ending position (Y2 = desired line height)

I use "margin" to add padding on any side of the vertical line. In this instance, there are 5 pixels on the left and 10 pixels on the right of the vertical line.

Since the line control lets you pick the x and y coordinates of the start and end of the line, you can also use it for horizontal lines and lines at any angle in between.

How To Run PHP From Windows Command Line in WAMPServer

UPDATED After few research, best solution was to use that info another stackoverflow thread to avoid ctrl+z input and also from the scree output. So, instead of php -a you should use call "php.exe" -f NAMED_SCRIPT.php

OLD Readline not possible under Windows, so none of existent php shells written in php will work. But there's a workaround using -a interactive mode.

2 commmon problems here. You cannot see result until executes CTRL Z command to indicate the final of code/file like EOF. When you do, result in most cases is printed result and fast closed window. Anyway, you will be returned to cmd not the -a interactive mode.

Save this content into a .bat file, and define your PHP PATH into Windows variables, or modify php.exe to "full path to exe" instead:

::
:: PHP Shell launch wrapper
::
@ECHO off
call "php.exe" -a

echo.
echo.

call "PHP Shell.bat"

This is a simple Batch launching -a mode of php.exe. When it launchs php, stop script even no pause is wrote because is "into" the interactive waiting for input. When you hit CTRL Z, gets the SIGSTEP (next step) not the SIGSTOP (close, CTRL+C usually), then read the next intruction, wich is a recursive call to .bat itself. Because you're always into PHP -a mode, no exit command. You must use CTRL+C or hit the exit cross with mouse. (No alt+f4)

You can also use "Bat to Exe" converter to easy use.

List<Map<String, String>> vs List<? extends Map<String, String>>

What I'm missing in the other answers is a reference to how this relates to co- and contravariance and sub- and supertypes (that is, polymorphism) in general and to Java in particular. This may be well understood by the OP, but just in case, here it goes:

Covariance

If you have a class Automobile, then Car and Truck are their subtypes. Any Car can be assigned to a variable of type Automobile, this is well-known in OO and is called polymorphism. Covariance refers to using this same principle in scenarios with generics or delegates. Java doesn't have delegates (yet), so the term applies only to generics.

I tend to think of covariance as standard polymorphism what you would expect to work without thinking, because:

List<Car> cars;
List<Automobile> automobiles = cars;
// You'd expect this to work because Car is-a Automobile, but
// throws inconvertible types compile error.

The reason of the error is, however, correct: List<Car> does not inherit from List<Automobile> and thus cannot be assigned to each other. Only the generic type parameters have an inherit relationship. One might think that the Java compiler simply isn't smart enough to properly understand your scenario there. However, you can help the compiler by giving him a hint:

List<Car> cars;
List<? extends Automobile> automobiles = cars;   // no error

Contravariance

The reverse of co-variance is contravariance. Where in covariance the parameter types must have a subtype relationship, in contravariance they must have a supertype relationship. This can be considered as an inheritance upper-bound: any supertype is allowed up and including the specified type:

class AutoColorComparer implements Comparator<Automobile>
    public int compare(Automobile a, Automobile b) {
        // Return comparison of colors
    }

This can be used with Collections.sort:

public static <T> void sort(List<T> list, Comparator<? super T> c)

// Which you can call like this, without errors:
List<Car> cars = getListFromSomewhere();
Collections.sort(cars, new AutoColorComparer());

You could even call it with a comparer that compares objects and use it with any type.

When to use contra or co-variance?

A bit OT perhaps, you didn't ask, but it helps understanding answering your question. In general, when you get something, use covariance and when you put something, use contravariance. This is best explained in an answer to Stack Overflow question How would contravariance be used in Java generics?.

So what is it then with List<? extends Map<String, String>>

You use extends, so the rules for covariance applies. Here you have a list of maps and each item you store in the list must be a Map<string, string> or derive from it. The statement List<Map<String, String>> cannot derive from Map, but must be a Map.

Hence, the following will work, because TreeMap inherits from Map:

List<Map<String, String>> mapList = new ArrayList<Map<String, String>>();
mapList.add(new TreeMap<String, String>());

but this will not:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new TreeMap<String, String>());

and this will not work either, because it does not satisfy the covariance constraint:

List<? extends Map<String, String>> mapList = new ArrayList<? extends Map<String, String>>();
mapList.add(new ArrayList<String>());   // This is NOT allowed, List does not implement Map

What else?

This is probably obvious, but you may have already noted that using the extends keyword only applies to that parameter and not to the rest. I.e., the following will not compile:

List<? extends Map<String, String>> mapList = new List<? extends Map<String, String>>();
mapList.add(new TreeMap<String, Element>())  // This is NOT allowed

Suppose you want to allow any type in the map, with a key as string, you can use extend on each type parameter. I.e., suppose you process XML and you want to store AttrNode, Element etc in a map, you can do something like:

List<? extends Map<String, ? extends Node>> listOfMapsOfNodes = new...;

// Now you can do:
listOfMapsOfNodes.add(new TreeMap<Sting, Element>());
listOfMapsOfNodes.add(new TreeMap<Sting, CDATASection>());

How do I get the scroll position of a document?

Something like this should solve your problem:

$.getDocHeight = function(){
     var D = document;
     return Math.max(Math.max(D.body.scrollHeight,    D.documentElement.scrollHeight), Math.max(D.body.offsetHeight, D.documentElement.offsetHeight), Math.max(D.body.clientHeight, D.documentElement.clientHeight));
};

alert( $.getDocHeight() );

Ps: Call that function every time you need it, the alert is for testing purposes..

Quickest way to convert a base 10 number to any base in .NET?

I too was looking for a fast way to convert decimal number to another base in the range of [2..36] so I developed the following code. Its simple to follow and uses a Stringbuilder object as a proxy for a character buffer that we can index character by character. The code appears to be very fast compared to alternatives and a lot faster than initialising individual characters in a character array.

For your own use you might prefer to: 1/ Return a blank string rather than throw an exception. 2/ remove the radix check to make the method run even faster 3/ Initialise the Stringbuilder object with 32 '0's and remove the the line result.Remove( 0, i );. This will cause the string to be returned with leading zeros and further increase the speed. 4/ Make the Stringbuilder object a static field within the class so no matter how many times the DecimalToBase method is called the Stringbuilder object is only initialised the once. If you do this change 3 above would no longer work.

I hope someone finds this useful :)

AtomicParadox

        static string DecimalToBase(int number, int radix)
    {
        // Check that the radix is between 2 and 36 inclusive
        if ( radix < 2 || radix > 36 )
            throw new ArgumentException("ConvertToBase(int number, int radix) - Radix must be between 2 and 36.");

        // Create a buffer large enough to hold the largest int value represented in binary digits 
        StringBuilder result = new StringBuilder("                                ");  // 32 spaces

        // The base conversion calculates the digits in reverse order so use
        // an index to point to the last unused space in our buffer
        int i = 32; 

        // Convert the number to the new base
        do
        {
            int remainder = number % radix;
            number = number / radix;
            if(remainder <= 9)
                result[--i] = (char)(remainder + '0');  // Converts [0..9] to ASCII ['0'..'9']
            else
                result[--i] = (char)(remainder + '7');  // Converts [10..36] to ASCII ['A'..'Z']
        } while ( number > 0 );

        // Remove the unwanted padding from the front of our buffer and return the result
        // Note i points to the last unused character in our buffer
        result.Remove( 0, i );
        return (result.ToString());
    }

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

The answers here helped me up to a point, but I had a problem on HTML5 Number input fields when clicking the up/down buttons in Chrome.

If you click one of the buttons, and left the mouse over the button the number would keep changing as if you were holding the mouse button because the mouseup was being thrown away.

I solved this by removing the mouseup handler as soon as it had been triggered as below:

    $("input:number").focus(function () {
        var $elem = $(this);
        $elem.select().mouseup(function (e) {
            e.preventDefault();
            $elem.unbind(e.type);
        });
    });

Hope this helps people in the future...

How can I make an entire HTML form "readonly"?

You add html invisible layer over the form. For instance

<div class="coverContainer">
<form></form>
</div>

and style:

.coverContainer{
    width: 100%;
    height: 100%;
    z-index: 100;
    background: rgba(0,0,0,0);
    position: absolute;
}

Ofcourse user can hide this layer in web browser.

Trying to use fetch and pass in mode: no-cors

If you are using Express as back-end you just have to install cors and import and use it in app.use(cors());. If it is not resolved then try switching ports. It will surely resolve after switching ports

Only on Firefox "Loading failed for the <script> with source"

I ran in the same situation and the script was correctly loading in safe mode. However, disabling all the Add-ons and other Firefox security features didn't help. One thing I tried, and this was the solution in my case, was to temporary disable the cache from the developer window for this particular request. After I saw this was the cause, I wiped out the cache for that site and everything started word normally.

Getting value of HTML text input

See my jsFiddle here: http://jsfiddle.net/fuDBL/

Whenever you change the email field, the link is updated automatically. This requires a small amount of jQuery. So now your form will work as needed, but your link will be updated dynamically so that when someone clicks on it, it contains what they entered in the email field. You should validate the input on the receiving page.

$('input[name="email"]').change(function(){
  $('#regLink').attr('href')+$('input[name="email"]').val();
});

Cast to generic type in C#

You can't do that. You could try telling your problem from a more high level point of view (i.e. what exactly do you want to accomplish with the casted variable) for a different solution.

You could go with something like this:

 public abstract class Message { 
     // ...
 }
 public class Message<T> : Message {
 }

 public abstract class MessageProcessor {
     public abstract void ProcessMessage(Message msg);
 }
 public class SayMessageProcessor : MessageProcessor {
     public override void ProcessMessage(Message msg) {
         ProcessMessage((Message<Say>)msg);
     }
     public void ProcessMessage(Message<Say> msg) {
         // do the actual processing
     }
 }

 // Dispatcher logic:
 Dictionary<Type, MessageProcessor> messageProcessors = {
    { typeof(Say), new SayMessageProcessor() },
    { typeof(string), new StringMessageProcessor() }
 }; // properly initialized

 messageProcessors[msg.GetType().GetGenericArguments()[0]].ProcessMessage(msg);

How to reset the state of a Redux store?

I'd like to point out that the accepted comment by Dan Abramov is correct except we experienced a strange issue when using the react-router-redux package along with this approach. Our fix was to not set state to undefined but rather still use the current routing reducer. So I would suggest implementing the solution below if you are using this package

const rootReducer = (state, action) => {
  if (action.type === 'USER_LOGOUT') {
    const { routing } = state
    state = { routing } 
  }
  return appReducer(state, action)
}

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

How to automatically generate unique id in SQL like UID12345678?

CREATE TABLE dbo.tblUsers
(
    ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
    UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED, 
    [Name] VARCHAR(50) NOT NULL,
)

marc_s's Answer Snap

marc_s's Answer Snap

How to center cell contents of a LaTeX table whose columns have fixed widths?

You can use \centering with your parbox to do this.

More info here and here.

(Sorry for the Google cached link; the original one I had doesn't work anymore.)

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

You could just simply do the following

In your js

$scope.id = 0;

In your template

<div id="number-{{$scope.id}}"></div>

which will render

<div id="number-0"></div>

It is not necessary to concatenate inside double curly brackets.