Programs & Examples On #Webtrends

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

Can I use Homebrew on Ubuntu?

As of February 2018, installing brew on Ubuntu (mine is 17.10) machine is as simple as:

sudo apt install linuxbrew-wrapper

Then, on first brew execution (just type brew --help) you will be asked for two installation options:

me@computer:~/$ brew --help
==> Select the Linuxbrew installation directory
- Enter your password to install to /home/linuxbrew/.linuxbrew (recommended)
- Press Control-D to install to /home/me/.linuxbrew
- Press Control-C to cancel installation
[sudo] password for me:

For recommended option type your password (if your current user is in sudo group), or, if you prefer installing all the dependencies in your own home folder, hit Ctrl+D. Enjoy.

PHP/regex: How to get the string value of HTML tag?

In your pattern, you simply want to match all text between the two tags. Thus, you could use for example a [\w\W] to match all characters.

function getTextBetweenTags($string, $tagname) {
    $pattern = "/<$tagname>([\w\W]*?)<\/$tagname>/";
    preg_match($pattern, $string, $matches);
    return $matches[1];
}

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

How to insert values into the database table using VBA in MS access

  1. Remove this line of code: For i = 1 To DatDiff. A For loop must have the word NEXT
  2. Also, remove this line of code: StrSQL = StrSQL & "SELECT 'Test'" because its making Access look at your final SQL statement like this; INSERT INTO Test (Start_Date) VALUES ('" & InDate & "' );SELECT 'Test' Notice the semicolon in the middle of the SQL statement (should always be at the end. its by the way not required. you can also omit it). also, there is no space between the semicolon and the key word SELECT

in summary: remove those two lines of code above and your insert statement will work fine. You can the modify the code it later to suit your specific needs. And by the way, some times, you have to enclose dates in pounds signs like #

default web page width - 1024px or 980px?

even there is no right or wrong answer for this question , but I personally prefer 960px width . since all modern monitors support at least 1024 × 768 pixel resolution. 960 is divisible by 2, 3, 4, 5, 6, 8, 10, 12, 15, 16, 20, 24, 30, 32, 40, 48, 60, 64, 80, 96, 120, 160, 192, 240, 320 and 480. This makes it a highly flexible base number to work with.

see this article that shows most popular screens resolutions 2013-2014 in US and UK : http://www.hobo-web.co.uk/best-screen-size/

Oracle SQL - DATE greater than statement

you have to use the To_Date() function to convert the string to date ! http://www.techonthenet.com/oracle/functions/to_date.php

SELECT INTO using Oracle

Use:

create table new_table_name 
as
select column_name,[more columns] from Existed_table;

Example:

create table dept
as
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

HashMap get/put complexity

I'm not sure the default hashcode is the address - I read the OpenJDK source for hashcode generation a while ago, and I remember it being something a bit more complicated. Still not something that guarantees a good distribution, perhaps. However, that is to some extent moot, as few classes you'd use as keys in a hashmap use the default hashcode - they supply their own implementations, which ought to be good.

On top of that, what you may not know (again, this is based in reading source - it's not guaranteed) is that HashMap stirs the hash before using it, to mix entropy from throughout the word into the bottom bits, which is where it's needed for all but the hugest hashmaps. That helps deal with hashes that specifically don't do that themselves, although i can't think of any common cases where you'd see that.

Finally, what happens when the table is overloaded is that it degenerates into a set of parallel linked lists - performance becomes O(n). Specifically, the number of links traversed will on average be half the load factor.

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

just bumped in this question and found here all the answers I took some of the codes above and made simple js function that works on android and iphone (it supports almost every android and iphones).

  function navigate(lat, lng) {
    // If it's an iPhone..
    if ((navigator.platform.indexOf("iPhone") !== -1) || (navigator.platform.indexOf("iPod") !== -1)) {
      function iOSversion() {
        if (/iP(hone|od|ad)/.test(navigator.platform)) {
          // supports iOS 2.0 and later
          var v = (navigator.appVersion).match(/OS (\d+)_(\d+)_?(\d+)?/);
          return [parseInt(v[1], 10), parseInt(v[2], 10), parseInt(v[3] || 0, 10)];
        }
      }
      var ver = iOSversion() || [0];

      var protocol = 'http://';
      if (ver[0] >= 6) {
        protocol = 'maps://';
      }
      window.location = protocol + 'maps.apple.com/maps?daddr=' + lat + ',' + lng + '&amp;ll=';
    }
    else {
      window.open('http://maps.google.com?daddr=' + lat + ',' + lng + '&amp;ll=');
    }
  }

The html:

 <a onclick="navigate(31.046051,34.85161199999993)" >Israel</a>

How to check task status in Celery?

You can also create custom states and update it's value duting task execution. This example is from docs:

@app.task(bind=True)
def upload_files(self, filenames):
    for i, file in enumerate(filenames):
        if not self.request.called_directly:
            self.update_state(state='PROGRESS',
                meta={'current': i, 'total': len(filenames)})

http://celery.readthedocs.org/en/latest/userguide/tasks.html#custom-states

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

Is Viewstate turned on?

Edit: Perhaps you should reconsider overriding the rendering function

  protected override void RenderContents(HtmlTextWriter output)
    {
        ddlCountries.RenderControl(output);
        ddlStates.RenderControl(output);
    }

and instead add the dropdownlists to the control and render the control using the default RenderContents.

Edit: See the answer from Dennis which I alluded to in my previous comment:

Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );

Tomcat Servlet: Error 404 - The requested resource is not available

You definitely need to map your servlet onto some URL. If you use Java EE 6 (that means at least Servlet API 3.0) then you can annotate your servlet like

@WebServlet(name="helloServlet", urlPatterns={"/hello"})
public class HelloWorld extends HttpServlet {
     //rest of the class

Then you can just go to the localhost:8080/yourApp/hello and the value should be displayed. In case you can't use Servlet 3.0 API than you need to register this servlet into web.xml file like

<servlet>
    <servlet-name>helloServlet</servlet-name>
    <servlet-class>crunch.HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>helloServlet</servlet-name>
    <url-pattern>/hello</url-pattern>
</servlet-mapping>

Finding rows that don't contain numeric data in Oracle

You can use this one check:

create or replace function to_n(c varchar2) return number is
begin return to_number(c);
exception when others then return -123456;
end;

select id, n from t where to_n(n) = -123456;

Matplotlib different size subplots

I used pyplot's axes object to manually adjust the sizes without using GridSpec:

import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# definitions for the axes
left, width = 0.07, 0.65
bottom, height = 0.1, .8
bottom_h = left_h = left+width+0.02

rect_cones = [left, bottom, width, height]
rect_box = [left_h, bottom, 0.17, height]

fig = plt.figure()

cones = plt.axes(rect_cones)
box = plt.axes(rect_box)

cones.plot(x, y)

box.plot(y, x)

plt.show()

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

My solution is that i want data from all docs and i dont want _id, so

User.find({}, {_id:0, keyToShow:1, keyToNotShow:0})

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

This worked for me:

  • Go to the settings app of your iPhone.
  • Open your Facebook Settings
  • Scroll down to your app and make sure your app allows facebook interaction.

This could happen on any device, therefore in your app you will have to make sure to handle this error correctly. I reckon you give the user feedback why Login With Facebook failed and ask the user to check their Facebook settings on their device.

 - (void)facebookSessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{
    switch (state) {
        case FBSessionStateOpen:
            // handle successful login here
        case FBSessionStateClosed:
        case FBSessionStateClosedLoginFailed:
            [FBSession.activeSession closeAndClearTokenInformation];

            if (error) {
                // handle error here, for example by showing an alert to the user
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Could not login with Facebook"
                                                                message:@"Facebook login failed. Please check your Facebook settings on your phone."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                  otherButtonTitles:nil];
                [alert show];
            }
            break;
        default:
            break;
    }

Dynamic Web Module 3.0 -- 3.1

  1. Go to Workspace location
  2. select your project folder
  3. .setting folder
  4. edit "org.eclipse.wst.common.project.facet.core"
  5. change installed facet="jst.web" version="3.0"

Issue in installing php7.2-mcrypt

Mcrypt PECL extenstion

 sudo apt-get -y install gcc make autoconf libc-dev pkg-config
 sudo apt-get -y install libmcrypt-dev
 sudo pecl install mcrypt-1.0.1

When you are shown the prompt

 libmcrypt prefix? [autodetect] :

Press [Enter] to autodetect.

After success installing mcrypt trought pecl, you should add mcrypt.so extension to php.ini.

The output will look like this:

...
Build process completed successfully
Installing '/usr/lib/php/20170718/mcrypt.so'    ---->   this is our path to mcrypt extension lib
install ok: channel://pecl.php.net/mcrypt-1.0.1
configuration option "php_ini" is not set to php.ini location
You should add "extension=mcrypt.so" to php.ini

Grab installing path and add to cli and apache2 php.ini configuration.

sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/cli/conf.d/mcrypt.ini"
sudo bash -c "echo extension=/usr/lib/php/20170718/mcrypt.so > /etc/php/7.2/apache2/conf.d/mcrypt.ini"

Verify that the extension was installed

Run command:

php -i | grep "mcrypt"

The output will look like this:

/etc/php/7.2/cli/conf.d/mcrypt.ini
Registered Stream Filters => zlib.*, string.rot13, string.toupper, string.tolower, string.strip_tags, convert.*, consumed, dechunk, convert.iconv.*, mcrypt.*, mdecrypt.*
mcrypt
mcrypt support => enabled
mcrypt_filter support => enabled
mcrypt.algorithms_dir => no value => no value
mcrypt.modes_dir => no value => no value

How to change default text file encoding in Eclipse?

Nanda's answer wasn't enough in my setup. What I needed to do is:

  • Window > Preferences > General > Content Types
  • Select Text > HTML in the tree
  • Select all file associations, particularly .html
  • Input "UTF-8" in the text-field "default encoding"

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

Loading basic HTML in Node.js

This is a pretty old question...but if your use case here is to simply send a particular HTML page to the browser on an ad hoc basis, I would use something simple like this:

var http = require('http')
,       fs = require('fs');

var server = http.createServer(function(req, res){
  var stream = fs.createReadStream('test.html');
  stream.pipe(res);
});
server.listen(7000);

How to reload/refresh an element(image) in jQuery

Based on @kasper Taeymans' answer.

If u simply need reload image (not replace it's src with smth new), try:

_x000D_
_x000D_
$(function() {_x000D_
  var img = $('#img');_x000D_
_x000D_
  var refreshImg = function(img) {_x000D_
    // the core of answer is 2 lines below_x000D_
    var dummy = '?dummy=';_x000D_
    img.attr('src', img.attr('src').split(dummy)[0] + dummy + (new Date()).getTime());_x000D_
_x000D_
    // remove call on production_x000D_
    updateImgVisualizer();_x000D_
  };_x000D_
_x000D_
_x000D_
  // for display current img url in input_x000D_
  // for sandbox only!_x000D_
  var updateImgVisualizer = function() {_x000D_
    $('#img-url').val(img.attr('src'));_x000D_
  };_x000D_
_x000D_
  // bind img reload on btn click_x000D_
  $('.img-reloader').click(function() {_x000D_
    refreshImg(img);_x000D_
  });_x000D_
_x000D_
  // remove call on production_x000D_
  updateImgVisualizer();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<img id="img" src="http://dummyimage.com/628x150/">_x000D_
_x000D_
_x000D_
<p>_x000D_
  <label>_x000D_
    Current url of img:_x000D_
    <input id="img-url" type="text" readonly style="width:500px">_x000D_
  </label>_x000D_
</p>_x000D_
_x000D_
<p>_x000D_
  <button class="img-reloader">Refresh</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

accessing a docker container from another container

Using docker-compose, services are exposed to each other by name by default. Docs.
You could also specify an alias like;

version: '2.1'
services:
  mongo:
    image: mongo:3.2.11
  redis:
    image: redis:3.2.10
  api:
    image: some-image
    depends_on:
      - mongo
      - solr
    links:
      - "mongo:mongo.openconceptlab.org"
      - "solr:solr.openconceptlab.org"
      - "some-service:some-alias"

And then access the service using the specified alias as a host name, e.g mongo.openconceptlab.org for mongo in this case.

How to close Browser Tab After Submitting a Form?

You can try this methods

window.open(location, '_self').close();

How do I add Git version control (Bitbucket) to an existing source code folder?

User johannes told you how to do add existing files to a Git repository in a general situation. Because you talk about Bitbucket, I suggest you do the following:

  1. Create a new repository on Bitbucket (you can see a Create button on the top of your profile page) and you will go to this page:

    Create repository on Bitbucket

  2. Fill in the form, click next and then you automatically go to this page:

    Create repository from scratch or add existing files

  3. Choose to add existing files and you go to this page:

    Enter image description here

  4. You use those commands and you upload the existing files to Bitbucket. After that, the files are online.

HEAD and ORIG_HEAD in Git

HEAD is (direct or indirect, i.e. symbolic) reference to the current commit. It is a commit that you have checked in the working directory (unless you made some changes, or equivalent), and it is a commit on top of which "git commit" would make a new one. Usually HEAD is symbolic reference to some other named branch; this branch is currently checked out branch, or current branch. HEAD can also point directly to a commit; this state is called "detached HEAD", and can be understood as being on unnamed, anonymous branch.

And @ alone is a shortcut for HEAD, since Git 1.8.5

ORIG_HEAD is previous state of HEAD, set by commands that have possibly dangerous behavior, to be easy to revert them. It is less useful now that Git has reflog: HEAD@{1} is roughly equivalent to ORIG_HEAD (HEAD@{1} is always last value of HEAD, ORIG_HEAD is last value of HEAD before dangerous operation).

For more information read git(1) manpage / [gitrevisions(7) manpage][git-revisions], Git User's Manual, the Git Community Book and Git Glossary

What's the best way to determine the location of the current PowerShell script?

If you want to load modules from a path relative to where the script runs, such as from a "lib" subfolder", you need to use one of the following:

$PSScriptRoot which works when invoked as a script, such as via the PowerShell command $psISE.CurrentFile.FullPath which works when you're running inside ISE

But if you're in neither, and just typing away within a PowerShell shell, you can use:

pwd.Path

You can could assign one of the three to a variable called $base depending on the environment you're running under, like so:

$base=$(if ($psISE) {Split-Path -Path $psISE.CurrentFile.FullPath} else {$(if ($global:PSScriptRoot.Length -gt 0) {$global:PSScriptRoot} else {$global:pwd.Path})})

Then in your scripts, you can use it like so:

Import-Module $base\lib\someConstants.psm1
Import-Module $base\lib\myCoolPsModule1.psm1
#etc.

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Read file from aws s3 bucket using node fs

With the new version of sdk, the accepted answer does not work - it does not wait for the object to be downloaded. The following code snippet will help with the new version:

// dependencies

const AWS = require('aws-sdk');

// get reference to S3 client

const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {

var bucket = "TestBucket"

var key = "TestKey"

   try {

      const params = {
            Bucket: Bucket,
            Key: Key
        };

       var theObject = await s3.getObject(params).promise();

    } catch (error) {
        console.log(error);
        return;
    }  
}

How to add a custom HTTP header to every WCF call?

var endpoint = new EndpointAddress(new Uri(RemoteAddress),
               new[] { AddressHeader.CreateAddressHeader(
                       "APIKey", 
                       "",
                       "bda11d91-7ade-4da1-855d-24adfe39d174") 
                     });

How to display hexadecimal numbers in C?

You can use the following snippet code:

#include<stdio.h>
int main(int argc, char *argv[]){
    unsigned int i;
    printf("decimal  hexadecimal\n");
    for (i = 0; i <= 256; i+=16)
        printf("%04d     0x%04X\n", i, i);
    return 0;
}

It prints both decimal and hexadecimal numbers in 4 places with zero padding.

any tool for java object to object mapping?

Another one is Orika - https://github.com/orika-mapper/orika

Orika is a Java Bean mapping framework that recursively copies (among other capabilities) data from one object to another. It can be very useful when developing multi-layered applications.

Orika focuses on automating as much as possible, while providing customization through configuration and extension where needed.

Orika enables the developer to :

  • Map complex and deeply structured objects
  • "Flatten" or "Expand" objects by mapping nested properties to top-level properties, and vice versa
  • Create mappers on-the-fly, and apply customizations to control some or all of the mapping
  • Create converters for complete control over the mapping of a specific set of objects anywhere in the object graph--by type, or even by specific property name
  • Handle proxies or enhanced objects (like those of Hibernate, or the various mock frameworks)
  • Apply bi-directional mapping with one configuration
  • Map to instances of an appropriate concrete class for a target abstract class or interface
  • Handle reverse mappings
  • Handle complex conventions beyond JavaBean specs.

Orika uses byte code generation to create fast mappers with minimal overhead.

PostgreSQL: days/months/years between two dates

@WebWanderer 's answer is very close to the DateDiff using SQL server, but inaccurate. That is because of the usage of age() function.

e.g. days between '2019-07-29' and '2020-06-25' should return 332, however, using the age() function it will returns 327. Because the age() returns '10 mons 27 days" and it treats each month as 30 days which is incorrect.

You shold use the timestamp to get the accurate result. e.g.

ceil((select extract(epoch from (current_date::timestamp - <your_date>::timestamp)) / 86400))

Adding/removing items from a JavaScript object with jQuery

Keep things simple :)

var my_form_obj = {};
my_form_obj.name = "Captain America";
my_form_obj.weapon = "Shield";

Hope this helps!

How to change color of Android ListView separator line?

There are two ways to doing the same:

  1. You may set the value of android:divider="#FFCCFF" in layout xml file. With this you also have to specify height of divider like this android:dividerHeight="5px".

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
      <ListView 
      android:id="@+id/lvMyList"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:divider="#FFCCFF"
      android:dividerHeight="5px"/>
    
    </LinearLayout>
    
  2. You may also do this by programmatically...

    ListView listView = getListView();
    ColorDrawable myColor = new ColorDrawable(
        this.getResources().getColor(R.color.myColor)
    );
    listView.setDivider(myColor);
    listView.setDividerHeight();
    

How do I run a bat file in the background from another bat file?

This works on my Windows XP Home installation, the Unix way:

call notepad.exe & 

php variable in html no other way than: <?php echo $var; ?>

I really think you should adopt Smarty template engine as a standard php lib for your projects.

http://www.smarty.net/

Name: {$name|capitalize}<br>

How to skip to next iteration in jQuery.each() util?

Javascript sort of has the idea of 'truthiness' and 'falsiness'. If a variable has a value then, generally 9as you will see) it has 'truthiness' - null, or no value tends to 'falsiness'. The snippets below might help:

var temp1; 
if ( temp1 )...  // false

var temp2 = true;
if ( temp2 )...  // true

var temp3 = "";
if ( temp3 ).... // false

var temp4 = "hello world";
if ( temp4 )...  // true

Hopefully that helps?

Also, its worth checking out these videos from Douglas Crockford

update: thanks @cphpython for spotting the broken links - I've updated to point at working versions now

The Javascript language

Javascript - The Good Parts

Clone() vs Copy constructor- which is recommended in java

See also: How to properly override clone method?. Cloning is broken in Java, it's so hard to get it right, and even when it does it doesn't really offer much, so it's not really worth the hassle.

How to calculate Date difference in Hive

If you need the difference in seconds (i.e.: you're comparing dates with timestamps, and not whole days), you can simply convert two date or timestamp strings in the format 'YYYY-MM-DD HH:MM:SS' (or specify your string date format explicitly) using unix_timestamp(), and then subtract them from each other to get the difference in seconds. (And can then divide by 60.0 to get minutes, or by 3600.0 to get hours, etc.)

Example:

UNIX_TIMESTAMP('2017-12-05 10:01:30') - UNIX_TIMESTAMP('2017-12-05 10:00:00') AS time_diff -- This will return 90 (seconds). Unix_timestamp converts string dates into BIGINTs. 

More on what you can do with unix_timestamp() here, including how to convert strings with different date formatting: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

You can use less code, writing this:

    $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name'));

And of course if you want to select more fields, just write a "," and add more:

 $users = DB::table('really_long_table_name')
       ->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));

This is very practical when you use a joins complex query

Sending data from HTML form to a Python script in Flask

The form tag needs some attributes set:

  1. action: The URL that the form data is sent to on submit. Generate it with url_for. It can be omitted if the same URL handles showing the form and processing the data.
  2. method="post": Submits the data as form data with the POST method. If not given, or explicitly set to get, the data is submitted in the query string (request.args) with the GET method instead.
  3. enctype="multipart/form-data": When the form contains file inputs, it must have this encoding set, otherwise the files will not be uploaded and Flask won't see them.

The input tag needs a name parameter.

Add a view to handle the submitted data, which is in request.form under the same key as the input's name. Any file inputs will be in request.files.

@app.route('/handle_data', methods=['POST'])
def handle_data():
    projectpath = request.form['projectFilepath']
    # your code
    # return a response

Set the form's action to that view's URL using url_for:

<form action="{{ url_for('handle_data') }}" method="post">
    <input type="text" name="projectFilepath">
    <input type="submit">
</form>

Angular JS - angular.forEach - How to get key of the object?

The first parameter to the iterator in forEach is the value and second is the key of the object.

angular.forEach(objectToIterate, function(value, key) {
    /* do something for all key: value pairs */
});

In your example, the outer forEach is actually:

angular.forEach($scope.filters, function(filterObj , filterKey)

Connect over ssh using a .pem file

You can connect to a AWS ec-2 instance using the following commands.

chmod 400 mykey.pem

ssh -i mykey.pem username@your-ip

by default the machine name usually be like ubuntu since usually ubuntu machine is used as a server so the following command will work in that case.

ssh -i mykey.pem ubuntu@your-ip

Switch statement equivalent in Windows batch file

I ended up using label names containing the values for the case expressions as suggested by AjV Jsy. Anyway, I use CALL instead of GOTO to jump into the correct case block and GOTO :EOF to jump back. The following sample code is a complete batch script illustrating the idea.

@ECHO OFF

SET /P COLOR="Choose a background color (type red, blue or black): "

2>NUL CALL :CASE_%COLOR% # jump to :CASE_red, :CASE_blue, etc.
IF ERRORLEVEL 1 CALL :DEFAULT_CASE # If label doesn't exist

ECHO Done.
EXIT /B

:CASE_red
  COLOR CF
  GOTO END_CASE
:CASE_blue
  COLOR 9F
  GOTO END_CASE
:CASE_black
  COLOR 0F
  GOTO END_CASE
:DEFAULT_CASE
  ECHO Unknown color "%COLOR%"
  GOTO END_CASE
:END_CASE
  VER > NUL # reset ERRORLEVEL
  GOTO :EOF # return from CALL

PHP: How to remove specific element from an array?

A better approach would maybe be to keep your values as keys in an associative array, and then call array_keys() on it when you want to actual array. That way you don't need to use array_search to find your element.

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Expected response code 220 but got code "", with message "" in Laravel

That error message means that there was not response OR the server could not be connected.

The following settings worked on my end:

'stream' => [
        'ssl' => [
            'allow_self_signed' => true,
            'verify_peer' => false,
            'verify_peer_name' => false,
        ],
    ]

Note that my SMTP settings are:

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465
MAIL_USERNAME=[full gmail address]
MAIL_PASSWORD=[App Password obtained after two step verification]
MAIL_ENCRYPTION=ssl

Date in to UTC format Java

What Time Zones?

No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.

ISO 8601

Your input string is in ISO 8601 format, except that it lacks an offset from UTC.

Joda-Time

Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.

String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();

As for generating string representations in other formats, search StackOverflow for "Joda format".

Android - Package Name convention

The package name is used for unique identification for your application.
Android uses the package name to determine if the application has been installed or not.
The general naming is:

com.companyname.applicationname

eg:

com.android.Camera

how to drop database in sqlite?

SQLite database FAQ: How do I drop a SQLite database?

People used to working with other databases are used to having a "drop database" command, but in SQLite there is no similar command. The reason? In SQLite there is no "database server" -- SQLite is an embedded database, and your database is entirely contained in one file. So there is no need for a SQLite drop database command.

To "drop" a SQLite database, all you have to do is delete the SQLite database file you were accessing.

copy from http://alvinalexander.com/android/sqlite-drop-database-how

CSS: Set a background color which is 50% of the width of the window

_x000D_
_x000D_
.background{_x000D_
 background: -webkit-linear-gradient(top, #2897e0 40%, #F1F1F1 40%);_x000D_
 height:200px;_x000D_
 _x000D_
}_x000D_
_x000D_
.background2{_x000D_
  background: -webkit-linear-gradient(right, #2897e0 50%, #28e09c 50%);_x000D_
_x000D_
 height:200px;_x000D_
 _x000D_
}
_x000D_
<html>_x000D_
<body class="one">_x000D_
_x000D_
<div class="background">_x000D_
</div>_x000D_
<div class="background2">_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Notice: Undefined variable: _SESSION in "" on line 9

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");

Is there a command line command for verifying what version of .NET is installed

Since you said you want to know if its actually installed, I think the best way (short of running version specific code), is to check the reassuringly named "Install" registry key. 0x1 means yes:

C:\>reg query "HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5"| findstr Install

   Install     REG_DWORD       0x1
   InstallPath REG_SZ  c:\WINNT\Microsoft.NET\Framework\v3.5\

This also happens to be the "Microsoft Recommended" official method.

WMI is another possibility, but seems impractical (Slow? Takes 2 min on my C2D, SSD). Maybe it works better on your server:

C:\>wmic product where "Name like 'Microsoft .Net%'" get Name, Version

Name                                                Version
Microsoft .NET Compact Framework 1.0 SP3 Developer  1.0.4292
Microsoft .NET Framework 3.0 Service Pack 2         3.2.30729
Microsoft .NET Framework 3.5 SP1                    3.5.30729
Microsoft .NET Compact Framework 2.0                2.0.5238
Microsoft .NET Framework 4 Client Profile           4.0.30319
Microsoft .NET Framework 4 Multi-Targeting Pack     4.0.30319
Microsoft .NET Framework 2.0 Service Pack 2         2.2.30729
Microsoft .NET Framework 1.1                        1.1.4322
Microsoft .NET Framework 4 Extended                 4.0.30319

C:\>wmic product where "name like 'Microsoft .N%' and version='3.5.30729'" get name

Name  
Microsoft .NET Framework 3.5 SP1

Other than these I think the only way to be 100% sure is to actually run a simple console app compiled targeting your framework version. Personally, I consider this unnecessary and trust the registry method just fine.

Finally, you could set up an intranet test site which is reachable from your server and sniffs the User Agent to determine .NET versions. But that's not a batch file solution of course. Also see doc here.

git checkout all the files

Other way which I found useful is:

git checkout <wildcard> 

Example:

git checkout *.html

More generally:

git checkout <branch> <filename/wildcard>

How do I change the background color of a plot made with ggplot2

To change the panel's background color, use the following code:

myplot + theme(panel.background = element_rect(fill = 'green', colour = 'red'))

To change the color of the plot (but not the color of the panel), you can do:

myplot + theme(plot.background = element_rect(fill = 'green', colour = 'red'))

See here for more theme details Quick reference sheet for legends, axes and themes.

Including external HTML file to another HTML file

The iframe element.

<iframe src="name.html"></iframe>

But content that you way to have appear on multiple pages is better handled using templates.

convert datetime to date format dd/mm/yyyy

DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);

SQL Server Linked Server Example Query

SELECT * FROM OPENQUERY([SERVER_NAME], 'SELECT * FROM DATABASE_NAME..TABLENAME')

This may help you.

How to encode the plus (+) symbol in a URL

Is you want a plus (+) symbol in the body you have to encode it as 2B.

For example: Try this

Example of SOAP request authenticated with WS-UsernameToken

The Hash Password Support and Token Assertion Parameters in Metro 1.2 explains very nicely what a UsernameToken with Digest Password looks like:

Digest Password Support

The WSS 1.1 Username Token Profile allows digest passwords to be sent in a wsse:UsernameToken of a SOAP message. Two more optional elements are included in the wsse:UsernameToken in this case: wsse:Nonce and wsse:Created. A nonce is a random value that the sender creates to include in each UsernameToken that it sends. A creation time is added to combine nonces to a "freshness" time period. The Password Digest in this case is calculated as:

Password_Digest = Base64 ( SHA-1 ( nonce + created + password ) )

This is how a UsernameToken with Digest Password looks like:

<wsse:UsernameToken wsu:Id="uuid_faf0159a-6b13-4139-a6da-cb7b4100c10c">
   <wsse:Username>Alice</wsse:Username>
   <wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">6S3P2EWNP3lQf+9VC3emNoT57oQ=</wsse:Password>
   <wsse:Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">YF6j8V/CAqi+1nRsGLRbuZhi</wsse:Nonce>
   <wsu:Created>2008-04-28T10:02:11Z</wsu:Created>
</wsse:UsernameToken>

Remove Object from Array using JavaScript

Performance

Today 2021.01.27 I perform tests on MacOs HighSierra 10.13.6 on Chrome v88, Safari v13.1.2 and Firefox v84 for chosen solutions.

Results

For all browsers:

  • fast/fastest solutions when element not exists: A and B
  • fast/fastest solutions for big arrays: C
  • fast/fastest solutions for big arrays when element exists: H
  • quite slow solutions for small arrays: F and G
  • quite slow solutions for big arrays: D, E and F

enter image description here

Details

I perform 4 tests cases:

  • small array (10 elements) and element exists - you can run it HERE
  • small array (10 elements) and element NOT exists - you can run it HERE
  • big array (milion elements) and element exists - you can run it HERE
  • big array (milion elements) and element NOT exists - you can run it HERE

Below snippet presents differences between solutions A B C D E F G H I

_x000D_
_x000D_
function A(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  if(idx>=0) arr.splice(idx, 1);
  return arr;
}


function B(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  return idx<0 ? arr : arr.slice(0,idx).concat(arr.slice(idx+1,arr.length));
}


function C(arr, name) {
  let idx = arr.findIndex(o => o.name==name);
  delete arr[idx];
  return arr;
}


function D(arr, name) {
  return arr.filter(el => el.name != name);
}


function E(arr, name) {
  let result = [];
  arr.forEach(o => o.name==name || result.push(o));
  return result;
}


function F(arr, name) {
  return _.reject(arr, el => el.name == name);
}


function G(arr, name) {
  let o = arr.find(o => o.name==name);
  return _.without(arr,o);
}


function H(arr, name) {
  $.each(arr, function(i){
      if(arr[i].name === 'Kristian') {
          arr.splice(i,1);
          return false;
      }
  });
  return arr;
}


function I(arr, name) {
  return $.grep(arr,o => o.name!=name);
}








// Test
let test1 = [   
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},  
];

let test2 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"Kristian", lines:"2,5,10"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

let test3 = [   
    {name:"John3", lines:"1,19,26,96"},
    {name:"John", lines:"1,19,26,96"},
  {name:"Joh2", lines:"1,19,26,96"},
];

console.log(`
Test1: original array from question
Test2: array with more data
Test3: array without element which we want to delete
`);

[A,B,C,D,E,F,G,H,I].forEach(f=> console.log(`
Test1 ${f.name}: ${JSON.stringify(f([...test1],"Kristian"))}
Test2 ${f.name}: ${JSON.stringify(f([...test2],"Kristian"))}
Test3 ${f.name}: ${JSON.stringify(f([...test3],"Kristian"))}
`));
_x000D_
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
  
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"> </script>
  
This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

If you have Anaconda installed I recomend you to uninstall it and try installing python package from source, i fixed this problem in this way

Laravel 5 error SQLSTATE[HY000] [1045] Access denied for user 'homestead'@'localhost' (using password: YES)

Declare password like DB_PASSWORD="2o0@#5TGR1NG" in .env file

If # sign include in your password then password will declare in between " ".

Creating a static class with no instances

Seems that you need classmethod:

class World(object):

    allAirports = []

    @classmethod
    def initialize(cls):

        if not cls.allAirports:
            f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
            file_reader = csv.reader(f)

            for col in file_reader:
                cls.allAirports.append(Airport(col[0],col[2],col[3]))

        return cls.allAirports

How to press/click the button using Selenium if the button does not have the Id?

    You can achieve this by using cssSelector 
    // Use of List web elements:
    String cssSelectorOfLoginButton="input[type='button'][id='login']"; 
    //****Add cssSelector of your 1st webelement
    //List<WebElement> button 
    =driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
    button.get(0).click();

    I hope this work for you

Why does the JFrame setSize() method not set the size correctly?

The top border of frame is of size 30.You can write code for printing the coordinate of any point on the frame using MouseInputAdapter.You will find when the cursor is just below the top border of the frame the y coordinate is not zero , its close to 30.Hence if you give size to frame 300 * 300 , the size available for putting the components on the frame is only 300 * 270.So if you need to have size 300 * 300 ,give 300 * 330 size of the frame.

While variable is not defined - wait

I have upvoted @dnuttle's answer, but ended up using the following strategy:

// On doc ready for modern browsers
document.addEventListener('DOMContentLoaded', (e) => {
  // Scope all logic related to what you want to achieve by using a function
  const waitForMyFunction = () => {
    // Use a timeout id to identify your process and purge it when it's no longer needed
    let timeoutID;
    // Check if your function is defined, in this case by checking its type
    if (typeof myFunction === 'function') {
      // We no longer need to wait, purge the timeout id
      window.clearTimeout(timeoutID);
      // 'myFunction' is defined, invoke it with parameters, if any
      myFunction('param1', 'param2');
    } else {
      // 'myFunction' is undefined, try again in 0.25 secs
      timeoutID = window.setTimeout(waitForMyFunction, 250);
    }
  };
  // Initialize
  waitForMyFunction();
});

It is tested and working! ;)

Gist: https://gist.github.com/dreamyguy/f319f0b2bffb1f812cf8b7cae4abb47c

How can I make grep print the lines below and above each matching line?

Use -A and -B switches (mean lines-after and lines-before):

grep -A 1 -B 1 FAILED file.txt

How can I commit a single file using SVN over a network?

You have a file myFile.txt you want to commit.

The right procedure is :

  1. Move to the file folder
  2. svn up
  3. svn commit myFile.txt -m "Insert here a commit message!!!"

Hope this will help someone.

How to pass data from Javascript to PHP and vice versa?

There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.

<script language="javascript" type="text/javascript">
 function _vals(target, value){
   form1.all("target").value=target;
   form1.all("value").value=value;
   form1.submit();
 }
</script>

Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.

I'm sure there's probably more methods which are better, but these are just a few that spring to mind.

EDIT: Building on this from what others have said using the above method you would have an anchor tag like

<a onclick="_vals('name', 'val')" href="#">My Link</a>

And then in your PHP you can get form data using

$val = $_POST['value'];

So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.

Launching an application (.EXE) from C#?

Just put your file.exe in the \bin\Debug folder and use:

Process.Start("File.exe");

How should I read a file line-by-line in Python?

if you're turned off by the extra line, you can use a wrapper function like so:

def with_iter(iterable):
    with iterable as iter:
        for item in iter:
            yield item

for line in with_iter(open('...')):
    ...

in Python 3.3, the yield from statement would make this even shorter:

def with_iter(iterable):
    with iterable as iter:
        yield from iter

How do I add a newline to a windows-forms TextBox?

You can also use vbNewLine Object as in

MessageLabel.Text = "The Sales tax was:" & Format(douSales_tax, "Currency") & "." & vbNewLine & "The sale person: " & mstrSalesPerson

how to break the _.each function in underscore.js

Update:

_.find would be better as it breaks out of the loop when the element is found:

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var count = 0;
var filteredEl = _.find(searchArr,function(arrEl){ 
              count = count +1;
              if(arrEl.id === 1 ){
                  return arrEl;
              }
            });

console.log(filteredEl);
//since we are searching the first element in the array, the count will be one
console.log(count);
//output: filteredEl : {id:1,text:"foo"} , count: 1

** Old **

If you want to conditionally break out of a loop, use _.filter api instead of _.each. Here is a code snippet

var searchArr = [{id:1,text:"foo"},{id:2,text:"bar"}];
var filteredEl = _.filter(searchArr,function(arrEl){ 
                  if(arrEl.id === 1 ){
                      return arrEl;
                  }
                });
console.log(filteredEl);
//output: {id:1,text:"foo"}

Convert an ArrayList to an object array

Something like the standard Collection.toArray(T[]) should do what you need (note that ArrayList implements Collection):

TypeA[] array = a.toArray(new TypeA[a.size()]);

On a side note, you should consider defining a to be of type List<TypeA> rather than ArrayList<TypeA>, this avoid some implementation specific definition that may not really be applicable for your application.

Also, please see this question about the use of a.size() instead of 0 as the size of the array passed to a.toArray(TypeA[])

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

IF you have adapter attached with recyclerView then just do this.

mRecyclerView.smoothScrollToPosition(mRecyclerView.getAdapter().getItemCount());

Android Studio Stuck at Gradle Download on create new project

The Gradle popup window only shows intermittent progress and is not very helpful in understanding if the download is actually stuck or is very slow.

enter image description here

It will help to build your app from the command line where you can actually get the real progress of downloading with

./gradlew build

enter image description here

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

Add following code in app.js of NODEJ Restful api to avoid "Access-Control-Allow-Origin" error in angular 6 or any other framework

var express = require('express');
var app = express();

var cors = require('cors');
var bodyParser = require('body-parser');

//enables cors
app.use(cors({
  'allowedHeaders': ['sessionId', 'Content-Type'],
  'exposedHeaders': ['sessionId'],
  'origin': '*',
  'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
  'preflightContinue': false
}));

PHP: Split string into array, like explode with no delimiter

str_split can do the trick. Note that strings in PHP can be accessed just like a chars array, in most cases, you won't need to split your string into a "new" array.

How to save/restore serializable object to/from file?

You can use JsonConvert from Newtonsoft library. To serialize an object and write to a file in json format:

File.WriteAllText(filePath, JsonConvert.SerializeObject(obj));

And to deserialize it back into object:

var obj = JsonConvert.DeserializeObject<ObjType>(File.ReadAllText(filePath));

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

OS_ACTIVITY_MODE = disable

This will also disable the ability to debug in real devices (no console output from real devices from then on).

How do I display a ratio in Excel in the format A:B?

The second formula on that page uses the GCD function of the Analysis ToolPak, you can add it from Tools > Add-Ins.

=A1/GCD(A1,B1)&":"&B1/GCD(A1,B1)

This is a more mathematical formula rather than a text manipulation based on.

WebView showing ERR_CLEARTEXT_NOT_PERMITTED although site is HTTPS

Solution:

Add the below line in your application tag:

android:usesCleartextTraffic="true"

As shown below:

<application
    ....
    android:usesCleartextTraffic="true"
    ....>

UPDATE: If you have network security config such as: android:networkSecurityConfig="@xml/network_security_config"

No Need to set clear text traffic to true as shown above, instead use the below code:

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <domain-config cleartextTrafficPermitted="true">
        ....
        ....
    </domain-config>

    <base-config cleartextTrafficPermitted="false"/>
</network-security-config>  

Set the cleartextTrafficPermitted to true

Hope it helps.

Sound effects in JavaScript / HTML5

The selected answer will work in everything except IE. I wrote a tutorial on how to make it work cross browser = http://www.andy-howard.com/how-to-play-sounds-cross-browser-including-ie/index.html

Here is the function I wrote;

function playSomeSounds(soundPath)
 {

 var trident = !!navigator.userAgent.match(/Trident\/7.0/);
 var net = !!navigator.userAgent.match(/.NET4.0E/);
 var IE11 = trident && net
 var IEold = ( navigator.userAgent.match(/MSIE/i) ? true : false );
 if(IE11 || IEold){
 document.all.sound.src = soundPath;
 }
 else
 {
 var snd = new Audio(soundPath); // buffers automatically when created
 snd.play();
 }
 };

You also need to add the following tag to the html page:

<bgsound id="sound">

Finally you can call the function and simply pass through the path here:

playSomeSounds("sounds/welcome.wav");

Getting values from query string in an url using AngularJS $location

Very late answer :( but for someone who is in need, this works Angular js works too :) URLSearchParams Let's have a look at how we can use this new API to get values from the location!

// Assuming "?post=1234&action=edit"

var urlParams = new URLSearchParams(window.location.search);
console.log(urlParams.has('post')); // true
console.log(urlParams.get('action')); // "edit"
console.log(urlParams.getAll('action')); // ["edit"]
console.log(urlParams.toString()); // "?post=1234&action=edit"
console.log(urlParams.append('active', '1')); // "?

post=1234&action=edit&active=1"

FYI: IE is not supported

use this function from instead of URLSearchParams

urlParam = function (name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)')
                      .exec(window.location.search);

    return (results !== null) ? results[1] || 0 : false;
}

console.log(urlParam('action')); //edit

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

Only install the Service Pack (VS10sp1-KB983509.msp) wasn't enough to me.

I had to uninstall the Visual Studio Team Explorer 2010 to continue the installation :)

iPhone/iOS JSON parsing tutorial

As of iOS 5.0 Apple provides the NSJSONSerialization class "to convert JSON to Foundation objects and convert Foundation objects to JSON". No external frameworks to incorporate and according to benchmarks its performance is quite good, significantly better than SBJSON.

How to set cursor to input box in Javascript?

This way sets the focus and cursor to the end of your input:

div.getElementsByTagName("input")[0].focus();
div.getElementsByTagName("input")[0].setSelectionRange(div.getElementsByTagName("input")[0].value.length,div.getElementsByTagName("input")[0].value.length,"forward");

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

If anyone faces the following error message when they use adb devices

no permissions (verify udev rules); see [http://developer.android.com/tools/device.html]

Execute the following

sudo -s 
adb kill-server
adb start-server

That fixed the issue for me on a custom build android device

javascript remove "disabled" attribute from html input

Best answer is just removeAttribute

element.removeAttribute("disabled");

How can I regenerate ios folder in React Native project?

It seems like react-native eject is no more available. The only way I could find for recreating the ios folder was to generate it from scratch.

Take a backup of your ios folder

mv /path_to_your_old_project/ios /path_to_your_backup_dir/ios_backup

Navigate to a temporary directory and create a new project with the same name as your current project

react-native init project_name
mv project_name/ios /path_to_your_old_project/ios

Install the pod dependencies inside the ios folder within your project

cd /path_to_your_old_project/ios
pod install

How to get week numbers from dates?

I understand the need for packages in certain situations, but the base language is so elegant and so proven (and debugged and optimized).

Why not:

dt <- as.Date("2014-03-16")
dt2 <- as.POSIXlt(dt)
dt2$yday
[1] 74

And then your choice whether the first week of the year is zero (as in indexing in C) or 1 (as in indexing in R).

No packages to learn, update, worry about bugs in.

Cannot assign requested address - possible causes?

Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:

$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);

It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig.

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

When to use MongoDB or other document oriented database systems?

After two years using MongoDb for a social app, I have witnessed what it really means to live without a SQL RDBMS.

  1. You end up writing jobs to do things like joining data from different tables/collections, something that an RDBMS would do for you automatically.
  2. Your query capabilities with NoSQL are drastically crippled. MongoDb may be the closest thing to SQL but it is still extremely far behind. Trust me. SQL queries are super intuitive, flexible and powerful. MongoDb queries are not.
  3. MongoDb queries can retrieve data from only one collection and take advantage of only one index. And MongoDb is probably one of the most flexible NoSQL databases. In many scenarios, this means more round-trips to the server to find related records. And then you start de-normalizing data - which means background jobs.
  4. The fact that it is not a relational database means that you won't have (thought by some to be bad performing) foreign key constrains to ensure that your data is consistent. I assure you this is eventually going to create data inconsistencies in your database. Be prepared. Most likely you will start writing processes or checks to keep your database consistent, which will probably not perform better than letting the RDBMS do it for you.
  5. Forget about mature frameworks like hibernate.

I believe that 98% of all projects probably are way better with a typical SQL RDBMS than with NoSQL.

How do I reference the input of an HTML <textarea> control in codebehind?

Missed property runat="server" or in code use Request.Params["TextArea1"]

Android: How to Enable/Disable Wifi or Internet Connection Programmatically

In Android Q (Android 10) you can't enable/disable wifi programmatically anymore. Use Settings Panel to toggle wifi connectivity:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    val panelIntent = Intent(Settings.Panel.ACTION_INTERNET_CONNECTIVITY)
    startActivityForResult(panelIntent, 0)
} else {
    // use previous solution, add appropriate permissions to AndroidManifest file (see answers above)
    (this.context?.getSystemService(Context.WIFI_SERVICE) as? WifiManager)?.apply { isWifiEnabled = true /*or false*/ }
}

Best way to copy a database (SQL Server 2008)

If you want to take a copy of a live database, do the Backup/Restore method.

[In SQLS2000, not sure about 2008:] Just keep in mind that if you are using SQL Server accounts in this database, as opposed to Windows accounts, if the master DB is different or out of sync on the development server, the user accounts will not translate when you do the restore. I've heard about an SP to remap them, but I can't remember which one it was.

How to handle onchange event on input type=file in jQuery?

 $('#fileupload').bind('change', function (e) { //dynamic property binding
alert('hello');// message you want to display
});

You can use this one also

How to use bluetooth to connect two iPhone?

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

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

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

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

How do I use properly CASE..WHEN in MySQL

SELECT
   CASE 
    WHEN course_enrollment_settings.base_price = 0      THEN 1
    WHEN course_enrollment_settings.base_price>0 AND  
         course_enrollment_settings.base_price<=100     THEN 2
    WHEN course_enrollment_settings.base_price>100 AND   
         course_enrollment_settings.base_price<201      THEN 3
        ELSE 6
   END AS 'calc_base_price',
   course_enrollment_settings.base_price
FROM
    course_enrollment_settings
WHERE course_enrollment_settings.base_price = 0

How to loop through each and every row, column and cells in a GridView and get its value

foreach (DataGridViewRow row in GridView2.Rows)
            {
                if ( ! row.IsNewRow)
                {
                    for (int i = 0; i < GridView2.Columns.Count; i++)
                    {
                        String header = GridView2.Columns[i].HeaderText;
                        String cellText = Convert.ToString(row.Cells[i].Value);
                    }
                }
            }

Here Before Iterating for cell Values need to check for NewRow.

How to get all enum values in Java?

... or MyEnum.values() ? Or am I missing something?

How do I quickly rename a MySQL database (change schema name)?

Three options:

  1. Create the new database, bring down the server, move the files from one database folder to the other, and restart the server. Note that this will only work if ALL of your tables are MyISAM.

  2. Create the new database, use CREATE TABLE ... LIKE statements, and then use INSERT ... SELECT * FROM statements.

  3. Use mysqldump and reload with that file.

Upgrading PHP in XAMPP for Windows?

Simplest method to upgrade PHP in XAMPP:

  1. Download latest portable version of XAMPP.
  2. Extract the archive(not where XAMPP already installed).
  3. Copy the PHP folder from the extracted archive.
  4. Keep back up of PHP folder which is in installed XAMPP directory. You can backup it like changing the PHP folder name to PHP-old or like PHP-version-number
  5. Paste the PHP folder which you copied from the extracted archive.
  6. Replace the php.ini file with your backup folder php.ini file in case you have changed the default settings earlier.
  7. That's all, start/restart the server.

The listener supports no services

The database registers its service name(s) with the listener when it starts up. If it is unable to do so then it tries again periodically - so if the listener starts after the database then there can be a delay before the service is recognised.

If the database isn't running, though, nothing will have registered the service, so you shouldn't expect the listener to know about it - lsnrctl status or lsnrctl services won't report a service that isn't registered yet.

You can start the database up without the listener; from the Oracle account and with your ORACLE_HOME, ORACLE_SID and PATH set you can do:

sqlplus /nolog

Then from the SQL*Plus prompt:

connect / as sysdba
startup

Or through the Grid infrastructure, from the grid account, use the srvctl start database command:

srvctl start database -d db_unique_name [-o start_options] [-n node_name]

You might want to look at whether the database is set to auto-start in your oratab file, and depending on what you're using whether it should have started automatically. If you're expecting it to be running and it isn't, or you try to start it and it won't come up, then that's a whole different scenario - you'd need to look at the error messages, alert log, possibly trace files etc. to see exactly why it won't start, and if you can't figure it out, maybe ask on Database Adminsitrators rather than on Stack Overflow.


If the database can't see +DATA then ASM may not be running; you can see how to start that here; or using srvctl start asm. As the documentation says, make sure you do that from the grid home, not the database home.

Python list of dictionaries search

You have to go through all elements of the list. There is not a shortcut!

Unless somewhere else you keep a dictionary of the names pointing to the items of the list, but then you have to take care of the consequences of popping an element from your list.

Converting an integer to binary in C

If you want to transform a number into another number (not number to string of characters), and you can do with a small range (0 to 1023 for implementations with 32-bit integers), you don't need to add char* to the solution

unsigned int_to_int(unsigned k) {
    if (k == 0) return 0;
    if (k == 1) return 1;                       /* optional */
    return (k % 2) + 10 * int_to_int(k / 2);
}

HalosGhost suggested to compact the code into a single line

unsigned int int_to_int(unsigned int k) {
    return (k == 0 || k == 1 ? k : ((k % 2) + 10 * int_to_int(k / 2)));
}

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

MySQL create stored procedure syntax with delimiter

MY SQL STORED PROCEDURE CREATION

DELIMiTER $$
create procedure GetUserRolesEnabled(in UserId int)
Begin

select * from users
where id=UserId ;
END $$
DELIMITER ;

How to get element by class name?

You need to use the document.getElementsByClassName('class_name');

and dont forget that the returned value is an array of elements so if you want the first one use:

document.getElementsByClassName('class_name')[0]

UPDATE

Now you can use:

document.querySelector(".class_name") to get the first element with the class_name CSS class (null will be returned if non of the elements on the page has this class name)

or document.querySelectorAll(".class_name") to get a NodeList of elements with the class_name css class (empty NodeList will be returned if non of. the elements on the the page has this class name).

How to use JQuery with ReactJS

Step 1:

npm install jquery

Step 2:

touch loader.js 

Somewhere in your project folder

Step 3:

//loader.js
window.$ = window.jQuery = require('jquery')

Step 4:

Import the loader into your root file before you import the files which require jQuery

//App.js
import '<pathToYourLoader>/loader.js'

Step 5:

Now use jQuery anywhere in your code:

//SomeReact.js
class SomeClass extends React.Compontent {

...

handleClick = () => {
   $('.accor > .head').on('click', function(){
      $('.accor > .body').slideUp();
      $(this).next().slideDown();
   });
}

...

export default SomeClass

Efficient way to return a std::vector in c++

As nice as "return by value" might be, it's the kind of code that can lead one into error. Consider the following program:

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    static std::vector<std::string> strings;
    std::vector<std::string> vecFunc(void) { return strings; };
    int main(int argc, char * argv[]){
      // set up the vector of strings to hold however
      // many strings the user provides on the command line
      for(int idx=1; (idx<argc); ++idx){
         strings.push_back(argv[idx]);
      }

      // now, iterate the strings and print them using the vector function
      // as accessor
      for(std::vector<std::string>::interator idx=vecFunc().begin(); (idx!=vecFunc().end()); ++idx){
         cout << "Addr: " << idx->c_str() << std::endl;
         cout << "Val:  " << *idx << std::endl;
      }
    return 0;
    };
  • Q: What will happen when the above is executed? A: A coredump.
  • Q: Why didn't the compiler catch the mistake? A: Because the program is syntactically, although not semantically, correct.
  • Q: What happens if you modify vecFunc() to return a reference? A: The program runs to completion and produces the expected result.
  • Q: What is the difference? A: The compiler does not have to create and manage anonymous objects. The programmer has instructed the compiler to use exactly one object for the iterator and for endpoint determination, rather than two different objects as the broken example does.

The above erroneous program will indicate no errors even if one uses the GNU g++ reporting options -Wall -Wextra -Weffc++

If you must produce a value, then the following would work in place of calling vecFunc() twice:

   std::vector<std::string> lclvec(vecFunc());
   for(std::vector<std::string>::iterator idx=lclvec.begin(); (idx!=lclvec.end()); ++idx)...

The above also produces no anonymous objects during iteration of the loop, but requires a possible copy operation (which, as some note, might be optimized away under some circumstances. But the reference method guarantees that no copy will be produced. Believing the compiler will perform RVO is no substitute for trying to build the most efficient code you can. If you can moot the need for the compiler to do RVO, you are ahead of the game.

What is a typedef enum in Objective-C?

The enum (abbreviation of enumeration) is used to enumerate a set of values (enumerators). A value is an abstract thing represented by a symbol (a word). For example, a basic enum could be

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl };

This enum is called anonymous because you do not have a symbol to name it. But it is still perfectly correct. Just use it like this

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;

Ok. The life is beautiful and everything goes well. But one day you need to reuse this enum to define a new variable to store myGrandFatherPantSize, then you write:

enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandFatherPantSize;

But then you have a compiler error "redefinition of enumerator". Actually, the problem is that the compiler is not sure that you first enum and you are second describe the same thing.

Then if you want to reuse the same set of enumerators (here xs...xxxxl) in several places you must tag it with a unique name. The second time you use this set you just have to use the tag. But don't forget that this tag does not replace the enum word but just the set of enumerators. Then take care to use enum as usual. Like this:

// Here the first use of my enum
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize; 
// here the second use of my enum. It works now!
enum sizes myGrandFatherPantSize;

you can use it in a parameter definition as well:

// Observe that here, I still use the enum
- (void) buyANewDressToMyGrandMother:(enum sizes)theSize;

You could say that rewriting enum everywhere is not convenient and makes the code looks a bit strange. You are right. A real type would be better.

This is the final step of our great progression to the summit. By just adding a typedef let's transform our enum in a real type. Oh the last thing, typedef is not allowed within your class. Then define your type just above. Do it like this:

// enum definition
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl };
typedef enum sizes size_type

@interface myClass {
   ...
   size_type myGrandMotherDressSize, myGrandFatherPantSize;
   ...
}

Remember that the tag is optional. Then since here, in that case, we do not tag the enumerators but just to define a new type. Then we don't really need it anymore.

// enum definition
typedef enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } size_type;

@interface myClass : NSObject {
  ...
  size_type myGrandMotherDressSize, myGrandFatherPantSize;
  ...
}
@end

If you are developing in Objective-C with XCode I let you discover some nice macros prefixed with NS_ENUM. That should help you to define good enums easily and moreover will help the static analyzer to do some interesting checks for you before to compile.

Good Enum!

How to call shell commands from Ruby

My favourite is Open3

  require "open3"

  Open3.popen3('nroff -man') { |stdin, stdout, stderr| ... }

Right mime type for SVG images with fonts embedded

There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml mediatype.

Failed to execute removeChild on Node

As others have mentioned, myCoolDiv is a child of markerDiv not playerContainer. If you want to remove myCoolDiv but keep markerDiv for some reason you can do the following

myCoolDiv.parentNode.removeChild(myCoolDiv);

JSFiddle

How to export all collections in MongoDB?

Even in mongo version 4 there is no way to export all collections at once. Export the specified collection to the specified output file from a local MongoDB instance running on port 27017 you can do with the following command:

.\mongoexport.exe --db=xstaging --collection=products --out=c:/xstaging.products.json

Getting a random value from a JavaScript array

~~ is much faster than Math.Floor(), so when it comes to performance optimization while producing output using UI elements, ~~ wins the game. MORE INFO

var rand = myArray[~~(Math.random() * myArray.length)];

But if you know that the array is going to have millions of elements than you might want to reconsider between Bitwise Operator and Math.Floor(), as bitwise operator behave weirdly with large numbers. See below example explained with the output. MORE INFO(deadlink)

var number = Math.floor(14444323231.2); // => 14444323231
var number = 14444323231.2 | 0; // => 1559421343

How to write a cursor inside a stored procedure in SQL Server 2008

You can create a trigger which updates NoofUses column in Coupon table whenever couponid is used in CouponUse table

query :

CREATE TRIGGER [dbo].[couponcount] ON [dbo].[couponuse]
FOR INSERT
AS
if EXISTS (SELECT 1 FROM Inserted)
  BEGIN
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
end 

How do I declare an array with a custom class?

You need a parameterless constructor to be able to create an instance of your class. Your current constructor requires two input string parameters.

Normally C++ implies having such a constructor (=default parameterless constructor) if there is no other constructor declared. By declaring your first constructor with two parameters you overwrite this default behaviour and now you have to declare this constructor explicitly.

Here is the working code:

#include <iostream> 
#include <string>  // <-- you need this if you want to use string type

using namespace std; 

class name { 
  public: 
    string first; 
    string last; 

  name(string a, string b){ 
    first = a; 
    last = b; 

  }

  name ()  // <-- this is your explicit parameterless constructor
  {}

}; 

int main (int argc, const char * argv[]) 
{ 

  const int howManyNames = 3; 

  name someName[howManyNames]; 

  return 0; 
}

(BTW, you need to include to make the code compilable.)

An alternative way is to initialize your instances explicitly on declaration

  name someName[howManyNames] = { {"Ivan", "The Terrible"}, {"Catherine", "The Great"} };

How to decode viewstate

Use Fiddler and grab the view state in the response and paste it into the bottom left text box then decode.

Entity Framework - Generating Classes

1) First you need to generate EDMX model using your database. To do that you should add new item to your project:

  • Select ADO.NET Entity Data Model from the Templates list.
  • On the Choose Model Contents page, select the Generate from Database option and click Next.
  • Choose your database.
  • On the Choose Your Database Objects page, check the Tables. Choose Views or Stored Procedures if you need.

So now you have Model1.edmx file in your project.

2) To generate classes using your model:

  • Open your EDMX model designer.
  • On the design surface Right Click –> Add Code Generation Item…
  • Select Online templates.
  • Select EF 4.x DbContext Generator for C#.
  • Click ‘Add’.

Notice that two items are added to your project:

  • Model1.tt (This template generates very simple POCO classes for each entity in your model)
  • Model1.Context.tt (This template generates a derived DbContext to use for querying and persisting data)

3) Read/Write Data example:

 var dbContext = new YourModelClass(); //class derived from DbContext
 var contacts = from c in dbContext.Contacts select c; //read data
 contacts.FirstOrDefault().FirstName = "Alex"; //edit data
 dbContext.SaveChanges(); //save data to DB

Don't forget that you need 4.x version of EntityFramework. You can download EF 4.1 here: Entity Framework 4.1.

How to get String Array from arrays.xml file

You can't initialize your testArray field this way, because the application resources still aren't ready.

Just change the code to:

package com.xtensivearts.episode.seven;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class Episode7 extends ListActivity {
    String[] mTestArray;

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        mTestArray = getResources().getStringArray(R.array.testArray);    

        /* Assign the name array to that adapter and 
        also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
            this,
            android.R.layout.simple_list_item_1,
            mTestArray);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Removing leading and trailing spaces from a string

No boost, no regex, just the string library. It's that simple.

string trim(const string s) { // removes whitespace characters from beginnig and end of string s
    const int l = (int)s.length();
    int a=0, b=l-1;
    char c;
    while(a<l && ((c=s.at(a))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) a++;
    while(b>a && ((c=s.at(b))==' '||c=='\t'||c=='\n'||c=='\v'||c=='\f'||c=='\r'||c=='\0')) b--;
    return s.substr(a, 1+b-a);
}

How to remove all debug logging calls before building the release version of an Android app?

I have improved on the solution above by providing support for different log levels and by changing the log levels automatically depending on if the code is being run on a live device or on the emulator.

public class Log {

final static int WARN = 1;
final static int INFO = 2;
final static int DEBUG = 3;
final static int VERB = 4;

static int LOG_LEVEL;

static
{
    if ("google_sdk".equals(Build.PRODUCT) || "sdk".equals(Build.PRODUCT)) {
        LOG_LEVEL = VERB;
    } else {
        LOG_LEVEL = INFO;
    }

}


/**
 *Error
 */
public static void e(String tag, String string)
{
        android.util.Log.e(tag, string);
}

/**
 * Warn
 */
public static void w(String tag, String string)
{
        android.util.Log.w(tag, string);
}

/**
 * Info
 */
public static void i(String tag, String string)
{
    if(LOG_LEVEL >= INFO)
    {
        android.util.Log.i(tag, string);
    }
}

/**
 * Debug
 */
public static void d(String tag, String string)
{
    if(LOG_LEVEL >= DEBUG)
    {
        android.util.Log.d(tag, string);
    }
}

/**
 * Verbose
 */
public static void v(String tag, String string)
{
    if(LOG_LEVEL >= VERB)
    {
        android.util.Log.v(tag, string);
    }
}


}

Node.js + Nginx - What now?

We can easily setup a Nodejs app by Nginx acting as a reverse proxy.
The following configuration assumes the NodeJS application is running on 127.0.0.1:8080,

  server{
     server_name domain.com sub.domain.com; # multiple domains

     location /{ 
      proxy_pass http://127.0.0.1:8080;  
      proxy_set_header Host $host;
      proxy_pass_request_headers on;  
     }

     location /static/{
       alias /absolute/path/to/static/files; # nginx will handle js/css
     }
   } 

in above setup your Nodejs app will,

  • get HTTP_HOST header where you can apply domain specific logic to serve the response. '
  • Your Application must be managed by a process manager like pm2 or supervisor for handling situations/reusing sockets or resources etc.

  • Setup an error reporting service for getting production errors like sentry or rollbar

NOTE: you can setup logic for handing domain specific request routes, create a middleware for expressjs application

List of remotes for a Git repository?

FWIW, I had exactly the same question, but I could not find the answer here. It's probably not portable, but at least for gitolite, I can run the following to get what I want:

$ ssh [email protected] info
hello akim, this is gitolite 2.3-1 (Debian) running on git 1.7.10.4
the gitolite config gives you the following access:
     R   W     android
     R   W     bistro
     R   W     checkpn
...

Python: import module from another directory at the same level in project hierarchy

In the "root" __init__.py you can also do a

import sys
sys.path.insert(1, '.')

which should make both modules importable.

Setting JDK in Eclipse

JDK 1.8 have some more enrich feature which doesn't support to many eclipse .

If you didn't find java compliance level as 1.8 in java compiler ,then go ahead and install the below eclipse 32bit or 64 bit depending on your system supports.

  1. Install jdk 1.8 and then set the JAVA_HOME and CLASSPATH in environment variable.
  2. Download eclipse-jee-neon-3-win32 and unzip : supports to java 1.8
  3. Or download Oracle Enterprise Pack for Eclipse (12.2.1.5) and unzip :Supports java 1.8 with 64 bit OS
  4. Right click your project > properties
  5. Select “Java Compiler” on left and set java compliance level to 1.8 [select from the dropdown 1.8]
  6. Try running one java program supports to java 8 like lambda expression as below and if no compilation error ,means your eclipse supports to java 1.8, something like this:

    interface testI{
        void show();
    }
    
    /*class A implements testI{
        public void show(){
            System.out.println("Hello");
        }
    }*/
    
    public class LambdaDemo1 {
        public static void main(String[] args) {
            testI test ;
            /*test= new A();
            test.show();*/
            test = () ->System.out.println("Hello,how are you?"); //lambda 
            test.show();
        }        
    }
    

Count words in a string method?

Hi I just figured out with StringTokenizer like this:

String words = "word word2 word3 word4";
StringTokenizer st = new Tokenizer(words);
st.countTokens();

Pull all images from a specified directory and then display them

You need to change the loop from for ($i=1; $i<count($files); $i++) to for ($i=0; $i<count($files); $i++):

So the correct code is

<?php
$files = glob("images/*.*");

for ($i=0; $i<count($files); $i++) {
    $image = $files[$i];
    print $image ."<br />";
    echo '<img src="'.$image .'" alt="Random image" />'."<br /><br />";
}

?>

How to change the commit author for one specific commit?

Interactive rebase off of a point earlier in the history than the commit you need to modify (git rebase -i <earliercommit>). In the list of commits being rebased, change the text from pick to edit next to the hash of the one you want to modify. Then when git prompts you to change the commit, use this:

git commit --amend --author="Author Name <[email protected]>" --no-edit

For example, if your commit history is A-B-C-D-E-F with F as HEAD, and you want to change the author of C and D, then you would...

  1. Specify git rebase -i B (here is an example of what you will see after executing the git rebase -i B command)
    • if you need to edit A, use git rebase -i --root
  2. Change the lines for both C and D from pick to edit
  3. Exit the editor (for vim, this would be pressing Esc and then typing :wq).
  4. Once the rebase started, it would first pause at C
  5. You would git commit --amend --author="Author Name <[email protected]>"
  6. Then git rebase --continue
  7. It would pause again at D
  8. Then you would git commit --amend --author="Author Name <[email protected]>" again
  9. git rebase --continue
  10. The rebase would complete.
  11. Use git push -f to update your origin with the updated commits.

SASS and @font-face

I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).

The cross-browser @font-face solution from Font Squirrel looks like this:

@font-face {
    font-family: 'fontname';
    src: url('fontname.eot');
    src: url('fontname.eot?#iefix') format('embedded-opentype'),
         url('fontname.woff') format('woff'),
         url('fontname.ttf') format('truetype'),
         url('fontname.svg#fontname') format('svg');
    font-weight: normal;
    font-style: normal;
}

To produce the src property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:

@font-face
  font-family: 'fontname'
  src: url('fontname.eot')
  src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
  font-weight: normal
  font-style: normal

I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:

=font-face($family, $path, $svg, $weight: normal, $style: normal)
  @font-face
    font-family: $family
    src: url('#{$path}.eot')
    src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
    font-weight: $weight
    font-style: $style

Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:

+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

How to Display Multiple Google Maps per page with API V3

var maps_qty;
for (var i = 1; i <= maps_qty; i++)
    {
        $(".append_container").append('<div class="col-lg-10 grid_container_'+ (i) +'" >' + '<div id="googleMap'+ i +'" style="height:300px;"></div>'+'</div>');
        map = document.getElementById('googleMap' + i);
        initialize(map,i);
    }

// Intialize Google Map with Polyline Feature in it.

function initialize(map,i)
    {
        map_index = i-1;
        path_lat_long = [];
        var mapOptions = {
            zoom: 2,
            center: new google.maps.LatLng(51.508742,-0.120850)
        };

        var polyOptions = {
            strokeColor: '#000000',
            strokeOpacity: 1.0,
            strokeWeight: 3
        };

        //Push element(google map) in an array of google maps
        map_array.push(new google.maps.Map(map, mapOptions));
        //For Mapping polylines to MUltiple Google Maps
        polyline_array.push(new google.maps.Polyline(polyOptions));
        polyline_array[map_index].setMap(map_array[map_index]);
    }

// For Resizing Maps Multiple Maps.

google.maps.event.addListener(map, "idle", function()
    {
      google.maps.event.trigger(map, 'resize');
    });

map.setZoom( map.getZoom() - 1 );
map.setZoom( map.getZoom() + 1 );

Increasing the JVM maximum heap size for memory intensive applications

When you are using JVM in 32-bit mode, the maximum heap size that can be allocated is 1280 MB. So, if you want to go beyond that, you need to invoke JVM in 64-mode.

You can use following:

$ java -d64 -Xms512m -Xmx4g HelloWorld

where,

  • -d64: Will enable 64-bit JVM
  • -Xms512m: Will set initial heap size as 512 MB
  • -Xmx4g: Will set maximum heap size as 4 GB

You can tune in -Xms and -Xmx as per you requirements (YMMV)

A very good resource on JVM performance tuning, which might want to look into: http://java.sun.com/javase/technologies/hotspot/gc/gc_tuning_6.html

How to convert DateTime to a number with a precision greater than days in T-SQL?

DECLARE @baseTicks AS BIGINT;
SET @baseTicks = 599266080000000000; --# ticks up to 1900-01-01

DECLARE @ticksPerDay AS BIGINT;
SET @ticksPerDay = 864000000000;

SELECT CAST(@baseTicks + (@ticksPerDay * CAST(GETDATE() AS FLOAT)) AS BIGINT) AS currentDateTicks;

JavaScript Extending Class

Updated below for ES6

March 2013 and ES5

This MDN document describes extending classes well:

https://developer.mozilla.org/en-US/docs/JavaScript/Introduction_to_Object-Oriented_JavaScript

In particular, here is now they handle it:

// define the Person Class
function Person() {}

Person.prototype.walk = function(){
  alert ('I am walking!');
};
Person.prototype.sayHello = function(){
  alert ('hello');
};

// define the Student class
function Student() {
  // Call the parent constructor
  Person.call(this);
}

// inherit Person
Student.prototype = Object.create(Person.prototype);

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

// replace the sayHello method
Student.prototype.sayHello = function(){
  alert('hi, I am a student');
}

// add sayGoodBye method
Student.prototype.sayGoodBye = function(){
  alert('goodBye');
}

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

Note that Object.create() is unsupported in some older browsers, including IE8:

Object.create browser support

If you are in the position of needing to support these, the linked MDN document suggests using a polyfill, or the following approximation:

function createObject(proto) {
    function ctor() { }
    ctor.prototype = proto;
    return new ctor();
}

Using this like Student.prototype = createObject(Person.prototype) is preferable to using new Person() in that it avoids calling the parent's constructor function when inheriting the prototype, and only calls the parent constructor when the inheritor's constructor is being called.

May 2017 and ES6

Thankfully, the JavaScript designers have heard our pleas for help and have adopted a more suitable way of approaching this issue.

MDN has another great example on ES6 class inheritance, but I'll show the exact same set of classes as above reproduced in ES6:

class Person {
    sayHello() {
        alert('hello');
    }

    walk() {
        alert('I am walking!');
    }
}

class Student extends Person {
    sayGoodBye() {
        alert('goodBye');
    }

    sayHello() {
        alert('hi, I am a student');
    }
}

var student1 = new Student();
student1.sayHello();
student1.walk();
student1.sayGoodBye();

// check inheritance
alert(student1 instanceof Person); // true 
alert(student1 instanceof Student); // true

Clean and understandable, just like we all want. Keep in mind, that while ES6 is pretty common, it's not supported everywhere:

ES6 browser support

Find maximum value of a column and return the corresponding row values using Pandas

Use the index attribute of DataFrame. Note that I don't type all the rows in the example.

In [14]: df = data.groupby(['Country','Place'])['Value'].max()

In [15]: df.index
Out[15]: 
MultiIndex
[Spain  Manchester, UK     London    , US     Mchigan   ,        NewYork   ]

In [16]: df.index[0]
Out[16]: ('Spain', 'Manchester')

In [17]: df.index[1]
Out[17]: ('UK', 'London')

You can also get the value by that index:

In [21]: for index in df.index:
    print index, df[index]
   ....:      
('Spain', 'Manchester') 512
('UK', 'London') 778
('US', 'Mchigan') 854
('US', 'NewYork') 562

Edit

Sorry for misunderstanding what you want, try followings:

In [52]: s=data.max()

In [53]: print '%s, %s, %s' % (s['Country'], s['Place'], s['Value'])
US, NewYork, 854

Completely removing phpMyAdmin

Try purge

sudo aptitude purge phpmyadmin

Not sure this works with plain old apt-get though

How to convert Javascript datetime to C# datetime?

You were almost right, there's just need one little fix to be made:

var a = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
    .AddMilliseconds(1310522400000)
    .ToLocalTime();

Select arrow style change

Have you tried something like this:

.styled-select select {
    -moz-appearance:none; /* Firefox */
    -webkit-appearance:none; /* Safari and Chrome */
    appearance:none;
}

Haven't tested, but should work.

EDIT: It looks like Firefox doesn't support this feature up until version 35 (read more here)

There is a workaround here, take a look at jsfiddle on that post.

How are people unit testing with Entity Framework 6, should you bother?

It is important to test what you are expecting entity framework to do (i.e. validate your expectations). One way to do this that I have used successfully, is using moq as shown in this example (to long to copy into this answer):

https://docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking

However be careful... A SQL context is not guaranteed to return things in a specific order unless you have an appropriate "OrderBy" in your linq query, so its possible to write things that pass when you test using an in-memory list (linq-to-entities) but fail in your uat / live environment when (linq-to-sql) gets used.

Spring JUnit: How to Mock autowired component in autowired component

You could use Mockito. I am not sure with PostConstruct specifically, but this generally works:

// Create a mock of Resource to change its behaviour for testing
@Mock
private Resource resource;

// Testing instance, mocked `resource` should be injected here 
@InjectMocks
@Resource
private TestedClass testedClass;

@Before
public void setUp() throws Exception {
    // Initialize mocks created above
    MockitoAnnotations.initMocks(this);
    // Change behaviour of `resource`
    when(resource.getSomething()).thenReturn("Foo");   
}

How can we redirect a Java program console output to multiple files?

To solve the problem I use ${string_prompt} variable. It shows a input dialog when application runs. I can set the date/time manually at that dialog.

  1. Move cursor at the end of file path. enter image description here

  2. Click variables and select string_prompt enter image description here

  3. Select Apply and Run enter image description here enter image description here

Create Hyperlink in Slack

python

x = "http://xxxxxx"
y = "text title"
text_link = '<{}|{}>'.format(x,y)

post text_link in using python slack client

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

RoBorg is correct, but I wanted to add a side note.

In IE7/IE8 when Microsoft added Tabs to their browser they broke one thing that will cause havoc with your JS if you are not careful.

Imagine this page layout:

MainPage.html
  IframedPage1.html   (named "foo")
  IframedPage2.html   (named "bar")
    IframedPage3.html (named "baz")

Now in frame "baz" you click a link (no target, loads in the "baz" frame) it works fine.

If the page that gets loaded, lets call it special.html, uses JS to check if "it" has a parent frame named "bar" it will return true (expected).

Now lets say that the special.html page when it loads, checks the parent frame (for existence and its name, and if it is "bar" it reloads itself in the bar frame. e.g.

if(window.parent && window.parent.name == 'bar'){
  window.parent.location = self.location;
}

So far so good. Now comes the bug.

Lets say instead of clicking on the original link like normal, and loading the special.html page in the "baz" frame, you middle-clicked it or chose to open it in a new Tab.

When that new tab loads (with no parent frames at all!) IE will enter an endless loop of page loading! because IE "copies over" the frame structure in JavaScript such that the new tab DOES have a parent, and that parent HAS the name "bar".

The good news, is that checking:

if(self == top){
  //this returns true!
}

in that new tab does return true, and thus you can test for this odd condition.

Adobe Acrobat Pro make all pages the same dimension

You have to use the Print to a New PDF option using the PDF printer. Once in the dialog box, set the page scaling to 100% and set your page size. Once you do that, your new PDF will be uniform in page sizes.

returning a Void object

Just for the sake of it, there is of course the possibility to create Void instance using reflection:

interface B<E>{ E method(); }

class A implements B<Void>{

    public Void method(){
        // do something

        try {
            Constructor<Void> voidConstructor = Void.class.getDeclaredConstructor();
            voidConstructor.setAccessible(true);
            return voidConstructor.newInstance();
        } catch (Exception ex) {
            // Rethrow, or return null, or whatever.
        }
    }
}

You probably won't do that in production.

Matplotlib-Animation "No MovieWriters Available"

(be sure to follow JPH feedback above about the proper ffmpeg download) Not sure why, but in my case here is the one that worked (in my case was on windows).

Initialize a writer:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
Writer = animation.FFMpegWriter(fps=30, codec='libx264')  #or 
Writer = animation.FFMpegWriter(fps=20, metadata=dict(artist='Me'), bitrate=1800) ==> This is WORKED FINE ^_^

Writer = animation.writers['ffmpeg'] ==> GIVES ERROR ""RuntimeError: Requested MovieWriter (ffmpeg) not available""

SELECT INTO a table variable in T-SQL

You can also use common table expressions to store temporary datasets. They are more elegant and adhoc friendly:

WITH userData (name, oldlocation)
AS
(
  SELECT name, location 
  FROM   myTable    INNER JOIN 
         otherTable ON ...
  WHERE  age>30
)
SELECT * 
FROM   userData -- you can also reuse the recordset in subqueries and joins

How do you read CSS rule values with JavaScript?

function getStyle(className) {
    document.styleSheets.item("menu").cssRules.item(className).cssText;
}
getStyle('.test')

Note : "menu" is an element ID which you have applied CSS. "className" a css class name which we need to get its text.

max(length(field)) in mysql

Use:

  SELECT mt.name 
    FROM MY_TABLE mt
GROUP BY mt.name
  HAVING MAX(LENGTH(mt.name)) = 18

...assuming you know the length beforehand. If you don't, use:

  SELECT mt.name 
    FROM MY_TABLE mt
    JOIN (SELECT MAX(LENGTH(x.name) AS max_length
            FROM MY_TABLE x) y ON y.max_length = LENGTH(mt.name)

What special characters must be escaped in regular expressions?

POSIX recognizes multiple variations on regular expressions - basic regular expressions (BRE) and extended regular expressions (ERE). And even then, there are quirks because of the historical implementations of the utilities standardized by POSIX.

There isn't a simple rule for when to use which notation, or even which notation a given command uses.

Check out Jeff Friedl's Mastering Regular Expressions book.

Using global variables between files?

See Python's document on sharing global variables across modules:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import config
print (config.x)

or

from config import x
print (x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

Add border-bottom to table row <tr>

I found when using this method that the space between the td elements caused a gap to form in the border, but have no fear...

One way around this:

<tr>
    <td>
        Example of normal table data
    </td>

    <td class="end" colspan="/* total number of columns in entire table*/">
        /* insert nothing in here */ 
    </td>
</tr>

With the CSS:

td.end{
    border:2px solid black;
}

jQuery multiselect drop down menu

You can use chosen.i download all file from this link Chosen download Link

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link href="prism.css" rel="stylesheet" type="text/css" />
    <link href="chosen.css" rel="stylesheet" type="text/css" />
    <script src="jquery-2.1.4.min.js" type="text/javascript"></script>
    <script src="chosen.jquery.js" type="text/javascript"></script>
    <script src="prism.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $(".chzn-select").chosen();
        });
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>

<ion-view view-title="Profile">
<ion-content class="padding">

<div>
    <label class="item item-input">
        <div class="input-label">Enter Your Option</div>
            <select class="chzn-select" multiple="true" name="faculty" style="width:1000px;">
                <option value="Option 2.1">Option 2.1</option>
                <option value="Option 2.2">Option 2.2</option>
                <option value="Option 2.3">Option 2.3</option>
            </select>   
    </label>
</div>
</ion-content>
</ion-view> 
    </div>
    </form>
</body>
</html>

All file on all same folder

why I can't get value of label with jquery and javascript?

Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

Thus,

$('#telefon').html() 
// or
$('#telefon').text()

or

var telefon = document.getElementById('telefon');
telefon.innerHTML;

If you are starting with your form element, check out the labels list of it. That is,

var el = $('#myformelement');
var label = $( el.prop('labels') );
// label.html();
// el.val();
// blah blah blah you get the idea

Getting the actual usedrange

I use the following vba code to determine the entire used rows range for the worksheet to then shorten the selected range of a column:

    Set rUsedRowRange = Selection.Worksheet.UsedRange.Columns( _
    Selection.Column - Selection.Worksheet.UsedRange.Column + 1)

Also works the other way around:

    Set rUsedColumnRange = Selection.Worksheet.UsedRange.Rows( _
    Selection.Row - Selection.Worksheet.UsedRange.Row + 1)

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

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

For me the git:// just doesn't work through the proxy although the https:// does. This caused some bit of headache because I was running scripts that all used git:// so I couldn't just easily change them all. However I found this GEM

git config --global url."https://github.com/".insteadOf git://github.com/

Print "\n" or newline characters as part of the output on terminal

Another suggestion is to do that way:

string = "abcd\n"
print(string.replace("\n","\\n"))

But be aware that the print function actually print to the terminal the "\n", your terminal interpret that as a newline, that's it. So, my solution just change the newline in \ + n

Do sessions really violate RESTfulness?

First, let's define some terms:

  • RESTful:

    One can characterise applications conforming to the REST constraints described in this section as "RESTful".[15] If a service violates any of the required constraints, it cannot be considered RESTful.

    according to wikipedia.

  • stateless constraint:

    We next add a constraint to the client-server interaction: communication must be stateless in nature, as in the client-stateless-server (CSS) style of Section 3.4.3 (Figure 5-3), such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server. Session state is therefore kept entirely on the client.

    according to the Fielding dissertation.

So server side sessions violate the stateless constraint of REST, and so RESTfulness either.

As such, to the client, a session cookie is exactly the same as any other HTTP header based authentication mechanism, except that it uses the Cookie header instead of the Authorization or some other proprietary header.

By session cookies you store the client state on the server and so your request has a context. Let's try to add a load balancer and another service instance to your system. In this case you have to share the sessions between the service instances. It is hard to maintain and extend such a system, so it scales badly...

In my opinion there is nothing wrong with cookies. The cookie technology is a client side storing mechanism in where the stored data is attached automatically to cookie headers by every request. I don't know of a REST constraint which has problem with that kind of technology. So there is no problem with the technology itself, the problem is with its usage. Fielding wrote a sub-section about why he thinks HTTP cookies are bad.

From my point of view:

  • authentication is not prohibited for RESTfulness (otherwise there'd be little use in RESTful services)
  • authentication is done by sending an authentication token in the request, usually the header
  • this authentication token needs to be obtained somehow and may be revoked, in which case it needs to be renewed
  • the authentication token needs to be validated by the server (otherwise it wouldn't be authentication)

Your point of view was pretty solid. The only problem was with the concept of creating authentication token on the server. You don't need that part. What you need is storing username and password on the client and send it with every request. You don't need more to do this than HTTP basic auth and an encrypted connection:

Figure 1. - Stateless authentication by trusted clients

  • Figure 1. - Stateless authentication by trusted clients

You probably need an in-memory auth cache on server side to make things faster, since you have to authenticate every request.

Now this works pretty well by trusted clients written by you, but what about 3rd party clients? They cannot have the username and password and all the permissions of the users. So you have to store separately what permissions a 3rd party client can have by a specific user. So the client developers can register they 3rd party clients, and get an unique API key and the users can allow 3rd party clients to access some part of their permissions. Like reading the name and email address, or listing their friends, etc... After allowing a 3rd party client the server will generate an access token. These access token can be used by the 3rd party client to access the permissions granted by the user, like so:

Figure 2. - Stateless authentication by 3rd party clients

  • Figure 2. - Stateless authentication by 3rd party clients

So the 3rd party client can get the access token from a trusted client (or directly from the user). After that it can send a valid request with the API key and access token. This is the most basic 3rd party auth mechanism. You can read more about the implementation details in the documentation of every 3rd party auth system, e.g. OAuth. Of course this can be more complex and more secure, for example you can sign the details of every single request on server side and send the signature along with the request, and so on... The actual solution depends on your application's need.

SQL Server: Multiple table joins with a WHERE clause

The third row you expect (the one with Powerpoint) is filtered out by the Computer.ID = 1 condition (try running the query with the Computer.ID = 1 or Computer.ID is null it to see what happens).

However, dropping that condition would not make sense, because after all, we want the list for a given Computer.

The only solution I see is performing a UNION between your original query and a new query that retrieves the list of application that are not found on that Computer.

The query might look like this:

DECLARE @ComputerId int
SET @ComputerId = 1

-- your original query
SELECT Computer.ComputerName, Application.Name, Software.Version
    FROM Computer
    JOIN dbo.Software_Computer
        ON Computer.ID = Software_Computer.ComputerID
    JOIN dbo.Software
        ON Software_Computer.SoftwareID = Software.ID
    RIGHT JOIN dbo.Application
        ON Application.ID = Software.ApplicationID
    WHERE Computer.ID = @ComputerId

UNION

-- query that retrieves the applications not installed on the given computer
SELECT Computer.ComputerName, Application.Name, NULL as Version
FROM Computer, Application
WHERE Application.ID not in 
    (
        SELECT s.ApplicationId
        FROM Software_Computer sc
        LEFT JOIN Software s on s.ID = sc.SoftwareId
        WHERE sc.ComputerId = @ComputerId
    )
AND Computer.id = @ComputerId

Is there a way to pass optional parameters to a function?

You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:

class _NO_DEFAULT:
    def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()

def func(optional= _NO_DEFAULT):
    if optional is _NO_DEFAULT:
        print("the optional argument was not passed")
    else:
        print("the optional argument was:",optional)

then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:

# these two work the same as using **
func()
func(optional=1)

# the optional argument can be positional or keyword unlike using **
func(1) 

#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

Lambda expression to convert array/List of String to array/List of Integers

You could create helper methods that would convert a list (array) of type T to a list (array) of type U using the map operation on stream.

//for lists
public static <T, U> List<U> convertList(List<T> from, Function<T, U> func) {
    return from.stream().map(func).collect(Collectors.toList());
}

//for arrays
public static <T, U> U[] convertArray(T[] from, 
                                      Function<T, U> func, 
                                      IntFunction<U[]> generator) {
    return Arrays.stream(from).map(func).toArray(generator);
}

And use it like this:

//for lists
List<String> stringList = Arrays.asList("1","2","3");
List<Integer> integerList = convertList(stringList, s -> Integer.parseInt(s));

//for arrays
String[] stringArr = {"1","2","3"};
Double[] doubleArr = convertArray(stringArr, Double::parseDouble, Double[]::new);


Note that s -> Integer.parseInt(s) could be replaced with Integer::parseInt (see Method references)

Use formula in custom calculated field in Pivot Table

I'll post this comment as answer, as I'm confident enough that what I asked is not possible.

I) Couple of similar questions trying to do the same, without success:

II) This article: Excel Pivot Table Calculated Field for example lists many restrictions of Calculated Field:

  • For calculated fields, the individual amounts in the other fields are summed, and then the calculation is performed on the total amount.
  • Calculated field formulas cannot refer to the pivot table totals or subtotals
  • Calculated field formulas cannot refer to worksheet cells by address or by name.
  • Sum is the only function available for a calculated field.
  • Calculated fields are not available in an OLAP-based pivot table.

III) There is tiny limited possibility to use AVERAGE() and similar function for a range of cells, but that applies only if Pivot table doesn't have grouped cells, which allows listing the cells as items in new group (right to "Fileds" listbox in above screenshot) and then user can calculate AVERAGE(), referencing explicitly every item (cell), from Items listbox, as argument. Maybe it's better explained here: Calculate values in a PivotTable report
For my Pivot table it wasn't applicable because my range wasn't small enough, this option to be sane choice.

How to write a function that takes a positive integer N and returns a list of the first N natural numbers

Here are a few ways to create a list with N of continuous natural numbers starting from 1.

1 range:

def numbers(n): 
    return range(1, n+1);

2 List Comprehensions:

def numbers(n):
    return [i for i in range(1, n+1)]

You may want to look into the method xrange and the concepts of generators, those are fun in python. Good luck with your Learning!

border-radius not working

Now I am using the browser kit like this:

{
border-radius: 7px;
-webkit-border-radius: 7px;
-moz-border-radius: 7px;
}

AppSettings get value from .config file

  1. Open "Properties" on your project
  2. Go to "Settings" Tab
  3. Add "Name" and "Value"

CODE WILL BE GENERATED AUTOMATICALLY

    <configuration>
      <configSections>
        <sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup ..." ... >
          <section name="XX....Properties.Settings" type="System.Configuration.ClientSettingsSection ..." ... />
        </sectionGroup>
      </configSections>
      <applicationSettings>
        <XX....Properties.Settings>
          <setting name="name" serializeAs="String">
            <value>value</value>
          </setting>
          <setting name="name2" serializeAs="String">
            <value>value2</value>
          </setting>
       </XX....Properties.Settings>
      </applicationSettings>
    </configuration>

To get a value

Properties.Settings.Default.Name

OR

Properties.Settings.Default["name"]

Set object property using reflection

Yes, using System.Reflection:

using System.Reflection;

...

    string prop = "name";
    PropertyInfo pi = myObject.GetType().GetProperty(prop);
    pi.SetValue(myObject, "Bob", null);

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

Rxjs 5.5 “ Property ‘map’ does not exist on type Observable.

The problem was related to the fact that you need to add pipe around all operators.

Change this,

this.myObservable().map(data => {})

to this

this.myObservable().pipe(map(data => {}))

And

Import map like this,

import { map } from 'rxjs/operators';

It will solve your issues.

Java: how do I check if a Date is within a certain range?

Consider using Joda Time. I love this library and wish it would replace the current horrible mess that are the existing Java Date and Calendar classes. It's date handling done right.

EDIT: It's not 2009 any more, and Java 8's been out for ages. Use Java 8's built in java.time classes which are based on Joda Time, as Basil Bourque mentions above. In this case you'll want the Period class, and here's Oracle's tutorial on how to use it.

Left function in c#

use substring function:

yourString.Substring(0, length);

Entity Framework Core: DbContextOptionsBuilder does not contain a definition for 'usesqlserver' and no extension method 'usesqlserver'

I got around this by simply:

Add SqlServerDbContextOptionsExtensions to the class in question Resolve SqlServerDbContextOptionsExtensions

This fixes the issue, must be missing some reference by default.

Deploying Java webapp to Tomcat 8 running in Docker container

Tomcat will only extract the war which is copied to webapps directory. Change Dockerfile as below:

FROM tomcat:8.0.20-jre8
COPY /1.0-SNAPSHOT/my-app-1.0-SNAPSHOT.war /usr/local/tomcat/webapps/myapp.war

You might need to access the url as below unless you have specified the webroot

http://192.168.59.103:8888/myapp/getData

C#: how to get first char of a string?

Following example for getting first character from a string might help someone

string anyNameForString = "" + stringVariableName[0];

How can I undo a `git commit` locally and on a remote after `git push`

Generally, make an "inverse" commit, using:

git revert 364705c

then send it to the remote as usual:

git push

This won't delete the commit: it makes an additional commit that undoes whatever the first commit did. Anything else, not really safe, especially when the changes have already been propagated.

Read input from console in Ruby?

you can also pass the parameters through the command line. Command line arguments are stores in the array ARGV. so ARGV[0] is the first number and ARGV[1] the second number

#!/usr/bin/ruby

first_number = ARGV[0].to_i
second_number = ARGV[1].to_i

puts first_number + second_number

and you call it like this

% ./plus.rb 5 6
==> 11

"Application tried to present modally an active controller"?

I had same problem.I solve it. You can try This code:

[tabBarController setSelectedIndex:1];
[self dismissModalViewControllerAnimated:YES];

Python Save to file

You need to open the file again using open(), but this time passing 'w' to indicate that you want to write to the file. I would also recommend using with to ensure that the file will be closed when you are finished writing to it.

with open('Failed.txt', 'w') as f:
    for ip in [k for k, v in ips.iteritems() if v >=5]:
        f.write(ip)

Naturally you may want to include newlines or other formatting in your output, but the basics are as above.

The same issue with closing your file applies to the reading code. That should look like this:

ips = {}
with open('today','r') as myFile:
    for line in myFile:
        parts = line.split(' ')
        if parts[1] == 'Failure':
            if parts[0] in ips:
                ips[pars[0]] += 1
            else:
                ips[parts[0]] = 0

Python add item to the tuple

Bottom line, the easiest way to append to a tuple is to enclose the element being added with parentheses and a comma.

t = ('a', 4, 'string')
t = t + (5.0,)
print(t)

out: ('a', 4, 'string', 5.0)

python: changing row index of pandas data frame

followers_df.reset_index()
followers_df.reindex(index=range(0,20))

How to output to the console and file?

Use logging module (http://docs.python.org/library/logging.html):

import logging

logger = logging.getLogger('scope.name')

file_log_handler = logging.FileHandler('logfile.log')
logger.addHandler(file_log_handler)

stderr_log_handler = logging.StreamHandler()
logger.addHandler(stderr_log_handler)

# nice output format
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
file_log_handler.setFormatter(formatter)
stderr_log_handler.setFormatter(formatter)

logger.info('Info message')
logger.error('Error message')

How to set up Spark on Windows?

You can use following ways to setup Spark:

  • Building from Source
  • Using prebuilt release

Though there are various ways to build Spark from Source.
First I tried building Spark source with SBT but that requires hadoop. To avoid those issues, I used pre-built release.

Instead of Source,I downloaded Prebuilt release for hadoop 2.x version and ran it. For this you need to install Scala as prerequisite.

I have collated all steps here :
How to run Apache Spark on Windows7 in standalone mode

Hope it'll help you..!!!

window.open(url, '_blank'); not working on iMac/Safari

There's a setting in Safari under "Tabs" that labeled Open pages in tabs instead of windows: with a drop down with a few options. I'm thinking yours may be set to Always. Bottom line is you can't rely on a browser opening a new window.

Can't import Numpy in Python

The following command worked for me:

python.exe -m pip install numpy

Get Value of a Edit Text field

public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

  Button  rtn = (Button)findViewById(R.id.button);
  EditText edit_text   = (EditText)findViewById(R.id.edittext1);

    rtn .setOnClickListener(
        new View.OnClickListener()
        {
            public void onClick(View view)
            {
                Log.v("EditText value=", edit_text.getText().toString());
            }
        });
}

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

Call a function from another file?

Inside MathMethod.Py.

def Add(a,b):
   return a+b 

def subtract(a,b):
  return a-b

Inside Main.Py

import MathMethod as MM 
  print(MM.Add(200,1000))

Output:1200

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.