Programs & Examples On #Vendor

error NG6002: Appears in the NgModule.imports of AppModule, but could not be resolved to an NgModule class

I had the same problem. I followed these steps (in this exact order, this is VERY important):

  1. Create child component in the "app.module.ts"
  2. Build the application
  3. Create parent component
  4. Build the application
  5. Create HTML archive
  6. Build the application

This happens mainly because Angular won't build those modules in the correct order, i.e before the HTML.

e.g My code:

_x000D_
_x000D_
  <mat-toolbar> <!-- 2 -->
    <button mat-icon-button class="example-icon" aria-label="Example icon-button with menu icon">
      <mat-icon>favorite</mat-icon> <!-- 1 -->
    </button>
    <span>My App</span>
    <span class="example-spacer"></span>
    <button mat-icon-button class="example-icon favorite-icon" aria-label="Example icon-button with heart icon">
    </button>
    <button mat-icon-button class="example-icon" aria-label="Example icon-button with share icon">
    </button>
  </mat-toolbar>
_x000D_
_x000D_
_x000D_

Can not find module “@angular-devkit/build-angular”

I've just encountered this problem and fixed it. I think the root cause of this problem is ng and current version of node.js (10.6.0) and accompanying npm are not in sync. I've installed the LTS version of node.js (8.11.3) and the problem disappeared.

Could not find module "@angular-devkit/build-angular"

I resolved this by installing Angular on a 64 bit operating system. I was getting the error because I was initially running it on a 32 bit OS

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Your can use DataSourceBuilder for this purpose.

@Primary
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource(Environment env) {
    final String datasourceUsername = env.getRequiredProperty("spring.datasource.username");
    final String datasourcePassword = env.getRequiredProperty("spring.datasource.password");
    final String datasourceUrl = env.getRequiredProperty("spring.datasource.url");
    final String datasourceDriver = env.getRequiredProperty("spring.datasource.driver-class-name");
    return DataSourceBuilder
            .create()
            .username(datasourceUsername)
            .password(datasourcePassword)
            .url(datasourceUrl)
            .driverClassName(datasourceDriver)
            .build();
}

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

You can specify maven source/target version by adding these properties to your pom.xml file

<properties>
    <maven.compiler.source>1.6</maven.compiler.source>
    <maven.compiler.target>1.6</maven.compiler.target>
</properties>

No provider for Http StaticInjectorError

I was trying to fix the issue for about an hour and just deiced to restart the server. Only to see the issue is fixed.

If you make changes to APP module and the issue remains the same, stop the server and try running the serve command again.

Using ionic 4 with angular 7

No provider for HttpClient

I was facing the same problem, then in my app.module.ts I updated the file this way,

import { HttpModule } from '@angular/http';
import { HttpClientModule } from '@angular/common/http';

and in the same file (app.module.ts) in my @NgModule imports[]array I wrote this way,

HttpModule,
HttpClientModule

"The specified Android SDK Build Tools version (26.0.0) is ignored..."

just clean and make project / rebuilt fixed my issue give a try :-)

ERROR in ./node_modules/css-loader?

My case:

Missing node-sass in package.json

Solution:

  1. npm i --save node-sass@latest
  2. remove node-modules folder
  3. npm i
  4. check "@angular-devkit/build-angular": "^0.901.0" version in package.json

PHP Parse error: syntax error, unexpected '?' in helpers.php 233

If you have newly upgraded your php version you might be forget to restart your webserver service.

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

As pointed out here you must use the script in the UMD subdirectory, in my case

        bundles.Add(new ScriptBundle("~/bundles/projectbundle").Include(
            "~/Scripts/umd/popper.js",
            "~/Scripts/bootstrap.js",
            "~/Scripts/respond.js",
            "~/Scripts/summernote-bs4.js"));

Specifically this: "~/Scripts/umd/popper.js",

How do I fix maven error The JAVA_HOME environment variable is not defined correctly?

I have removed JAVA_HOME variable and kept only path and classpath variables by pointing them to jdk and jre respectively. It worked for me.

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

Why isn't this code to plot a histogram on a continuous value Pandas column working?

Here's another way to plot the data, involves turning the date_time into an index, this might help you for future slicing

#convert column to datetime
trip_data['lpep_pickup_datetime'] = pd.to_datetime(trip_data['lpep_pickup_datetime'])
#turn the datetime to an index
trip_data.index = trip_data['lpep_pickup_datetime']
#Plot
trip_data['Trip_distance'].plot(kind='hist')
plt.show()

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

A somewhat unlikely situation.

I have removed the yarn.lock file, which referenced an older version of webpack.

So check to see the differences in your yarn.lock file as a possiblity.

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

How to decrease prod bundle size?

Check you have configuration named "production" for ng build --prod, since it is shorthand for ng build --configuration=production No answer solved my problem, because the problem was sitting right in front of the screen. I think this might be quite common... I've internationalized the app with i18n renaming all configurations to e.g. production-en. Then I built with ng build --prod assuming, that the default optimization is used and should be close to optimal, but in fact just ng build has been executed resulting in 7mb bundle instead of 250kb.

require(vendor/autoload.php): failed to open stream

What you're missing is running composer install, which will import your packages and create the vendor folder, along with the autoload script.

Make sure your relative path is correct. For example the example scripts in PHPMailer are in examples/, below the project root, so the correct relative path to load the composer autoloader from there would be ../vendor/autoload.php.

The autoload.php you found in C:\Windows\SysWOW64\vendor\autoload.php is probably a global composer installation – where you'll usually put things like phpcs, phpunit, phpmd etc.

composer update is not the same thing, and probably not what you want to use. If your code is tested with your current package versions then running update may cause breakages which may require further work and testing, so don't run update unless you have a specific reason to and understand exactly what it means. To clarify further – you should probably only ever run composer update locally, never on your server as it is reasonably likely to break apps in production.

I often see complaints that people can't use composer because they can't run it on their server (e.g. because it's shared and they have no shell access). In that case, you can still use composer: run it locally (an environment that has no such restrictions), and upload the local vendor folder it generates along with all your other PHP scripts.

Running composer update also performs a composer install, and if you do not currently have a vendor folder (normal if you have a fresh checkout of a project), then it will create one, and also overwrite any composer.lock file you already have, updating package versions tagged in it, and this is what is potentially dangerous.

Similarly, if you do not currently have a composer.lock file (e.g. if it was not committed to the project), then composer install also effectively performs a composer update. It's thus vital to understand the difference between the two as they are definitely not interchangeable.

It is also possible to update a single package by naming it, for example:

composer update ramsey/uuid

This will re-resolve the version specified in your composer.json and install it in your vendor folder, and update your composer.lock file to match. This is far less likely to cause problems than a general composer update if you just need a specific update to one package.

It is normal for libraries to not include a composer.lock file of their own; it's up to apps to fix versions, not the libraries they use. As a result, library developers are expected to maintain compatibility with a wider range of host environments than app developers need to. For example, a library might be compatible with Laravel 5, 6, 7, and 8, but an app using it might require Laravel 8 for other reasons.

Composer 2.0 (out soon) should remove any remaining inconsistencies between install and update results.

Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed

For those who use Gradle instead of Maven, add this to the dependencies in your build file:

compile('javax.xml.bind:jaxb-api:2.3.0')

Didn't find class "com.google.firebase.provider.FirebaseInitProvider"?

This issue occurred when I switched to Android Studio 3.4 with Android Gradle plugin 3.4.0. which works with the R8 compiler.

The Android Gradle plugin includes additional predefined ProGuard rules files, but it is recommended that you use proguard-android-optimize.txt. More info here.

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile(
          'proguard-android-optimize.txt'),
          // List additional ProGuard rules for the given build type here. By default,
          // Android Studio creates and includes an empty rules file for you (located
          // at the root directory of each module).
          'proguard-rules.pro'
    }
}

Angular 2 : No NgModule metadata found

I finally found the solution.

  1. Remove webpack by using following command.
npm remove webpack
  1. Install cli by using following command.
npm install --save-dev @angular/cli@latest

after successfully test app, it will work :)

If not then follow below steps:

  1. Delete node_module folder.
  2. Clear cache by using following command.
npm cache clean --force
  1. Install node packages by using following command.
npm install
  1. Install angular@cli by using following command.
npm install --save-dev @angular/cli@latest

Note: If failed, try step 4 again. It will work.

"Please provide a valid cache path" error in laravel

You need to create folders inside "framework". Please Follow these steps:

cd storage/
mkdir -p framework/{sessions,views,cache}

You also need to set permissions to allow Laravel to write data in this directory.

chmod -R 775 framework
chown -R www-data:www-data framework

Node Sass couldn't find a binding for your current environment

Worked for me:

Just delete the node-sass folder and run npm install.

How to add bootstrap to an angular-cli project

Now with new ng-bootstrap 1.0.0-beta.5 version supports most of the native Angular directives based on Bootstrap's markup and CSS.

The only dependency required to work with this is bootstrap. No Need to use jquery and popper.js dependencies.

ng-bootstrap is to completely replaced JavaScript implementation for components. So you don't need to include bootstrap.min.js in the scripts section in your .angular-cli.json.

follow these steps when you are integrating bootstrap with generated project with angular-cli latest version.

  • Inculde bootstrap.min.css in your .angular-cli.json, styles section.

    "styles": [
       "styles.scss",
       "../node_modules/bootstrap/dist/css/bootstrap.min.css"
    ],
    
  • Install ng-bootstrap dependency.

    npm install --save @ng-bootstrap/ng-bootstrap
    
  • Add this to your main module class.

    import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
    
  • Include the following in your main module imports section.

    @NgModule({
       imports: [NgbModule.forRoot(), ...],
    })
    
  • Do the following also in your sub module(s) if you are going to use ng-bootstrap components inside those module classes.

    import {NgbModule} from '@ng-bootstrap/ng-bootstrap';
    
    @NgModule({
       imports: [NgbModule, ...],
    })
    
  • Now your project is ready to use available ng-bootstrap components.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Add Favicon with React and Webpack

The correct answer in the present if you dont use Create React App is the next:

new HtmlWebpackPlugin({
   favicon: "./public/fav-icon.ico"
})

If you use CRA then you can modificate the manifest.json in the public directory

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Some other service may be using port 80: try to stop the other services: HTTPD, SSL, NGINX, PHP, with the command sudo systemctl stop and then use the command sudo systemctl start httpd

Session 'app': Error Installing APK

In my case with Android 8.0(Oreo), no one of this solutions worked! If you have more than 1 user, then you should go to Settings->Applications->All Applications->Find the application and uninstall for all users! After this steps, it worked!

Angular 2 - View not updating after model changes

In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:

  • ChangeDetectorRef.detectChanges()
  • ChangeDetectorRef.markForCheck()
  • ApplicationRef.tick()

Uncaught TypeError: $(...).datepicker is not a function(anonymous function)

Including more than one reference to Jquery library is the reason for the error Only Include one reference to the Jquery library and that will resolve the issue

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

I've had this issue, adding --recursive to the command will help.

At this point it doesn't quite make sense as you (like me) are only trying to copy a single file down, but it does the trick!

Nginx: Job for nginx.service failed because the control process exited

Try set a user in nginx.conf, maybe that's why he can not start the service:

User www-data;

Forward X11 failed: Network error: Connection refused

Other answers are outdated, or incomplete, or simply don't work.

You need to also specify an X-11 server on the host machine to handle the launch of GUId programs. If the client is a Windows machine install Xming. If the client is a Linux machine install XQuartz.

Now suppose this is Windows connecting to Linux. In order to be able to launch X11 programs as well over putty do the following:

- Launch XMing on Windows client
- Launch Putty
    * Fill in basic options as you know in session category
    * Connection -> SSH -> X11
        -> Enable X11 forwarding
        -> X display location = :0.0
        -> MIT-Magic-Cookie-1
        -> X authority file for local display = point to the Xming.exe executable

Of course the ssh server should have permitted Desktop Sharing "Allow other user to view your desktop".

MobaXterm and other complete remote desktop programs work too.

Allowed memory size of 536870912 bytes exhausted in Laravel

for xampp it there is in xampp\php\php.ini now mine new option in it looks as :

;Maximum amount of memory a script may consume
;http://php.net/memory-limit
memory_limit=2048M
;memory_limit=512M

Failed to authenticate on SMTP server error using gmail

I had the same issue, but when I ran the following command, it was ok:

php artisan config:cache

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

You have enabled CORS and enabled Access-Control-Allow-Origin : * in the server.If still you get GET method working and POST method is not working then it might be because of the problem of Content-Type and data problem.

First AngularJS transmits data using Content-Type: application/json which is not serialized natively by some of the web servers (notably PHP). For them we have to transmit the data as Content-Type: x-www-form-urlencoded

Example :-

        $scope.formLoginPost = function () {
            $http({
                url: url,
                method: "POST",
                data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
            }).then(function (response) {
                // success
                console.log('success');
                console.log("then : " + JSON.stringify(response));
            }, function (response) { // optional
                // failed
                console.log('failed');
                console.log(JSON.stringify(response));
            });
        };

Note : I am using $.params to serialize the data to use Content-Type: x-www-form-urlencoded. Alternatively you can use the following javascript function

function params(obj){
    var str = "";
    for (var key in obj) {
        if (str != "") {
            str += "&";
        }
        str += key + "=" + encodeURIComponent(obj[key]);
    }
    return str;
}

and use params({ 'username': $scope.username, 'Password': $scope.Password }) to serialize it as the Content-Type: x-www-form-urlencoded requests only gets the POST data in username=john&Password=12345 form.

Docker command can't connect to Docker daemon

For Ubuntu:
Happened with me when I updated docker.
You need to unmask the service and socket and then restart the service.

Following worked for me:

systemctl unmask docker.service
systemctl unmask docker.socket
systemctl start docker.service

What happend behind the scenes
systemd also has the ability to mark a unit as completely unstartable, automatically or manually, by linking it to /dev/null. This is called masking the unit, and is possible with the mask command.

sudo systemctl mask docker.service

You can check the list of masked services using:

sudo systemctl list-unit-files

Output of sudo systemctl list-unit-files

To enable auto/manual start of service you need to unmask it using:

sudo sytemctl unmask docker.service

Now the service will be enabled as shown below enter image description here

ImportError: No module named pandas

I fixed the same problem with the below commands... Type python on your terminal. If you see python version 2.x then run these two commands to install pandas:

sudo python -m pip install wheel

and

sudo python -m pip install pandas

Else if you see python version 3.x then run these two commands to install pandas:

sudo python3 -m pip install wheel

and

sudo python3 -m pip install pandas

Good Luck!

Spring - No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call

I removed the mode from

<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />

to make this work

Set adb vendor keys

I tried almost anything but no help...

Everytime was just this

?  ~ adb devices    
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
aeef5e4e    unauthorized

However I've managed to connect device!

There is tutor, step by step.

  1. Remove existing adb keys on PC:

$ rm -v .android/adbkey* .android/adbkey .android/adbkey.pub

  1. Remove existing authorized adb keys on device, path is /data/misc/adb/adb_keys

  2. Now create new adb keypair

? ~ adb keygen .android/adbkey adb I 47453 711886 adb_auth_host.cpp:220] generate_key '.android/adbkey' adb I 47453 711886 adb_auth_host.cpp:173] Writing public key to '.android/adbkey.pub'

  1. Manually copy from PC .android/adbkey.pub (pubkic key) to Device on path /data/misc/adb/adb_keys

  2. Reboot device and check adb devices :

? ~ adb devices List of devices attached aeef5e4e device

Permissions of /data/misc/adb/adb_keys are (766/-rwxrw-rw-) on my device

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

In case it helps anyone, the solution mentioned in this other question worked for me when pip stopped working today after upgrading it: Pip broken after upgrading

It seems that it's an issue when a previously cached location changes, so you can refresh the cache with this command:

hash -r

Android ADB devices unauthorized

I had this problem and it wasnt solved by the deleting of any keys (at least deleting them didnt fix it, maybe had an effect after i did fix it though)

I actually had a discrepancy between my sdk-tools version and my Android Studio version. After updating my tools it still didnt work, but after updating AS (to 1.4) everything worked fine again.

Always update both sdk-tools and AS version together ;)

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I saw it's solved, but I still want to share a solution which worked for me.

.env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=[your database name]
DB_USERNAME=[your MySQL username]
DB_PASSWORD=[your MySQL password]

MySQL admin:

 SELECT user, host FROM mysql.user

Thank you, spencer7593

Console:

php artisan cache:clear
php artisan config:cache

Now it works for me.

Laracasts answers

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I know it's already an old question, but i had the same error today. For me setting the connection variable on model did the work.

/**
 * Table properties
 */
protected $connection = 'mysql-utf8';
protected $table = 'notification';
protected $primaryKey = 'id';

I don't know if the issue was with the database (probably), but the texts fields with special chars (like ~, ´ e etc) were all messed up.

---- Editing

That $connection var is used to select wich db connection your model will use. Sometimes it happens that in database.php (under /config folder) you have multiples connections and the default one is not using UTF-8 charset.

In any case, be sure to properly use charset and collation into your connection.

'connections' => [

    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'your_database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', 'database_password'),
        'unix_socket' => env('DB_SOCKET', ''),
        'prefix' => '',
        'strict' => false,
        'engine' => null
    ],

    'mysql-utf8' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'your_database'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', 'database_password'),
        'unix_socket' => env('DB_SOCKET', ''),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix' => '',
        'strict' => false,
        'engine' => null
    ],

Impact of Xcode build options "Enable bitcode" Yes/No

Make sure to select "All" to find the enable bitcode build settings:

Build settings

New warnings in iOS 9: "all bitcode will be dropped"

Method canOpenUrl is in iOS 9 (due to privacy) changed and is not free to use any more. Your banner provider checks for installed apps so that they do not show banners for an app that is already installed.

That gives all the log statements like

-canOpenURL: failed for URL: "kindle://home" - error: "This app is not allowed to query for scheme kindle"

The providers should update their logic for this.

If you need to query for installed apps/available schemes you need to add them to your info.plist file.

Add the key 'LSApplicationQueriesSchemes' to your plist as an array. Then add strings in that array like 'kindle'.

Of course this is not really an option for the banner ads (since those are dynamic), but you can still query that way for your own apps or specific other apps like Twitter and Facebook.

Documentation of the canOpenUrl: method canOpenUrl:

Documentation about the LSApplicationQueriesSchemes key

How to set up file permissions for Laravel?

Just to state the obvious for anyone viewing this discussion.... if you give any of your folders 777 permissions, you are allowing ANYONE to read, write and execute any file in that directory.... what this means is you have given ANYONE (any hacker or malicious person in the entire world) permission to upload ANY file, virus or any other file, and THEN execute that file...

IF YOU ARE SETTING YOUR FOLDER PERMISSIONS TO 777 YOU HAVE OPENED YOUR SERVER TO ANYONE THAT CAN FIND THAT DIRECTORY. Clear enough??? :)

There are basically two ways to setup your ownership and permissions. Either you give yourself ownership or you make the webserver the owner of all files.

Webserver as owner (the way most people do it, and the Laravel doc's way):

assuming www-data (it could be something else) is your webserver user.

sudo chown -R www-data:www-data /path/to/your/laravel/root/directory

if you do that, the webserver owns all the files, and is also the group, and you will have some problems uploading files or working with files via FTP, because your FTP client will be logged in as you, not your webserver, so add your user to the webserver user group:

sudo usermod -a -G www-data ubuntu

Of course, this assumes your webserver is running as www-data (the Homestead default), and your user is ubuntu (it's vagrant if you are using Homestead).

Then you set all your directories to 755 and your files to 644... SET file permissions

sudo find /path/to/your/laravel/root/directory -type f -exec chmod 644 {} \;    

SET directory permissions

sudo find /path/to/your/laravel/root/directory -type d -exec chmod 755 {} \;

Your user as owner

I prefer to own all the directories and files (it makes working with everything much easier), so, go to your laravel root directory:

cd /var/www/html/laravel >> assuming this is your current root directory
sudo chown -R $USER:www-data .

Then I give both myself and the webserver permissions:

sudo find . -type f -exec chmod 664 {} \;   
sudo find . -type d -exec chmod 775 {} \;

Then give the webserver the rights to read and write to storage and cache

Whichever way you set it up, then you need to give read and write permissions to the webserver for storage, cache and any other directories the webserver needs to upload or write too (depending on your situation), so run the commands from bashy above :

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

Now, you're secure and your website works, AND you can work with the files fairly easily

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

I resolved this issue by switching to the oracle jdk from open jdk 8.

$ java -version java version "1.8.0_221" Java(TM) SE Runtime Environment (build 1.8.0_221-b11) Java HotSpot(TM) 64-Bit Server VM (build 25.221-b11, mixed mode)

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

How to combine multiple inline style objects?

Ways of inline styling:

<View style={[styles.red, {fontSize: 25}]}>
  <Text>Hello World</Text>
</View>

<View style={[styles.red, styles.blue]}>
  <Text>Hello World</Text>
</View>

  <View style={{fontSize:10,marginTop:10}}>
  <Text>Hello World</Text>
</View>

Choose folders to be ignored during search in VS Code

Exclude all from subfolders works like this (version 2019)

include

./db

exclude

./db/*

Fatal error: Class 'Illuminate\Foundation\Application' not found

I had accidentally commented out:

require __DIR__.'/../bootstrap/autoload.php';

in /public/index.php

When pasting in some debugging statements.

UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory'

Well, you're getting a java.lang.NoClassDefFoundError. In your pom.xml, hibernate-core version is 3.3.2.GA and declared after hibernate-entitymanager, so it prevails. You can remove that dependency, since will be inherited version 3.6.7.Final from hibernate-entitymanager.

You're using spring-boot as parent, so no need to declare version of some dependencies, since they are managed by spring-boot.

Also, hibernate-commons-annotations is inherited from hibernate-entitymanager and hibernate-annotations is an old version of hibernate-commons-annotations, you can remove both.

Finally, your pom.xml can look like this:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.elsys.internetprogramming.trafficspy.server</groupId>
    <artifactId>TrafficSpyService</artifactId>
    <version>0.1.0</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.3.RELEASE</version>
    </parent>

    <dependencies>
        <!-- Spring -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cloud-connectors</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <dependency>
            <groupId>org.eclipse.persistence</groupId>
            <artifactId>javax.persistence</artifactId>
            <version>2.0.0</version>
        </dependency>

        <!-- Hibernate -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
        </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>

    <properties>
        <java.version>1.7</java.version>
    </properties>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </repository>

        <repository>
            <id>codehaus</id>
            <url>http://repository.codehaus.org/org/codehaus</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <url>https://repo.spring.io/libs-release</url>
        </pluginRepository>
    </pluginRepositories>

</project>

Let me know if you have a problem.

Error: Unable to run mksdcard SDK tool

This worked for me on Ubuntu 15.04

sudo aptitude install lib32stdc++6

Firstly, I installed aptitude, which helps in installing other dependencies too.

Managing jQuery plugin dependency in webpack

Add this to your plugins array in webpack.config.js

new webpack.ProvidePlugin({
    'window.jQuery': 'jquery',
    'window.$': 'jquery',
})

then require jquery normally

require('jquery');

If pain persists getting other scripts to see it, try explicitly placing it in the global context via (in the entry js)

window.$ = jQuery;

How to make custom dialog with rounded corners in android

For anyone who like do things in XML, specially in case where you are using Navigation architecture component actions in order to navigate to dialogs

You can use:

<style name="DialogStyle" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">

    <!-- dialog_background is drawable shape with corner radius -->
    <item name="android:background">@drawable/dialog_background</item>

    <item name="android:windowBackground">@android:color/transparent</item>
</style>

Laravel 5 Class 'form' not found

In Laravel Version - 4, HTML and Form existed, but not now.

Why:

The only reason is they have collected some user requirements and they want it more lightweight and so they removed it as in the sense that a user can add it manually.

What to do to add HTML & Forms in Laravel 5.2 or 5.3:

For 5.2:

Go to the Laravel Collective site and installation processes have demonstrated their.

Like for 5.2: on the command line, run the command

composer require "laravelcollective/html":"^5.2.0"

Then, in the provider array which is in config/app.php. Add this line at last using a comma(,):

Collective\Html\HtmlServiceProvider::class,

For using HTML and FORM text we need to alias them in the aliases array of config/app.php. Add the two lines at the last

'Form' => Collective\Html\FormFacade::class,
'Html' => Collective\Html\HtmlFacade::class,

And for 5.3:

Just run the command

composer require "laravelcollective/html":"^5.3.0"

And the rest of the procedure is like 5.2.

Then you can use Laravel Form and other HTML links in your projects. For this, follow this documentation:

5.2: https://laravelcollective.com/docs/5.2/html

5.3: https://laravelcollective.com/docs/5.3/html

Demo Code:

To open a form, open and close a tag:

{!! Form::open(['url' => 'foo/bar']) !!}

{!! Form::close() !!}

And for creating label and input text with a Bootstrap form-control class and other use:

{!! Form::label('title', 'Post Title') !!}
{!! Form::text('title', null, array('class' => 'form-control')) !!}

And for more, use the documentation, https://laravelcollective.com/.

Redirect to external URL with return in laravel

Define the url you want to redirect in $url

Then just use

return Redirect::away($url);

If you want to redirect inside your views use

return Redirect::to($url);

Read more about Redirect here

Update 1 :

Here is the simple example

return Redirect::to('http://www.google.com');

Update 2 :

As the Questioner wants to return in the same page

$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;

Laravel 5 Failed opening required bootstrap/../vendor/autoload.php

I also had that error. But none of the above solved the issue. So i uninstalled and again installed the composer. Then i did composer update. and the problem was fixed.

How to get DropDownList SelectedValue in Controller in MVC

Thanks - this helped me to understand better ansd solve a problem I had. The JQuery provided to get the text of selectedItem did NOT wwork for me I changed it to

$(function () {
  $("#SelectedVender").on("change", function () {
   $("#SelectedvendorText").val($(**"#SelectedVender option:selected"**).text());
  });
});

System.loadLibrary(...) couldn't find native library in my case

Try to call your library after include PREBUILT_SHARED_LIBRARY section:

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := <PATH>/libcalculate.so
include $(PREBUILT_SHARED_LIBRARY)

#...

LOCAL_SHARED_LIBRARIES += libcalculate

Update:

If you will use this library in Java you need compile it as shared library

LOCAL_PATH := $(call my-dir)

include $(CLEAR_VARS)
LOCAL_MODULE    := libcalculate
LOCAL_SRC_FILES := <PATH>/libcalculate.so
include $(BUILD_SHARED_LIBRARY)

And you need deploy the library in the /vendor/lib directory.

java.lang.UnsatisfiedLinkError: dalvik.system.PathClassLoader

This helped me. Sharing it for someone who might come up with same issue.

android {
    ....
    defaultConfig {
        ....
        ndk {
            abiFilters "armeabi", "armeabi-v7a", "x86", "mips"
        }
    }
}

Laravel PHP Command Not Found

I set the PATH,but it didn't work.I find other way to solve it. (OSX 10.10 & laravel 5.2)
1) find the executable file:

~/.composer/vendor/laravel/installer/laravel 

2) give execute permissions:

chmod +x ~/.composer/vendor/laravel/installer/laravel 

3) make a soft link to /usr/bin:

sudo ln -s /Users/zhao/.composer/vendor/laravel/installer/laravel /usr/bin/laravel

Maven error :Perhaps you are running on a JRE rather than a JDK?

This is because of running jre rather than jdk, to install jdk follow below steps

Installing java 8 in amazon linux/redhat

--> yum search java | grep openjdk

--> yum install java-1.8.0-openjdk-headless.x86_64

--> yum install java-1.8.0-openjdk-devel.x86_64

--> update-alternatives --config java #pick java 1.8 and press 1

--> update-alternatives --config javac #pick java 1.8 and press 2

Thank You

Spring Boot, Spring Data JPA with multiple DataSources

I have written a complete article at Spring Boot JPA Multiple Data Sources Example. In this article, we will learn how to configure multiple data sources and connect to multiple databases in a typical Spring Boot web application. We will use Spring Boot 2.0.5, JPA, Hibernate 5, Thymeleaf and H2 database to build a simple Spring Boot multiple data sources web application.

Specify path to node_modules in package.json

Yarn supports this feature:

# .yarnrc file in project root
--modules-folder /node_modules

But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.

Problems using Maven and SSL behind proxy

I ran into this problem in the same situation, and I wrote up a detailed answer to a related question on stack overflow explaining how to more easily modify the system's cacerts using a GUI tool. I think it's a little bit better than using a one-off keystore for a specific project or modifying the settings for maven (which may cause trouble down the road).

How to place the ~/.composer/vendor/bin directory in your PATH?

On Fedora:

Some composer bins are not in the .composer directory So you need to locate them using:

locate composer | grep vendor/bin

Then echo the the part into the .bashrc

echo 'export PATH="$PATH:$HOME/{you_composer_vendor_path}"' >> ~/.bashrc

Mine was "/.config/composer/vendor/bin" Cheers!

How do I import a specific version of a package using go get?

Really surprised nobody has mentioned gopkg.in.

gopkg.in is a service that provides a wrapper (redirect) that lets you express versions as repo urls, without actually creating repos. E.g. gopkg.in/yaml.v1 vs gopkg.in/yaml.v2, even though they both live at https://github.com/go-yaml/yaml

This isn't perfect if the author is not following proper versioning practices (by incrementing the version number when breaking backwards compatibility), but it does work with branches and tags.

Why am I getting a "401 Unauthorized" error in Maven?

I've had similar errors when trying to deploy a Gradle artefact to a Nexus Sonatype repository. You will get a 401 Unauthorized error if you supply the wrong credentials (password etc). You also get an error (and off the top of my head is also a 401) if you try to publish something to a releases repository and that version already exists in the repository. So you might find that by publishing from the command line it works, but then when you do it from a script it fails (because it didn't exist in the repository the first time around). Either publish using a different version number, or delete the old artefact on the server and republish.

The SNAPSHOTS repository (as opposed to the releases repository) allows you to overwrite a similarly numbered version, but your version number should have "-SNAPSHOT" at the end of it.

Composer Update Laravel

When you run composer update, composer generates a file called composer.lock which lists all your packages and the currently installed versions. This allows you to later run composer install, which will install the packages listed in that file, recreating the environment that you were last using.

It appears from your log that some of the versions of packages that are listed in your composer.lock file are no longer available. Thus, when you run composer install, it complains and fails. This is usually no big deal - just run composer update and it will attempt to build a set of packages that work together and write a new composer.lock file.

However, you're running into a different problem. It appears that, in your composer.json file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate command. This can be avoided by running the following: composer update --no-scripts

This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.

However, this does not solve the problem long-term. There are two problems:

  1. A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.

  2. Assets should not be compiled each time you run composer update. Remove that step from the composer.json file.

From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.

Can't start Tomcat as Windows Service

The simplest answer that worked for me was the one mentioned by Prashant, and edited by Bluish.

Go to Start > Configure Tomcat > Startup > Mode = Java Shutdown > Mode = Java

Unfortunately I had(and possibly others) to do this in a different way, I went to the tomcat bin directory and ran the "tomcat7w" application, which is how I changed the configuration.

There I was able to change the startup mode and shutdown mode to Java. Like this:

Step1) Locate tomcat7w:

general location => %TomCatHomeDIR%/bin In my case tomcat was in the xampp folder so my address was:

C:\xampp\tomcat\bin

tomcat7w file location screenshot

Step2) Launch tomcat7w && change the Mode in the Startup and Shutdown tabs

tomcat7w startup tab screenshot

Note >This based on version 7.0.22 that comes standard with XAMPP.

Cannot get OpenCV to compile because of undefined references?

This is a linker issue. Try:

g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`

This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:

sudo ldconfig

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Here what I did in the similar case.

That sitatuation means that same entity has already been existed in the context.So following can help

First check from ChangeTracker if the entity is in the context

var trackedEntries=GetContext().ChangeTracker.Entries<YourEntityType>().ToList();

var isAlreadyTracked =
                    trackedEntries.Any(trackedItem => trackedItem.Entity.Id ==myEntityToSave.Id);

If it exists

  if (isAlreadyTracked)
            {
                myEntityToSave= trackedEntries.First(trackedItem => trackedItem.Entity.Id == myEntityToSave.Id).Entity;
            } 

else
{
//Attach or Modify depending on your needs
}

use "netsh wlan set hostednetwork ..." to create a wifi hotspot and the authentication can't work correctly

Use these commands on a windows command prompt(cmd) with administrator privilege (run as administrator):

netsh wlan set hostednetwork mode=allow ssid=tests key=tests123

netsh wlan start hostednetwork

Then you go to Network and sharing center and click on "change adapter settings" (I'm using windows 7, it can be a little different on windows 8)

Then right click on the lan connection (internet connection that you are using), properties.

Click on sharing tab, select the wireless connection tests (the name tests you can change on the command line) and check "Allow other network users to connect through this network connection"

This done, your connection is ready to use!

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

Concat scripts in order with Gulp

merge2 looks like the only working and maintained ordered stream merging tool at the moment.

Update 2020

The APIs are always changing, some libraries become unusable or contain vulnerabilities, or their dependencies contain vulnerabilities, that are not fixed for years. For text files manipulations you'd better use custom NodeJS scripts and popular libraries like globby and fs-extra along with other libraries without Gulp, Grunt, etc wrappers.

import globby from 'globby';
import fs from 'fs-extra';

async function bundleScripts() {
    const rootPaths = await globby('./source/js/*.js');
    const otherPaths = (await globby('./source/**/*.js'))
        .filter(f => !rootFiles.includes(f));
    const paths = rootPaths.concat(otherPaths);

    const files = Promise.all(
        paths.map(
            // Returns a Promise
            path => fs.readFile(path, {encoding: 'utf8'})
        )
    );

    let bundle = files.join('\n');
    bundle = uglify(bundle);
    bundle = whatever(bundle);
    bundle = bundle.replace(/\/\*.*?\*\//g, '');

    await fs.outputFile('./build/js/script.js', bundle, {encoding: 'utf8'});
}

bundleScripts.then(() => console.log('done');

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

How to uninstall with msiexec using product id guid without .msi file present

you need /q at the end

MsiExec.exe /x {2F808931-D235-4FC7-90CD-F8A890C97B2F} /q

javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake during web service communicaiton

I encountered this problem with Java 1.6. Running under Java 1.7 fixed my particular rendition of the problem. I think the underlying cause was that the server I was connecting to must have required stronger encryption than was available under 1.6.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Deciding between HttpClient and WebClient

HttpClient is the newer of the APIs and it has the benefits of

  • has a good async programming model
  • being worked on by Henrik F Nielson who is basically one of the inventors of HTTP, and he designed the API so it is easy for you to follow the HTTP standard, e.g. generating standards-compliant headers
  • is in the .Net framework 4.5, so it has some guaranteed level of support for the forseeable future
  • also has the xcopyable/portable-framework version of the library if you want to use it on other platforms - .Net 4.0, Windows Phone etc.

If you are writing a web service which is making REST calls to other web services, you should want to be using an async programming model for all your REST calls, so that you don't hit thread starvation. You probably also want to use the newest C# compiler which has async/await support.

Note: It isn't more performant AFAIK. It's probably somewhat similarly performant if you create a fair test.

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

I had the same issue. When compared the java version mentioned in the pom.xml file is different and the JAVA_HOME env variable was pointing to different version of jdk.

Have the JAVA_HOME and pom.xml updated to the same jdk installation path

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Try to run Maven from the command line or type "-X" in the text field - you can't break anything this way, at the worst, you'll get an error (I don't have Netbeans; in Eclipse, there is a checkbox "Debug" for this).

When running with debug output enabled, you should see the paths which the exec-maven-plugin plugin uses.

The next step would then be to copy the command into a command prompt or terminal and execute it manually to see if you get a useful error message there.

Disable Laravel's Eloquent timestamps

If you only need to only to disable updating updated_at just add this method to your model.

public function setUpdatedAtAttribute($value)
{
    // to Disable updated_at
}

This will override the parent setUpdatedAtAttribute() method. created_at will work as usual. Same way you can write a method to disable updating created_at only.

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in position 7: ordinal not in range(128)

You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.

Pick an encoding and stick with it:

f.write(printinfo.encode('utf8') + '\n')

or use io.open() to create a file object that'll encode for you as you write to the file:

import io

f = io.open(filename, 'w', encoding='utf8')

You may want to read:

before continuing.

Spring Data JPA - "No Property Found for Type" Exception

You should have that property defined in your model or entity class.

Android ClassNotFoundException: Didn't find class on path

If you are using Multidex on Android 4.4 and prior, your issue might be that your activity class is located in the second dex file and therefore not found by the android system.

To keep your activity class in the main dex file, see this page:

https://developer.android.com/studio/build/multidex.html#keep


To find which classes are located in a dex file use Android Studio.

Simply drag n drop your apk into Android Studio. You should be able to see your dex files in the apk explorer.

Then select the dex file to see what classes are inside.


another alternative is dexdump:

You can check the content of your dex files contained in your apk by using the command dexdump which can be found in

android-sdk/build-tools/27.0.3/dexdump

For windows users see this tool I made to ease the process

Flexbox Not Centering Vertically in IE

Here is my working solution (SCSS):

.item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 120px;
  &:after{
    content:'';
    min-height:inherit;
    font-size:0;
  }
}

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

Why Maven uses JDK 1.6 but my java -version is 1.7

Get into

/System/Library/Frameworks/JavaVM.framework/Versions

and update the CurrentJDK symbolic link to point to

/Library/Java/JavaVirtualMachines/YOUR_JDK_VERSION/Contents/

E.g.

cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo rm CurrentJDK
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/ CurrentJDK

Now it shall work immediately.

" netsh wlan start hostednetwork " command not working no matter what I try

If none of the above solution worked for you, locate the Wifi adapter from "Control Panel\Network and Internet\Network Connections", right click on it, and select "Diagnose", then follow the given instructions on the screen. It worked for me.

PHP Composer update "cannot allocate memory" error (using Laravel 4)

Here is the workaround that I found that works for me every time:

df -h 
dd if=/dev/zero of=/swapfile bs=1M count=1024
sudo dd if=/dev/zero of=/swapfile bs=1M count=1024
mkswap /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo 'echo "/swapfile  none  swap  defaults  0  0" >> /etc/fstab' | sudo sh

free -m

confirm u see your swap there:
total used free shared buffers cached
Mem: 494 335 158 0 19 62
-/+ buffers/cache: 254 240
Swap: 1023 3 1020

watch free -m

PHP parse/syntax errors; and how to solve them

Unexpected '.'

This can occur if you are trying to use the splat operator(...) in an unsupported version of PHP.

... first became available in PHP 5.6 to capture a variable number of arguments to a function:

function concatenate($transform, ...$strings) {
    $string = '';
    foreach($strings as $piece) {
        $string .= $piece;
    }
    return($transform($string));
}

echo concatenate("strtoupper", "I'd ", "like ", 4 + 2, " apples");
// This would print:
// I'D LIKE 6 APPLES

In PHP 7.4, you could use it for Array expressions.

$parts = ['apple', 'pear'];
$fruits = ['banana', 'orange', ...$parts, 'watermelon'];
// ['banana', 'orange', 'apple', 'pear', 'watermelon'];

'mvn' is not recognized as an internal or external command, operable program or batch file

To solve this problem please follow the steps below:

  1. Download the maven zip file from http://maven.apache.org/download.cgi
  2. Extract the maven zip file
  3. Open the environment variable and in user variable section click on new button and make a variable called MAVEN_HOME and assign it the value of bin path of extracted maven zip
  4. Now in System Variable click on Path and click on Edit button --> Now Click on New button and paste the bin path of maven zip
  5. Now click on OK button
  6. Open CMD and type mvn -version
  7. Installed Maven version will be displayed and your setup is completed

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

I have had the same error recently. I have checked the folder Log of my Server instance.

x:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\Log\

and I have found this errors in logs

Starting up database 'master'.
Error: 17204, Severity: 16, State: 1.
FCB::Open failed: Could not open file
x:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf for file number 1.  OS error: 5(Access is denied.).
Error: 5120, Severity: 16, State: 101.
Unable to open the physical file "E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\master.mdf". Operating system error 5:    "5(Access is denied.)".
Error: 17204, Severity: 16, State: 1. FCB::Open failed: Could not open file E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf for file number 2.  OS  error: 5(Access is denied.).
Error: 5120, Severity: 16, State: 101.  Unable to open the physical file "E:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA\mastlog.ldf". Operating system error 5: "5(Access is denied.)".
SQL Server shutdown has been initiated

So for me it was an easy fix. I just added proper access rights to this files to the sql server service account. I hope it will help

Fill background color left to right CSS

If you are like me and need to change color of text itself also while in the same time filling the background color check my solution.

Steps to create:

  1. Have two text, one is static colored in color on hover, and the other one in default state color which you will be moving on hover
  2. On hover move wrapper of the not static one text while in the same time move inner text of that wrapper to the opposite direction.
  3. Make sure to add overflow hidden where needed

Good thing about this solution:

  • Support IE9, uses only transform
  • Button (or element you are applying animation) is fluid in width, so no fixed values are being used here

Not so good thing about this solution:

  • A really messy markup, could be solved by using pseudo elements and att(data)?
  • There is some small glitch in animation when having more then one button next to each other, maybe it could be easily solved but I didn't take much time to investigate yet.

Check the pen ---> https://codepen.io/nikolamitic/pen/vpNoNq

<button class="btn btn--animation-from-right">
  <span class="btn__text-static">Cover left</span>
  <div class="btn__text-dynamic">
    <span class="btn__text-dynamic-inner">Cover left</span>
  </div>
</button>

.btn {
  padding: 10px 20px;
  position: relative;

  border: 2px solid #222;
  color: #fff;
  background-color: #222;
  position: relative;

  overflow: hidden;
  cursor: pointer;

  text-transform: uppercase;
  font-family: monospace;
  letter-spacing: -1px;

  [class^="btn__text"] {
    font-size: 24px;
  }

  .btn__text-dynamic,
  .btn__text-dynamic-inner {    
    display: flex;
    justify-content: center;
    align-items: center;

    position: absolute;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index: 2;

    transition: all ease 0.5s;
  }

  .btn__text-dynamic {
    background-color: #fff;
    color: #222;

    overflow: hidden;
  }

  &:hover {
    .btn__text-dynamic {
      transform: translateX(-100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(100%);
    }
  }
}

.btn--animation-from-right {
    &:hover {
    .btn__text-dynamic {
      transform: translateX(100%);
    }
    .btn__text-dynamic-inner {
      transform: translateX(-100%);
    }
  }
}

You can remove .btn--animation-from-right modifier if you want to animate to the left.

Is there an equivalent of lsusb for OS X

I typically run this command to list USB devices on Mac OS X, along with details about them:

ioreg -p IOUSB -l -w 0

How to know which version of Symfony I have?

If you want to dynamicallly display your Symfony 2 version in pages, for example in footer, you can do it this way.

Create a service:

<?php

namespace Project\Bundle\DuBundle\Twig;

class SymfonyVersionExtension extends \Twig_Extension
{


 public function getFunctions()
 {
 return array(
 //this is the name of the function you will use in twig
 new \Twig_SimpleFunction('symfony_version', array($this, 'b'))
   );
 }

public function getName()
{
//return 'number_employees';
 return 'symfony_version_extension';
}   

public function b()
{
 $symfony_version = \Symfony\Component\HttpKernel\Kernel::VERSION;
 return $symfony_version;
}
}

Register in service.yml

 dut.twig.symfony_version_extension:
    class: Project\Bundle\DutBundle\Twig\SymfonyVersionExtension
    tags:
        - { name: twig.extension }
    #arguments: []

And you can call it anywhere. In Controller, wrap it in JSON, or in pages example footer

 <p> Built With Symfony {{ symfony_version() }} Version MIT License</p>

Now every time you run composer update to update your vendor, symfony version will also automatically update in your template.I know this is overkill but this is how I do it in my projects and it is working.

How to update a single library with Composer?

You can basically do following one to install new package as well.

php composer.phar require

then terminal will ask you to enter the name of the package for searching.

$ Search for a package []: //Your package name here

Then terminal will ask the version of the package (If you would like to have the latest version just leave it blank)

$ Enter the version constraint to require (or leave blank to use the latest version) []: //your version number here

Then you just press the return key. Terminal will ask for another package, if you dont want to install another one just press the return key and you will be done.

Using LINQ to group by multiple properties and sum

Use the .Select() after grouping:

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyContractID, // required by your view model. should be omited
                                            // in most cases because group by primary key
                                            // makes no sense.
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyContractID = ac.Key.AgencyContractID,
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Amount = ac.Sum(acs => acs.Amount),
                       Fee = ac.Sum(acs => acs.Fee)
                   });

npm ERR cb() never called

I had the cb() never called! error, and none of the answers here directly worked for me. I was running Node v8.11.2, and I had to manually delete the package-lock.json file to get anywhere. After doing this, I ran npm cache verify per what some of the answers recommended. Then, running npm i yielded the following result:

npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN [email protected] No description
npm WARN [email protected] No repository field.

up to date in 5.118s

Eclipse will not start and I haven't changed anything

I deleted the workbench.xmi in the folder workspace/.metadata/.plugins/org.eclipse.e4.workbench/.

I got this error because a build hung and then I tried to quit. However, I had unsaved changes. This prompted the following errors in logfile about unsaved changes and jobs that are not finished.

How to get list of all installed packages along with version in composer?

List installed dependencies:

  • Flat: composer show -i
  • Tree: composer show -i -t

-i short for --installed.

-t short for --tree.

ref: https://getcomposer.org/doc/03-cli.md#show

How to rollback or commit a transaction in SQL Server

The good news is a transaction in SQL Server can span multiple batches (each exec is treated as a separate batch.)

You can wrap your EXEC statements in a BEGIN TRANSACTION and COMMIT but you'll need to go a step further and rollback if any errors occur.

Ideally you'd want something like this:

BEGIN TRY
    BEGIN TRANSACTION 
        exec( @sqlHeader)
        exec(@sqlTotals)
        exec(@sqlLine)
    COMMIT
END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK
END CATCH

The BEGIN TRANSACTION and COMMIT I believe you are already familiar with. The BEGIN TRY and BEGIN CATCH blocks are basically there to catch and handle any errors that occur. If any of your EXEC statements raise an error, the code execution will jump to the CATCH block.

Your existing SQL building code should be outside the transaction (above) as you always want to keep your transactions as short as possible.

Background color not showing in print preview

The best solution for this if you are using bootstrap so just do one thing remove @media print {} all code inside this. and enable background graphics from more settings while taking print preview.

Use underscore inside Angular controllers

I use this:

var myapp = angular.module('myApp', [])
  // allow DI for use in controllers, unit tests
  .constant('_', window._)
  // use in views, ng-repeat="x in _.range(3)"
  .run(function ($rootScope) {
     $rootScope._ = window._;
  });

See https://github.com/angular/angular.js/wiki/Understanding-Dependency-Injection about halfway for some more info on run.

How to set custom location for local installation of npm package?

For OSX, you can go to your user's $HOME (probably /Users/yourname/) and, if it doesn't already exist, create an .npmrc file (a file that npm uses for user configuration), and create a directory for your npm packages to be installed in (e.g., /Users/yourname/npm). In that .npmrc file, set "prefix" to your new npm directory, which will be where "globally" installed npm packages will be installed; these "global" packages will, obviously, be available only to your user account.

In .npmrc:

prefix=${HOME}/npm

Then run this command from the command line:

npm config ls -l

It should give output on both your own local configuration and the global npm configuration, and you should see your local prefix configuration reflected, probably near the top of the long list of output.

For security, I recommend this approach to configuring your user account's npm behavior over chown-ing your /usr/local folders, which I've seen recommended elsewhere.

Android Debug Bridge (adb) device - no permissions

The answer is weaved amongst the various posts here, I'll so my best, but it looks like a really simple and obvious reason.

1) is that there usually is a "user" variable in the udev rule some thing like USER="your_user" probably right after the GROUP="plugdev"

2) You need to use the correct SYSFS{idVendor}==”####" and SYSFS{idProduct}=="####" values for your device/s. If you have devices from more than one manufacture, say like one from Samsung and one from HTC, then you need to have an entry(rule) for each vendor, not an entry for each device but for each different vendor you will use, so you need an entry for HTC and Samsung. It looks like you have your entry for Samsung now you need another. Remember the USER="your_user". Use 'lsusb' like Robert Seimer suggests to find the idVendor and idProduct, they are usually some numbers and letters in this format X#X#:#X#X I think the first one is the idVendor and the second idProduct but your going to need to do this for each brand of phone/tablet you have.

3) I havent figured out how 51-adb.rules and 99-adb.rules are different or why.

4) maybe try adding "plugdev" group to your user with "usermod -a -G plugdev your_user", Try that at your own risk, though I don't thinks it anyriskier than launching a gui as root but I believe if necessary you should at least use "gksudo eclipse" instead.

I hope that helped clearify some things, the udev rules syntax is a bit of a mystery to me aswell, but from what I hear it can be different for different systems so try some things out, one ate a time, and note what change works.

Vendor code 17002 to connect to SQLDeveloper

I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.

See LISTENER: TNS-12545 ... No such file or directory.

maven "cannot find symbol" message unhelpful

This is not a function of Maven; it's a function of the compiler. Look closely; the information you're looking for is most likely in the following line.

Autowiring fails: Not an managed Type

After encountering this issue and tried different method of adding the entity packaname name to EntityScan, ComponentScan etc, none of it worked.

Added the package to packageScan config in the EntityManagerFactory of the repository config. The below code gives the code based configuration as opposed to XML based ones answered above.

@Primary
@Bean(name = "entityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    emf.setJpaVendorAdapter(jpaVendorAdapter);
    emf.setPackagesToScan("org.package.entity");
    emf.setPersistenceUnitName("default"); 
    emf.afterPropertiesSet();
    return emf.getObject();
}

Compiling Java 7 code via Maven

Try to change Java compiler settings in Properties in Eclipse-

Goto: Preferences->Java->Compiler->Compiler Compliance Level-> 1.7 Apply Ok

Restart IDE.

Confirm Compiler setting for project- Goto: Project Properties->Java Compiler-> Uncheck(Use Compliance from execution environment 'JavaSE-1.6' on the java Build path.) and select 1.7 from the dropdown. (Ignore if already 1.7)

Restart IDE.

If still the problem persist- Run individual test cases using command in terminal-

mvn -Dtest=<test class name> test

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

How to change maven java home

I have two Java versions on my Ubuntu server 14.04: java 1.7 and java 1.8.

I have a project that I need to build using java 1.8.

If I check my Java version using java -version

I get

java version "1.8.0_144"

But when I did mvn -version I get:

Java version: 1.7.0_79, vendor: Oracle Corporation

To set the mvn version to java8

I do this:

export JAVA_HOME=/usr/lib/jvm/java-8-oracle/jre/

Then when I do mvn -version I get:

Java version: 1.8.0_144, vendor: Oracle Corporation

Enabling/Disabling Microsoft Virtual WiFi Miniport

Microsoft Virtual WiFi Miniport should start and bind automatically to the underlying function driver. Try disabling and reenabling the AR9285 driver.

"Non-resolvable parent POM: Could not transfer artifact" when trying to refer to a parent pom from a child pom with ${parent.groupid}

As Nayan said the Path has to updated properly in my case the apache-maven was installed in C:\apache-maven and settings.xml was found inside C:\apache-maven\conf\settings.xml

if this doesn't work go to your local repos
in my case C:\Users\<<"name">>.m2\
and search for .lastUpdated and delete them
then build the maven

Heroku deployment error H10 (App crashed)

I encountered the same problem today. I did heroku run rake db:migrate though I migrated the model before, and the app doesn't crash.

fatal: Unable to create temporary file '/home/username/git/myrepo.git/./objects/pack/tmp_pack_XXXXXX': Permission denied

It sounds like you have file in the git repo owned by root. Since you're ssh'ing in as 'username' to do the push, the files must be writable by username. The easiest thing is probably to create the repo as the user, and use the same user to do your pushes. Another option is to create a group, make everything writable by the group, and make your user a member of that group.

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

Give the relative path URL value to the pom.xml file
../parentfoldername/pom.xml

Using Composer's Autoload

The autoload config does start below the vendor dir. So you might want change the vendor dir, e.g.

{
    "config": {
        "vendor-dir": "../vendor/"
    },
    "autoload": {
        "psr-0": {"AppName": "src/"}
    }
}

Or isn't this possible in your project?

Query error with ambiguous column name in SQL

We face this error when we are selecting data from more than one tables by joining tables and at least one of the selected columns (it will also happen when use * to select all columns) exist with same name in more than one tables (our selected/joined tables). In that case we must have to specify from which table we are selecting out column.

Following is a an example solution implementation of concept explained above

I think you have ambiguity only in InvoiceID that exists both in InvoiceLineItems and Invoices Other fields seem distinct. So try This

I just replace InvoiceID with Invoices.InvoiceID

   SELECT 
        VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
    FROM Vendors 
    JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
    JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
    WHERE  
        Invoices.InvoiceID IN
            (SELECT InvoiceSequence 
             FROM InvoiceLineItems
             WHERE InvoiceSequence > 1)
    ORDER BY 
        VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount

You can use tablename.columnnae for all columns (in selection,where,group by and order by) without using any alias. However you can use an alias as guided by other answers

angular js unknown provider

For me the problem was lazy loading; I loaded my controller and service late, so they were not available at page load (and Angular initialization). I did this with an ui-if tag, but that's irrelevant. The solution was to load the service with the page load already.

Implement a loading indicator for a jQuery AJAX call

This is how I got it working with loading remote content that needs to be refreshed:

$(document).ready(function () {
    var loadingContent = '<div class="modal-header"><h1>Processing...</h1></div><div class="modal-body"><div class="progress progress-striped active"><div class="bar" style="width: 100%;"></div></div></div>';

    // This is need so the content gets replaced correctly.
    $("#myModal").on("show.bs.modal", function (e) {
        $(this).find(".modal-content").html(loadingContent);        
        var link = $(e.relatedTarget);
        $(this).find(".modal-content").load(link.attr("href"));
    });    

    $("#myModal2").on("hide.bs.modal", function (e) {
        $(this).removeData('bs.modal');
    });
});

Basically, just replace the modal content while it's loading with a loading message. The content will then be replaced once it's finished loading.

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

My biggest concern with not checking folder node_modules into Git is that 10 years down the road, when your production application is still in use, npm may not be around. Or npm might become corrupted; or the maintainers might decide to remove the library that you rely on from their repository; or the version you use might be trimmed out.

This can be mitigated with repository managers like Maven, because you can always use your own local Nexus (Sonatype) or Artifactory to maintain a mirror with the packages that you use. As far as I understand, such a system doesn't exist for npm. The same goes for client-side library managers like Bower and Jam.js.

If you've committed the files to your own Git repository, then you can update them when you like, and you have the comfort of repeatable builds and the knowledge that your application won't break because of some third-party action.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

As mentioned in earlier responses, this error can occur when interacting with a SOAP service over an HTTPS connection, and an issue is identified with the connection. The issue may be on the remote end (invalid cert) or on the client (in case of missing CA or PEM files). See http://php.net/manual/en/context.ssl.php for all possible SSL context settings. In my case, setting the path to my local certificate resolved the issue:

$context = ['ssl' => [
    'local_cert' => '/path/to/pem/file',
]];

$params = [
    'soap_version' => SOAP_1_2, 
    'trace' => 1, 
    'exceptions' => 1, 
    'connection_timeout' => 180, 
    'stream_context' => stream_context_create($context), 
    'cache_wsdl' => WSDL_CACHE_NONE, // eliminate possible issue from cached wsdl
];

$client = new SoapClient('https://remoteservice/wsdl', $params);

Apache VirtualHost and localhost

Just change <VirtualHost *:80> to <VirtualHost 127.0.0.1:80>.

Then the default DocumentRoot will serve for all domains or IP addresses that point to your server and specified VirtualHost will work.

Using fonts with Rails asset pipeline

You need to use font-url in your @font-face block, not url

@font-face {
font-family: 'Inconsolata';
src:font-url('Inconsolata-Regular.ttf') format('truetype');
font-weight: normal;
font-style: normal;
}

as well as this line in application.rb, as you mentioned (for fonts in app/assets/fonts

config.assets.paths << Rails.root.join("app", "assets", "fonts")

configure: error: C compiler cannot create executables

Setting 'clang' as the compiler configure should use worked for me:

export CC=clang
pip install --no-clean pycrypto

Eclipse cannot load SWT libraries

For Windows Subsystem for Linux (WSL) you'll need

apt install libswt-gtk-4-jni

If you don't have an OpenJDK 8 you'll also need

apt install openjdk-8-jdk

Google Android USB Driver and ADB

Driver for Huawei was not found. So I've been using the universal ADB driver:

  • Download this:
  • Extract ADBDriverInstaller and Run the file. Make sure you have connected your device through USB to your computer.
  • A window is displayed.
  • Click Install.
  • A dialog box will appear. It will ask you to press the Restart button.

Before doing that read this link:

(The above. in brief, says to press Restart button in the dialog box. Select Troubleshoot. Select Advance Option. Select Startup Setting. Press Restart. After system's been restarted, on the appearing screen press 7)

  • When PC has been Restarted, Run the ADBDriverInstaller file again. Select your device from the options. Press install.

And it's done :)

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

Vim: insert the same characters across multiple lines

  1. Ctrl + v to go to visual block mode
  2. Select the lines using the up and down arrow
  3. Enter lowercase 3i (press lowercase I three times)
  4. I (press capital I. That will take you into insert mode.)
  5. Write the text you want to add
  6. Esc
  7. Press the down arrow

set up device for development (???????????? no permissions)

I had the same problem and I followed these steps:

# Clone this repository
git clone https://github.com/M0Rf30/android-udev-rules.git
cd android-udev-rules
# Copy rules file
sudo cp -v 51-android.rules /etc/udev/rules.d/51-android.rules
# OR create a sym-link to the rules file - choose this option if you'd like to update your udev rules using git.
sudo ln -sf "$PWD"/51-android.rules /etc/udev/rules.d/51-android.rules
# Change file permissions
sudo chmod a+r /etc/udev/rules.d/51-android.rules
# If adbusers group already exists remove old adbusers group
groupdel adbusers
# add the adbusers group if it's doesn't already exist
sudo mkdir -p /usr/lib/sysusers.d/ && sudo cp android-udev.conf /usr/lib/sysusers.d/
sudo systemd-sysusers # (1)
# OR on Fedora:
groupadd adbusers
# Add your user to the adbusers group
sudo usermod -a -G adbusers $(whoami)
# Restart UDEV
sudo udevadm control --reload-rules
sudo service udev restart
# OR on Fedora:
sudo systemctl restart systemd-udevd.service
# Restart the ADB server
adb kill-server
# Replug your Android device and verify that USB debugging is enabled in developer options
adb devices
# You should now see your device

The above steps are described on android-udev-rules. It worked for me.

Just be sure to confirm the dialog that will appear on your phone screen after replug it.

LDAP root query syntax to search more than one specific OU

I don't think this is possible with AD. The distinguishedName attribute is the only thing I know of that contains the OU piece on which you're trying to search, so you'd need a wildcard to get results for objects under those OUs. Unfortunately, the wildcard character isn't supported on DNs.

If at all possible, I'd really look at doing this in 2 queries using OU=Staff... and OU=Vendors... as the base DNs.

How to get form values in Symfony2 controller

If Symfony 4 or 5, juste use this code (Where name is the name of your field):

$request->request->get('name');

How to determine if Javascript array contains an object with an attribute that equals a given value?

I would rather go with regex.

If your code is as follows,

vendors = [
    {
      Name: 'Magenic',
      ID: 'ABC'
     },
    {
      Name: 'Microsoft',
      ID: 'DEF'
    }
];

I would recommend

/"Name":"Magenic"/.test(JSON.stringify(vendors))

Simple way to query connected USB devices info in Python?

For a system with legacy usb coming back and libusb-1.0, this approach will work to retrieve the various actual strings. I show the vendor and product as examples. It can cause some I/O, because it actually reads the info from the device (at least the first time, anyway.) Some devices don't provide this information, so the presumption that they do will throw an exception in that case; that's ok, so we pass.

import usb.core
import usb.backend.libusb1

busses = usb.busses()
for bus in busses:
    devices = bus.devices
    for dev in devices:
        if dev != None:
            try:
                xdev = usb.core.find(idVendor=dev.idVendor, idProduct=dev.idProduct)
                if xdev._manufacturer is None:
                    xdev._manufacturer = usb.util.get_string(xdev, xdev.iManufacturer)
                if xdev._product is None:
                    xdev._product = usb.util.get_string(xdev, xdev.iProduct)
                stx = '%6d %6d: '+str(xdev._manufacturer).strip()+' = '+str(xdev._product).strip()
                print stx % (dev.idVendor,dev.idProduct)
            except:
                pass

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

If you installed using the graphical installer by BigSQL from the official postgres site and if you installed in the default location...

You can find your uninstaller in your home directory: /Users/<yourusername/PostGreSQL/uninstall/

How to start rails server?

In rails 2.3.x application you can start your server by following command:

ruby script/server

In rails 3.x, you need to go for:

rails s

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

sqldeveloper error message: Network adapter could not establish the connection error

If you have such error when using remote oracle database, you can delete your tnsname and listener then create new config with "hostname" or ip address instead of "localhost". such as listener.ora

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
    )

tnsnames.ora

DB =
  (DESCRIPTION =
    (ADDRESS_LIST =
      (ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521))
    )
    (CONNECT_DATA =
      (SERVICE_NAME = DB)
    )
  )

It works fine for me.

Fastest way to count exact number of rows in a very large table?

I found this good article SQL Server–HOW-TO: quickly retrieve accurate row count for table from martijnh1 which gives a good recap for each scenarios.

I need this to be expanded where I need to provide a count based on a specific condition and when I figure this part, I'll update this answer further.

In the meantime, here are the details from article:

Method 1:

Query:

SELECT COUNT(*) FROM Transactions 

Comments:

Performs a full table scan. Slow on large tables.

Method 2:

Query:

SELECT CONVERT(bigint, rows) 
FROM sysindexes 
WHERE id = OBJECT_ID('Transactions') 
AND indid < 2 

Comments:

Fast way to retrieve row count. Depends on statistics and is inaccurate.

Run DBCC UPDATEUSAGE(Database) WITH COUNT_ROWS, which can take significant time for large tables.

Method 3:

Query:

SELECT CAST(p.rows AS float) 
FROM sys.tables AS tbl 
INNER JOIN sys.indexes AS idx ON idx.object_id = tbl.object_id and
idx.index_id < 2 
INNER JOIN sys.partitions AS p ON p.object_id=CAST(tbl.object_id AS int) 
AND p.index_id=idx.index_id 
WHERE ((tbl.name=N'Transactions' 
AND SCHEMA_NAME(tbl.schema_id)='dbo')) 

Comments:

The way the SQL management studio counts rows (look at table properties, storage, row count). Very fast, but still an approximate number of rows.

Method 4:

Query:

SELECT SUM (row_count) 
FROM sys.dm_db_partition_stats 
WHERE object_id=OBJECT_ID('Transactions')    
AND (index_id=0 or index_id=1); 

Comments:

Quick (although not as fast as method 2) operation and equally important, reliable.

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

sometimes, when you create package like com.mydomain.something the directory structure does not get created and you are left with a single folder named "com.mydomain.something" in this case you should create directory structure, like

com
|_mydomain
  |_something 

How do I configure the proxy settings so that Eclipse can download new plugins?

finally work for me !

In Eclipse, Window > Preferences > General > Network Connections,
set Active Provider to Native
add to eclipse.ini :

-Djava.net.useSystemProxies=true
-Dhttp.proxyPort=8080
-Dhttp.proxyHost=myproxy
-Dhttp.proxyUser=mydomain\myusername
-Dhttp.proxyPassword=mypassword
-Dhttp.nonProxyHosts=localhost|127.0.0.1|192.168.*|10.*
-Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient4

Folder structure for a Node.js project

It's important to note that there's no consensus on what's the best approach and related frameworks in general do not enforce nor reward certain structures.

I find this to be a frustrating and huge overhead but equally important. It is sort of a downplayed version (but IMO more important) of the style guide issue. I like to point this out because the answer is the same: it doesn't matter what structure you use as long as it's well defined and coherent.

So I'd propose to look for a comprehensive guide that you like and make it clear that the project is based on this.

It's not easy, especially if you're new to this! Expect to spend hours researching. You'll find most guides recommending an MVC-like structure. While several years ago that might have been a solid choice, nowadays that's not necessarily the case. For example here's another approach.

How to implement the factory method pattern in C++ correctly

extern std::pair<std::string_view, Base*(*)()> const factories[2];

decltype(factories) factories{
  {"blah", []() -> Base*{return new Blah;}},
  {"foo", []() -> Base*{return new Foo;}}
};

How can I map "insert='false' update='false'" on a composite-id key-property which is also used in a one-to-many FK?

"Dino TW" has provided the link to the comment Hibernate Mapping Exception : Repeated column in mapping for entity which has the vital information.

The link hints to provide "inverse=true" in the set mapping, I tried it and it actually works. It is such a rare situation wherein a Set and Composite key come together. Make inverse=true, we leave the insert & update of the table with Composite key to be taken care by itself.

Below can be the required mapping,

<class name="com.example.CompanyEntity" table="COMPANY">
    <id name="id" column="COMPANY_ID"/>
    <set name="names" inverse="true" table="COMPANY_NAME" cascade="all-delete-orphan" fetch="join" batch-size="1" lazy="false">
        <key column="COMPANY_ID" not-null="true"/>
        <one-to-many entity-name="vendorName"/>
    </set>
</class>

How to do sed like text replace with python?

If you are using Python3 the following module will help you: https://github.com/mahmoudadel2/pysed

wget https://raw.githubusercontent.com/mahmoudadel2/pysed/master/pysed.py

Place the module file into your Python3 modules path, then:

import pysed
pysed.replace(<Old string>, <Replacement String>, <Text File>)
pysed.rmlinematch(<Unwanted string>, <Text File>)
pysed.rmlinenumber(<Unwanted Line Number>, <Text File>)

Random / noise functions for GLSL

Just found this version of 3d noise for GPU, alledgedly it is the fastest one available:

#ifndef __noise_hlsl_
#define __noise_hlsl_

// hash based 3d value noise
// function taken from https://www.shadertoy.com/view/XslGRr
// Created by inigo quilez - iq/2013
// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License.

// ported from GLSL to HLSL

float hash( float n )
{
    return frac(sin(n)*43758.5453);
}

float noise( float3 x )
{
    // The noise function returns a value in the range -1.0f -> 1.0f

    float3 p = floor(x);
    float3 f = frac(x);

    f       = f*f*(3.0-2.0*f);
    float n = p.x + p.y*57.0 + 113.0*p.z;

    return lerp(lerp(lerp( hash(n+0.0), hash(n+1.0),f.x),
                   lerp( hash(n+57.0), hash(n+58.0),f.x),f.y),
               lerp(lerp( hash(n+113.0), hash(n+114.0),f.x),
                   lerp( hash(n+170.0), hash(n+171.0),f.x),f.y),f.z);
}

#endif

How to track untracked content?

This question has been answered already, but thought I'd add to the mix what I found out when I got these messages.

I have a repo called playground that contains a number of sandbox apps. I added two new apps from a tutorial to the playground directory by cloning the tutorial's repo. The result was that the new apps' git stuff pointed to the tutorial's repo and not to my repo. The solution was to delete the .git directory from each of those apps' directories, mv the apps' directories outside the playground directory, and then mv them back and run git add .. After that it worked.

Loading inline content using FancyBox

The way I figured this out was going through the example index.html/style.css that comes packaged with the Fancybox installation.

If you view the code that is used for the demo website and basically copy/paste, you'll be fine.

To get an inline Fancybox working, you will need to have this code present in your index.html file:

  <head>
    <link href="./fancybox/jquery.fancybox-1.3.4.css" rel="stylesheet" type="text/css" media="screen" />
    <script>!window.jQuery && document.write('<script src="jquery-1.4.3.min.js"><\/script>');</script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="./fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript">
    $(document).ready(function() {

    $("#various1").fancybox({
            'titlePosition'     : 'inside',
            'transitionIn'      : 'none',
            'transitionOut'     : 'none'
        });
    });
    </script>
  </head>

 <body>

    <a id="various1" href="#inline1" title="Put a title here">Name of Link Here</a>
    <div style="display: none;">
        <div id="inline1" style="width:400px;height:100px;overflow:auto;">
                   Write whatever text you want right here!!
        </div>
    </div> 

</body>

Remember to be precise about what folders your script files are placed in and where you are pointing to in the Head tag; they must correspond.

Gradients in Internet Explorer 9

Opera will soon start having builds available with gradient support, as well as other CSS features.

The W3C CSS Working Group is not even finished with CSS 2.1, y'all know that, right? We intend to be finished very soon. CSS3 is modularized precisely so we can move modules through to implementation faster rather than an entire spec.

Every browser company uses a different software cycle methodology, testing, and so on. So the process takes time.

I'm sure many, many readers well know that if you're using anything in CSS3, you're doing what's called "progressive enhancement" - the browsers with the most support get the best experience. The other part of that is "graceful degradation" meaning the experience will be agreeable but perhaps not the best or most attractive until that browser has implemented the module, or parts of the module that are relevant to what you want to do.

This creates quite an odd situation that unfortunately front-end devs get extremely frustrated by: inconsistent timing on implementations. So it's a real challenge on either side - do you blame the browser companies, the W3C, or worse yet - yourself (goodness knows we can't know it all!) Do those of us who are working for a browser company and W3C group members blame ourselves? You?

Of course not. It's always a game of balance, and as of yet, we've not as an industry figured out where that point of balance really is. That's the joy of working in evolutionary technology :)

How to use PowerShell select-string to find more than one pattern in a file?

If you want to match the two words in either order, use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)|(Failed.*VendorEnquiry)'

If Failed always comes after VendorEnquiry on the line, just use:

gci C:\Logs| select-string -pattern '(VendorEnquiry.*Failed)'

proper hibernate annotation for byte[]

What is the portable way to annotate a byte[] property?

It depends on what you want. JPA can persist a non annotated byte[]. From the JPA 2.0 spec:

11.1.6 Basic Annotation

The Basic annotation is the simplest type of mapping to a database column. The Basic annotation can be applied to a persistent property or instance variable of any of the following types: Java primitive, types, wrappers of the primitive types, java.lang.String, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], enums, and any other type that implements Serializable. As described in Section 2.8, the use of the Basic annotation is optional for persistent fields and properties of these types. If the Basic annotation is not specified for such a field or property, the default values of the Basic annotation will apply.

And Hibernate will map a it "by default" to a SQL VARBINARY (or a SQL LONGVARBINARY depending on the Column size?) that PostgreSQL handles with a bytea.

But if you want the byte[] to be stored in a Large Object, you should use a @Lob. From the spec:

11.1.24 Lob Annotation

A Lob annotation specifies that a persistent property or field should be persisted as a large object to a database-supported large object type. Portable applications should use the Lob annotation when mapping to a database Lob type. The Lob annotation may be used in conjunction with the Basic annotation or with the ElementCollection annotation when the element collection value is of basic type. A Lob may be either a binary or character type. The Lob type is inferred from the type of the persistent field or property and, except for string and character types, defaults to Blob.

And Hibernate will map it to a SQL BLOB that PostgreSQL handles with a oid .

Is this fixed in some recent version of hibernate?

Well, the problem is that I don't know what the problem is exactly. But I can at least say that nothing has changed since 3.5.0-Beta-2 (which is where a changed has been introduced)in the 3.5.x branch.

But my understanding of issues like HHH-4876, HHH-4617 and of PostgreSQL and BLOBs (mentioned in the javadoc of the PostgreSQLDialect) is that you are supposed to set the following property

hibernate.jdbc.use_streams_for_binary=false

if you want to use oid i.e. byte[] with @Lob (which is my understanding since VARBINARY is not what you want with Oracle). Did you try this?

As an alternative, HHH-4876 suggests using the deprecated PrimitiveByteArrayBlobType to get the old behavior (pre Hibernate 3.5).

References

  • JPA 2.0 Specification
    • Section 2.8 "Mapping Defaults for Non-Relationship Fields or Properties"
    • Section 11.1.6 "Basic Annotation"
    • Section 11.1.24 "Lob Annotation"

Resources

Specifying an Index (Non-Unique Key) Using JPA

I'd really like to be able to specify database indexes in a standardized way but, sadly, this is not part of the JPA specification (maybe because DDL generation support is not required by the JPA specification, which is a kind of road block for such a feature).

So you'll have to rely on a provider specific extension for that. Hibernate, OpenJPA and EclipseLink clearly do offer such an extension. I can't confirm for DataNucleus but since indexes definition is part of JDO, I guess it does.

I really hope index support will get standardized in next versions of the specification and thus somehow disagree with other answers, I don't see any good reason to not include such a thing in JPA (especially since the database is not always under your control) for optimal DDL generation support.

By the way, I suggest downloading the JPA 2.0 spec.

JUnit tests pass in Eclipse but fail in Maven Surefire

I had the same problem, and the solution for me was to allow Maven to handle all dependencies, including to local jars. I used Maven for online dependencies, and configured build path manually for local dependencies. Thus, Maven was not aware of the dependencies I configured manually.

I used this solution to install the local jar dependencies into Maven:

How to add local jar files in maven project?

How can I use Oracle SQL developer to run stored procedures?

Not only is there a way to do this, there is more than one way to do this (which I concede is not very Pythonic, but then SQL*Developer is written in Java ).

I have a procedure with this signature: get_maxsal_by_dept( dno number, maxsal out number).

I highlight it in the SQL*Developer Object Navigator, invoke the right-click menu and chose Run. (I could use ctrl+F11.) This spawns a pop-up window with a test harness. (Note: If the stored procedure lives in a package, you'll need to right-click the package, not the icon below the package containing the procedure's name; you will then select the sproc from the package's "Target" list when the test harness appears.) In this example, the test harness will display the following:

DECLARE
  DNO NUMBER;
  MAXSAL NUMBER;
BEGIN
  DNO := NULL;

  GET_MAXSAL_BY_DEPT(
    DNO => DNO,
    MAXSAL => MAXSAL
  );
  DBMS_OUTPUT.PUT_LINE('MAXSAL = ' || MAXSAL);
END;

I set the variable DNO to 50 and press okay. In the Running - Log pane (bottom right-hand corner unless you've closed/moved/hidden it) I can see the following output:

Connecting to the database apc.
MAXSAL = 4500
Process exited.
Disconnecting from the database apc. 

To be fair the runner is less friendly for functions which return a Ref Cursor, like this one: get_emps_by_dept (dno number) return sys_refcursor.

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );
  -- Modify the code to output the variable
  -- DBMS_OUTPUT.PUT_LINE('v_Return = ' || v_Return);
END;

However, at least it offers the chance to save any changes to file, so we can retain our investment in tweaking the harness...

DECLARE
  DNO NUMBER;
  v_Return sys_refcursor;
  v_rec emp%rowtype;
BEGIN
  DNO := 50;

  v_Return := GET_EMPS_BY_DEPT(
    DNO => DNO
  );

  loop
    fetch v_Return into v_rec;
    exit when v_Return%notfound;
    DBMS_OUTPUT.PUT_LINE('name = ' || v_rec.ename);
  end loop;
END;

The output from the same location:

Connecting to the database apc.
name = TRICHLER
name = VERREYNNE
name = FEUERSTEIN
name = PODER
Process exited.
Disconnecting from the database apc. 

Alternatively we can use the old SQLPLus commands in the SQLDeveloper worksheet:

var rc refcursor 
exec :rc := get_emps_by_dept(30) 
print rc

In that case the output appears in Script Output pane (default location is the tab to the right of the Results tab).

The very earliest versions of the IDE did not support much in the way of SQL*Plus. However, all of the above commands have been supported since 1.2.1. Refer to the matrix in the online documentation for more info.


"When I type just var rc refcursor; and select it and run it, I get this error (GUI):"

There is a feature - or a bug - in the way the worksheet interprets SQLPlus commands. It presumes SQLPlus commands are part of a script. So, if we enter a line of SQL*Plus, say var rc refcursor and click Execute Statement (or F9 ) the worksheet hurls ORA-900 because that is not an executable statement i.e. it's not SQL . What we need to do is click Run Script (or F5 ), even for a single line of SQL*Plus.


"I am so close ... please help."

You program is a procedure with a signature of five mandatory parameters. You are getting an error because you are calling it as a function, and with just the one parameter:

exec :rc := get_account(1)

What you need is something like the following. I have used the named notation for clarity.

var ret1 number
var tran_cnt number
var msg_cnt number
var rc refcursor

exec :tran_cnt := 0
exec :msg_cnt := 123

exec get_account (Vret_val => :ret1, 
                  Vtran_count => :tran_cnt, 
                  Vmessage_count => :msg_cnt, 
                  Vaccount_id   => 1,
                  rc1 => :rc )

print tran_count 
print rc

That is, you need a variable for each OUT or IN OUT parameter. IN parameters can be passed as literals. The first two EXEC statements assign values to a couple of the IN OUT parameters. The third EXEC calls the procedure. Procedures don't return a value (unlike functions) so we don't use an assignment syntax. Lastly this script displays the value of a couple of the variables mapped to OUT parameters.

Multiple conditions with CASE statements

Another way based on amadan:

    SELECT * FROM [Purchasing].[Vendor] WHERE  

      ( (@url IS null OR @url = '' OR @url = 'ALL') and   PurchasingWebServiceURL LIKE '%')
    or

       ( @url = 'blank' and  PurchasingWebServiceURL = '')
    or
        (@url = 'fail' and  PurchasingWebServiceURL NOT LIKE '%treyresearch%')
    or( (@url not in ('fail','blank','','ALL') and @url is not null and 
          PurchasingWebServiceUrl Like '%'+@ur+'%') 
END

How do I list all tables in all databases in SQL Server in a single result set?

I realize this is a very old thread, but it was very helpful when I had to put together some system documentation for several different servers that were hosting different versions of Sql Server. I ended up creating 4 stored procedures which I am posting here for the benefit of the community. We use Dynamics NAV so the two stored procedures with NAV in the name split the Nav company out of the table name. Enjoy...

1 of 4 - ListServerDatabases

USE [YourDatabase]
GO

/****** Object:  StoredProcedure [pssi].[ListServerDatabases]    Script Date: 10/3/2017 8:56:45 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROC [dbo].[ListServerDatabases]
(
    @SearchDatabases varchar(max) = NULL,  
    @ExcludeSystemDatabases bit = 1,
    @Sql varchar(max) OUTPUT
)
AS BEGIN

/**************************************************************************************************************************************
* Lists all of the databases for a given server.
*   Parameters
*       SearchDatabases - Comma delimited list of database names for which to search - converted into series of Like statements
*                         Defaults to null  
*       ExcludeSystemDatabases - 1 to exclude system databases, otherwise 0
*                                Defaults to 1
*       Sql - Output - the stored proc generated sql
*
*   Adapted from answer by 
*   From: How do I list all tables in all databases in SQL Server in a single result set?
*   Link: https://stackoverflow.com/questions/2875768/how-do-i-list-all-tables-in-all-databases-in-sql-server-in-a-single-result-set
*
**************************************************************************************************************************************/

    SET NOCOUNT ON

    DECLARE @l_CompoundLikeStatement varchar(max) = ''
    DECLARE @l_DatabaseName sysname

    DECLARE @l_Index int

    DECLARE @lUseAndText bit = 0

    DECLARE @l_AllDatabases table (ServerName sysname, DbName sysname)

    SET @Sql = 
        'select @@ServerName as ''ServerName'', ''?'' as ''DbName'''

    IF @SearchDatabases IS NOT NULL BEGIN
        SET @l_CompoundLikeStatement = char(13) + 'where (' + char(13)
        WHILE LEN(LTRIM(RTRIM(@SearchDatabases))) > 0 BEGIN
            SET @l_Index = CHARINDEX(',', @SearchDatabases)
            IF @l_Index = 0 BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(@SearchDatabases))
            END ELSE BEGIN
                SET @l_DatabaseName = LTRIM(RTRIM(LEFT(@SearchDatabases, @l_Index - 1)))
            END

            SET @SearchDatabases = LTRIM(RTRIM(REPLACE(LTRIM(RTRIM(REPLACE(@SearchDatabases, @l_DatabaseName, ''))), ',', '')))
            SET @l_CompoundLikeStatement = @l_CompoundLikeStatement + char(13) + ' ''?'' like ''' + @l_DatabaseName + '%'' COLLATE Latin1_General_CI_AS or '
        END

        -- Trim trailing Or and add closing right parenthesis )
        SET @l_CompoundLikeStatement = LTRIM(RTRIM(@l_CompoundLikeStatement))
        SET @l_CompoundLikeStatement = LEFT(@l_CompoundLikeStatement, LEN(@l_CompoundLikeStatement) - 2) + ' )'

        SET @Sql = @Sql + char(13) +
            @l_CompoundLikeStatement

        SET @lUseAndText = 1
    END

    IF @ExcludeSystemDatabases = 1 BEGIN
        SET @Sql = @Sql + char(13)
        SET @Sql = @Sql + case when @lUseAndText = 1 THEN '  and ' ELSE 'where ' END +
            '''?'' not in (''master'' COLLATE Latin1_General_CI_AS, ''model'' COLLATE Latin1_General_CI_AS, ''msdb'' COLLATE Latin1_General_CI_AS, ''tempdb'' COLLATE Latin1_General_CI_AS)' 
    END

/*  PRINT @Sql  */

    INSERT INTO @l_AllDatabases 
    EXEC sp_msforeachdb @Sql

    SELECT * FROM @l_AllDatabases ORDER BY DbName
END

How to set up default schema name in JPA configuration?

Don't know of JPA property for this either. But you could just add the Hibernate property (assuming you use Hibernate as provider) as

...

<property name="hibernate.default_schema" value="myschema"/>

...

Hibernate should pick that up

Java web start - Unable to load resource

Include your IP address in your host file (C:\Windows\System32\drivers\etc\host) for the respective server:

Sample Entry:

10.100.101.102 server1.us.vijay.com Vijay's Server

Closing database connections in Java

Yes, you need to close Connection. Otherwise, the database client will typically keep the socket connection and other resources open.

Reduce git repository size

git gc --aggressive is one way to force the prune process to take place (to be sure: git gc --aggressive --prune=now). You have other commands to clean the repo too. Don't forget though, sometimes git gc alone can increase the size of the repo!

It can be also used after a filter-branch, to mark some directories to be removed from the history (with a further gain of space); see here. But that means nobody is pulling from your public repo. filter-branch can keep backup refs in .git/refs/original, so that directory can be cleaned too.

Finally, as mentioned in this comment and this question; cleaning the reflog can help:

git reflog expire --all --expire=now
git gc --prune=now --aggressive

An even more complete, and possibly dangerous, solution is to remove unused objects from a git repository


Update Feb. 2021, eleven years later: the new git maintenance command (man page) should supersede git gc, and can be scheduled.

Why aren't variable-length arrays part of the C++ standard?

Arrays like this are part of C99, but not part of standard C++. as others have said, a vector is always a much better solution, which is probably why variable sized arrays are not in the C++ standatrd (or in the proposed C++0x standard).

BTW, for questions on "why" the C++ standard is the way it is, the moderated Usenet newsgroup comp.std.c++ is the place to go to.

When to use "ON UPDATE CASCADE"

My comment is mainly in reference to point #3: under what circumstances is ON UPDATE CASCADE applicable if we're assuming that the parent key is not updateable? Here is one case.

I am dealing with a replication scenario in which multiple satellite databases need to be merged with a master. Each satellite is generating data on the same tables, so merging of the tables to the master leads to violations of the uniqueness constraint. I'm trying to use ON UPDATE CASCADE as part of a solution in which I re-increment the keys during each merge. ON UPDATE CASCADE should simplify this process by automating part of the process.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

Create a .c file containing just the line:

_MSC_VER

or

CompilerVersion=_MSC_VER

then pre-process with

cl /nologo /EP <filename>.c

It is easy to parse the output.

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

In my case this was the error.

Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.T4CConnection.isValid(I)Z at org.apache.tomcat.dbcp.dbcp2.DelegatingConnection.isValid(DelegatingConnection.java:917) at org.apache.tomcat.dbcp.dbcp2.PoolableConnection.validate(PoolableConnection.java:282) at org.apache.tomcat.dbcp.dbcp2.PoolableConnectionFactory.validateConnection(PoolableConnectionFactory.java:356) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.validateConnectionFactory(BasicDataSource.java:2306) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createPoolableConnectionFactory(BasicDataSource.java:2289) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.createDataSource(BasicDataSource.java:2038) at org.apache.tomcat.dbcp.dbcp2.BasicDataSource.getConnection(BasicDataSource.java:1532) at beans.Test.main(Test.java:24)

Solution: I just change ojdbc14.jar to ojdbc6.jar

How can I access an internal class from an external assembly?

I would like to argue one point - that you cannot augment the original assembly - using Mono.Cecil you can inject [InternalsVisibleTo(...)] to the 3pty assembly. Note there might be legal implications - you're messing with 3pty assembly and technical implications - if the assembly has strong name you either need to strip it or re-sign it with different key.

 Install-Package Mono.Cecil

And the code like:

static readonly string[] s_toInject = {
  // alternatively "MyAssembly, PublicKey=0024000004800000... etc."
  "MyAssembly"
};

static void Main(string[] args) {
  const string THIRD_PARTY_ASSEMBLY_PATH = @"c:\folder\ThirdPartyAssembly.dll";

   var parameters = new ReaderParameters();
   var asm = ModuleDefinition.ReadModule(INPUT_PATH, parameters);
   foreach (var toInject in s_toInject) {
     var ca = new CustomAttribute(
       asm.Import(typeof(InternalsVisibleToAttribute).GetConstructor(new[] {
                      typeof(string)})));
     ca.ConstructorArguments.Add(new CustomAttributeArgument(asm.TypeSystem.String, toInject));
     asm.Assembly.CustomAttributes.Add(ca);
   }
   asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll");
   // note if the assembly is strongly-signed you need to resign it like
   // asm.Write(@"c:\folder-modified\ThirdPartyAssembly.dll", new WriterParameters {
   //   StrongNameKeyPair = new StrongNameKeyPair(File.ReadAllBytes(@"c:\MyKey.snk"))
   // });
}

Difference between an API and SDK

API is specifications on how to do something, an interface, such as "The railroad tracks are four feet apart, and the metal bar is 1 inch wide" Now that you have the API you can now build a train that will fit on those railroad tracks if you want to go anywhere. API is just information on how to build your code, it doesn't do anything.

SDK is some package of actual tools that already worried about the specifications. "Here's a train, some coal, and a maintenance man. Use it to go from place to place" With the SDK you don't worry about specifics. An SDK is actual code, it can be used by itself to do something, but of course, the train won't start up spontaneously, you still have to get a conductor to control the train.

SDKs also have their own APIs. "If you want to power the train put coal in it", "Pull the blue lever to move the train.", "If the train starts acting funny, call the maintenance man" etc.

Why is document.write considered a "bad practice"?

I don't think using document.write is a bad practice at all. In simple words it is like a high voltage for inexperienced people. If you use it the wrong way, you get cooked. There are many developers who have used this and other dangerous methods at least once, and they never really dig into their failures. Instead, when something goes wrong, they just bail out, and use something safer. Those are the ones who make such statements about what is considered a "Bad Practice".

It's like formatting a hard drive, when you need to delete only a few files and then saying "formatting drive is a bad practice".

Consistency of hashCode() on a Java string

I can see that documentation as far back as Java 1.2.

While it's true that in general you shouldn't rely on a hash code implementation remaining the same, it's now documented behaviour for java.lang.String, so changing it would count as breaking existing contracts.

Wherever possible, you shouldn't rely on hash codes staying the same across versions etc - but in my mind java.lang.String is a special case simply because the algorithm has been specified... so long as you're willing to abandon compatibility with releases before the algorithm was specified, of course.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

you can append the jdbc url with

?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

With the help of this, sql convert '0000-00-00 00:00:00' as null value.

eg:

jdbc:mysql:<host-name>/<db-name>?zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=UTF-8&characterSetResults=UTF-8

How many threads can a Java VM support?

Additional information for modern (systemd) linux systems.

There are many resources about this of values that may need tweaking (such as How to increase maximum number of JVM threads (Linux 64bit)); however a new limit is imposed by way of the systemd "TasksMax" limit which sets pids.max on the cgroup.

For login sessions the UserTasksMax default is 33% of the kernel limit pids_max (usually 12,288) and can be override in /etc/systemd/logind.conf.

For services the DefaultTasksMax default is 15% of the kernel limit pids_max (usually 4,915). You can override it for the service by setting TasksMax in "systemctl edit" or update DefaultTasksMax in /etc/systemd/system.conf

How do I use a third-party DLL file in Visual Studio C++?

In order to use Qt with dynamic linking you have to specify the lib files (usually qtmaind.lib, QtCored4.lib and QtGuid4.lib for the "Debug" configration) in
Properties » Linker » Input » Additional Dependencies.

You also have to specify the path where the libs are, namely in
Properties » Linker » General » Additional Library Directories.

And you need to make the corresponding .dlls are accessible at runtime, by either storing them in the same folder as your .exe or in a folder that is on your path.

Git command to show which specific files are ignored by .gitignore

It should be sufficient to use

git ls-files --others -i --exclude-standard

as that covers everything covered by

git ls-files --others -i --exclude-from=.git/info/exclude

therefore the latter is redundant.


You can make this easier by adding an alias to your ~/.gitconfig file:

git config --global alias.ignored "ls-files --others -i --exclude-standard"

Now you can just type git ignored to see the list. Much easier to remember, and faster to type.

If you prefer the more succinct display of Jason Geng's solution, you can add an alias for that like this:

git config --global alias.ignored "status --ignored -s"

However the more verbose output is more useful for troubleshooting problems with your .gitignore files, as it lists every single cotton-pickin' file that is ignored. You would normally pipe the results through grep to see if a file you expect to be ignored is in there, or if a file you don't want to be ignore is in there.

git ignored | grep some-file-that-isnt-being-ignored-properly

Then, when you just want to see a short display, it's easy enough to remember and type

git status --ignored

(The -s can normally be left off.)

Linq to Sql: Multiple left outer joins

I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:

Dim db As New ContractDataContext()

Dim query = From o In db.Orders _
            Group Join v In db.Vendors _
            On v.VendorNumber Equals o.VendorNumber _
            Into ov = Group _
            From x In ov.DefaultIfEmpty() _
            Group Join s In db.Status _
            On s.Id Equals o.StatusId Into os = Group _
            From y In os.DefaultIfEmpty() _
            Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _
            Select Vendor_Name = x.Name, _
                   Order_Number = o.OrderNumber, _
                   Status_Name = y.StatusName

Intro to GPU programming

Try GPU++ and libSh

LibSh link has a good description of how they bound the programming language to the graphics primitives (and obviously, the primitives themselves), and GPU++ describes what its all about, both with code examples.

Windows could not start the Apache2 on Local Computer - problem

the better way to resolve the issue is change the port number in Apache2\conf\httpd.conf . Change the port number as fallows::: Listen 8888 and ServerName machinename:8888 .Restart the Apache server after changing the port number.

Professional jQuery based Combobox control?

Unfortunately, the best thing I have seen is the jquery.combobox, but it doesn't really look like something I'd really want to use in my web applications. I think there are some usability issues with this control, but as a user I don't think I'd know to start typing for the dropdownlist to turn into a textbox.

I much prefer the Combo Dropdown Box, but it still has some features that I'd want and it's still in alpha. The only think I don't like about this other than its being alpha... is that once I type in the combobox, the original dropdownlist items disappear. However, maybe there is a setting for this... or maybe it could be added fairly easily.

Those are the only two options that I know of. Good luck in your search. I'd love to hear if you find one or if the second option works out for you.

How do I pull from a Git repository through an HTTP proxy?

This worked to me.

git config --global http.proxy proxy_user:proxy_passwd@proxy_ip:proxy_port

Good PHP ORM Library?

I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.

mysqli_fetch_array while loop columns

Try this :

   $i = 0;    
    while($row = mysqli_fetch_array($result)) {  

            $posts['post_id'] = $row[$i]['post_id'];
            $posts['post_title'] = $row[$i]['post_title'];
            $posts['type'] = $row[$i]['type'];
            $posts['author'] = $row[$i]['author'];  

        }   
    $i++;
    }

print_r($posts);

Can I install Python 3.x and 2.x on the same Windows computer?

Try using Anaconda.

Using the concept of Anaconda environments, let’s say you need Python 3 to learn programming, but you don’t want to wipe out your Python 2.7 environment by updating Python. You can create and activate a new environment named "snakes" (or whatever you want), and install the latest version of Python 3 as follows:

conda create --name snakes python=3

Its simpler than it sounds, take a look at the intro page here: Getting Started with Anaconda

And then to handle your specific problem of having version 2.x and 3.x running side by side, see:

c# dictionary one key many values

You can have a dictionary with a collection (or any other type/class) as a value. That way you have a single key and you store the values in your collection.

Python Infinity - Any caveats?

A VERY BAD CAVEAT : Division by Zero

in a 1/x fraction, up to x = 1e-323 it is inf but when x = 1e-324 or little it throws ZeroDivisionError

>>> 1/1e-323
inf

>>> 1/1e-324
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: float division by zero

so be cautious!

Export and import table dump (.sql) using pgAdmin

Click "query tool" button in the list of "tool".

image

And then click the "open file" image button in the tool bar.

image

How to extract .war files in java? ZIP vs JAR

If you look at the JarFile API you'll see that it's a subclass of the ZipFile class.

The jar-specific classes mostly just add jar-specific functionality, like direct support for manifest file attributes and so on.

It's OOP "in action"; since jar files are zip files, the jar classes can use zip functionality and provide additional utility.

How to use __doPostBack()

This is also a good way to get server-side controls to postback inside FancyBox and/or jQuery Dialog. For example, in FancyBox-div:

   <asp:Button OnClientClick="testMe('param1');" ClientIDMode="Static"  ID="MyButton"  runat="server" Text="Ok" >
</asp:Button>

JavaScript:

function testMe(params) {
    var btnID= '<%=MyButton.ClientID %>';          
    __doPostBack(btnID, params);
}

Server-side Page_Load:

 string parameter = Request["__EVENTARGUMENT"];
 if (parameter == "param1")
     MyButton_Click(sender, e);

How do I alter the precision of a decimal column in Sql Server?

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DATA_TYPE();

For you problem:

ALTER TABLE (Your_Table_Name) MODIFY (Your_Column_Name) DECIMAL(Precision, Scale); 

PowerShell and the -contains operator

-Contains is actually a collection operator. It is true if the collection contains the object. It is not limited to strings.

-match and -imatch are regular expression string matchers, and set automatic variables to use with captures.

-like, -ilike are SQL-like matchers.

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

Python spacing and aligning strings

Try %*s and %-*s and prefix each string with the column width:

>>> print "Location: %-*s  Revision: %s" % (20,"10-10-10-10","1")
Location: 10-10-10-10           Revision: 1
>>> print "District: %-*s  Date: %s" % (20,"Tower","May 16, 2012")
District: Tower                 Date: May 16, 2012

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

In this two queries, you are using JOIN to query all employees that have at least one department associated.

But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.

So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.

You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.

I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

Update

If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.

How to git clone a specific tag

Cloning a specific tag, might return 'detached HEAD' state.

As a workaround, try to clone the repo first, and then checkout a specific tag. For example:

repo_url=https://github.com/owner/project.git
repo_dir=$(basename $repo_url .git)
repo_tag=0.5

git clone --single-branch $repo_url # using --depth 1 can show no tags
git --work-tree=$repo_dir --git-dir=$repo_dir/.git checkout tags/$repo_tag

Note: Since Git 1.8.5, you can use -C <path>, instead of --work-tree and --git-dir.

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

How to print jquery object/array

var arrofobject = [{"id":"197","category":"Damskie"},{"id":"198","category":"M\u0119skie"}];

$.each(arrofobject, function(index, val) {
    console.log(val.category);
});

Remove empty strings from array while keeping record Without Loop?

arr = arr.filter(v => v);

as returned v is implicity converted to truthy

Split by comma and strip whitespace in Python

I came to add:

map(str.strip, string.split(','))

but saw it had already been mentioned by Jason Orendorff in a comment.

Reading Glenn Maynard's comment in the same answer suggesting list comprehensions over map I started to wonder why. I assumed he meant for performance reasons, but of course he might have meant for stylistic reasons, or something else (Glenn?).

So a quick (possibly flawed?) test on my box applying the three methods in a loop revealed:

[word.strip() for word in string.split(',')]
$ time ./list_comprehension.py 
real    0m22.876s

map(lambda s: s.strip(), string.split(','))
$ time ./map_with_lambda.py 
real    0m25.736s

map(str.strip, string.split(','))
$ time ./map_with_str.strip.py 
real    0m19.428s

making map(str.strip, string.split(',')) the winner, although it seems they are all in the same ballpark.

Certainly though map (with or without a lambda) should not necessarily be ruled out for performance reasons, and for me it is at least as clear as a list comprehension.

Edit:

Python 2.6.5 on Ubuntu 10.04

How to get directory size in PHP

Object Oriented Approach :

/**
 * Returns a directory size
 *
 * @param string $directory
 *
 * @return int $size directory size in bytes
 *
 */
function dir_size($directory)
{
    $size = 0;
    foreach(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)) as $file)
    {
        $size += $file->getSize();
    }
    return $size;
}

Fast and Furious Approach :

function dir_size2($dir)
{
    $line = exec('du -sh ' . $dir);
    $line = trim(str_replace($dir, '', $line));
    return $line;
}

Unable to install pyodbc on Linux

How about installing pyobdc from zip file? From How to connect to Microsoft Sql Server from Ubuntu using pyODBC:

Download source vs apt-get

The apt-get utility in Ubuntu does have a version of pyODBC. (version 2.1.7).
However, it is badly out-of-date (2.1.7 vs 3.0.6) and may not work well with the newer versions of unixODBC and freetds.
This is especially important if you are trying to connect to later versions of Microsoft Sql Server (2008 onwards).
It is recommended that you use the latest versions of unixODBC, freetds and pyODBC when working with the latest Microsoft Sql Server instead of relying on packages in apt-get.

How to find the last field using 'cut'

It is not possible using just cut. Here is a way using grep:

grep -o '[^,]*$'

Replace the comma for other delimiters.

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

This will simply transform you first letter of text:

yourtext.substr(0,1).toUpperCase()+yourtext.substr(1);

Can you get a Windows (AD) username in PHP?

If you are looking for retrieving remote user IDSID/Username, use:

echo gethostbyaddr($_SERVER['REMOTE_ADDR']);

You will get something like iamuser1-mys.corp.company.com

Filter the rest of the domain behind, and you are able to get the idsid only.

For more information visit http://lostwithin.net/how-to-get-users-ip-and-computer-name-using-php/

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Function that creates a timestamp in c#

You could use the DateTime.Ticks property, which is a long and universal storable, always increasing and usable on the compact framework as well. Just make sure your code isn't used after December 31st 9999 ;)

Hex to ascii string conversion

Few characters like alphabets i-o couldn't be converted into respective ASCII chars . like in string '6631653064316f30723161' corresponds to fedora . but it gives fedra

Just modify hex_to_int() function a little and it will work for all characters. modified function is

int hex_to_int(char c)
{
    if (c >= 97)
        c = c - 32;
    int first = c / 16 - 3;
    int second = c % 16;
    int result = first * 10 + second;
    if (result > 9) result--;
    return result;
}

Now try it will work for all characters.

Change remote repository credentials (authentication) on Intellij IDEA 14

I needed to change my user name and password in Intellij Did it by

preferences -> version control -> GitHub

There you can change user name and password.

Java code To convert byte to Hexadecimal

Creating (and destroying) a bunch of String instances is not a good way if performance is an issue.

Please ignore those verbose (duplicate) arguments checking statements (ifs). That's for (another) educational purposes.

Full maven project: http://jinahya.googlecode.com/svn/trunk/com.googlecode.jinahya/hex-codec/

Encoding...

/**
 * Encodes a single nibble.
 *
 * @param decoded the nibble to encode.
 *
 * @return the encoded half octet.
 */
protected static int encodeHalf(final int decoded) {

    switch (decoded) {
        case 0x00:
        case 0x01:
        case 0x02:
        case 0x03:
        case 0x04:
        case 0x05:
        case 0x06:
        case 0x07:
        case 0x08:
        case 0x09:
            return decoded + 0x30; // 0x30('0') - 0x39('9')
        case 0x0A:
        case 0x0B:
        case 0x0C:
        case 0x0D:
        case 0x0E:
        case 0x0F:
            return decoded + 0x57; // 0x41('a') - 0x46('f')
        default:
            throw new IllegalArgumentException("illegal half: " + decoded);
    }
}


/**
 * Encodes a single octet into two nibbles.
 *
 * @param decoded the octet to encode.
 * @param encoded the array to which each encoded nibbles are written.
 * @param offset the offset in the array.
 */
protected static void encodeSingle(final int decoded, final byte[] encoded,
                                   final int offset) {

    if (encoded == null) {
        throw new IllegalArgumentException("null encoded");
    }

    if (encoded.length < 2) {
        // not required
        throw new IllegalArgumentException(
            "encoded.length(" + encoded.length + ") < 2");
    }

    if (offset < 0) {
        throw new IllegalArgumentException("offset(" + offset + ") < 0");
    }

    if (offset >= encoded.length - 1) {
        throw new IllegalArgumentException(
            "offset(" + offset + ") >= encoded.length(" + encoded.length
            + ") - 1");
    }

    encoded[offset] = (byte) encodeHalf((decoded >> 4) & 0x0F);
    encoded[offset + 1] = (byte) encodeHalf(decoded & 0x0F);
}


/**
 * Decodes given sequence of octets into a sequence of nibbles.
 *
 * @param decoded the octets to encode
 *
 * @return the encoded nibbles.
 */
protected static byte[] encodeMultiple(final byte[] decoded) {

    if (decoded == null) {
        throw new IllegalArgumentException("null decoded");
    }

    final byte[] encoded = new byte[decoded.length << 1];

    int offset = 0;
    for (int i = 0; i < decoded.length; i++) {
        encodeSingle(decoded[i], encoded, offset);
        offset += 2;
    }

    return encoded;
}


/**
 * Encodes given sequence of octets into a sequence of nibbles.
 *
 * @param decoded the octets to encode.
 *
 * @return the encoded nibbles.
 */
public byte[] encode(final byte[] decoded) {

    return encodeMultiple(decoded);
}

Decoding...

/**
 * Decodes a single nibble.
 *
 * @param encoded the nibble to decode.
 *
 * @return the decoded half octet.
 */
protected static int decodeHalf(final int encoded) {

    switch (encoded) {
        case 0x30: // '0'
        case 0x31: // '1'
        case 0x32: // '2'
        case 0x33: // '3'
        case 0x34: // '4'
        case 0x35: // '5'
        case 0x36: // '6'
        case 0x37: // '7'
        case 0x38: // '8'
        case 0x39: // '9'
            return encoded - 0x30;
        case 0x41: // 'A'
        case 0x42: // 'B'
        case 0x43: // 'C'
        case 0x44: // 'D'
        case 0x45: // 'E'
        case 0x46: // 'F'
            return encoded - 0x37;
        case 0x61: // 'a'
        case 0x62: // 'b'
        case 0x63: // 'c'
        case 0x64: // 'd'
        case 0x65: // 'e'
        case 0x66: // 'f'
            return encoded - 0x57;
        default:
            throw new IllegalArgumentException("illegal half: " + encoded);
    }
}


/**
 * Decodes two nibbles into a single octet.
 *
 * @param encoded the nibble array.
 * @param offset the offset in the array.
 *
 * @return decoded octet.
 */
protected static int decodeSingle(final byte[] encoded, final int offset) {

    if (encoded == null) {
        throw new IllegalArgumentException("null encoded");
    }

    if (encoded.length < 2) {
        // not required
        throw new IllegalArgumentException(
            "encoded.length(" + encoded.length + ") < 2");
    }

    if (offset < 0) {
        throw new IllegalArgumentException("offset(" + offset + ") < 0");
    }

    if (offset >= encoded.length - 1) {
        throw new IllegalArgumentException(
            "offset(" + offset + ") >= encoded.length(" + encoded.length
            + ") - 1");
    }

    return (decodeHalf(encoded[offset]) << 4)
           | decodeHalf(encoded[offset + 1]);
}


/**
 * Encodes given sequence of nibbles into a sequence of octets.
 *
 * @param encoded the nibbles to decode.
 *
 * @return the encoded octets.
 */
protected static byte[] decodeMultiple(final byte[] encoded) {

    if (encoded == null) {
        throw new IllegalArgumentException("null encoded");
    }

    if ((encoded.length & 0x01) == 0x01) {
        throw new IllegalArgumentException(
            "encoded.length(" + encoded.length + ") is not even");
    }

    final byte[] decoded = new byte[encoded.length >> 1];

    int offset = 0;
    for (int i = 0; i < decoded.length; i++) {
        decoded[i] = (byte) decodeSingle(encoded, offset);
        offset += 2;
    }

    return decoded;
}


/**
 * Decodes given sequence of nibbles into a sequence of octets.
 *
 * @param encoded the nibbles to decode.
 *
 * @return the decoded octets.
 */
public byte[] decode(final byte[] encoded) {

    return decodeMultiple(encoded);
}

How to read value of a registry key c#

Change:

using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))

To:

 using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

How to reset a select element with jQuery

If you don't want to use the first option (in case the field is hidden or something) then the following jQuery code is enough:

_x000D_
_x000D_
$(document).ready(function(){_x000D_
    $('#but').click(function(){_x000D_
        $('#baba').val(false);_x000D_
    })_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>_x000D_
<select id="baba">_x000D_
<option>select something</option>_x000D_
<option value="1">something 1</option>_x000D_
<option value=2">something 2</option>_x000D_
</select>_x000D_
    _x000D_
    <input type="button" id="but" value="click">
_x000D_
_x000D_
_x000D_

Android ListView with onClick items

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

Here I launch the kmlreader class of my app when I recieve an onclick in the listview.

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

How do I initialize the base (super) class?

Both

SuperClass.__init__(self, x)

or

super(SubClass,self).__init__( x )

will work (I prefer the 2nd one, as it adheres more to the DRY principle).

See here: http://docs.python.org/reference/datamodel.html#basic-customization

Popup window in PHP?

if (isset($_POST['Register']))
    {
        $ErrorArrays = array (); //Empty array for input errors 

        $Input_Username = $_POST['Username'];
        $Input_Password = $_POST['Password'];
        $Input_Confirm = $_POST['ConfirmPass'];
        $Input_Email = $_POST['Email'];

        if (empty($Input_Username))
        {
            $ErrorArrays[] = "Username Is Empty";
        }
        if (empty($Input_Password))
        {
            $ErrorArrays[] = "Password Is Empty";
        }
        if ($Input_Password !== $Input_Confirm)
        {
            $ErrorArrays[] = "Passwords Do Not Match!";
        }
        if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

        if (count($ErrorArrays) == 0)
        {
            // No Errors
        }
        else
        {
            foreach ($ErrorArrays AS $Errors)
            {
                echo "<font color='red'><b>".$Errors."</font></b><br>";
            }
        }
    }

?>

    <form method="POST"> 
        Username: <input type='text' name='Username'> <br>
        Password: <input type='password' name='Password'><br>
        Confirm Password: <input type='password' name='ConfirmPass'><br>
        Email: <input type='text' name='Email'> <br><br>

        <input type='submit' name='Register' value='Register'>


    </form> 

This is a very basic PHP Form validation. This could be put in a try block, but for basic reference, I see this fit following our conversation in the comment box.

What this script will do, is process each of the post elements, and act accordingly, for example:

    if (!filter_var($Input_Email, FILTER_VALIDATE_EMAIL))
        {
            $ErrorArrays[] = "Incorrect Email Formatting";
        }

This will check:

if $Input_Email is not a valid email. If this is not a valid E-mail, then a message will get added to a empty array.

Further down the script, you will see:

    if (count($ErrorArrays) == 0)
    {
        // No Errors
    }
    else
    {
        foreach ($ErrorArrays AS $Errors)
        {
            echo "<font color='red'><b>".$Errors."</font></b><br>";
        }
    }

Basically. if the array count is not 0, errors have been found. Then the script will print out the errors.

Remember, this is a reference based on our conversation in the comment box, and should be used as such.

jQuery event to trigger action when a div is made visible

I had this same problem and created a jQuery plugin to solve it for our site.

https://github.com/shaunbowe/jquery.visibilityChanged

Here is how you would use it based on your example:

$('#contentDiv').visibilityChanged(function(element, visible) {
    alert("do something");
});

jQuery Event : Detect changes to the html/text of a div

Tried some of answers given above but those fires event twice. Here is working solution if you may need the same.

$('mydiv').one('DOMSubtreeModified', function(){
    console.log('changed');
});

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

How to set width to 100% in WPF

You could use HorizontalContentAlignment="Stretch" as follows:

<ListBox HorizontalContentAlignment="Stretch"/>

Extract names of objects from list

You can just use:

> names(LIST)
[1] "A" "B"

Obviously the names of the first element is just

> names(LIST)[1]
[1] "A"

How to match "anything up until this sequence of characters" in a regular expression?

What you need is look around assertion like .+? (?=abc).

See: Lookahead and Lookbehind Zero-Length Assertions

Be aware that [abc] isn't the same as abc. Inside brackets it's not a string - each character is just one of the possibilities. Outside the brackets it becomes the string.

Convert Python program to C/C++ code?

Yes. Look at Cython. It does just that: Converts Python to C for speedups.

Refresh image with a new one at the same url

No need for new Date().getTime() shenanigans. You can trick the browser by having an invisible dummy image and using jQuery .load(), then creating a new image each time:

<img src="" id="dummy", style="display:none;" />  <!-- dummy img -->
<div id="pic"></div>

<script type="text/javascript">
  var url = whatever;
  // You can repeat the following as often as you like with the same url
  $("#dummy").load(url);
  var image = new Image();
  image.src = url;
  $("#pic").html("").append(image);
</script>

How to implement endless list with RecyclerView?

if (layoutManager.findLastCompletelyVisibleItemPosition() == 
 recyclerAdapter.getItemCount() - 1) {
    //load more items.
 }

Fair and simple. This will work.

Fetching data from MySQL database to html dropdown list

What you are asking is pretty straight forward

  1. execute query against your db to get resultset or use API to get the resultset

  2. loop through the resultset or simply the result using php

  3. In each iteration simply format the output as an element

the following refernce should help

HTML option tag

Getting Datafrom MySQL database

hope this helps :)

javascript check for not null

this will do the trick for you

if (!!val) {
    alert("this is not null")
} else {
    alert("this is null")
}

error: resource android:attr/fontVariationSettings not found

I removed all the unused plugins in the pubspec.yaml and in the External Libraries to solve the problem.

LINQ query to find if items in a list are contained in another list

something like this:

List<string> test1 = new List<string> { "@bob.com", "@tom.com" };
List<string> test2 = new List<string> { "[email protected]", "[email protected]" };

var res = test2.Where(f => test1.Count(z => f.Contains(z)) == 0)

Live example: here

AngularJS - Find Element with attribute

You haven't stated where you're looking for the element. If it's within the scope of a controller, it is possible, despite the chorus you'll hear about it not being the 'Angular Way'. The chorus is right, but sometimes, in the real world, it's unavoidable. (If you disagree, get in touch—I have a challenge for you.)

If you pass $element into a controller, like you would $scope, you can use its find() function. Note that, in the jQueryLite included in Angular, find() will only locate tags by name, not attribute. However, if you include the full-blown jQuery in your project, all the functionality of find() can be used, including finding by attribute.

So, for this HTML:

<div ng-controller='MyCtrl'>
    <div>
        <div name='foo' class='myElementClass'>this one</div>
    </div>
</div>

This AngularJS code should work:

angular.module('MyClient').controller('MyCtrl', [
    '$scope',
    '$element',
    '$log',
    function ($scope, $element, $log) {

        // Find the element by its class attribute, within your controller's scope
        var myElements = $element.find('.myElementClass');

        // myElements is now an array of jQuery DOM elements

        if (myElements.length == 0) {
            // Not found. Are you sure you've included the full jQuery?
        } else {
            // There should only be one, and it will be element 0
            $log.debug(myElements[0].name); // "foo"
        }

    }
]);

SQL Server : Arithmetic overflow error converting expression to data type int

On my side, this error came from the data type "INT' in the Null values column. The error is resolved by just changing the data a type to varchar.

HTML iframe - disable scroll

Unfortunately I do not believe it's possible in fully-conforming HTML5 with just HTML and CSS properties. Fortunately however, most browsers do still support the scrolling property (which was removed from the HTML5 specification).

overflow isn't a solution for HTML5 as the only modern browser which wrongly supports this is Firefox.

A current solution would be to combine the two:

<iframe src="" scrolling="no"></iframe>
iframe {
  overflow: hidden;
}

But this could be rendered obsolete as browsers update. You may want to check this for a JavaScript solution: http://www.christersvensson.com/html-tool/iframe.htm

Edit: I've checked and scrolling="no" will work in IE10, Chrome 25 and Opera 12.12.

How do you handle a form change in jQuery?

Extending Udi's answer, this only checks on form submission, not on every input change.

$(document).ready( function () {
  var form_data = $('#myform').serialize();
  $('#myform').submit(function () {
      if ( form_data == $(this).serialize() ) {
        alert('no change');
      } else {
        alert('change');
      }
   });
});

Same font except its weight seems different on different browsers

I have many sites with this issue & finally found a fix to firefox fonts being thicker than chrome.

You need this line next to your -webkit fix -moz-osx-font-smoothing: grayscale;

body{
    text-rendering: optimizeLegibility;
   -webkit-font-smoothing: subpixel-antialiased;
   -webkit-font-smoothing: antialiased;
   -moz-osx-font-smoothing: grayscale;
}

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

if key in array:
  # do something

Associative arrays are called dictionaries in Python and you can learn more about them in the stdtypes documentation.

Sort a List of objects by multiple fields

Your Comparator would look like this:

public class GraduationCeremonyComparator implements Comparator<GraduationCeremony> {
    public int compare(GraduationCeremony o1, GraduationCeremony o2) {
        int value1 = o1.campus.compareTo(o2.campus);
        if (value1 == 0) {
            int value2 = o1.faculty.compareTo(o2.faculty);
            if (value2 == 0) {
                return o1.building.compareTo(o2.building);
            } else {
                return value2;
            }
        }
        return value1;
    }
}

Basically it continues comparing each successive attribute of your class whenever the compared attributes so far are equal (== 0).

How to convert a Binary String to a base 10 integer in Java

Fixed version of java's Integer.parseInt(text) to work with negative numbers:

public static int parseInt(String binary) {
    if (binary.length() < Integer.SIZE) return Integer.parseInt(binary, 2);

    int result = 0;
    byte[] bytes = binary.getBytes();

    for (int i = 0; i < bytes.length; i++) {
        if (bytes[i] == 49) {
            result = result | (1 << (bytes.length - 1 - i));
        }
    }

    return result;
}

Adding items in a Listbox with multiple columns

There is one more way to achieve it:-

Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
    .Top = 30
    .Left = 30
    .Width = 200
    .Height = 340
    .ColumnHeads = True
    .ColumnCount = 2
    .ColumnWidths = "100;100"
    .MultiSelect = fmMultiSelectExtended
    .RowSource = "Sheet1!C4:D25"
End With End Sub

Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.

The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.

jQuery scroll() detect when user stops scrolling

$(window).scroll(function() {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function() {
        // do something
        console.log("Haven't scrolled in 250ms!");
    }, 250));
});

Update

I wrote an extension to enhance jQuery's default on-event-handler. It attaches an event handler function for one or more events to the selected elements and calls the handler function if the event was not triggered for a given interval. This is useful if you want to fire a callback only after a delay, like the resize event, or such.

It is important to check the github-repo for updates!

https://github.com/yckart/jquery.unevent.js

;(function ($) {
    var on = $.fn.on, timer;
    $.fn.on = function () {
        var args = Array.apply(null, arguments);
        var last = args[args.length - 1];

        if (isNaN(last) || (last === 1 && args.pop())) return on.apply(this, args);

        var delay = args.pop();
        var fn = args.pop();

        args.push(function () {
            var self = this, params = arguments;
            clearTimeout(timer);
            timer = setTimeout(function () {
                fn.apply(self, params);
            }, delay);
        });

        return on.apply(this, args);
    };
}(this.jQuery || this.Zepto));

Use it like any other on or bind-event handler, except that you can pass an extra parameter as a last:

$(window).on('scroll', function(e) {
    console.log(e.type + '-event was 250ms not triggered');
}, 250);

http://yckart.github.com/jquery.unevent.js/

(this demo uses resize instead of scroll, but who cares?!)

How to run multiple SQL commands in a single SQL connection?

No one has mentioned this, but you can also separate your commands using a ; semicolon in the same CommandText:

using (SqlConnection conn = new SqlConnection(connString))
    {
        using (SqlCommand comm = new SqlCommand())
        {
                comm.Connection = conn;
                comm.CommandText = @"update table ... where myparam=@myparam1 ; " +
                                    "update table ... where myparam=@myparam2 ";
                comm.Parameters.AddWithValue("@myparam1", myparam1);
                comm.Parameters.AddWithValue("@myparam2", myparam2);
                conn.Open();
                comm.ExecuteNonQuery();

        }
    }

How to get the mouse position without events (without moving the mouse)?

var x = 0;
var y = 0;

document.addEventListener('mousemove', onMouseMove, false)

function onMouseMove(e){
    x = e.clientX;
    y = e.clientY;
}

function getMouseX() {
    return x;
}

function getMouseY() {
    return y;
}

How to start a Process as administrator mode in C#

This works when I try it. I double-checked with two sample programs:

using System;
using System.Diagnostics;

namespace ConsoleApplication1 {
  class Program {
    static void Main(string[] args) {
      Process.Start("ConsoleApplication2.exe");
    }
  }
}

using System;
using System.IO;

namespace ConsoleApplication2 {
  class Program {
    static void Main(string[] args) {
      try {
        File.WriteAllText(@"c:\program files\test.txt", "hello world");
      }
      catch (Exception ex) {
        Console.WriteLine(ex.ToString());
        Console.ReadLine();
      }
    }
  }
}

First verified that I get the UAC bomb:

System.UnauthorizedAccessException: Access to the path 'c:\program files\test.txt' is denied.
// etc..

Then added a manifest to ConsoleApplication1 with the phrase:

    <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

No bomb. And a file I can't easily delete :) This is consistent with several previous tests on various machines running Vista and Win7. The started program inherits the security token from the starter program. If the starter has acquired admin privileges, the started program has them as well.

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

Android - set TextView TextStyle programmatically?

You may try this one

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                textView.setTextAppearance(R.style.Lato_Bold);
            } else {
                textView.setTextAppearance(getActivity(), R.style.Lato_Bold);
            }

How does ifstream's eof() work?

iostream doesn't know it's at the end of the file until it tries to read that first character past the end of the file.

The sample code at cplusplus.com says to do it like this: (But you shouldn't actually do it this way)

  while (is.good())     // loop while extraction from file is possible
  {
    c = is.get();       // get character from file
    if (is.good())
      cout << c;
  }

A better idiom is to move the read into the loop condition, like so: (You can do this with all istream read operations that return *this, including the >> operator)

  char c;
  while(is.get(c))
    cout << c;

Test if object implements interface

In addition to testing using the "is" operator, you can decorate your methods to make sure that variables passed to it implement a particular interface, like so:

public static void BubbleSort<T>(ref IList<T> unsorted_list) where T : IComparable
{
     //Some bubbly sorting
}

I'm not sure which version of .Net this was implemented in so it may not work in your version.

Pass Method as Parameter using C#

You need to use a delegate. In this case all your methods take a string parameter and return an int - this is most simply represented by the Func<string, int> delegate1. So your code can become correct with as simple a change as this:

public bool RunTheMethod(Func<string, int> myMethodName)
{
    // ... do stuff
    int i = myMethodName("My String");
    // ... do more stuff
    return true;
}

Delegates have a lot more power than this, admittedly. For example, with C# you can create a delegate from a lambda expression, so you could invoke your method this way:

RunTheMethod(x => x.Length);

That will create an anonymous function like this:

// The <> in the name make it "unspeakable" - you can't refer to this method directly
// in your own code.
private static int <>_HiddenMethod_<>(string x)
{
    return x.Length;
}

and then pass that delegate to the RunTheMethod method.

You can use delegates for event subscriptions, asynchronous execution, callbacks - all kinds of things. It's well worth reading up on them, particularly if you want to use LINQ. I have an article which is mostly about the differences between delegates and events, but you may find it useful anyway.


1 This is just based on the generic Func<T, TResult> delegate type in the framework; you could easily declare your own:

public delegate int MyDelegateType(string value)

and then make the parameter be of type MyDelegateType instead.

How can I convert a DOM element to a jQuery element?

var elm = document.createElement("div");
var jelm = $(elm);//convert to jQuery Element
var htmlElm = jelm[0];//convert to HTML Element

How to access nested elements of json object using getJSONArray method

I suggest you to use Gson library. It allows to parse JSON string into object data model. Please, see my example:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.SerializedName;

public class GsonProgram {

    public static void main(String... args) {
        String response = "{\"result\":{\"map\":{\"entry\":[{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentA\"},\"value\":\"fsdf\"},{\"key\":{\"@xsi.type\":\"xs:string\",\"$\":\"ContentB\"},\"value\":\"dfdf\"}]}}}";

        Gson gson = new GsonBuilder().serializeNulls().create();
        Response res = gson.fromJson(response, Response.class);

        System.out.println("Entries: " + res.getResult().getMap().getEntry());
    }
}

class Response {

    private Result result;

    public Result getResult() {
        return result;
    }

    public void setResult(Result result) {
        this.result = result;
    }

    @Override
    public String toString() {
        return result.toString();
    }
}

class Result {

    private MapNode map;

    public MapNode getMap() {
        return map;
    }

    public void setMap(MapNode map) {
        this.map = map;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}

class MapNode {

    List<Entry> entry = new ArrayList<Entry>();

    public List<Entry> getEntry() {
        return entry;
    }

    public void setEntry(List<Entry> entry) {
        this.entry = entry;
    }

    @Override
    public String toString() {
        return Arrays.toString(entry.toArray());
    }
}

class Entry {

    private Key key;
    private String value;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public Key getKey() {
        return key;
    }

    public void setKey(Key key) {
        this.key = key;
    }

    @Override
    public String toString() {
        return "[key=" + key + ", value=" + value + "]";
    }
}

class Key {

    @SerializedName("$")
    private String value;

    @SerializedName("@xsi.type")
    private String type;

    public String getValue() {
        return value;
    }

    public void setValue(String value) {
        this.value = value;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    @Override
    public String toString() {
        return "[value=" + value + ", type=" + type + "]";
    }
}

Program output:

Entries: [[key=[value=ContentA, type=xs:string], value=fsdf], [key=[value=ContentB, type=xs:string], value=dfdf]]

If you not familiar with this library, then you can find a lot of informations in "Gson User Guide".

MySQL show current connection info

If you want to know the port number of your local host on which Mysql is running you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'port';


mysql> SHOW VARIABLES WHERE Variable_name = 'port';
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| port          | 3306  |
+---------------+-------+
1 row in set (0.00 sec)

It will give you the port number on which MySQL is running.


If you want to know the hostname of your Mysql you can use this query on MySQL Command line client --

SHOW VARIABLES WHERE Variable_name = 'hostname';


mysql> SHOW VARIABLES WHERE Variable_name = 'hostname';
+-------------------+-------+
| Variable_name     | Value |
+-------------------+-------+
| hostname          | Dell  |
+-------------------+-------+
1 row in set (0.00 sec)

It will give you the hostname for mysql.


If you want to know the username of your Mysql you can use this query on MySQL Command line client --

select user();   


mysql> select user();
+----------------+
| user()         |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)

It will give you the username for mysql.

How can I run a PHP script in the background after a form is submitted?

In my case I have 3 params, one of them is string (mensaje):

exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");

In my Process.php I have this code:

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{   
    die("Error.");
} 

$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];

Angular2 dynamic change CSS property

Just use standard CSS variables:

Your global css (eg: styles.css)

body {
  --my-var: #000
}

In your component's css or whatever it is:

span {
  color: var(--my-var)
}

Then you can change the value of the variable directly with TS/JS by setting inline style to html element:

document.querySelector("body").style.cssText = "--my-var: #000";

Otherwise you can use jQuery for it:

$("body").css("--my-var", "#fff");

ansible : how to pass multiple commands

To run multiple shell commands with ansible you can use the shell module with a multi-line string (note the pipe after shell:), as shown in this example:

  - name: Build nginx 
    shell: |
      cd nginx-1.11.13
      sudo ./configure
      sudo make
      sudo make install

Git asks for username every time I push

In addition to user701648's answer, you can store your credentials in your home folder (global for all projects), instead of project folder using the following command

$ git config --global credential.helper store
$ git push http://example.com/repo.git
Username: <type your username>
Password: <type your password>

jQuery show for 5 seconds then hide

You can use .delay() before an animation, like this:

$("#myElem").show().delay(5000).fadeOut();

If it's not an animation, use setTimeout() directly, like this:

$("#myElem").show();
setTimeout(function() { $("#myElem").hide(); }, 5000);

You do the second because .hide() wouldn't normally be on the animation (fx) queue without a duration, it's just an instant effect.

Or, another option is to use .delay() and .queue() yourself, like this:

$("#myElem").show().delay(5000).queue(function(n) {
  $(this).hide(); n();
});

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

how to set width for PdfPCell in ItextSharp

try this code I think it is more optimal.

HeaderRow is used to repeat the header of the table for each new page automatically

        BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
        iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

        PdfPTable table = new PdfPTable(10) { HorizontalAlignment = Element.ALIGN_CENTER, WidthPercentage = 100, HeaderRows = 2 };
        table.SetWidths(new float[] { 2f, 6f, 6f, 3f, 5f, 8f, 5f, 5f, 5f, 5f });
        table.AddCell(new PdfPCell(new Phrase("SER.\nNO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("TYPE OF SHIPPING", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("ORDER NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("QTY.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISCHARGE PPORT", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESCRIPTION OF GOODS", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("LINE DOC. RECL DATE", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CLEARANCE DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("CUSTOM PERMIT NO.", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DISPATCH DATE", times)) { Rowspan = 2, GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("AWB/BL NO.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("COMPLEX NAME", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("G. W. Kgs.", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("DESTINATION", times)) { GrayFill = 0.95f });
        table.AddCell(new PdfPCell(new Phrase("OWNER DOC. RECL DATE", times)) { GrayFill = 0.95f });

How can I see which Git branches are tracking which remote / upstream branch?

git for-each-ref --format='%(refname:short) <- %(upstream:short)' refs/heads

will show a line for each local branch. A tracking branch will look like:

master <- origin/master

A non-tracking one will look like:

test <- 

Construct pandas DataFrame from items in nested dictionary

Building on verified answer, for me this worked best:

ab = pd.concat({k: pd.DataFrame(v).T for k, v in data.items()}, axis=0)
ab.T

Converting an integer to binary in C

You can use function this function to return char* with string representation of the integer:

   char* itob(int i) {
      static char bits[8] = {'0','0','0','0','0','0','0','0'};
      int bits_index = 7;
      while ( i > 0 ) {
         bits[bits_index--] = (i & 1) + '0';
         i = ( i >> 1);
      }
      return bits;
   }

It's not a perfect implementation, but if you test with a simple printf("%s", itob(170)), you'll get 01010101 as I recall 170 was. Add atoi(itob(170)) and you'll get the integer but it's definitely not 170 in integer value.

Random character generator with a range of (A..Z, 0..9) and punctuation

  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. Profit!

I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)

How to make a DIV always float on the screen in top right corner?

Use position:fixed, as previously stated, IE6 doesn't recognize position:fixed, but with some css magic you can get IE6 to behave:

html, body {
    height: 100%;
    overflow:auto;
}
body #fixedElement {
    position:fixed !important;
    position: absolute; /*ie6 */
    bottom: 0;
}

The !important flag makes it so you don't have to use a conditional comment for IE. This will have #fixedElement use position:fixed in all browsers but IE, and in IE, position:absolute will take effect with bottom:0. This will simulate position:fixed for IE6

What are intent-filters in Android?

The Activity which you want it to be the very first screen if your app is opened, then mention it as LAUNCHER in the intent category and remaining activities mention Default in intent category.

For example :- There is 2 activity A and B
The activity A is LAUNCHER so make it as LAUNCHER in the intent Category and B is child for Activity A so make it as DEFAULT.

<application android:icon="@drawable/icon" android:label="@string/app_name">
    <activity android:name=".ListAllActivity"
              android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".AddNewActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>
</application>

React Native TextInput that only accepts numeric characters

For Decimal /Floating point number only try this

    onChangeMyFloatNumber(text){
let newText = '';
let numbers = '0123456789.';

for (var i=0; i < text.length; i++) {
    if(numbers.indexOf(text[i]) > -1 ) {
        newText = newText + text[i];
        if(text[i]=="."){
          numbers = '0123456789'
        }
    }
    else {
        // your call back function
        alert("please enter numbers only");
    }
}
this.setState({ MyFloatNumber: newText });

}

Python return statement error " 'return' outside function"

As per the documentation on the return statement, return may only occur syntactically nested in a function definition. The same is true for yield.

How to convert an array of strings to an array of floats in numpy?

Another option might be numpy.asarray:

import numpy as np
a = ["1.1", "2.2", "3.2"]
b = np.asarray(a, dtype=np.float64, order='C')

For Python 2*:

print a, type(a), type(a[0])
print b, type(b), type(b[0])

resulting in:

['1.1', '2.2', '3.2'] <type 'list'> <type 'str'>
[1.1 2.2 3.2] <type 'numpy.ndarray'> <type 'numpy.float64'>

How to run a script at the start up of Ubuntu?

First of all, the easiest way to run things at startup is to add them to the file /etc/rc.local.

Another simple way is to use @reboot in your crontab. Read the cron manpage for details.

However, if you want to do things properly, in addition to adding a script to /etc/init.d you need to tell ubuntu when the script should be run and with what parameters. This is done with the command update-rc.d which creates a symlink from some of the /etc/rc* directories to your script. So, you'd need to do something like:

update-rc.d yourscriptname start 2

However, real init scripts should be able to handle a variety of command line options and otherwise integrate to the startup process. The file /etc/init.d/README has some details and further pointers.

How to install toolbox for MATLAB

For installing standard toolboxes: Just insert your CD/DVD of MATLAB and start installing, when you see typical/Custom, choose custom and check the toolboxes you want to install and uncheck the others which are installed already.

How can you use optional parameters in C#?

optional parameters are for methods. if you need optional arguments for a class and you are:

  • using c# 4.0: use optional arguments in the constructor of the class, a solution i prefer, since it's closer to what is done with methods, so easier to remember. here's an example:

    class myClass
    {
        public myClass(int myInt = 1, string myString =
                               "wow, this is cool: i can have a default string")
        {
            // do something here if needed
        }
    }
    
  • using c# versions previous to c#4.0: you should use constructor chaining (using the :this keyword), where simpler constructors lead to a "master constructor". example:

    class myClass
    {
        public myClass()
        {
        // this is the default constructor
        }
    
        public myClass(int myInt)
            : this(myInt, "whatever")
        {
            // do something here if needed
        }
        public myClass(string myString)
            : this(0, myString)
        {
            // do something here if needed
        }
        public myClass(int myInt, string myString)
        {
            // do something here if needed - this is the master constructor
        }
    }
    

How can I check for NaN values?

For nan of type float

>>> import pandas as pd
>>> value = float(nan)
>>> type(value)
>>> <class 'float'>
>>> pd.isnull(value)
True
>>>
>>> value = 'nan'
>>> type(value)
>>> <class 'str'>
>>> pd.isnull(value)
False

How to create a windows service from java app

With Apache Commons Daemon you can now have a custom executable name and icon! You can also get a custom Windows tray monitor with your own name and icon!

I now have my service running with my own name and icon (prunsrv.exe), and the system tray monitor (prunmgr.exe) also has my own custom name and icon!

  1. Download the Apache Commons Daemon binaries (you will need prunsrv.exe and prunmgr.exe).

  2. Rename them to be MyServiceName.exe and MyServiceNamew.exe respectively.

  3. Download WinRun4J and use the RCEDIT.exe program that comes with it to modify the Apache executable to embed your own custom icon like this:

    > RCEDIT.exe /I MyServiceName.exe customIcon.ico
    > RCEDIT.exe /I MyServiceNamew.exe customTrayIcon.ico
    
  4. Now install your Windows service like this (see documentation for more details and options):

    > MyServiceName.exe //IS//MyServiceName \
      --Install="C:\path-to\MyServiceName.exe" \
      --Jvm=auto --Startup=auto --StartMode=jvm \
      --Classpath="C:\path-to\MyJarWithClassWithMainMethod.jar" \
      --StartClass=com.mydomain.MyClassWithMainMethod
    
  5. Now you have a Windows service of your Jar that will run with your own icon and name! You can also launch the monitor file and it will run in the system tray with your own icon and name.

    > MyServiceNamew.exe //MS//MyServiceName
    

Java: how to import a jar file from command line

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

Efficiently finding the last line in a text file

Use the file's seek method with a negative offset and whence=os.SEEK_END to read a block from the end of the file. Search that block for the last line end character(s) and grab all the characters after it. If there is no line end, back up farther and repeat the process.

def last_line(in_file, block_size=1024, ignore_ending_newline=False):
    suffix = ""
    in_file.seek(0, os.SEEK_END)
    in_file_length = in_file.tell()
    seek_offset = 0

    while(-seek_offset < in_file_length):
        # Read from end.
        seek_offset -= block_size
        if -seek_offset > in_file_length:
            # Limit if we ran out of file (can't seek backward from start).
            block_size -= -seek_offset - in_file_length
            if block_size == 0:
                break
            seek_offset = -in_file_length
        in_file.seek(seek_offset, os.SEEK_END)
        buf = in_file.read(block_size)

        # Search for line end.
        if ignore_ending_newline and seek_offset == -block_size and buf[-1] == '\n':
            buf = buf[:-1]
        pos = buf.rfind('\n')
        if pos != -1:
            # Found line end.
            return buf[pos+1:] + suffix

        suffix = buf + suffix

    # One-line file.
    return suffix

Note that this will not work on things that don't support seek, like stdin or sockets. In those cases, you're stuck reading the whole thing (like the tail command does).

Android SQLite Example

The DBHelper class is what handles the opening and closing of sqlite databases as well sa creation and updating, and a decent article on how it all works is here. When I started android it was very useful (however I've been objective-c lately, and forgotten most of it to be any use.

T-SQL STOP or ABORT command in SQL Server

To work around the RETURN/GO issue you could put RAISERROR ('Oi! Stop!', 20, 1) WITH LOG at the top.

This will close the client connection as per RAISERROR on MSDN.

The very big downside is you have to be sysadmin to use severity 20.

Edit:

A simple demonstration to counter Jersey Dude's comment...

RAISERROR ('Oi! Stop!', 20, 1)  WITH LOG
SELECT 'Will not run'
GO
SELECT 'Will not run'
GO
SELECT 'Will not run'
GO

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long and long int are identical. So are long long and long long int. In both cases, the int is optional.

As to the difference between the two sets, the C++ standard mandates minimum ranges for each, and that long long is at least as wide as long.

The controlling parts of the standard (C++11, but this has been around for a long time) are, for one, 3.9.1 Fundamental types, section 2 (a later section gives similar rules for the unsigned integral types):

There are five standard signed integer types : signed char, short int, int, long int, and long long int. In this list, each type provides at least as much storage as those preceding it in the list.

There's also a table 9 in 7.1.6.2 Simple type specifiers, which shows the "mappings" of the specifiers to actual types (showing that the int is optional), a section of which is shown below:

Specifier(s)         Type
-------------    -------------
long long int    long long int
long long        long long int
long int         long int
long             long int

Note the distinction there between the specifier and the type. The specifier is how you tell the compiler what the type is but you can use different specifiers to end up at the same type.

Hence long on its own is neither a type nor a modifier as your question posits, it's simply a specifier for the long int type. Ditto for long long being a specifier for the long long int type.

Although the C++ standard itself doesn't specify the minimum ranges of integral types, it does cite C99, in 1.2 Normative references, as applying. Hence the minimal ranges as set out in C99 5.2.4.2.1 Sizes of integer types <limits.h> are applicable.


In terms of long double, that's actually a floating point value rather than an integer. Similarly to the integral types, it's required to have at least as much precision as a double and to provide a superset of values over that type (meaning at least those values, not necessarily more values).

pip install: Please check the permissions and owner of that directory

If you altered your $PATH variable that could also cause the problem. If you think that might be the issue, check your ~/.bash_profile or ~/.bashrc

Evaluate if list is empty JSTL

empty is an operator:

The empty operator is a prefix operation that can be used to determine whether a value is null or empty.

<c:if test="${empty myObject.featuresList}">

A free tool to check C/C++ source code against a set of coding standards?

Check universalindentgui on sourceforge.net.

it has many style checkers for C and you can customise the checkers.

How to create timer in angular2

Another solution is to use TimerObservable

TimerObservable is a subclass of Observable.

import {Component, OnInit, OnDestroy} from '@angular/core';
import {Subscription} from "rxjs";
import {TimerObservable} from "rxjs/observable/TimerObservable";

@Component({
  selector: 'app-component',
  template: '{{tick}}',
})
export class Component implements OnInit, OnDestroy {

  private tick: string;
  private subscription: Subscription;

  constructor() {
  }

  ngOnInit() {
    let timer = TimerObservable.create(2000, 1000);
    this.subscription = timer.subscribe(t => {
      this.tick = t;
    });
  }

  ngOnDestroy() {
    this.subscription.unsubscribe();
  }
}

P.S.: Don't forget to unsubsribe.

Randomize a List<T>

I'm bit surprised by all the clunky versions of this simple algorithm here. Fisher-Yates (or Knuth shuffle) is bit tricky but very compact. Why is it tricky? Because your need to pay attention to whether your random number generator r(a,b) returns value where b is inclusive or exclusive. I've also edited Wikipedia description so people don't blindly follow pseudocode there and create hard to detect bugs. For .Net, Random.Next(a,b) returns number exclusive of b so without further ado, here's how it can be implemented in C#/.Net:

public static void Shuffle<T>(this IList<T> list, Random rnd)
{
    for(var i=list.Count; i > 0; i--)
        list.Swap(0, rnd.Next(0, i));
}

public static void Swap<T>(this IList<T> list, int i, int j)
{
    var temp = list[i];
    list[i] = list[j];
    list[j] = temp;
}

Try this code.

Export MySQL database using PHP only

Best way to export database using php script.

Or add 5th parameter(array) of specific tables: array("mytable1","mytable2","mytable3") for multiple tables

<?php 
    //ENTER THE RELEVANT INFO BELOW
    $mysqlUserName      = "Your Username";
    $mysqlPassword      = "Your Password";
    $mysqlHostName      = "Your Host";
    $DbName             = "Your Database Name here";
    $backup_name        = "mybackup.sql";
    $tables             = "Your tables";

   //or add 5th parameter(array) of specific tables:    array("mytable1","mytable2","mytable3") for multiple tables

    Export_Database($mysqlHostName,$mysqlUserName,$mysqlPassword,$DbName,  $tables=false, $backup_name=false );

    function Export_Database($host,$user,$pass,$name,  $tables=false, $backup_name=false )
    {
        $mysqli = new mysqli($host,$user,$pass,$name); 
        $mysqli->select_db($name); 
        $mysqli->query("SET NAMES 'utf8'");

        $queryTables    = $mysqli->query('SHOW TABLES'); 
        while($row = $queryTables->fetch_row()) 
        { 
            $target_tables[] = $row[0]; 
        }   
        if($tables !== false) 
        { 
            $target_tables = array_intersect( $target_tables, $tables); 
        }
        foreach($target_tables as $table)
        {
            $result         =   $mysqli->query('SELECT * FROM '.$table);  
            $fields_amount  =   $result->field_count;  
            $rows_num=$mysqli->affected_rows;     
            $res            =   $mysqli->query('SHOW CREATE TABLE '.$table); 
            $TableMLine     =   $res->fetch_row();
            $content        = (!isset($content) ?  '' : $content) . "\n\n".$TableMLine[1].";\n\n";

            for ($i = 0, $st_counter = 0; $i < $fields_amount;   $i++, $st_counter=0) 
            {
                while($row = $result->fetch_row())  
                { //when started (and every after 100 command cycle):
                    if ($st_counter%100 == 0 || $st_counter == 0 )  
                    {
                            $content .= "\nINSERT INTO ".$table." VALUES";
                    }
                    $content .= "\n(";
                    for($j=0; $j<$fields_amount; $j++)  
                    { 
                        $row[$j] = str_replace("\n","\\n", addslashes($row[$j]) ); 
                        if (isset($row[$j]))
                        {
                            $content .= '"'.$row[$j].'"' ; 
                        }
                        else 
                        {   
                            $content .= '""';
                        }     
                        if ($j<($fields_amount-1))
                        {
                                $content.= ',';
                        }      
                    }
                    $content .=")";
                    //every after 100 command cycle [or at last line] ....p.s. but should be inserted 1 cycle eariler
                    if ( (($st_counter+1)%100==0 && $st_counter!=0) || $st_counter+1==$rows_num) 
                    {   
                        $content .= ";";
                    } 
                    else 
                    {
                        $content .= ",";
                    } 
                    $st_counter=$st_counter+1;
                }
            } $content .="\n\n\n";
        }
        //$backup_name = $backup_name ? $backup_name : $name."___(".date('H-i-s')."_".date('d-m-Y').")__rand".rand(1,11111111).".sql";
        $backup_name = $backup_name ? $backup_name : $name.".sql";
        header('Content-Type: application/octet-stream');   
        header("Content-Transfer-Encoding: Binary"); 
        header("Content-disposition: attachment; filename=\"".$backup_name."\"");  
        echo $content; exit;
    }
?>

Check if $_POST exists

I would like to add my answer even though this thread is years old and it ranked high in Google for me.

My best method is to try:

if(sizeof($_POST) !== 0){
// Code...
}

As $_POST is an array, if the script loads and no data is present in the $_POST variable it will have an array length of 0. This can be used in an IF statement.

You may also be wondering if this throws an "undefined index" error seeing as though we're checking if $_POST is set... In fact $_POST always exists, the "undefined index" error will only appear if you try to search for a $_POST array value that doesn't exist.

$_POST always exists in itself being either empty or has array values. $_POST['value'] may not exist, thus throwing an "undefined index" error.

Remove leading zeros from a number in Javascript

It is not clear why you want to do this. If you want to get the correct numerical value, you could use unary + [docs]:

value = +value;

If you just want to format the text, then regex could be better. It depends on the values you are dealing with I'd say. If you only have integers, then

input.value = +input.value;

is fine as well. Of course it also works for float values, but depending on how many digits you have after the point, converting it to a number and back to a string could (at least for displaying) remove some.

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

How to detect when an Android app goes to the background and come back to the foreground

I found a good method to detect application whether enter foreground or background. Here is my code. Hope this help you.

/**
 * Custom Application which can detect application state of whether it enter
 * background or enter foreground.
 *
 * @reference http://www.vardhan-justlikethat.blogspot.sg/2014/02/android-solution-to-detect-when-android.html
 */
 public abstract class StatusApplication extends Application implements ActivityLifecycleCallbacks {

public static final int STATE_UNKNOWN = 0x00;
public static final int STATE_CREATED = 0x01;
public static final int STATE_STARTED = 0x02;
public static final int STATE_RESUMED = 0x03;
public static final int STATE_PAUSED = 0x04;
public static final int STATE_STOPPED = 0x05;
public static final int STATE_DESTROYED = 0x06;

private static final int FLAG_STATE_FOREGROUND = -1;
private static final int FLAG_STATE_BACKGROUND = -2;

private int mCurrentState = STATE_UNKNOWN;
private int mStateFlag = FLAG_STATE_BACKGROUND;

@Override
public void onCreate() {
    super.onCreate();
    mCurrentState = STATE_UNKNOWN;
    registerActivityLifecycleCallbacks(this);
}

@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
    // mCurrentState = STATE_CREATED;
}

@Override
public void onActivityStarted(Activity activity) {
    if (mCurrentState == STATE_UNKNOWN || mCurrentState == STATE_STOPPED) {
        if (mStateFlag == FLAG_STATE_BACKGROUND) {
            applicationWillEnterForeground();
            mStateFlag = FLAG_STATE_FOREGROUND;
        }
    }
    mCurrentState = STATE_STARTED;

}

@Override
public void onActivityResumed(Activity activity) {
    mCurrentState = STATE_RESUMED;

}

@Override
public void onActivityPaused(Activity activity) {
    mCurrentState = STATE_PAUSED;

}

@Override
public void onActivityStopped(Activity activity) {
    mCurrentState = STATE_STOPPED;

}

@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

}

@Override
public void onActivityDestroyed(Activity activity) {
    mCurrentState = STATE_DESTROYED;
}

@Override
public void onTrimMemory(int level) {
    super.onTrimMemory(level);
    if (mCurrentState == STATE_STOPPED && level >= TRIM_MEMORY_UI_HIDDEN) {
        if (mStateFlag == FLAG_STATE_FOREGROUND) {
            applicationDidEnterBackground();
            mStateFlag = FLAG_STATE_BACKGROUND;
        }
    }else if (mCurrentState == STATE_DESTROYED && level >= TRIM_MEMORY_UI_HIDDEN) {
        if (mStateFlag == FLAG_STATE_FOREGROUND) {
            applicationDidDestroyed();
            mStateFlag = FLAG_STATE_BACKGROUND;
        }
    }
}

/**
 * The method be called when the application been destroyed. But when the
 * device screen off,this method will not invoked.
 */
protected abstract void applicationDidDestroyed();

/**
 * The method be called when the application enter background. But when the
 * device screen off,this method will not invoked.
 */
protected abstract void applicationDidEnterBackground();

/**
 * The method be called when the application enter foreground.
 */
protected abstract void applicationWillEnterForeground();

}

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

How do I show the schema of a table in a MySQL database?

Perhaps the question needs to be slightly more precise here about what is required because it can be read it two different ways. i.e.

  1. How do I get the structure/definition for a table in mysql?
  2. How do I get the name of the schema/database this table resides in?

Given the accepted answer, the OP clearly intended it to be interpreted the first way. For anybody reading the question the other way try

SELECT `table_schema` 
FROM `information_schema`.`tables` 
WHERE `table_name` = 'whatever';

Git Remote: Error: fatal: protocol error: bad line length character: Unab

i also encounter that error once in a while, but when it does, it means that my branch is not up-to-date so i have to do git pull origin <current_branch>

The term 'Get-ADUser' is not recognized as the name of a cmdlet

For the particular case of Windows 10 October 2018 Update or later activedirectory module is not available unless the optional feature RSAT: Active Directory Domain Services and Lightweight Directory Services Tools is installed (instructions here + uncollapse install instructions).

Reopen Windows Powershell and import-module activedirectory will work as expected.

Random / noise functions for GLSL

It occurs to me that you could use a simple integer hash function and insert the result into a float's mantissa. IIRC the GLSL spec guarantees 32-bit unsigned integers and IEEE binary32 float representation so it should be perfectly portable.

I gave this a try just now. The results are very good: it looks exactly like static with every input I tried, no visible patterns at all. In contrast the popular sin/fract snippet has fairly pronounced diagonal lines on my GPU given the same inputs.

One disadvantage is that it requires GLSL v3.30. And although it seems fast enough, I haven't empirically quantified its performance. AMD's Shader Analyzer claims 13.33 pixels per clock for the vec2 version on a HD5870. Contrast with 16 pixels per clock for the sin/fract snippet. So it is certainly a little slower.

Here's my implementation. I left it in various permutations of the idea to make it easier to derive your own functions from.

/*
    static.frag
    by Spatial
    05 July 2013
*/

#version 330 core

uniform float time;
out vec4 fragment;



// A single iteration of Bob Jenkins' One-At-A-Time hashing algorithm.
uint hash( uint x ) {
    x += ( x << 10u );
    x ^= ( x >>  6u );
    x += ( x <<  3u );
    x ^= ( x >> 11u );
    x += ( x << 15u );
    return x;
}



// Compound versions of the hashing algorithm I whipped together.
uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y)                         ); }
uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z)             ); }
uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }



// Construct a float with half-open range [0:1] using low 23 bits.
// All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
float floatConstruct( uint m ) {
    const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
    const uint ieeeOne      = 0x3F800000u; // 1.0 in IEEE binary32

    m &= ieeeMantissa;                     // Keep only mantissa bits (fractional part)
    m |= ieeeOne;                          // Add fractional part to 1.0

    float  f = uintBitsToFloat( m );       // Range [1:2]
    return f - 1.0;                        // Range [0:1]
}



// Pseudo-random value in half-open range [0:1].
float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
float random( vec2  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec3  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec4  v ) { return floatConstruct(hash(floatBitsToUint(v))); }





void main()
{
    vec3  inputs = vec3( gl_FragCoord.xy, time ); // Spatial and temporal inputs
    float rand   = random( inputs );              // Random per-pixel value
    vec3  luma   = vec3( rand );                  // Expand to RGB

    fragment = vec4( luma, 1.0 );
}

Screenshot:

Output of random(vec3) in static.frag

I inspected the screenshot in an image editing program. There are 256 colours and the average value is 127, meaning the distribution is uniform and covers the expected range.

Merging dictionaries in C#

Here is a helper function I use:

using System.Collections.Generic;
namespace HelperMethods
{
    public static class MergeDictionaries
    {
        public static void Merge<TKey, TValue>(this IDictionary<TKey, TValue> first, IDictionary<TKey, TValue> second)
        {
            if (second == null || first == null) return;
            foreach (var item in second) 
                if (!first.ContainsKey(item.Key)) 
                    first.Add(item.Key, item.Value);
        }
    }
}

Warning: implode() [function.implode]: Invalid arguments passed

It happens when $ret hasn't been defined. The solution is simple. Right above $tags = get_tags();, add the following line:

$ret = array();

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I have found that images in the 'drawable' folder will get converted to a much larger image on high def phones. For example, a 200k image will be resampled to a higher res, like 800k or 32000k. I had to discover this on my own and to date have not seen documentation for this heap memory trap. To prevent this I put everything in a drawable-nodpi folder (in addition to using 'options' in BitmapFactory based on the particular device heap). I can't afford to have the size of my app bloated with multiple drawable folders, particularly as the range of screen defs is so vast now. The tricky thing is studio now doesn't specifically indicate the 'drawable-nodpi' folder as such in the project view, it just shows a 'drawable' folder. If you're not careful, when you drop an image to this folder in studio, it won't actually get dropped into the drawable-nodpi:

Careful here 'backgroundtest' did not actually go to drawable-nodpi and will 
be resampled higher, such as 4x or 16x of the original dimensions for high def screens.

enter image description here

Be sure to click down to the nodpi folder in the dialogue, as the project view won't show you all drawable folders separately like it used to, so it won't be immediately apparent that it went to wrong one. Studio recreated the vanilla 'drawable' at some point for me after I had deleted it long ago:

enter image description here

Do copyright dates need to be updated?

Your OCD is to blame :)

You do not have to put anything about copyright on your page - copyright automatically applies until you explicitly license it otherwise. Copyright also applies for a preset number of years as determined by international treaties. I do not know what the exact number of years is, but it is a lot, so there is absolutely no point in updating the year in your copyright notice.

Simple Java Client/Server Program

this is client code

first run the server program then on another cmd run client program

import java.io.*;
import java.net.*;

public class frmclient 
{
 public static void main(String args[])throws Exception
 {

   try
        {
          DataInputStream d=new DataInputStream(System.in);
          System.out.print("\n1.fact\n2.Sum of digit\nEnter ur choice:");

           int ch=Integer.parseInt(d.readLine());
           System.out.print("\nEnter number:");
           int num=Integer.parseInt(d.readLine());

           Socket s=new Socket("localhost",1024);

           PrintStream ps=new PrintStream(s.getOutputStream());
           ps.println(ch+"");
           ps.println(num+"");

          DataInputStream dis=new DataInputStream(s.getInputStream());
           String response=dis.readLine();
                 System.out.print("Answer:"+response);


                s.close();
        }
        catch(Exception ex)
        {

        }
 }


}

this is sever side code

import java.io.*;
import java.net.*;
public class frmserver {

  public static void main(String args[])throws Exception
  {

try
    {

    ServerSocket ss=new ServerSocket(1024);
       System.out.print("\nWaiting for client.....");
       Socket s=ss.accept();
       System.out.print("\nConnected");

       DataInputStream d=new DataInputStream(s.getInputStream());

        int ch=Integer.parseInt(d.readLine());
       int num=Integer.parseInt(d.readLine());
         int result=0;

        PrintStream ps=new PrintStream(s.getOutputStream());
        switch(ch)
        {
          case 1:result=fact(num);
                 ps.println(result);
                  break;
          case 2:result=sum(num);
                 ps.println(result);
                  break;
        }

          ss.close();
          s.close();
    }
catch(Exception ex)
{

}
  }

  public static int fact(int n)
  {
  int ans=1;
    for(int i=n;i>0;i--)
    {
      ans=ans*i;
    }
    return ans;
  }
  public static int sum(int n)
  {
   String str=n+"";
   int ans=0;
    for(int i=0;i<str.length();i++)
    {
      int tmp=Integer.parseInt(str.charAt(i)+"");
      ans=ans+tmp;
    }
    return ans;
  }
}

mysql update column with value from another table

Second possibility is,

UPDATE TableB 
SET TableB.value = (
    SELECT TableA.value 
    FROM TableA
    WHERE TableA.name = TableB.name
);

How can I get column names from a table in Oracle?

For MySQL, use

SELECT column_name 
FROM information_schema.columns 
WHERE 
table_schema = 'Schema' AND table_name = 'Table_Name'

Are HTTP headers case-sensitive?

header('Content-type: image/png') did not work with PHP 5.5 serving IE11, as in the image stream was shown as text

header('Content-Type: image/png') worked, as in the image appeared as an image

Only difference is the capital 'T'.

MySQL Database won't start in XAMPP Manager-osx

What I did was the following: In XAMPP Control Panel I edited the my.ini file of configuration of MySql and changed the port from 3306 to 3307 and it worked, hope it helped!

Edit: after you save this changes be sure that the service is off and then restart the service. I had this same problem when I installed MySQL, it's just the port.

Color text in terminal applications in UNIX

Use ANSI escape sequences. This article goes into some detail about them. You can use them with printf as well.

How to make a SIMPLE C++ Makefile

Why does everyone like to list out source files? A simple find command can take care of that easily.

Here's an example of a dirt simple C++ Makefile. Just drop it in a directory containing .C files and then type make...

appname := myapp

CXX := clang++
CXXFLAGS := -std=c++11

srcfiles := $(shell find . -name "*.C")
objects  := $(patsubst %.C, %.o, $(srcfiles))

all: $(appname)

$(appname): $(objects)
    $(CXX) $(CXXFLAGS) $(LDFLAGS) -o $(appname) $(objects) $(LDLIBS)

depend: .depend

.depend: $(srcfiles)
    rm -f ./.depend
    $(CXX) $(CXXFLAGS) -MM $^>>./.depend;

clean:
    rm -f $(objects)

dist-clean: clean
    rm -f *~ .depend

include .depend

How can I reorder my divs using only CSS?

This can be done using Flexbox.

Create a container that applies both display:flex and flex-flow:column-reverse.

_x000D_
_x000D_
/* -- Where the Magic Happens -- */_x000D_
_x000D_
.container {_x000D_
  _x000D_
  /* Setup Flexbox */_x000D_
  display: -webkit-box;_x000D_
  display: -moz-box;_x000D_
  display: -ms-flexbox;_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
_x000D_
  /* Reverse Column Order */_x000D_
  -webkit-flex-flow: column-reverse;_x000D_
  flex-flow: column-reverse;_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
/* -- Styling Only -- */_x000D_
_x000D_
.container > div {_x000D_
  background: red;_x000D_
  color: white;_x000D_
  padding: 10px;_x000D_
}_x000D_
_x000D_
.container > div:last-of-type {_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  _x000D_
  <div class="first">_x000D_
_x000D_
     first_x000D_
_x000D_
  </div>_x000D_
  _x000D_
  <div class="second">_x000D_
_x000D_
    second_x000D_
_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

Sources:

Can't get Python to import from a different folder

import user

u=user.User() #error on this line

Because of the lack of __init__ mentioned above, you would expect an ImportError which would make the problem clearer.

You don't get one because 'user' is also an existing module in the standard library. Your import statement grabs that one and tries to find the User class inside it; that doesn't exist and only then do you get the error.

It is generally a good idea to make your import absolute:

import Server.Models.user

to avoid this kind of ambiguity. Indeed from Python 2.7 'import user' won't look relative to the current module at all.

If you really want relative imports, you can have them explicitly in Python 2.5 and up using the somewhat ugly syntax:

from .user import User

HTML <select> selected option background-color CSS style

You may not be able to do this using pure CSS. But, a little javascript can do it nicely.

A crude way to do it -

var sel = document.getElementById('select_id');
sel.addEventListener('click', function(el){
    var options = this.children;
    for(var i=0; i < this.childElementCount; i++){
        options[i].style.color = 'white';
    }
    var selected = this.children[this.selectedIndex];
        selected.style.color = 'red';
    }, false);

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

I juste made this code, from some StackOverflow discussions. I didn't test on Linux environment yet. It is made in order to delete a file or a directory, completely :

function splRm(SplFileInfo $i)
{
    $path = $i->getRealPath();

    if ($i->isDir()) {
        echo 'D - ' . $path . '<br />';
        rmdir($path);
    } elseif($i->isFile()) {
        echo 'F - ' . $path . '<br />';
        unlink($path);
    }
}

function splRrm(SplFileInfo $j)
{
    $path = $j->getRealPath();

    if ($j->isDir()) {
        $rdi = new RecursiveDirectoryIterator($path, FilesystemIterator::SKIP_DOTS);
        $rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::CHILD_FIRST);
        foreach ($rii as $i) {
            splRm($i);
        }
    }
    splRm($j);

}

splRrm(new SplFileInfo(__DIR__.'/../dirOrFileName'));

How to simulate a mouse click using JavaScript?

You can use elementFromPoint:

document.elementFromPoint(x, y);

supported in all browsers: https://caniuse.com/#feat=element-from-point

Passing data from controller to view in Laravel

The best and easy way to pass single or multiple variables to view from controller is to use compact() method.

For passing single variable to view,

return view("user/regprofile",compact('students'));

For passing multiple variable to view,

return view("user/regprofile",compact('students','teachers','others'));

And in view, you can easily loop through the variable,

@foreach($students as $student)
   {{$student}}
@endforeach

Which language uses .pde extension?

Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here

Looks very cool.

How to add plus one (+1) to a SQL Server column in a SQL Query

"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"

Send password when using scp to copy files from one server to another

// copy /tmp/abc.txt to /tmp/abc.txt (target path)

// username and password of 10.1.1.2 is "username" and "password"

sshpass -p "password" scp /tmp/abc.txt [email protected]:/tmp/abc.txt

// install sshpass (ubuntu)

sudo apt-get install sshpass

Difference between == and ===

In both Objective-C and Swift, the == and != operators test for value equality for number values (e.g., NSInteger, NSUInteger, int, in Objective-C and Int, UInt, etc. in Swift). For objects (NSObject/NSNumber and subclasses in Objective-C and reference types in Swift), == and != test that the objects/reference types are the same identical thing -- i.e., same hash value -- or are not the same identical thing, respectively.

let a = NSObject()
let b = NSObject()
let c = a
a == b // false
a == c // true

Swift's identity equality operators, === and !==, check referential equality -- and thus, should probably be called the referential equality operators IMO.

a === b // false
a === c // true

It's also worth pointing out that custom reference types in Swift (that do not subclass a class that conforms to Equatable) do not automatically implement the equal to operators, but the identity equality operators still apply. Also, by implementing ==, != is automatically implemented.

class MyClass: Equatable {
  let myProperty: String

  init(s: String) {
    myProperty = s
  }
}

func ==(lhs: MyClass, rhs: MyClass) -> Bool {
  return lhs.myProperty == rhs.myProperty
}

let myClass1 = MyClass(s: "Hello")
let myClass2 = MyClass(s: "Hello")
myClass1 == myClass2 // true
myClass1 != myClass2 // false
myClass1 === myClass2 // false
myClass1 !== myClass2 // true

These equality operators are not implemented for other types such as structures in either language. However, custom operators can be created in Swift, which would, for example, enable you to create an operator to check equality of a CGPoint.

infix operator <==> { precedence 130 }
func <==> (lhs: CGPoint, rhs: CGPoint) -> Bool {
  return lhs.x == rhs.x && lhs.y == rhs.y
}

let point1 = CGPoint(x: 1.0, y: 1.0)
let point2 = CGPoint(x: 1.0, y: 1.0)
point1 <==> point2 // true

Best way to track onchange as-you-type in input type="text"?

Javascript is unpredictable and funny here.

  • onchange occurs only when you blur the textbox
  • onkeyup & onkeypress doesn't always occur on text change
  • onkeydown occurs on text change (but cannot track cut & paste with mouse click)
  • onpaste & oncut occurs with keypress and even with the mouse right click.

So, to track the change in textbox, we need onkeydown, oncut and onpaste. In the callback of these event, if you check the value of the textbox then you don't get the updated value as the value is changed after the callback. So a solution for this is to set a timeout function with a timeout of 50 mili-seconds (or may be less) to track the change.

This is a dirty hack but this is the only way, as I researched.

Here is an example. http://jsfiddle.net/2BfGC/12/

How do I tell CMake to link in a static library in the source directory?

If you don't want to include the full path, you can do

add_executable(main main.cpp)
target_link_libraries(main bingitup)

bingitup is the same name you'd give a target if you create the static library in a CMake project:

add_library(bingitup STATIC bingitup.cpp)

CMake automatically adds the lib to the front and the .a at the end on Linux, and .lib at the end on Windows.

If the library is external, you might want to add the path to the library using

link_directories(/path/to/libraries/)

set column width of a gridview in asp.net

<asp:GridView ID="GridView1" runat="server">
    <HeaderStyle Width="10%" />
    <RowStyle Width="10%" />
    <FooterStyle Width="10%" />
    <Columns>
        <asp:BoundField HeaderText="Name" DataField="LastName" 
            HeaderStyle-Width="10%" ItemStyle-Width="10%"
            FooterStyle-Width="10%" />
    </Columns>
</asp:GridView>

An example of how to use getopts in bash

"getops" and "getopt" are very limited. While "getopt" is suggested not to be used at all, it does offer long options. Where as "getopts" does only allow single character options such as "-a" "-b". There are a few more disadvantages when using either one.

So i've written a small script that replaces "getopts" and "getopt". It's a start, it could probably be improved a lot.

Update 08-04-2020: I've added support for hyphens e.g. "--package-name".

Usage: "./script.sh package install --package "name with space" --build --archive"

# Example:
# parseArguments "${@}"
# echo "${ARG_0}" -> package
# echo "${ARG_1}" -> install
# echo "${ARG_PACKAGE}" -> "name with space"
# echo "${ARG_BUILD}" -> 1 (true)
# echo "${ARG_ARCHIVE}" -> 1 (true)
function parseArguments() {
  PREVIOUS_ITEM=''
  COUNT=0
  for CURRENT_ITEM in "${@}"
  do
    if [[ ${CURRENT_ITEM} == "--"* ]]; then
      printf -v "ARG_$(formatArgument "${CURRENT_ITEM}")" "%s" "1" # could set this to empty string and check with [ -z "${ARG_ITEM-x}" ] if it's set, but empty.
    else
      if [[ $PREVIOUS_ITEM == "--"* ]]; then
        printf -v "ARG_$(formatArgument "${PREVIOUS_ITEM}")" "%s" "${CURRENT_ITEM}"
      else
        printf -v "ARG_${COUNT}" "%s" "${CURRENT_ITEM}"
      fi
    fi

    PREVIOUS_ITEM="${CURRENT_ITEM}"
    (( COUNT++ ))
  done
}

# Format argument.
function formatArgument() {
  ARGUMENT="${1^^}" # Capitalize.
  ARGUMENT="${ARGUMENT/--/}" # Remove "--".
  ARGUMENT="${ARGUMENT//-/_}" # Replace "-" with "_".
  echo "${ARGUMENT}"
}

Hamcrest compare collections

For list of objects you may need something like this:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.beans.HasPropertyWithValue.hasProperty;
import static org.hamcrest.Matchers.is;

@Test
@SuppressWarnings("unchecked")
public void test_returnsList(){

    arrange();
  
    List<MyBean> myList = act();
    
    assertThat(myList , contains(allOf(hasProperty("id",          is(7L)), 
                                       hasProperty("name",        is("testName1")),
                                       hasProperty("description", is("testDesc1"))),
                                 allOf(hasProperty("id",          is(11L)), 
                                       hasProperty("name",        is("testName2")),
                                       hasProperty("description", is("testDesc2")))));
}

Use containsInAnyOrder if you do not want to check the order of the objects.

P.S. Any help to avoid the warning that is suppresed will be really appreciated.

How do I open a Visual Studio project in design view?

My problem, it showed an error called "The class Form1 can be designed, but is not the first class in the file. Visual Studio requires that designers use the first class in the file. Move the class code so that it is the first class in the file and try loading the designer again. ". So I moved the Form class to the first one and it worked. :)

jQuery and TinyMCE: textarea value doesn't submit

I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:

$("textarea[id='id_answer']").change(function(){
    var editor_id = $(this).attr('id');
    var editor = tinymce.get(editor_id);
    editor.setContent($(this).val()).save();
});

It works for me.

How to update Ruby to 1.9.x on Mac?

I'll disagree with The Tin Man here. I regard rbenv as preferable to RVM. rbenv doesn't interfere drastically with your shell the way RVM does, and it lets you add separate Ruby installations in ordinary folders that you can examine directly. It allows you to compile Ruby yourself. Good outline of the differences here: https://github.com/sstephenson/rbenv/wiki/Why-rbenv%3F

I provide instructions for compiling Ruby 1.9 for rbenv here. Further, more detailed information here. I have used this technique with easy success on Snow Leopard, Lion, and Mountain Lion.

Fit website background image to screen size

background: url("../image/b21.jpg") no-repeat center center fixed;

background-size: 100% 100%;

height: 100%;

position: absolute; 

width: 100%;

Pagination response payload from a RESTful API

As someone who has written several libraries for consuming REST services, let me give you the client perspective on why I think wrapping the result in metadata is the way to go:

  • Without the total count, how can the client know that it has not yet received everything there is and should continue paging through the result set? In a UI that didn't perform look ahead to the next page, in the worst case this might be represented as a Next/More link that didn't actually fetch any more data.
  • Including metadata in the response allows the client to track less state. Now I don't have to match up my REST request with the response, as the response contains the metadata necessary to reconstruct the request state (in this case the cursor into the dataset).
  • If the state is part of the response, I can perform multiple requests into the same dataset simultaneously, and I can handle the requests in any order they happen to arrive in which is not necessarily the order I made the requests in.

And a suggestion: Like the Twitter API, you should replace the page_number with a straight index/cursor. The reason is, the API allows the client to set the page size per-request. Is the returned page_number the number of pages the client has requested so far, or the number of the page given the last used page_size (almost certainly the later, but why not avoid such ambiguity altogether)?

C# '@' before a String

Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.

For example if your string contains a path you would typically do this:

string path = "c:\\mypath\\to\\myfile.txt";

The @ allows you to do this:

string path = @"c:\mypath\to\myfile.txt";

Notice the lack of double slashes (escaping)

What is “assert” in JavaScript?

In addition to other options like console.assert or rolling your own, you can use invariant. It has a couple of unique features:

  • It supports formatted error messages (using a %s specifier).
  • In production environments (as determined by the Node.js or Webpack environment), the error message is optional, allowing for (slightly) smaller .js.

How to update cursor limit for ORA-01000: maximum open cursors exceed

you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts

Is it possible to capture the stdout from the sh DSL command in the pipeline

You can try to use as well this functions to capture StdErr StdOut and return code.

def runShell(String command){
    def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt" 
    def output =  readFile(file: "tmp.txt")

    if (responseCode != 0){
      println "[ERROR] ${output}"
      throw new Exception("${output}")
    }else{
      return "${output}"
    }
}

Notice:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name

Difference between logger.info and logger.debug

What is the difference between logger.debug and logger.info?

These are only some default level already defined. You can define your own levels if you like. The purpose of those levels is to enable/disable one or more of them, without making any change in your code.

When logger.debug will be printed ??

When you have enabled the debug or any higher level in your configuration.

Why do I get PLS-00302: component must be declared when it exists?

You can get that error if you have an object with the same name as the schema. For example:

create sequence s2;

begin
  s2.a;
end;
/

ORA-06550: line 2, column 6:
PLS-00302: component 'A' must be declared
ORA-06550: line 2, column 3:
PL/SQL: Statement ignored

When you refer to S2.MY_FUNC2 the object name is being resolved so it doesn't try to evaluate S2 as a schema name. When you just call it as MY_FUNC2 there is no confusion, so it works.

The documentation explains name resolution. The first piece of the qualified object name - S2 here - is evaluated as an object on the current schema before it is evaluated as a different schema.

It might not be a sequence; other objects can cause the same error. You can check for the existence of objects with the same name by querying the data dictionary.

select owner, object_type, object_name
from all_objects
where object_name = 'S2';

ERROR in ./node_modules/css-loader?

I tried both

npm rebuild node-sass

and

npm install --save node-sass

Later by seeing EACCESS, i checked the folder permission of /node_modules, which was not 777 permission

Then I gave

chmod -R 777 *

-R for recursively(setting the same permission not in the dir but also inside nested sub dir) * is for all files in current directory

What is file permission

To check for permission you can use

ls -l

If u don't know about it, first see here, then check the url

Every file and directory has permission of 'rwx'(read, write, execute). and if 'x' permission is not there, then you can not execture, if no 'w', you can not write into the file. if some thing is missiing it will show in place of r/w/x with '-'. So, if 'x' permission is not there, it will show like 'rw-'

And there will be 3 category of user Owner(who created the file/directory), Group(some people who shares same permission and user previlege), Others(general public)

So 1st letter is 'd'(if it is a directory) or '-'(if it is not a directory), followed by rwx for owner, followed by for group, followed by other

drwxrwxrwx

For example, for 'node_modules'directory I want to give permission to owner all permission and for rest only read, then it will be

drwxr--r--

And about the number assume for 'r/w/x' it is 1 and for '-' it is 0, 777, first 7 is for owner, followed by group, followed by other

Let's assume the permission is rwxr-xrw-

Now 'rwx' is like '111' and it's equivalent decimal is 1*2^2+1*2^1+1*2^0=7

Now 'r-x' is like '101' and it's equivalent decimal is 1*2^2+0*2^1+1*2^0=5

Now 'rw-' is like '110' and it's equivalent decimal is 1*2^2+1*2^1+0*2^0=6

So, it will be 756

SQL Server - NOT IN

It's because of the way NOT IN works.

To avoid these headaches (and for a faster query in many cases), I always prefer NOT EXISTS:

SELECT  *  
FROM Table1 t1 
WHERE NOT EXISTS (
    SELECT * 
    FROM Table2 t2 
    WHERE t1.MAKE = t2.MAKE
    AND   t1.MODEL = t2.MODEL
    AND   t1.[Serial Number] = t2.[serial number]);

Rails: How does the respond_to block work?

This is a block of Ruby code that takes advantage of a Rails helper method. If you aren't familiar with blocks yet, you will see them a lot in Ruby.

respond_to is a Rails helper method that is attached to the Controller class (or rather, its super class). It is referencing the response that will be sent to the View (which is going to the browser).

The block in your example is formatting data - by passing in a 'format' paramater in the block - to be sent from the controller to the view whenever a browser makes a request for html or json data.

If you are on your local machine and you have your Post scaffold set up, you can go to http://localhost:3000/posts and you will see all of your posts in html format. But, if you type in this: http://localhost:3000/posts.json, then you will see all of your posts in a json object sent from the server.

This is very handy for making javascript heavy applications that need to pass json back and forth from the server. If you wanted, you could easily create a json api on your rails back-end, and only pass one view - like the index view of your Post controller. Then you could use a javascript library like Jquery or Backbone (or both) to manipulate data and create your own interface. These are called asynchronous UIs and they are becomming really popular (Gmail is one). They are very fast and give the end-user a more desktop-like experience on the web. Of course, this is just one advantage of formatting your data.

The Rails 3 way of writing this would be this:

    class PostsController < ApplicationController
      # GET /posts
      # GET /posts.xml


      respond_to :html, :xml, :json

      def index
        @posts = Post.all

        respond_with(@posts)
      end

#
# All your other REST methods
#

end

By putting respond_to :html, :xml, :json at the top of the class, you can declare all the formats that you want your controller to send to your views.

Then, in the controller method, all you have to do is respond_with(@whatever_object_you_have)

It just simplifies your code a little more than what Rails auto-generates.

If you want to know about the inner-workings of this...

From what I understand, Rails introspects the objects to determine what the actual format is going to be. The 'format' variables value is based on this introspection. Rails can do a whole lot with a little bit of info. You'd be surprised at how far a simple @post or :post will go.

For example, if I had a _user.html.erb partial file that looked like this:

_user.html.erb

<li>    
    <%= link_to user.name, user %>
</li>

Then, this alone in my index view would let Rails know that it needed to find the 'users' partial and iterate through all of the 'users' objects:

index.html.erb

 <ul class="users">
   <%= render @users %>     
 </ul>

would let Rails know that it needed to find the 'user' partial and iterate through all of the 'users' objects:

You may find this blog post useful: http://archives.ryandaigle.com/articles/2009/8/6/what-s-new-in-edge-rails-cleaner-restful-controllers-w-respond_with

You can also peruse the source: https://github.com/rails/rails

Direct download from Google Drive using Google Drive API

I would consider downloading from the link, scraping the page that you get to grab the confirmation link, and then downloading that.

If you look at the "download anyway" URL it has an extra confirm query parameter with a seemingly randomly generated token. Since it's random...and you probably don't want to figure out how to generate it yourself, scraping might be the easiest way without knowing anything about how the site works.

You may need to consider various scenarios.

How to get the system uptime in Windows?

Following are eight ways to find the Uptime in Windows OS.

1: By using the Task Manager

In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.

  1. Right-click on the Taskbar, and click Task Manager. You can also click CTRL+SHIFT+ESC to get to the Task Manager.
  2. In Task Manager, select the Performance tab.
  3. The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.

    "Up Time" field in Task Manager

2: By using the System Information Utility

The systeminfo command line utility checks and displays various system statistics such as installation date, installed hotfixes and more. Open a Command Prompt and type the following command:

systeminfo

You can also narrow down the results to just the line you need:

systeminfo | find "System Boot Time:"

enter image description here

3: By using the Uptime Utility

Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.

Read the following KB for more info and for the download links:

To use it, follow these steps:

  1. Download uptime.exe from the above link, and save it to a folder, preferably in one that's in the system's path (such as SYSTEM32).
  2. Open an elevated Command Prompt window. To open an elevated Command Prompt, click Start, click All Programs, click Accessories, right-click Command Prompt, and then click Run as administrator. You can also type CMD in the search box of the Start menu, and when you see the Command Prompt icon click on it to select it, hold CTRL+SHIFT and press ENTER.
  3. Navigate to where you've placed the uptime.exe utility.
  4. Run the uptime.exe utility. You can add a /? to the command in order to get more options. enter image description here

It does not offer many command line parameters:

C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
    -V   display version

C:\uptimefromcodeplex\> uptime -V
version 1.1.0

3.1: By using the old Uptime Utility

There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)

Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)

C:\uptimev100download>uptime.exe /?

UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
        server          Name or IP address of remote server to process.
        /s              Display key system events and statistics.
        /a              Display application failure events (assumes /s).
        /d:             Only calculate for events after mm/dd/yyyy.
        /p:             Only calculate for events in the previous n days.
        /heartbeat      Turn on/off the system's heartbeat
        /?              Basic usage.
        /help           Additional usage information.

4: By using the NET STATISTICS Utility

Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:

net statistics workstation

The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.

enter image description here

5: By Using the Event Viewer

Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.

Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.

Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.

  1. Click on Event Viewer (Local) in the left navigation pane.
  2. In the middle pane, click on the Information event type, and scroll down till you see Event ID 6005. Double-click the 6005 Event ID, or right-click it and select View All Instances of This Event.
  3. A list of all instances of the 6005 Event ID will be displayed. You can examine this list, look at the dates and times of each reboot event, and so on.
  4. Open Server Manager tool by right-clicking the Computer icon on the start menu (or on the Desktop if you have it enabled) and select Manage. Navigate to the Event Viewer.

enter image description here

5.1: Eventlog via PowerShell

Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}

6: Programmatically, by using GetTickCount64

GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.

7: By using WMI

wmic os get lastbootuptime

8: The new uptime.exe for Windows XP and up

Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h command-line parameter).

Additionally, this version of uptime.exe will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:

enter image description here

and when executed as uptime -h:

enter image description here

How to run a function in jquery

I would do it this way:

(function($) {
jQuery.fn.doSomething = function() {
   return this.each(function() {
      var $this = $(this);

      $this.click(function(event) {
         event.preventDefault();
         // Your function goes here
      });
   });
};
})(jQuery);

Then on document ready you can do stuff like this:

$(document).ready(function() {
   $('#div1').doSomething();
   $('#div2').doSomething();
});

the easiest way to convert matrix to one row vector

You can use the function RESHAPE:

B = reshape(A.',1,[]);

ASP.NET MVC 3 Razor - Adding class to EditorFor

I just needed to set the size of one textbox on one page. Coding attributes on the model and creating custom editor templates were overkill, so I just wrapped the @Html.EditorFor call with a span tag that called a class which specifies the size of the textbox.

CSS class declaration:

.SpaceAvailableSearch input
{
    width:25px;
}

View code:

<span class="SpaceAvailableSearch">@Html.EditorFor(model => model.SearchForm.SpaceAvailable)</span>

Git diff says subproject is dirty

Also removing the submodule and then running git submodule init and git submodule update will obviously do the trick, but may not always be appropriate or possible.

Calling a function every 60 seconds

In jQuery you can do like this.

_x000D_
_x000D_
function random_no(){_x000D_
     var ran=Math.random();_x000D_
     jQuery('#random_no_container').html(ran);_x000D_
}_x000D_
           _x000D_
window.setInterval(function(){_x000D_
       /// call your function here_x000D_
      random_no();_x000D_
}, 6000);  // Change Interval here to test. For eg: 5000 for 5 sec
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="random_no_container">_x000D_
      Hello. Here you can see random numbers after every 6 sec_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to cd into a directory with space in the name?

Instead of:

DOCS="/cygdrive/c/Users/my\ dir/Documents"

Try:

DOCS="/cygdrive/c/Users/my dir/Documents" 

This should work on any POSIX system.

C: What is the difference between ++i and i++?

a=i++ means a contains current i value a=++i means a contains incremented i value

Center Plot title in ggplot2

From the release news of ggplot 2.2.0: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title argument in ?theme: "left-aligned by default".

As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5)) to center the title.

ggplot() +
  ggtitle("Default in 2.2.0 is left-aligned")

enter image description here

ggplot() +
  ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
  theme(plot.title = element_text(hjust = 0.5))

enter image description here

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

NULL or BLANK fields (ORACLE)

SELECT COUNT (COL_NAME) 
FROM TABLE 
WHERE TRIM (COL_NAME) IS NULL 
or COL_NAME='NULL'

What does "implements" do on a class?

An interface defines a simple contract of methods all implementing classes must implement. When a class implements an interface, it must provide implementations for all its methods.

I guess the poster assumes a certain level of knowledge about the language.

Select multiple value in DropDownList using ASP.NET and C#

Take a look at the ListBox control to allow multi-select.

<asp:ListBox runat="server" ID="lblMultiSelect" SelectionMode="multiple">
            <asp:ListItem Text="opt1" Value="opt1" />
            <asp:ListItem Text="opt2" Value="opt2" />
            <asp:ListItem Text="opt3" Value="opt3" />
</asp:ListBox> 

in the code behind

foreach(ListItem listItem in lblMultiSelect.Items)
    {
       if (listItem.Selected)
       {
          var val = listItem.Value;
          var txt = listItem.Text; 
       }
    }

document.getElementById(id).focus() is not working for firefox or chrome

Try using a timer:

var mnumber = document.getElementById('mobileno').value;
if (mnumber.length >=10) 
{ 
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    window.setTimeout(function ()
    {
        document.getElementById('mobileno').focus();
    }, 0);
    return false;
}

A timer with a count of 0 will run when the thread becomes idle. If that doesn't help, try the code (with the timer) in the onblur event instead.

Select distinct values from a list using LINQ in C#

I was curious about which method would be faster:

  1. Using Distinct with a custom IEqualityComparer or
  2. Using the GroupBy method described by Cuong Le.

I found that depending on the size of the input data and the number of groups, the Distinct method can be a lot more performant. (as the number of groups tends towards the number of elements in the list, distinct runs faster).

Code runs in LinqPad!

    void Main()
    {
        List<C> cs = new List<C>();
        foreach(var i in Enumerable.Range(0,Int16.MaxValue*1000))
        {
            int modValue = Int16.MaxValue; //vary this value to see how the size of groups changes performance characteristics. Try 1, 5, 10, and very large numbers
            int j = i%modValue; 
            cs.Add(new C{I = i, J = j});
        }
        cs.Count ().Dump("Size of input array");

        TestGrouping(cs);
        TestDistinct(cs);
    }

    public void TestGrouping(List<C> cs)
    {
        Stopwatch sw = Stopwatch.StartNew();
        sw.Restart();
        var groupedCount  = cs.GroupBy (o => o.J).Select(s => s.First()).Count();
        groupedCount.Dump("num groups");
        sw.ElapsedMilliseconds.Dump("elapsed time for using grouping");
    }

    public void TestDistinct(List<C> cs)
    {
        Stopwatch sw = Stopwatch.StartNew();
        var distinctCount = cs.Distinct(new CComparerOnJ()).Count ();
        distinctCount.Dump("num distinct");
        sw.ElapsedMilliseconds.Dump("elapsed time for using distinct");
    }

    public class C
    {
        public int I {get; set;}
        public int J {get; set;}
    }

    public class CComparerOnJ : IEqualityComparer<C>
    {
        public bool Equals(C x, C y)
        {
            return x.J.Equals(y.J);
        }

        public int GetHashCode(C obj)
        {
            return obj.J.GetHashCode();
        }
    }

Printing chars and their ASCII-code in C

To print all the ascii values from 0 to 255 using while loop.

#include<stdio.h>

int main(void)
{
    int a;
    a = 0;
    while (a <= 255)
    {
        printf("%d = %c\n", a, a);
        a++;
    }
    return 0;
}

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

SVN checkout the contents of a folder, not the folder itself

Just add the directory on the command line:

svn checkout svn://192.168.1.1/projectname/ target-directory/

ResourceDictionary in a separate assembly

An example, just to make this a 15 seconds answer -

Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:

  1. Add a reference from the main project to "common" project
  2. Your app.xaml should contain:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

SQL exclude a column using SELECT * [except columnA] FROM tableA?

You can use REGEX Column Specification.

The following query selects all columns except ds and hr SELECT (ds|hr)?+.+ FROM sales

Fastest check if row exists in PostgreSQL

as @MikeM pointed out.

select exists(select 1 from contact where id=12)

with index on contact, it can usually reduce time cost to 1 ms.

CREATE INDEX index_contact on contact(id);

C# Encoding a text string with line breaks

Try \n\n , it will work! :)

public async Task AjudaAsync(IDialogContext context, LuisResult result){
await context.PostAsync("How can I help you? \n\n 1.To Schedule \n\n 2.Consult");
context.Wait(MessageReceived);
}

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

How do I escape a reserved word in Oracle?

you have to rename the column to an other name because TABLE is reserved by Oracle.

You can see all reserved words of Oracle in the oracle view V$RESERVED_WORDS.

How to list branches that contain a given commit?

You may run:

git log <SHA1>..HEAD --ancestry-path --merges

From comment of last commit in the output you may find original branch name

Example:

       c---e---g--- feature
      /         \
-a---b---d---f---h---j--- master

git log e..master --ancestry-path --merges

commit h
Merge: g f
Author: Eugen Konkov <>
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'feature' into master

Convert a String In C++ To Upper Case

#include <algorithm>
#include <string>

std::string str = "Hello World";
std::transform(str.begin(), str.end(),str.begin(), ::toupper);

Is there any way to have a fieldset width only be as wide as the controls in them?

You can always use CSS to constrain the width of the fieldset, which would also constrain the controls inside.

I find that I often have to constrain the width of select controls, or else really long option text will make it totally unmanageable.

iOS 7.0 No code signing identities found

With fastlane installed, you can create and install an Development Certificate by

cert --development
sigh --development

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

One of the values you pass on to Ancestors becomes None at some point, it says, so check if otu, tree, tree[otu] or tree[otu][0] are None in the beginning of the function instead of only checking tree[otu][0][0] == None. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.

Maven - Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean

If you open the directory which it is trying to delete then also you will face same error so first close the folder.

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

How can you dynamically create variables via a while loop?

Keyword parameters allow you to pass variables from one function to another. In this way you can use the key of a dictionary as a variable name (which can be populated in your while loop). The dictionary name just needs to be preceded by ** when it is called.

# create a dictionary
>>> kwargs = {}
# add a key of name and assign it a value, later we'll use this key as a variable
>>> kwargs['name'] = 'python'

# an example function to use the variable
>>> def print_name(name):
...   print name

# call the example function
>>> print_name(**kwargs)
python

Without **, kwargs is just a dictionary:

>>> print_name(kwargs)
{'name': 'python'}

How to compare dates in Java?

Use compareTo:

date1.compareTo(date2);

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Writing a dictionary to a text file?

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

data = {'A': 'a', 'B': 'b', }

with open('file.py','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))
    file.write("}")

Then to import:

from file import dictionary_name

Best way to repeat a character in C#

The best version is certainly to use the builtin way:

string Tabs(int len) { return new string('\t', len); }

Of the other solutions, prefer the easiest; only if this is proving too slow, strive for a more efficient solution.

If you use a StringBuilder and know its resulting length in advance, then also use an appropriate constructor, this is much more efficient because it means that only one time-consuming allocation takes place, and no unnecessary copying of data. Nonsense: of course the above code is more efficient.

align textbox and text/labels in html?

you can do a multi div layout like this

<div class="fieldcontainer">
    <div class="label"></div>
    <div class="field"></div>
</div>

where .fieldcontainer { clear: both; } .label { float: left; width: ___ } .field { float: left; }

Or, I actually prefer tables for forms like this. This is very much tabular data and it comes out very clean. Both will work though.

Fatal error: Class 'SoapClient' not found

For PHP 8:

sudo apt update
sudo apt-get install php8.0-soap

Hide Show content-list with only CSS, no javascript used

Nowadays (2020) you can do this with pure HTML5 and you don't need JavaScript or CSS3.

<details>
<summary>Put your summary here</summary>
<p>Put your content here!</p>
</details>

Java SSLHandshakeException "no cipher suites in common"

Having had this exception myself, I delved into the JRE source code. It became apparent that the message is rather misleading. It could mean what it says, but it more generally means that the server doesn't have the data it needs to respond to the client in the requested way. This can happen, for example, if certificates are missing from the keystore, or haven't been generated with the an appropriate algoritm. Indeed, given the cipher suites that are installed by default, one would have to go to some lengths to really get this exception because of lack of common cipher suites. In my particular case I'd generated the certificates with the default algorithm of DSA, when what I needed to get the server to work with Firefox was RSA.

Check if a row exists using old mysql_* API

$result = mysql_query("select if(exists (SELECT * FROM  preditors_assigned WHERE lecture_name='$lectureName'),'Assigned', 'Available')");

How to remove duplicates from Python list and keep order?

A list can be sorted and deduplicated using built-in functions:

myList = sorted(set(myList))
  • set is a built-in function for Python >= 2.3
  • sorted is a built-in function for Python >= 2.4