Programs & Examples On #Alias method chain

100% width in React Native Flexbox

First add Dimension component:

import { AppRegistry, Text, View,Dimensions } from 'react-native';

Second define Variables:

var height = Dimensions.get('window').height;
var width = Dimensions.get('window').width;

Third put it in your stylesheet:

textOutputView: {
    flexDirection:'row',
    paddingTop:20,
    borderWidth:1,
    borderColor:'red',
    height:height*0.25,
    backgroundColor:'darkgrey',
    justifyContent:'flex-end'
}

Actually in this example I wanted to make responsive view and wanted to view only 0.25 of the screen view so I multiplied it with 0.25, if you wanted 100% of the screen don't multiply it with any thing like this:

textOutputView: {
    flexDirection:'row',
    paddingTop:20,
    borderWidth:1,
    borderColor:'red',
    height:height,
    backgroundColor:'darkgrey',
    justifyContent:'flex-end'
}

How to count duplicate value in an array in javascript

var testArray = ['a','b','c','d','d','e','a','b','c','f','g','h','h','h','e','a'];

var newArr = [];
testArray.forEach((item) => {
    newArr[item] = testArray.filter((el) => {
            return el === item;
    }).length;
})
console.log(newArr);

mysql select from n last rows

Starting from the answer given by @chaos, but with a few modifications:

  • You should always use ORDER BY if you use LIMIT. There is no implicit order guaranteed for an RDBMS table. You may usually get rows in the order of the primary key, but you can't rely on this, nor is it portable.

  • If you order by in the descending order, you don't need to know the number of rows in the table beforehand.

  • You must give a correlation name (aka table alias) to a derived table.

Here's my version of the query:

SELECT `id`
FROM (
    SELECT `id`, `val`
    FROM `big_table`
    ORDER BY `id` DESC
    LIMIT $n
) AS t
WHERE t.`val` = $certain_number;

Ternary operator ?: vs if...else

Ternary Operator always returns a value. So in situation when you want some output value from result and there are only 2 conditions always better to use ternary operator. Use if-else if any of the above mentioned conditions are not true.

Append text to input field

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <style type="text/css">
        *{
            font-family: arial;
            font-size: 15px;
        }
    </style>
</head>
<body>
    <button id="more">More</button><br/><br/>
    <div>
        User Name : <input type="text" class="users"/><br/><br/>
    </div>
    <button id="btn_data">Send Data</button>
    <script type="text/javascript">
        jQuery(document).ready(function($) {
            $('#more').on('click',function(x){
                var textMore = "User Name : <input type='text' class='users'/><br/><br/>";
                $("div").append(textMore);
            });

            $('#btn_data').on('click',function(x){
                var users=$(".users");
                $(users).each(function(i, e) {
                    console.log($(e).val());
                });
            })
        });
    </script>
</body>
</html>

Output enter image description here

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

Limit the length of a string with AngularJS

I would use the following a ternary operator alternative to accomplish the truncation with ... as follow:

<div>{{ modal.title.length > 20 ? (modal.title | limitTo : 20) + '...' : modal.title }}</div>

How to check for an empty object in an AngularJS view

This will do the object empty checking:

<div ng-if="isEmpty(card)">Object Empty!</div>


$scope.isEmpty = function(obj){
  return Object.keys(obj).length == 0;
}

BeanFactory not initialized or already closed - call 'refresh' before

I came across this issue twice once in upgrading to 3.2.18 from 3.2.1 and 4.3.5 from 3.2.8. In both cases, this error is because of different version of spring modules

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

Are you running the application as a jar? ( java -jar xxxx.jar)

If so, do you have the application.properties stored in that jar ?

If no, try to figure out why :

  • To be automatically package in the jar, the files can be in : src/main/resources/application.properties
  • The maven plugin in the pom.xml can also be configured

Android Studio Rendering Problems : The following classes could not be found

To use the class ActionBarOverlayLayout you need to include this in the dependencies section of build.gradle file:

compile 'com.android.support:design:24.1.1'

Sync the project once again and then you will find no problem

Removing items from a list

for (Iterator<String> iter = list.listIterator(); iter.hasNext(); ) {
    String a = iter.next();
    if (...) {
        iter.remove();
    }
}

Making an additional assumption that the list is of strings. As already answered, an list.iterator() is needed. The listIterator can do a bit of navigation too.

How to provide password to a command that prompts for one in bash?

Secure commands will not allow this, and rightly so, I'm afraid - it's a security hole you could drive a truck through.

If your command does not allow it using input redirection, or a command-line parameter, or a configuration file, then you're going to have to resort to serious trickery.

Some applications will actually open up /dev/tty to ensure you will have a hard time defeating security. You can get around them by temporarily taking over /dev/tty (creating your own as a pipe, for example) but this requires serious privileges and even it can be defeated.

Mac install and open mysql using terminal

open terminal and type

sudo sh -c 'echo /usr/local/mysql/bin > /etc/paths.d/mysql'

then close terminal and open a new terminal and type

mysql -u root -p

hit enter, and it will ask you for password

I have found this solution on https://teamtreehouse.com/community/says-mysql-command-not-found

now to set new password type

ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass';

Set color of TextView span in Android

  1. create textview in ur layout
  2. paste this code in ur MainActivity

    TextView textview=(TextView)findViewById(R.id.textviewid);
    Spannable spannable=new SpannableString("Hello my name is sunil");
    spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 0, 5, 
    Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    textview.setText(spannable);
    //Note:- the 0,5 is the size of colour which u want to give the strring
    //0,5 means it give colour to starting from h and ending with space i.e.(hello), if you want to change size and colour u can easily
    

PHPMailer - SMTP ERROR: Password command failed when send mail from my server

Your mail won't be sent online unless you complete the two-step verification for your g-mail account and use that password.

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

How to sort an array in Bash

If you don't need to handle special shell characters in the array elements:

array=(a c b f 3 5)
sorted=($(printf '%s\n' "${array[@]}"|sort))

With bash you'll need an external sorting program anyway.

With zsh no external programs are needed and special shell characters are easily handled:

% array=('a a' c b f 3 5); printf '%s\n' "${(o)array[@]}" 
3
5
a a
b
c
f

ksh has set -s to sort ASCIIbetically.

How to open some ports on Ubuntu?

If you want to open it for a range and for a protocol

ufw allow 11200:11299/tcp
ufw allow 11200:11299/udp

String replacement in Objective-C

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

How do I set default values for functions parameters in Matlab?

I am confused nobody has pointed out this blog post by Loren, one of Matlab's developers. The approach is based on varargin and avoids all those endless and painfull if-then-else or switch cases with convoluted conditions. When there are a few default values, the effect is dramatic. Here's an example from the linked blog:

function y = somefun2Alt(a,b,varargin)
% Some function that requires 2 inputs and has some optional inputs.

% only want 3 optional inputs at most
numvarargs = length(varargin);
if numvarargs > 3
    error('myfuns:somefun2Alt:TooManyInputs', ...
        'requires at most 3 optional inputs');
end

% set defaults for optional inputs
optargs = {eps 17 @magic};

% now put these defaults into the valuesToUse cell array, 
% and overwrite the ones specified in varargin.
optargs(1:numvarargs) = varargin;
% or ...
% [optargs{1:numvarargs}] = varargin{:};

% Place optional args in memorable variable names
[tol, mynum, func] = optargs{:};

If you still don't get it, then try reading the entire blog post by Loren. I have written a follow up blog post which deals with missing positional default values. I mean that you could write something like:

somefun2Alt(a, b, '', 42)

and still have the default eps value for the tol parameter (and @magic callback for func of course). Loren's code allows this with a slight but tricky modification.

Finally, just a few advantages of this approach:

  1. Even with a lot of defaults the boilerplate code doesn't get huge (as opposed to the family of if-then-else approaches, which get longer with each new default value)
  2. All the defaults are in one place. If any of those need to change, you have just one place to look at.

Trooth be told, there is a disadvantage too. When you type the function in Matlab shell and forget its parameters, you will see an unhelpful varargin as a hint. To deal with that, you're advised to write a meaningful usage clause.

How can I obfuscate (protect) JavaScript?

I'm under the impression that some enterprises (e.g.: JackBe) put encrypted JavaScript code inside *.gif files, rather than JS files, as an additional measure of obfuscation.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

I also had the same problem. I used next way:

1.Added settings.xml file (~/.m2/settings.xml) with next content

<proxies>
   <proxy>
      <active>true</active>
      <protocol>http</protocol>
      <host>qq-proxya</host>
      <port>8080</port>
      <username>user</username>
      <password>passw</password>
      <nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
    </proxy>
  </proxies>

3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !

  1. After that updated project in the Eclipse(Alt + F5) or right click on project -> Maven -> Update project

P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.

How to get an MD5 checksum in PowerShell

Here is the snippet that I am using to get the MD5 for a given string:

$text = "text goes here..."
$md5  = [Security.Cryptography.MD5CryptoServiceProvider]::new()
$utf8 = [Text.UTF8Encoding]::UTF8
$bytes= $md5.ComputeHash($utf8.GetBytes($text))
$hash = [string]::Concat($bytes.foreach{$_.ToString("x2")}) 

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

Real time face detection OpenCV, Python

Your line:

img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.

Try

cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2) 

How to show the text on a ImageButton?

Best way to show Text on button(with image)

example of text on button with image background

Your Question: How to show text on imagebutton?

Answer: You can not display text with imageButton. Method that tell in Accepted answer also not work.

because

If you use android:drawableLeft="@drawable/buttonok" then you can not set drawable in center of button.

If you use android:background="@drawable/button_bg" then color of your drawable will be changed.

In android world there are thousands of option to do this. But here i provide best alternate according to my point of view. (see below)

Solution: Use cardView with LinearLayout

Your drawable/image use in LinearLayout because it shows in center. And with help of textView you can set text on this. We makes cardView background to transparent.

<androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="99dp"
                android:layout_margin="16dp"
                app:cardBackgroundColor="@android:color/transparent"
                app:cardElevation="0dp"
                app:cardUseCompatPadding="true">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:background="@drawable/your_selected_image"
                    >

                    <TextView
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        android:text="Happy Coding"
                        android:textSize="33sp"
                        android:gravity="center"
                        >
                    </TextView>

                </LinearLayout>
            </androidx.cardview.widget.CardView>

here i explain some terms:

app:cardBackgroundColor="@android:color/transparent" for make transparent background of cardView

app:cardElevation="0dp" for hide evelation lines around cardView

app:cardUseCompatPadding="true" its provide actual size of cardView. Always use this when you use cardView

set your image/drawable in LinearLayout as a background.

Sorry, for my Bad English.

Happy Coding:)

Why is C so fast, and why aren't other languages as fast or faster?

There are a lot of questions in there - mostly ones I am not qualified to answer. But for this last one:

what's to stop other languages from being able to compile down to binary that runs every bit as fast as C?

In a word, Abstraction.

C is only one or 2 levels of abstraction away from machine language. Java and the .Net languages are at a minimum 3 levels of abstraction away from assembler. I'm not sure about Python and Ruby.

Typically, the more programmer toys (complex data types, etc.), the further you are from machine language and the more translation has to be done.

I'm off here and there but that's the basic gist.

Update ------- There are some good comments on this post with more details.

git visual diff between branches

You can also use vscode to compare branches using extension CodeLense, this is already answered in this SO: How to compare different branches on Visual studio code

How to use Sublime over SSH

You can use rsub, which is inspired on TextMate's rmate. From the description:

Rsub is an implementation of TextMate 2's 'rmate' feature for Sublime Text 2, allowing files to be edited on a remote server using SSH port forwarding / tunnelling.

Here's a good tutorial on how to set it up properly.

How can I limit the visible options in an HTML <select> dropdown?

A minor but important modification to existing solutions aiming at preserving framework styling (i.e. Bootstrap): replace this.size=0 with this.removeAttribute('size').

<select class="custom-select" onmousedown="if(this.options.length>5){this.size=5}"
    onchange='this.blur()' onblur="this.removeAttribute('size')">
    <option>option1</option>
    <option>option2</option>
    <option>option3</option>
    <option>option4</option>
    <option>option5</option>
    <option>option6</option>
    <option>option7</option>
</select>

How to convert time milliseconds to hours, min, sec format in JavaScript?

In my implementation I used Moment.js:

export default (value) => 
  const duration = moment.duration(value);

  const milliseconds = duration.milliseconds();
  const seconds = duration.seconds();
  const minutes = duration.minutes();
  const hours = duration.hours();
  const day = duration.days();

  const sDay = `${day}d `;
  const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
  const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
  const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
  const sMilliseconds = `${milliseconds}ms`;

  ...
}

Once got the strings, I composed them as I want.

How do search engines deal with AngularJS applications?

I have found an elegant solution that would cover most of your bases. I wrote about it initially here and answered another similar StackOverflow question here which references it.

FYI this solution also includes hardcoded fallback tags in case Javascript isn't picked up by the crawler. I haven't explicitly outlined it, but it is worth mentioning that you should be activating HTML5 mode for proper URL support.

Also note: these aren't the complete files, just the important parts of those that are relevant. If you need help writing the boilerplate for directives, services, etc. that can be found elsewhere. Anyway, here goes...

app.js

This is where you provide the custom metadata for each of your routes (title, description, etc.)

$routeProvider
   .when('/', {
       templateUrl: 'views/homepage.html',
       controller: 'HomepageCtrl',
       metadata: {
           title: 'The Base Page Title',
           description: 'The Base Page Description' }
   })
   .when('/about', {
       templateUrl: 'views/about.html',
       controller: 'AboutCtrl',
       metadata: {
           title: 'The About Page Title',
           description: 'The About Page Description' }
   })

metadata-service.js (service)

Sets the custom metadata options or use defaults as fallbacks.

var self = this;

// Set custom options or use provided fallback (default) options
self.loadMetadata = function(metadata) {
  self.title = document.title = metadata.title || 'Fallback Title';
  self.description = metadata.description || 'Fallback Description';
  self.url = metadata.url || $location.absUrl();
  self.image = metadata.image || 'fallbackimage.jpg';
  self.ogpType = metadata.ogpType || 'website';
  self.twitterCard = metadata.twitterCard || 'summary_large_image';
  self.twitterSite = metadata.twitterSite || '@fallback_handle';
};

// Route change handler, sets the route's defined metadata
$rootScope.$on('$routeChangeSuccess', function (event, newRoute) {
  self.loadMetadata(newRoute.metadata);
});

metaproperty.js (directive)

Packages the metadata service results for the view.

return {
  restrict: 'A',
  scope: {
    metaproperty: '@'
  },
  link: function postLink(scope, element, attrs) {
    scope.default = element.attr('content');
    scope.metadata = metadataService;

    // Watch for metadata changes and set content
    scope.$watch('metadata', function (newVal, oldVal) {
      setContent(newVal);
    }, true);

    // Set the content attribute with new metadataService value or back to the default
    function setContent(metadata) {
      var content = metadata[scope.metaproperty] || scope.default;
      element.attr('content', content);
    }

    setContent(scope.metadata);
  }
};

index.html

Complete with the hardcoded fallback tags mentioned earlier, for crawlers that can't pick up any Javascript.

<head>
  <title>Fallback Title</title>
  <meta name="description" metaproperty="description" content="Fallback Description">

  <!-- Open Graph Protocol Tags -->
  <meta property="og:url" content="fallbackurl.com" metaproperty="url">
  <meta property="og:title" content="Fallback Title" metaproperty="title">
  <meta property="og:description" content="Fallback Description" metaproperty="description">
  <meta property="og:type" content="website" metaproperty="ogpType">
  <meta property="og:image" content="fallbackimage.jpg" metaproperty="image">

  <!-- Twitter Card Tags -->
  <meta name="twitter:card" content="summary_large_image" metaproperty="twitterCard">
  <meta name="twitter:title" content="Fallback Title" metaproperty="title">
  <meta name="twitter:description" content="Fallback Description" metaproperty="description">
  <meta name="twitter:site" content="@fallback_handle" metaproperty="twitterSite">
  <meta name="twitter:image:src" content="fallbackimage.jpg" metaproperty="image">
</head>

This should help dramatically with most search engine use cases. If you want fully dynamic rendering for social network crawlers (which are iffy on Javascript support), you'll still have to use one of the pre-rendering services mentioned in some of the other answers.

Hope this helps!

How to pass credentials to the Send-MailMessage command for sending emails

And here is a simple Send-MailMessage example with username/password for anyone looking for just that

$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
Send-MailMessage -SmtpServer mysmptp -Credential $cred -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

How to make a owl carousel with arrows instead of next previous

Complete tutorial here

Demo link

enter image description here

JavaScript

$('.owl-carousel').owlCarousel({
    margin: 10,
    nav: true,
    navText:["<div class='nav-btn prev-slide'></div>","<div class='nav-btn next-slide'></div>"],
    responsive: {
        0: {
            items: 1
        },
        600: {
            items: 3
        },
        1000: {
            items: 5
        }
    }
});

CSS Style for navigation

.owl-carousel .nav-btn{
  height: 47px;
  position: absolute;
  width: 26px;
  cursor: pointer;
  top: 100px !important;
}

.owl-carousel .owl-prev.disabled,
.owl-carousel .owl-next.disabled{
pointer-events: none;
opacity: 0.2;
}

.owl-carousel .prev-slide{
  background: url(nav-icon.png) no-repeat scroll 0 0;
  left: -33px;
}
.owl-carousel .next-slide{
  background: url(nav-icon.png) no-repeat scroll -24px 0px;
  right: -33px;
}
.owl-carousel .prev-slide:hover{
 background-position: 0px -53px;
}
.owl-carousel .next-slide:hover{
background-position: -24px -53px;
}   

Spring Boot - Handle to Hibernate SessionFactory

The simplest and least verbose way to autowire your Hibernate SessionFactory is:

This is the solution for Spring Boot 1.x with Hibernate 4:

application.properties:

spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate4.SpringSessionContext

Configuration class:

@Bean
public HibernateJpaSessionFactoryBean sessionFactory() {
    return new HibernateJpaSessionFactoryBean();
}

Then you can autowire the SessionFactory in your services as usual:

@Autowired
private SessionFactory sessionFactory;

As of Spring Boot 1.5 with Hibernate 5, this is now the preferred way:

application.properties:

spring.jpa.properties.hibernate.current_session_context_class=
org.springframework.orm.hibernate5.SpringSessionContext

Configuration class:

@EnableAutoConfiguration
...
...
@Bean
public HibernateJpaSessionFactoryBean sessionFactory(EntityManagerFactory emf) {
    HibernateJpaSessionFactoryBean fact = new HibernateJpaSessionFactoryBean();
    fact.setEntityManagerFactory(emf);
    return fact;
}

Logcat not displaying my log calls

some times the problem is not from pc on the other hand IDE,ADB etc, but it arises from your device that doesn't send logs to ADB so if you tried all the ways mentioned before and still your logcat is empty try to restart your device and try again.I tried all the ways mentioned above and neither of them worked but after a restart on my phone logcat worked like magic

How do I get time of a Python program's execution?

I like the output the datetime module provides, where time delta objects show days, hours, minutes, etc. as necessary in a human-readable way.

For example:

from datetime import datetime
start_time = datetime.now()
# do your work here
end_time = datetime.now()
print('Duration: {}'.format(end_time - start_time))

Sample output e.g.

Duration: 0:00:08.309267

or

Duration: 1 day, 1:51:24.269711

As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it's safer to use:

import time
from datetime import timedelta
start_time = time.monotonic()
end_time = time.monotonic()
print(timedelta(seconds=end_time - start_time))

How to combine GROUP BY, ORDER BY and HAVING

Steps for Using Group by,Having By and Order by...

Select Attitude ,count(*) from Person
group by person
HAving PersonAttitude='cool and friendly'
Order by PersonName.

Node JS Promise.all and forEach

Just to add to the solution presented, in my case I wanted to fetch multiple data from Firebase for a list of products. Here is how I did it:

useEffect(() => {
  const fn = p => firebase.firestore().doc(`products/${p.id}`).get();
  const actions = data.occasion.products.map(fn);
  const results = Promise.all(actions);
  results.then(data => {
    const newProducts = [];
    data.forEach(p => {
      newProducts.push({ id: p.id, ...p.data() });
    });
    setProducts(newProducts);
  });
}, [data]);

Cloud Firestore collection count

UPDATE 11/20

I created an npm package for easy access to a counter function: https://fireblog.io/blog/post/firestore-counters


I created a universal function using all these ideas to handle all counter situations (except queries).

The only exception would be when doing so many writes a second, it slows you down. An example would be likes on a trending post. It is overkill on a blog post, for example, and will cost you more. I suggest creating a separate function in that case using shards: https://firebase.google.com/docs/firestore/solutions/counters

// trigger collections
exports.myFunction = functions.firestore
    .document('{colId}/{docId}')
    .onWrite(async (change: any, context: any) => {
        return runCounter(change, context);
    });

// trigger sub-collections
exports.mySubFunction = functions.firestore
    .document('{colId}/{docId}/{subColId}/{subDocId}')
    .onWrite(async (change: any, context: any) => {
        return runCounter(change, context);
    });

// add change the count
const runCounter = async function (change: any, context: any) {

    const col = context.params.colId;

    const eventsDoc = '_events';
    const countersDoc = '_counters';

    // ignore helper collections
    if (col.startsWith('_')) {
        return null;
    }
    // simplify event types
    const createDoc = change.after.exists && !change.before.exists;
    const updateDoc = change.before.exists && change.after.exists;

    if (updateDoc) {
        return null;
    }
    // check for sub collection
    const isSubCol = context.params.subDocId;

    const parentDoc = `${countersDoc}/${context.params.colId}`;
    const countDoc = isSubCol
        ? `${parentDoc}/${context.params.docId}/${context.params.subColId}`
        : `${parentDoc}`;

    // collection references
    const countRef = db.doc(countDoc);
    const countSnap = await countRef.get();

    // increment size if doc exists
    if (countSnap.exists) {
        // createDoc or deleteDoc
        const n = createDoc ? 1 : -1;
        const i = admin.firestore.FieldValue.increment(n);

        // create event for accurate increment
        const eventRef = db.doc(`${eventsDoc}/${context.eventId}`);

        return db.runTransaction(async (t: any): Promise<any> => {
            const eventSnap = await t.get(eventRef);
            // do nothing if event exists
            if (eventSnap.exists) {
                return null;
            }
            // add event and update size
            await t.update(countRef, { count: i });
            return t.set(eventRef, {
                completed: admin.firestore.FieldValue.serverTimestamp()
            });
        }).catch((e: any) => {
            console.log(e);
        });
        // otherwise count all docs in the collection and add size
    } else {
        const colRef = db.collection(change.after.ref.parent.path);
        return db.runTransaction(async (t: any): Promise<any> => {
            // update size
            const colSnap = await t.get(colRef);
            return t.set(countRef, { count: colSnap.size });
        }).catch((e: any) => {
            console.log(e);
        });;
    }
}

This handles events, increments, and transactions. The beauty in this, is that if you are not sure about the accuracy of a document (probably while still in beta), you can delete the counter to have it automatically add them up on the next trigger. Yes, this costs, so don't delete it otherwise.

Same kind of thing to get the count:

const collectionPath = 'buildings/138faicnjasjoa89/buildingContacts';
const colSnap = await db.doc('_counters/' + collectionPath).get();
const count = colSnap.get('count');

Also, you may want to create a cron job (scheduled function) to remove old events to save money on database storage. You need at least a blaze plan, and there may be some more configuration. You could run it every sunday at 11pm, for example. https://firebase.google.com/docs/functions/schedule-functions

This is untested, but should work with a few tweaks:

exports.scheduledFunctionCrontab = functions.pubsub.schedule('5 11 * * *')
    .timeZone('America/New_York')
    .onRun(async (context) => {

        // get yesterday
        const yesterday = new Date();
        yesterday.setDate(yesterday.getDate() - 1);

        const eventFilter = db.collection('_events').where('completed', '<=', yesterday);
        const eventFilterSnap = await eventFilter.get();
        eventFilterSnap.forEach(async (doc: any) => {
            await doc.ref.delete();
        });
        return null;
    });

And last, don't forget to protect the collections in firestore.rules:

match /_counters/{document} {
  allow read;
  allow write: if false;
}
match /_events/{document} {
  allow read, write: if false;
}

Update: Queries

Adding to my other answer if you want to automate query counts as well, you can use this modified code in your cloud function:

    if (col === 'posts') {

        // counter reference - user doc ref
        const userRef = after ? after.userDoc : before.userDoc;
        // query reference
        const postsQuery = db.collection('posts').where('userDoc', "==", userRef);
        // add the count - postsCount on userDoc
        await addCount(change, context, postsQuery, userRef, 'postsCount');

    }
    return delEvents();

Which will automatically update the postsCount in the userDocument. You could easily add other one to many counts this way. This just gives you ideas of how you can automate things. I also gave you another way to delete the events. You have to read each date to delete it, so it won't really save you to delete them later, just makes the function slower.

/**
 * Adds a counter to a doc
 * @param change - change ref
 * @param context - context ref
 * @param queryRef - the query ref to count
 * @param countRef - the counter document ref
 * @param countName - the name of the counter on the counter document
 */
const addCount = async function (change: any, context: any, 
  queryRef: any, countRef: any, countName: string) {

    // events collection
    const eventsDoc = '_events';

    // simplify event type
    const createDoc = change.after.exists && !change.before.exists;

    // doc references
    const countSnap = await countRef.get();

    // increment size if field exists
    if (countSnap.get(countName)) {
        // createDoc or deleteDoc
        const n = createDoc ? 1 : -1;
        const i = admin.firestore.FieldValue.increment(n);

        // create event for accurate increment
        const eventRef = db.doc(`${eventsDoc}/${context.eventId}`);

        return db.runTransaction(async (t: any): Promise<any> => {
            const eventSnap = await t.get(eventRef);
            // do nothing if event exists
            if (eventSnap.exists) {
                return null;
            }
            // add event and update size
            await t.set(countRef, { [countName]: i }, { merge: true });
            return t.set(eventRef, {
                completed: admin.firestore.FieldValue.serverTimestamp()
            });
        }).catch((e: any) => {
            console.log(e);
        });
        // otherwise count all docs in the collection and add size
    } else {
        return db.runTransaction(async (t: any): Promise<any> => {
            // update size
            const colSnap = await t.get(queryRef);
            return t.set(countRef, { [countName]: colSnap.size }, { merge: true });
        }).catch((e: any) => {
            console.log(e);
        });;
    }
}
/**
 * Deletes events over a day old
 */
const delEvents = async function () {

    // get yesterday
    const yesterday = new Date();
    yesterday.setDate(yesterday.getDate() - 1);

    const eventFilter = db.collection('_events').where('completed', '<=', yesterday);
    const eventFilterSnap = await eventFilter.get();
    eventFilterSnap.forEach(async (doc: any) => {
        await doc.ref.delete();
    });
    return null;
}

I should also warn you that universal functions will run on every onWrite call period. It may be cheaper to only run the function on onCreate and on onDelete instances of your specific collections. Like the noSQL database we are using, repeated code and data can save you money.

Get total of Pandas column

As other option, you can do something like below

Group   Valuation   amount
    0   BKB Tube    156
    1   BKB Tube    143
    2   BKB Tube    67
    3   BAC Tube    176
    4   BAC Tube    39
    5   JDK Tube    75
    6   JDK Tube    35
    7   JDK Tube    155
    8   ETH Tube    38
    9   ETH Tube    56

Below script, you can use for above data

import pandas as pd    
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()

Extract matrix column values by matrix column name

Yes. But place your "test" after the comma if you want the column...

> A <- matrix(sample(1:12,12,T),ncol=4)

> rownames(A) <- letters[1:3]

> colnames(A) <- letters[11:14]
> A[,"l"]
 a  b  c 
 6 10  1 

see also help(Extract)

Rails 4: how to use $(document).ready() with turbo-links

Here's what I have done to ensure things aren't executed twice:

$(document).on("page:change", function() {
     // ... init things, just do not bind events ...
     $(document).off("page:change");
});

I find using the jquery-turbolinks gem or combining $(document).ready and $(document).on("page:load") or using $(document).on("page:change") by itself behaves unexpectedly--especially if you're in development.

how to set the default value to the drop down list control?

Assuming that the DropDownList control in the other table also contains DepartmentName and DepartmentID:

lstDepartment.ClearSelection();

foreach (var item in lstDepartment.Items) 
{
  if (item.Value == otherDropDownList.SelectedValue)
  {
    item.Selected = true;
  }
}

How to get text with Selenium WebDriver in Python

You want just .text.

You can then verify it after you've got it, don't attempt to pass in what you expect it should have.

Selecting multiple columns in a Pandas dataframe

You can also use df.pop():

>>> df = pd.DataFrame([('falcon', 'bird',    389.0),
...                    ('parrot', 'bird',     24.0),
...                    ('lion',   'mammal',   80.5),
...                    ('monkey', 'mammal', np.nan)],
...                   columns=('name', 'class', 'max_speed'))
>>> df
     name   class  max_speed
0  falcon    bird      389.0
1  parrot    bird       24.0
2    lion  mammal       80.5
3  monkey  mammal

>>> df.pop('class')
0      bird
1      bird
2    mammal
3    mammal
Name: class, dtype: object

>>> df
     name  max_speed
0  falcon      389.0
1  parrot       24.0
2    lion       80.5
3  monkey        NaN

Please use df.pop(c).

JQuery: detect change in input field

You can use jQuery change() function

$('input').change(function(){
  //your codes
});

There are examples on how to use it on the API Page: http://api.jquery.com/change/

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

Scatter plot and Color mapping in Python

To add to wflynny's answer above, you can find the available colormaps here

Example:

import matplotlib.cm as cm
plt.scatter(x, y, c=t, cmap=cm.jet)

or alternatively,

plt.scatter(x, y, c=t, cmap='jet')

jackson deserialization json to java-objects

It looks like you are trying to read an object from JSON that actually describes an array. Java objects are mapped to JSON objects with curly braces {} but your JSON actually starts with square brackets [] designating an array.

What you actually have is a List<product> To describe generic types, due to Java's type erasure, you must use a TypeReference. Your deserialization could read: myProduct = objectMapper.readValue(productJson, new TypeReference<List<product>>() {});

A couple of other notes: your classes should always be PascalCased. Your main method can just be public static void main(String[] args) throws Exception which saves you all the useless catch blocks.

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

How to fix a collation conflict in a SQL Server query?

You can resolve the issue by forcing the collation used in a query to be a particular collation, e.g. SQL_Latin1_General_CP1_CI_AS or DATABASE_DEFAULT. For example:

SELECT MyColumn
FROM FirstTable a
INNER JOIN SecondTable b
ON a.MyID COLLATE SQL_Latin1_General_CP1_CI_AS = 
b.YourID COLLATE SQL_Latin1_General_CP1_CI_AS

In the above query, a.MyID and b.YourID would be columns with a text-based data type. Using COLLATE will force the query to ignore the default collation on the database and instead use the provided collation, in this case SQL_Latin1_General_CP1_CI_AS.

Basically what's going on here is that each database has its own collation which "provides sorting rules, case, and accent sensitivity properties for your data" (from http://technet.microsoft.com/en-us/library/ms143726.aspx) and applies to columns with textual data types, e.g. VARCHAR, CHAR, NVARCHAR, etc. When two databases have differing collations, you cannot compare text columns with an operator like equals (=) without addressing the conflict between the two disparate collations.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

It looks like you have a certificate in DER format instead of PEM. This is why it works correctly when you provide the -inform PEM command line argument (which tells openssl what input format to expect).

It's likely that your private key is using the same encoding. It looks as if the openssl rsa command also accepts a -inform argument, so try:

openssl rsa -text -in file.key -inform DER

A PEM encoded file is a plain-text encoding that looks something like:

-----BEGIN RSA PRIVATE KEY-----
MIGrAgEAAiEA0tlSKz5Iauj6ud3helAf5GguXeLUeFFTgHrpC3b2O20CAwEAAQIh
ALeEtAIzebCkC+bO+rwNFVORb0bA9xN2n5dyTw/Ba285AhEA9FFDtx4VAxMVB2GU
QfJ/2wIRANzuXKda/nRXIyRw1ArE2FcCECYhGKRXeYgFTl7ch7rTEckCEQDTMShw
8pL7M7DsTM7l3HXRAhAhIMYKQawc+Y7MNE4kQWYe
-----END RSA PRIVATE KEY-----

While DER is a binary encoding format.

Update

Sometimes keys are distributed in PKCS#8 format (which can be either PEM or DER encoded). Try this and see what you get:

openssl pkcs8 -in file.key -inform der

How to deep watch an array in angularjs?

This solution worked very well for me, i'm doing this in a directive:

scope.$watch(attrs.testWatch, function() {.....}, true);

the true works pretty well and react for all the chnages (add, delete, or modify a field).

Here is a working plunker for play with it.

Deeply Watching an Array in AngularJS

I hope this can be useful for you. If you have any questions, feel free for ask, I'll try to help :)

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

How to activate virtualenv?

Windows 10

In Windows these directories are created :

Windows 10 Virtual Environment directories

To activate Virtual Environment in Windows 10.

down\scripts\activate

\scripts directory contain activate file.

Linux Ubuntu

In Ubuntu these directories are created :

Linux Ubuntu Virtual Environment directories

To activate Virtual Environment in Linux Ubuntu.

source ./bin/activate

/bin directory contain activate file.


Virtual Environment copied from Windows to Linux Ubuntu vice versa

If Virtual environment folder copied from Windows to Linux Ubuntu then according to directories:

source ./down/Scripts/activate

Is there a way to reduce the size of the git folder?

One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.

Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).

In this article on git space, AlBlue mentions:

Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.

If you have large binaries stored in your git repo, you may consider:

As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).

Javascript - get array of dates between 2 dates

This may help someone,

You can get the row output from this and format the row_date object as you want.

var from_date = '2016-01-01';
var to_date = '2016-02-20';

var dates = getDates(from_date, to_date);

console.log(dates);

function getDates(from_date, to_date) {
  var current_date = new Date(from_date);
  var end_date     = new Date(to_date);

  var getTimeDiff = Math.abs(current_date.getTime() - end_date.getTime());
  var date_range = Math.ceil(getTimeDiff / (1000 * 3600 * 24)) + 1 ;

  var weekday = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
  var months = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"];
  var dates = new Array();

  for (var i = 0; i <= date_range; i++) {
     var getDate, getMonth = '';

     if(current_date.getDate() < 10) { getDate = ('0'+ current_date.getDate());}
     else{getDate = current_date.getDate();}

    if(current_date.getMonth() < 9) { getMonth = ('0'+ (current_date.getMonth()+1));}
    else{getMonth = current_date.getMonth();}

    var row_date = {day: getDate, month: getMonth, year: current_date.getFullYear()};
    var fmt_date = {weekDay: weekday[current_date.getDay()], date: getDate, month: months[current_date.getMonth()]};
    var is_weekend = false;
    if (current_date.getDay() == 0 || current_date.getDay() == 6) {
        is_weekend = true;
    }
    dates.push({row_date: row_date, fmt_date: fmt_date, is_weekend: is_weekend});
    current_date.setDate(current_date.getDate() + 1);
 }
 return dates;
}

https://gist.github.com/pranid/3c78f36253cbbc6a41a859c5d718f362.js

Why does the C++ STL not provide any "tree" containers?

I think there are several reasons why there are no STL trees. Primarily Trees are a form of recursive data structure which, like a container (list, vector, set), has very different fine structure which makes the correct choices tricky. They are also very easy to construct in basic form using the STL.

A finite rooted tree can be thought of as a container which has a value or payload, say an instance of a class A and, a possibly empty collection of rooted (sub) trees; trees with empty collection of subtrees are thought of as leaves.

template<class A>
struct unordered_tree : std::set<unordered_tree>, A
{};

template<class A>
struct b_tree : std::vector<b_tree>, A
{};

template<class A>
struct planar_tree : std::list<planar_tree>, A
{};

One has to think a little about iterator design etc. and which product and co-product operations one allows to define and be efficient between trees - and the original STL has to be well written - so that the empty set, vector or list container is really empty of any payload in the default case.

Trees play an essential role in many mathematical structures (see the classical papers of Butcher, Grossman and Larsen; also the papers of Connes and Kriemer for examples of they can be joined, and how they are used to enumerate). It is not correct to think their role is simply to facilitate certain other operations. Rather they facilitate those tasks because of their fundamental role as a data structure.

However, in addition to trees there are also "co-trees"; the trees above all have the property that if you delete the root you delete everything.

Consider iterators on the tree, probably they would be realised as a simple stack of iterators, to a node, and to its parent, ... up to the root.

template<class TREE>
struct node_iterator : std::stack<TREE::iterator>{
operator*() {return *back();}
...};

However, you can have as many as you like; collectively they form a "tree" but where all the arrows flow in the direction toward the root, this co-tree can be iterated through iterators towards the trivial iterator and root; however it cannot be navigated across or down (the other iterators are not known to it) nor can the ensemble of iterators be deleted except by keeping track of all the instances.

Trees are incredibly useful, they have a lot of structure, this makes it a serious challenge to get the definitively correct approach. In my view this is why they are not implemented in the STL. Moreover, in the past, I have seen people get religious and find the idea of a type of container containing instances of its own type challenging - but they have to face it - that is what a tree type represents - it is a node containing a possibly empty collection of (smaller) trees. The current language permits it without challenge providing the default constructor for container<B> does not allocate space on the heap (or anywhere else) for an B, etc.

I for one would be pleased if this did, in a good form, find its way into the standard.

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Error 'tunneling socket' while executing npm install

according to this it's proxy isssues, try to disable ssl and set registry to http instead of https . hope it helps!

npm config set registry=http://registry.npmjs.org/
npm config set strict-ssl false

How do you test to see if a double is equal to NaN?

Try Double.isNaN():

Returns true if this Double value is a Not-a-Number (NaN), false otherwise.

Note that [double.isNaN()] will not work, because unboxed doubles do not have methods associated with them.

How to create JSON object using jQuery

A "JSON object" doesn't make sense : JSON is an exchange format based on the structure of Javascript object declaration.

If you want to convert your javascript object to a json string, use JSON.stringify(yourObject);

If you want to create a javascript object, simply do it like this :

var yourObject = {
          test:'test 1',
          testData: [ 
                {testName: 'do',testId:''}
          ],
          testRcd:'value'   
};

How to convert rdd object to dataframe in spark

Note: This answer was originally posted here

I am posting this answer because I would like to share additional details about the available options that I did not find in the other answers


To create a DataFrame from an RDD of Rows, there are two main options:

1) As already pointed out, you could use toDF() which can be imported by import sqlContext.implicits._. However, this approach only works for the following types of RDDs:

  • RDD[Int]
  • RDD[Long]
  • RDD[String]
  • RDD[T <: scala.Product]

(source: Scaladoc of the SQLContext.implicits object)

The last signature actually means that it can work for an RDD of tuples or an RDD of case classes (because tuples and case classes are subclasses of scala.Product).

So, to use this approach for an RDD[Row], you have to map it to an RDD[T <: scala.Product]. This can be done by mapping each row to a custom case class or to a tuple, as in the following code snippets:

val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => (val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

or

case class MyClass(val1: String, ..., valN: Long = 0L)
val df = rdd.map({ 
  case Row(val1: String, ..., valN: Long) => MyClass(val1, ..., valN)
}).toDF("col1_name", ..., "colN_name")

The main drawback of this approach (in my opinion) is that you have to explicitly set the schema of the resulting DataFrame in the map function, column by column. Maybe this can be done programatically if you don't know the schema in advance, but things can get a little messy there. So, alternatively, there is another option:


2) You can use createDataFrame(rowRDD: RDD[Row], schema: StructType) as in the accepted answer, which is available in the SQLContext object. Example for converting an RDD of an old DataFrame:

val rdd = oldDF.rdd
val newDF = oldDF.sqlContext.createDataFrame(rdd, oldDF.schema)

Note that there is no need to explicitly set any schema column. We reuse the old DF's schema, which is of StructType class and can be easily extended. However, this approach sometimes is not possible, and in some cases can be less efficient than the first one.

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

The openssl extension is required for SSL/TLS protection

The same error occurred to me. I fixed it by turning off TLS for Composer, it's not safe but I assumed the risk on my develop machine.

try this:

composer config -g -- disable-tls true

and re-run your Composer. It works to me!

But it's unsecure and not recommended for your Server. The official website says:

If set to true all HTTPS URLs will be tried with HTTP instead and no network-level encryption is performed. Enabling this is a security risk and is NOT recommended. The better way is to enable the php_openssl extension in php.ini.

If you don't want to enable unsecure layer in your machine/server, then setup your php to enable openssl and it also works. Make sure the PHP Openssl extension has been installed and enable it on php.ini file.


To enable OpenSSL, add or find and uncomment this line on your php.ini file:

Linux/OSx:

extension=php_openssl.so

Windows:

extension=php_openssl.dll

And reload your php-fpm / web-server if needed!

Should image size be defined in the img tag height/width attributes or in CSS?

The historical reason to define height/width in tags is so that browsers can size the actual <img> elements in the page even before the CSS and/or image resources are loaded. If you do not supply height and width explicitly the <img> element will be rendered at 0x0 until the browser can size it based on the file. When this happens it causes a visual reflow of the page once the image loads, and is compounded if you have multiple images on the page. Sizing the <img> via height/width creates a physical placeholder in the page flow at the correct size, enabling your content to load asynchronously without disrupting the user experience.

Alternately, if you are doing mobile-responsive design, which is a best practice these days, it's quite common to specify a width (or max-width) only and define the height as auto. That way when you define media queries (e.g. CSS) for different screen widths, you can simply adjust the image width and let the browser deal with keeping the image height / aspect ratio correct. This is sort of a middle ground approach, as you may get some reflow, but it allows you to support a broad range of screen sizes, so the benefit usually outweighs the negative.

Finally, there are times when you may not know the image size ahead of time (image src might be loaded dynamically, or can change during the lifetime of the page via script) in which case using CSS only makes sense.

The bottom line is that you need to understand the trade-offs and decide which strategy makes the most sense for what you're trying to achieve.

Python DNS module import error

In my case, I hava writen the code in the file named "dns.py", it's conflict for the package, I have to rename the script filename.

Excel VBA Macro: User Defined Type Not Defined

Your error is caused by these:

Dim oTable As Table, oRow As Row,

These types, Table and Row are not variable types native to Excel. You can resolve this in one of two ways:

  1. Include a reference to the Microsoft Word object model. Do this from Tools | References, then add reference to MS Word. While not strictly necessary, you may like to fully qualify the objects like Dim oTable as Word.Table, oRow as Word.Row. This is called early-binding. enter image description here
  2. Alternatively, to use late-binding method, you must declare the objects as generic Object type: Dim oTable as Object, oRow as Object. With this method, you do not need to add the reference to Word, but you also lose the intellisense assistance in the VBE.

I have not tested your code but I suspect ActiveDocument won't work in Excel with method #2, unless you properly scope it to an instance of a Word.Application object. I don't see that anywhere in the code you have provided. An example would be like:

Sub DeleteEmptyRows()
Dim wdApp as Object
Dim oTable As Object, As Object, _
TextInRow As Boolean, i As Long

Set wdApp = GetObject(,"Word.Application")

Application.ScreenUpdating = False

For Each oTable In wdApp.ActiveDocument.Tables

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

After hours of effort, system restore, register, unregister cycles and a night's sleep I have managed to pinpoint the problem. It turns out that the project file contains the below line:

Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.0#0; MSCOMCTL.OCX

The version information "2.0" it seems was the reason of not loading. Changing it to "2.1" in notepad solved the problem:

Object={831FDD16-0C5C-11D2-A9FC-0000F8754DA1}#2.1#0; MSCOMCTL.OCX

So in a similar "OCX could not be loaded" situation one possible way of resolution is to start a new project. Put the control on one of the forms and check the vbp file with notepad to see what version it is expecting.


OR A MUCH EASIER METHOD:

(I have added this section after Bob's valuable comment below)

You can open your VBP project file in Notepad and find the nasty line that is preventing VB6 to upgrade the project automatically to 2.1 and remove it:

NoControlUpgrade=1

How to change value of ArrayList element in java

Use the set method to replace the old value with a new one.

list.set( 2, "New" );

How can I initialize a MySQL database with schema in a Docker container?

Below is the Dockerfile I used successfully to install xampp, create a MariaDB with scheme and pre populated with the info used on local server(usrs,pics orders,etc..)

FROM ubuntu:14.04

COPY Ecommerce.sql /root

RUN apt-get update \
 && apt-get install wget -yq \
 && apt-get install nano \
 && wget https://www.apachefriends.org/xampp-files/7.1.11/xampp-linux-x64-7.1.11-0-installer.run \
 && mv xampp-linux-x64-7.1.11-0-installer.run /opt/ \
 && cd /opt/ \
 && chmod +x xampp-linux-x64-7.1.11-0-installer.run \
 && printf 'y\n\y\n\r\n\y\n\r\n' | ./xampp-linux-x64-7.1.11-0-installer.run \
 && cd /opt/lampp/bin \
 && /opt/lampp/lampp start \
 && sleep 5s \

 && ./mysql -uroot -e "CREATE DATABASE Ecommerce" \
 && ./mysql -uroot -D Ecommerce < /root/Ecommerce.sql \
 && cd / \
 && /opt/lampp/lampp reload \
 && mkdir opt/lampp/htdocs/Ecommerce

COPY /Ecommerce /opt/lampp/htdocs/Ecommerce

EXPOSE 80

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Download it from here:

http://www.iis.net/downloads/microsoft/url-rewrite

or if you already have Web Platform Installer on your machine you can install it from there.

Android WebView Cookie Problem

I have a different approach from other people here, and it an approach that is guaranteed work without dealing with the CookieSyncManager (where you are at the mercy of semantics like "Note that even sync() happens asynchronously").

Essentially, we browse to the correct domain, then we execute javascript from the page context to set cookies for that domain (the same way the page itself would). Two drawbacks to the method are that may introduce an extra round trip time due to the extra http request you have to make; and if your site does not have the equivalent of a blank page, it may flash whatever URL you load first before taking you to the right place.

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.http.cookie.Cookie;
import android.annotation.SuppressLint;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class WebViewFragment {
    private static final String BLANK_PAGE = "/blank.html"

    private CookieSyncManager mSyncManager;
    private CookieManager mCookieManager;

    private String mTargetUrl;
    private boolean mInitializedCookies;
    private List<Cookie> mAllCookies;

    public WebViewFragment(Context ctx) {
        // We are still required to create an instance of Cookie/SyncManager.
        mSyncManager = CookieSyncManager.createInstance(ctx);
        mCookieManager = CookieManager.getInstance();
    }

    @SuppressLint("SetJavaScriptEnabled") public void loadWebView(
                String url, List<Cookie> cookies, String domain) {
        final WebView webView = ...

        webView.setWebViewClient(new CookeWebViewClient());
        webView.getSettings().setJavaScriptEnabled(true);

        mInitializedCookies = false;
        mTargetUrl = url;
        mAllCookies = cookies;
        // This is where the hack starts.
        // Instead of loading the url, we load a blank page.
        webView.loadUrl("http://" + domain + BLANK_PAGE);
    }

    public static String buildCookieString(final Cookie cookie) {
        // You may want to add the secure flag for https:
        // + "; secure"
        // In case you wish to convert session cookies to have an expiration:
        // + "; expires=Thu, 01-Jan-2037 00:00:10 GMT"
        // Note that you cannot set the HttpOnly flag as we are using
        // javascript to set the cookies.
        return cookie.getName() + "=" + cookie.getValue()
                    + "; path=" + cookie.getPath()
                    + "; domain=" + cookie.getDomain()
    };

    public synchronized String generateCookieJavascript() {
        StringBuilder javascriptCode = new StringBuilder();
        javascriptCode.append("javascript:(function(){");
        for (final Cookie cookie : mAllCookies) {
            String cookieString = buildCookieString(cookie);
            javascriptCode.append("document.cookie=\"");
            javascriptCode.append(
                     StringEscapeUtils.escapeJavascriptString(cookieString));
            javascriptCode.append("\";");
        }
        // We use javascript to load the next url because we do not
        // receive an onPageFinished event when this code finishes.
        javascriptCode.append("document.location=\"");
        javascriptCode.append(
                StringEscapeUtils.escapeJavascriptString(mTargetUrl));
        javascriptCode.append("\";})();");
        return javascriptCode.toString();
    }

    private class CookieWebViewClient extends WebViewClient {
        @Override public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (!mInitializedCookies) {
                mInitializedCookies = true;
                // Run our javascript code now that the temp page is loaded.
                view.loadUrl(generateCookieJavascript());
                return;
            }
        }
    }
}

If you trust the domain the cookies are from, you may be able to get away without apache commons, but you have to understand that this can present a XSS risk if you are not careful.

What's the difference between "end" and "exit sub" in VBA?

This is a bit outside the scope of your question, but to avoid any potential confusion for readers who are new to VBA: End and End Sub are not the same. They don't perform the same task.

End puts a stop to ALL code execution and you should almost always use Exit Sub (or Exit Function, respectively).

End halts ALL exectution. While this sounds tempting to do it also clears all global and static variables. (source)

See also the MSDN dox for the End Statement

When executed, the End statement resets allmodule-level variables and all static local variables in allmodules. To preserve the value of these variables, use the Stop statement instead. You can then resume execution while preserving the value of those variables.

Note The End statement stops code execution abruptly, without invoking the Unload, QueryUnload, or Terminate event, or any other Visual Basic code. Code you have placed in the Unload, QueryUnload, and Terminate events offorms andclass modules is not executed. Objects created from class modules are destroyed, files opened using the Open statement are closed, and memory used by your program is freed. Object references held by other programs are invalidated.

Nor is End Sub and Exit Sub the same. End Sub can't be called in the same way Exit Sub can be, because the compiler doesn't allow it.

enter image description here

This again means you have to Exit Sub, which is a perfectly legal operation:

Exit Sub
Immediately exits the Sub procedure in which it appears. Execution continues with the statement following the statement that called the Sub procedure. Exit Sub can be used only inside a Sub procedure.

Additionally, and once you get the feel for how procedures work, obviously, End Sub does not clear any global variables. But it does clear local (Dim'd) variables:

End Sub
Terminates the definition of this procedure.

document.getElementById vs jQuery $()

All the answers above are correct. In case you want to see it in action, don't forget you have Console in a browser where you can see the actual result crystal clear :

I have an HTML :

<div id="contents"></div>

Go to console (cntrl+shift+c) and use these commands to see your result clearly

document.getElementById('contents')
>>> div#contents

$('#contents')
>>> [div#contents,
 context: document,
 selector: "#contents",
 jquery: "1.10.1",
 constructor: function,
 init: function …]

As we can see, in the first case we got the tag itself (that is, strictly speaking, an HTMLDivElement object). In the latter we actually don’t have a plain object, but an array of objects. And as mentioned by other answers above, you can use the following command:

$('#contents')[0]
>>> div#contents

Max parallel http connections in a browser?

There is no definitive answer to this, as each browser has its own configuration for this, and this configuration may be changed. If you search on the internet you can find ways to change this limit (usually they're branded as "performance enhancement methods.") It might be worth advising your users to do so if it is required by your website.

Changing the resolution of a VNC session in linux

I have a simple idea, something like this:

#!/bin/sh

echo `xrandr --current | grep current | awk '{print $8}'` >> RES1
echo `xrandr --current | grep current | awk '{print $10}'` >> RES2
cat RES2 | sed -i 's/,//g' RES2

P1RES=$(cat RES1)
P2RES=$(cat RES2)
rm RES1 RES2
echo "$P1RES"'x'"$P2RES" >> RES
RES=$(cat RES)

# Play The Game

# Finish The Game with Lower Resolution

xrandr -s $RES

Well, I need a better solution for all display devices under Linux and Similars S.O

Importing a function from a class in another file?

from FOLDER_NAME import FILENAME
from FILENAME import CLASS_NAME FUNCTION_NAME

FILENAME is w/o the suffix

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

I know it's late, but I take the original code and change some stuff to control easily the css. So I made a code with the addClass() and the removeClass()

Here the full code : http://jsfiddle.net/e5qaD/4837/

        if( bottom_of_window > bottom_of_object ){
            $(this).addClass('showme');
       }
        if( bottom_of_window < bottom_of_object ){
            $(this).removeClass('showme');

Using "word-wrap: break-word" within a table

table-layout: fixed will get force the cells to fit the table (and not the other way around), e.g.:

<table style="border: 1px solid black; width: 100%; word-wrap:break-word;
              table-layout: fixed;">
  <tr>
    <td>
        aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
        bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
    </td>
  </tr>
</table>

Where do I put image files, css, js, etc. in Codeigniter?

add one folder any name e.g public and add .htaccess file and write allow from all it means, in this folder your all files and all folder will not give error Access forbidden! use it like this

<link href="<?php echo base_url(); ?>application/public/css/style.css" rel="stylesheet" type="text/css"  />
<script type="text/javascript" src="<?php echo base_url(); ?>application/public/js/javascript.js"></script>

Resolving MSB3247 - Found conflicts between different versions of the same dependent assembly

I made an application based on Mike Hadlow application: AsmSpy.

My app is a WPF app with GUI and can be download from my home webserver: AsmSpyPlus.exe.

Code is available at: GitHub

Gui Sample

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

How can I query for null values in entity framework?

Personnally, I prefer:

var result = from entry in table    
             where (entry.something??0)==(value??0)                    
              select entry;

over

var result = from entry in table
             where (value == null ? entry.something == null : entry.something == value)
             select entry;

because it prevents repetition -- though that's not mathematically exact, but it fits well most cases.

Difference between DOMContentLoaded and load events

The DOMContentLoaded event will fire as soon as the DOM hierarchy has been fully constructed, the load event will do it when all the images and sub-frames have finished loading.

DOMContentLoaded will work on most modern browsers, but not on IE including IE9 and above. There are some workarounds to mimic this event on older versions of IE, like the used on the jQuery library, they attach the IE specific onreadystatechange event.

What REST PUT/POST/DELETE calls should return by a convention?

Overall, the conventions are “think like you're just delivering web pages”.

For a PUT, I'd return the same view that you'd get if you did a GET immediately after; that would result in a 200 (well, assuming the rendering succeeds of course). For a POST, I'd do a redirect to the resource created (assuming you're doing a creation operation; if not, just return the results); the code for a successful create is a 201, which is really the only HTTP code for a redirect that isn't in the 300 range.

I've never been happy about what a DELETE should return (my code currently produces an HTTP 204 and an empty body in this case).

Why is 2 * (i * i) faster than 2 * i * i in Java?

(Editor's note: this answer is contradicted by evidence from looking at the asm, as shown by another answer. This was a guess backed up by some experiments, but it turned out not to be correct.)


When the multiplication is 2 * (i * i), the JVM is able to factor out the multiplication by 2 from the loop, resulting in this equivalent but more efficient code:

int n = 0;
for (int i = 0; i < 1000000000; i++) {
    n += i * i;
}
n *= 2;

but when the multiplication is (2 * i) * i, the JVM doesn't optimize it since the multiplication by a constant is no longer right before the n += addition.

Here are a few reasons why I think this is the case:

  • Adding an if (n == 0) n = 1 statement at the start of the loop results in both versions being as efficient, since factoring out the multiplication no longer guarantees that the result will be the same
  • The optimized version (by factoring out the multiplication by 2) is exactly as fast as the 2 * (i * i) version

Here is the test code that I used to draw these conclusions:

public static void main(String[] args) {
    long fastVersion = 0;
    long slowVersion = 0;
    long optimizedVersion = 0;
    long modifiedFastVersion = 0;
    long modifiedSlowVersion = 0;

    for (int i = 0; i < 10; i++) {
        fastVersion += fastVersion();
        slowVersion += slowVersion();
        optimizedVersion += optimizedVersion();
        modifiedFastVersion += modifiedFastVersion();
        modifiedSlowVersion += modifiedSlowVersion();
    }

    System.out.println("Fast version: " + (double) fastVersion / 1000000000 + " s");
    System.out.println("Slow version: " + (double) slowVersion / 1000000000 + " s");
    System.out.println("Optimized version: " + (double) optimizedVersion / 1000000000 + " s");
    System.out.println("Modified fast version: " + (double) modifiedFastVersion / 1000000000 + " s");
    System.out.println("Modified slow version: " + (double) modifiedSlowVersion / 1000000000 + " s");
}

private static long fastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long slowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

private static long optimizedVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        n += i * i;
    }
    n *= 2;
    return System.nanoTime() - startTime;
}

private static long modifiedFastVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * (i * i);
    }
    return System.nanoTime() - startTime;
}

private static long modifiedSlowVersion() {
    long startTime = System.nanoTime();
    int n = 0;
    for (int i = 0; i < 1000000000; i++) {
        if (n == 0) n = 1;
        n += 2 * i * i;
    }
    return System.nanoTime() - startTime;
}

And here are the results:

Fast version: 5.7274411 s
Slow version: 7.6190804 s
Optimized version: 5.1348007 s
Modified fast version: 7.1492705 s
Modified slow version: 7.2952668 s

How do I analyze a program's core dump file with GDB when it has command-line parameters?

You can analyze the core dump file using the "gdb" command.

 gdb - The GNU Debugger

 syntax:

 # gdb executable-file core-file

 example: # gdb out.txt core.xxx 

How to Specify Eclipse Proxy Authentication Credentials?

Window ? Preferences ? General ? Network Connections then under "Proxy ByPass" click "Add Host" and enter the link from which you will be getting your third-party plugin; that's it bingo, now it should get the plugin no problem.

How do you append rows to a table using jQuery?

I always use this code below for more readable

$('table').append([
'<tr>',
    '<td>My Item 1</td>',
    '<td>My Item 2</td>',
    '<td>My Item 3</td>',
    '<td>My Item 4</td>',
'</tr>'
].join(''));

or if it have tbody

$('table').find('tbody').append([
'<tr>',
    '<td>My Item 1</td>',
    '<td>My Item 2</td>',
    '<td>My Item 3</td>',
    '<td>My Item 4</td>',
'</tr>'
].join(''));

How to create a video from images with FFmpeg?

See the Create a video slideshow from images – FFmpeg

If your video does not show the frames correctly If you encounter problems, such as the first image is skipped or only shows for one frame, then use the fps video filter instead of -r for the output framerate

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf fps=25 -pix_fmt yuv420p out.mp4

Alternatively the format video filter can be added to the filter chain to replace -pix_fmt yuv420p like "fps=25,format=yuv420p". The advantage of this method is that you can control which filter goes first

ffmpeg -r 1/5 -i img%03d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4

I tested below parameters, it worked for me

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -vf "fps=25,format=yuv420p" e:\out.mp4

below parameters also worked but it always skips the first image

"e:\ffmpeg\ffmpeg.exe" -r 1/5 -start_number 0 -i "E:\images\01\padlock%3d.png" -c:v libx264 -r 30 -pix_fmt yuv420p e:\out.mp4

making a video from images placed in different folders

First, add image paths to imagepaths.txt like below.

# this is a comment details https://trac.ffmpeg.org/wiki/Concatenate

file 'E:\images\png\images__%3d.jpg'
file 'E:\images\jpg\images__%3d.jpg'

Sample usage as follows;

"h:\ffmpeg\ffmpeg.exe" -y -r 1/5 -f concat -safe 0 -i "E:\images\imagepaths.txt" -c:v libx264 -vf "fps=25,format=yuv420p" "e:\out.mp4"

-safe 0 parameter prevents Unsafe file name error

Related links

FFmpeg making a video from images placed in different folders

FFMPEG An Intermediate Guide/image sequence

Concatenate – FFmpeg

Best way to format if statement with multiple conditions

The first one is easier, because, if you read it left to right you get: "If something AND somethingelse AND somethingelse THEN" , which is an easy to understand sentence. The second example reads "If something THEN if somethingelse THEN if something else THEN", which is clumsy.

Also, consider if you wanted to use some ORs in your clause - how would you do that in the second style?

How to return a file (FileContentResult) in ASP.NET WebAPI

I am not exactly sure which part to blame, but here's why MemoryStream doesn't work for you:

As you write to MemoryStream, it increments it's Position property. The constructor of StreamContent takes into account the stream's current Position. So if you write to the stream, then pass it to StreamContent, the response will start from the nothingness at the end of the stream.

There's two ways to properly fix this:

1) construct content, write to stream

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    // ...
    // stream.Write(...);
    // ...
    return response;
}

2) write to stream, reset position, construct content

[HttpGet]
public HttpResponseMessage Test()
{
    var stream = new MemoryStream();
    // ...
    // stream.Write(...);
    // ...
    stream.Position = 0;

    var response = Request.CreateResponse(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    return response;
}

2) looks a little better if you have a fresh Stream, 1) is simpler if your stream does not start at 0

failed to lazily initialize a collection of role

Try swich fetchType from LAZY to EAGER

...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...

But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

==> 73

Calling a particular PHP function on form submit

Assuming that your script is named x.php, try this

<?php 
   function display($s) {
      echo $s;
   }
?>
<html>
    <body>
        <form method="post" action="x.php">
            <input type="text" name="studentname">
            <input type="submit" value="click">
        </form>
        <?php
           if($_SERVER['REQUEST_METHOD']=='POST')
           {
               display();
           } 
        ?>
    </body>
</html>

Which selector do I need to select an option by its text?

I tried a few of these things until I got one to work in both Firefox and IE. This is what I came up with.

$("#my-Select").val($("#my-Select" + " option").filter(function() { return this.text == myText }).val());

another way of writing it in a more readable fasion:

var valofText = $("#my-Select" + " option").filter(function() {
    return this.text == myText
}).val();
$(ElementID).val(valofText);

Pseudocode:

$("#my-Select").val( getValOfText( myText ) );

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

is there a function in lodash to replace matched item

You can do it without using lodash.

let arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];
let newObj = {id: 1, name: "new Person"}

/*Add new prototype function on Array class*/
Array.prototype._replaceObj = function(newObj, key) {
  return this.map(obj => (obj[key] === newObj[key] ? newObj : obj));
};

/*return [{id: 1, name: "new Person"}, {id: 2, name: "Person 2"}]*/
arr._replaceObj(newObj, "id") 

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

How to change the icon of an Android app in Eclipse?

Rob R.'s answer was definitely the way to go. I tried copying the ic_launcher.png files from another project and Eclipse still wouldn't read them. Going through the manifest is much quicker and easier.

How can I set the default value for an HTML <select> element?

HTML snippet:

<select data-selected="public" class="form-control" name="role">
    <option value="public">
        Pubblica
    </option>
    <option value="user">
        Utenti
    </option>
    <option value="admin">
        Admin
    </option>
</select>

Native JavaScript snippet:

document.querySelectorAll('[data-selected]').forEach(e => {
   e.value = e.dataset.selected
});

Please explain the exec() function and its family

Simplistically, in UNIX, you have the concept of processes and programs. A process is an environment in which a program executes.

The simple idea behind the UNIX "execution model" is that there are two operations you can do.

The first is to fork(), which creates a brand new process containing a duplicate (mostly) of the current program, including its state. There are a few differences between the two processes which allow them to figure out which is the parent and which is the child.

The second is to exec(), which replaces the program in the current process with a brand new program.

From those two simple operations, the entire UNIX execution model can be constructed.


To add some more detail to the above:

The use of fork() and exec() exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork() call makes a near duplicate of the current process, identical in almost every way (not everything is copied over, for example, resource limits in some implementations, but the idea is to create as close a copy as possible). Only one process calls fork() but two processes return from that call - sounds bizarre but it's really quite elegant

The new process (called the child) gets a different process ID (PID) and has the PID of the old process (the parent) as its parent PID (PPID).

Because the two processes are now running exactly the same code, they need to be able to tell which is which - the return code of fork() provides this information - the child gets 0, the parent gets the PID of the child (if the fork() fails, no child is created and the parent gets an error code).

That way, the parent knows the PID of the child and can communicate with it, kill it, wait for it and so on (the child can always find its parent process with a call to getppid()).

The exec() call replaces the entire current contents of the process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork() and exec() are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to call fork() without a following exec() if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions).

This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening. For this situation, the program contains both the parent and the child code.

Similarly, programs that know they're finished and just want to run another program don't need to fork(), exec() and then wait()/waitpid() for the child. They can just load the child directly into their current process space with exec().

Some UNIX implementations have an optimized fork() which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork() until the program attempts to change something in that space. This is useful for those programs using only fork() and not exec() in that they don't have to copy an entire process space. Under Linux, fork() only makes a copy of the page tables and a new task structure, exec() will do the grunt work of "separating" the memory of the two processes.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process, before modifications are allowed.

Linux also has a vfork(), even more optimised, which shares just about everything between the two processes. Because of that, there are certain restrictions in what the child can do, and the parent halts until the child calls exec() or _exit().

The parent has to be stopped (and the child is not permitted to return from the current function) since the two processes even share the same stack. This is slightly more efficient for the classic use case of fork() followed immediately by exec().

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

How can I change column types in Spark SQL's DataFrame?

Why not just do as described under http://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.Column.cast

df.select(df.year.cast("int"),"make","model","comment","blank")

How do I loop through or enumerate a JavaScript object?

In ES6 we have well-known symbols to expose some previously internal methods, you can use it to define how iterators work for this object:

var p = {
    "p1": "value1",
    "p2": "value2",
    "p3": "value3",
    *[Symbol.iterator]() {
        yield *Object.keys(this);
    }
};

[...p] //["p1", "p2", "p3"]

this will give the same result as using for...in es6 loop.

for(var key in p) {
    console.log(key);
}

But its important to know the capabilities you now have using es6!

How to Call a Function inside a Render in React/Jsx

The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,

First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.

So we use that variable to invoke the function by adding parentheses () at the end.

One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().

Right align text in android TextView

In my case, I was using Relative Layout for a emptyString

After struggling on this for an hour. Only this worked for me:

android:layout_toRightOf="@id/welcome"
android:layout_toEndOf="@id/welcome"
android:layout_alignBaseline="@id/welcome"

layout_toRightOf or layout_toEndOf both works, but to support it better, I used both.

To make it more clear:

This was what I was trying to do:

enter image description here

And this was the emulator's output

enter image description here

Layout:

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:text="Welcome "
    android:textSize="16sp" />
<TextView
    android:id="@+id/username"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@id/welcome"
    android:layout_toRightOf="@id/welcome"
    android:text="@string/emptyString"
    android:textSize="16sp" />

Notice that:

  1. android:layout_width="wrap_content" works
  2. Gravity is not used

Check if object exists in JavaScript

Apart from checking the existence of the object/variable you may want to provide a "worst case" output or at least trap it into an alert so it doesn't go unnoticed.

Example of function that checks, provides alternative, and catch errors.

function fillForm(obj) {
  try {
    var output;
    output = (typeof obj !== 'undefined') ? obj : '';
    return (output);
  } 
  catch (err) {
    // If an error was thrown, sent it as an alert
    // to help with debugging any problems
    alert(err.toString());
    // If the obj doesn't exist or it's empty 
    // I want to fill the form with ""
    return ('');
  } // catch End
} // fillForm End

I created this also because the object I was passing to it could be x , x.m , x.m[z] and typeof x.m[z] would fail with an error if x.m did not exist.

I hope it helps. (BTW, I am novice with JS)

Cleanest way to write retry logic?

Allowing for functions and retry messages

public static T RetryMethod<T>(Func<T> method, int numRetries, int retryTimeout, Action onFailureAction)
{
 Guard.IsNotNull(method, "method");            
 T retval = default(T);
 do
 {
   try
   {
     retval = method();
     return retval;
   }
   catch
   {
     onFailureAction();
      if (numRetries <= 0) throw; // improved to avoid silent failure
      Thread.Sleep(retryTimeout);
   }
} while (numRetries-- > 0);
  return retval;
}

Node.js global variables

You can just use the global object.

var X = ['a', 'b', 'c'];
global.x = X;

console.log(x);
//['a', 'b', 'c']

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

Below worked for me:

When you come to Server Configuration Screen, Change the Account Name of Database Engine Service to NT AUTHORITY\NETWORK SERVICE and continue installation and it will successfully install all components without any error. - See more at: https://superpctricks.com/sql-install-error-database-engine-recovery-handle-failed/

How can I pass a parameter to a setTimeout() callback?

I think you want:

setTimeout("postinsql(" + topicId + ")", 4000);

Bootstrap 3 Horizontal and Vertical Divider

I made the following little scss mixin to build for all the bootstrap breakpoints...

With it I get .col-xs-divider-left or col-lg-divider-right etc.

Note: this uses v4-alpha bootstrap syntax...

@import 'variables';

$divider-height: 100%;

@mixin make-column-dividers($breakpoints: $grid-breakpoints) {
    // Common properties for all breakpoints
    %col-divider {
        position: absolute;
        content: " ";
        top: (100% - $divider-height)/2;
        height: $divider-height;
        width: $hr-border-width;
        background-color: $hr-border-color;
    }
    @each $breakpoint in map-keys($breakpoints) {
        .col-#{$breakpoint}-divider-right:before {
            @include media-breakpoint-up($breakpoint) {
                @extend %col-divider;
                right: 0;
            }
        }
        .col-#{$breakpoint}-divider-left:before {
            @include media-breakpoint-up($breakpoint) {
                @extend %col-divider;
                left: 0;
            }
        }
    }
}

Passing arguments to AsyncTask, and returning results

I dont do it like this. I find it easier to overload the constructor of the asychtask class ..

public class calc_stanica extends AsyncTask>

String String mWhateveryouwantToPass;

 public calc_stanica( String whateveryouwantToPass)
{

    this.String mWhateveryouwantToPass = String whateveryouwantToPass;
}
/*Now you can use  whateveryouwantToPass in the entire asynchTask ... you could pass in a context to your activity and try that too.*/   ...  ...  

Convert list of dictionaries to a pandas DataFrame

For converting a list of dictionaries to a pandas DataFrame, you can use "append":

We have a dictionary called dic and dic has 30 list items (list1, list2,…, list30)

  1. step1: define a variable for keeping your result (ex: total_df)
  2. step2: initialize total_df with list1
  3. step3: use "for loop" for append all lists to total_df
total_df=list1
nums=Series(np.arange(start=2, stop=31))
for num in nums:
    total_df=total_df.append(dic['list'+str(num)])

bootstrap 3 tabs not working properly

One more thing to check for this issue is html tag attribute id. You should check any other html tags in that page have the same id as nav tab id.

Fit Image in ImageButton in Android

I'm using the following code in xml

android:adjustViewBounds="true"
android:scaleType="centerInside"

Best way to get user GPS location in background in Android

For Track the location every 10 mins(based on requirement) please follow this link it is working fine without any issues

https://github.com/safetysystemtechnology/location-tracker-background

Any reason not to use '+' to concatenate two strings?

''.join([a, b]) is better solution than +.

Because Code should be written in a way that does not disadvantage other implementations of Python (PyPy, Jython, IronPython, Cython, Psyco, and such)

form a += b or a = a + b is fragile even in CPython and isn't present at all in implementations that don't use refcounting (reference counting is a technique of storing the number of references, pointers, or handles to a resource such as an object, block of memory, disk space or other resource)

https://www.python.org/dev/peps/pep-0008/#programming-recommendations

How can I read and parse CSV files in C++?

If you don't care about escaping comma and newline,
AND you can't embed comma and newline in quotes (If you can't escape then...)
then its only about three lines of code (OK 14 ->But its only 15 to read the whole file).

std::vector<std::string> getNextLineAndSplitIntoTokens(std::istream& str)
{
    std::vector<std::string>   result;
    std::string                line;
    std::getline(str,line);

    std::stringstream          lineStream(line);
    std::string                cell;

    while(std::getline(lineStream,cell, ','))
    {
        result.push_back(cell);
    }
    // This checks for a trailing comma with no data after it.
    if (!lineStream && cell.empty())
    {
        // If there was a trailing comma then add an empty element.
        result.push_back("");
    }
    return result;
}

I would just create a class representing a row.
Then stream into that object:

#include <iterator>
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>

class CSVRow
{
    public:
        std::string_view operator[](std::size_t index) const
        {
            return std::string_view(&m_line[m_data[index] + 1], m_data[index + 1] -  (m_data[index] + 1));
        }
        std::size_t size() const
        {
            return m_data.size() - 1;
        }
        void readNextRow(std::istream& str)
        {
            std::getline(str, m_line);

            m_data.clear();
            m_data.emplace_back(-1);
            std::string::size_type pos = 0;
            while((pos = m_line.find(',', pos)) != std::string::npos)
            {
                m_data.emplace_back(pos);
                ++pos;
            }
            // This checks for a trailing comma with no data after it.
            pos   = m_line.size();
            m_data.emplace_back(pos);
        }
    private:
        std::string         m_line;
        std::vector<int>    m_data;
};

std::istream& operator>>(std::istream& str, CSVRow& data)
{
    data.readNextRow(str);
    return str;
}   
int main()
{
    std::ifstream       file("plop.csv");

    CSVRow              row;
    while(file >> row)
    {
        std::cout << "4th Element(" << row[3] << ")\n";
    }
}

But with a little work we could technically create an iterator:

class CSVIterator
{   
    public:
        typedef std::input_iterator_tag     iterator_category;
        typedef CSVRow                      value_type;
        typedef std::size_t                 difference_type;
        typedef CSVRow*                     pointer;
        typedef CSVRow&                     reference;

        CSVIterator(std::istream& str)  :m_str(str.good()?&str:NULL) { ++(*this); }
        CSVIterator()                   :m_str(NULL) {}

        // Pre Increment
        CSVIterator& operator++()               {if (m_str) { if (!((*m_str) >> m_row)){m_str = NULL;}}return *this;}
        // Post increment
        CSVIterator operator++(int)             {CSVIterator    tmp(*this);++(*this);return tmp;}
        CSVRow const& operator*()   const       {return m_row;}
        CSVRow const* operator->()  const       {return &m_row;}

        bool operator==(CSVIterator const& rhs) {return ((this == &rhs) || ((this->m_str == NULL) && (rhs.m_str == NULL)));}
        bool operator!=(CSVIterator const& rhs) {return !((*this) == rhs);}
    private:
        std::istream*       m_str;
        CSVRow              m_row;
};


int main()
{
    std::ifstream       file("plop.csv");

    for(CSVIterator loop(file); loop != CSVIterator(); ++loop)
    {
        std::cout << "4th Element(" << (*loop)[3] << ")\n";
    }
}

Now that we are in 2020 lets add a CSVRange object:

class CSVRange
{
    std::istream&   stream;
    public:
        CSVRange(std::istream& str)
            : stream(str)
        {}
        CSVIterator begin() const {return CSVIterator{stream};}
        CSVIterator end()   const {return CSVIterator{};}
};

int main()
{
    std::ifstream       file("plop.csv");

    for(auto& row: CSVRange(file))
    {
        std::cout << "4th Element(" << row[3] << ")\n";
    }
}

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

T-SQL STOP or ABORT command in SQL Server

Try running this as a TSQL Script

SELECT 1
RETURN
SELECT 2
SELECT 3

The return ends the execution.

RETURN (Transact-SQL)

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements that follow RETURN are not executed.

Pandas: Return Hour from Datetime Column Directly

For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour!

Import cycle not allowed

I just encountered this. You may be accessing a method/type from within the same package using the package name itself.

Here is an example to illustrate what I mean:

In foo.go:

// foo.go
package foo

func Foo() {...}

In foo_test.go:

// foo_test.go
package foo

// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT

c# - approach for saving user settings in a WPF application?

In my experience storing all the settings in a database table is the best solution. Don't even worry about performance. Today's databases are fast and can easily store thousands columns in a table. I learned this the hard way - before I was serilizing/deserializing - nightmare. Storing it in local file or registry has one big problem - if you have to support your app and computer is off - user is not in front of it - there is nothing you can do.... if setings are in DB - you can changed them and viola not to mention that you can compare the settings....

Get day of week using NSDate

This code is to find the whole current week. It is written in Swift 2.0 :

var i = 2
var weekday: [String] = []
var weekdate: [String] = []
var weekmonth: [String] = []

@IBAction func buttonaction(sender: AnyObject) {

    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-dd-yyyy"
    let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
    let weekdays = getDayOfWeek(dayOfWeekStrings)
    let calendar = NSCalendar.currentCalendar()

    while((weekdays - weekdays) + i < 9)
    {
        let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-weekdays+i), toDate: NSDate(), options: [])

        let dayFormatter = NSDateFormatter()
        dayFormatter.dateFormat = "EEEE"
        let dayOfWeekString = dayFormatter.stringFromDate(weekFirstDate!)
        weekday.append(dayOfWeekString)

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd"
        let dateOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
        weekdate.append(dateOfWeekString)

        let monthFormatter = NSDateFormatter()
        monthFormatter.dateFormat = "MMMM"
        let monthOfWeekString = monthFormatter.stringFromDate(weekFirstDate!)
        weekmonth.append(monthOfWeekString)

        i++
    }

    for(var j = 0; j<7 ; j++)
    {
    let day = weekday[j]
    let date = weekdate[j]
    let month = weekmonth[j]
    var wholeweek = date + "-" + month + "(" + day + ")"
    print(wholeweek)
    }

}

func getDayOfWeek(today:String)->Int {
    let formatter  = NSDateFormatter()
    formatter.dateFormat = "MMM-dd-yyyy"
    let todayDate = formatter.dateFromString(today)!
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
    let daynumber = myComponents.weekday
    return daynumber
}

The output will be like this:

14March(Monday) 15March(Tuesday) 16March(Wednesday) 17March(Thursday) 18March(Friday) 19March(Saturday) 20March(Sunday)

How to do a SOAP wsdl web services call from the command line

It's a standard, ordinary SOAP web service. SSH has nothing to do here. I just called it with (one-liner):

$ curl -X POST -H "Content-Type: text/xml" \
    -H 'SOAPAction: "http://api.eyeblaster.com/IAuthenticationService/ClientLogin"' \
    --data-binary @request.xml \
    https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc

Where request.xml file has the following contents:

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:api="http://api.eyeblaster.com/">
           <soapenv:Header/>
           <soapenv:Body>
              <api:ClientLogin>
                 <api:username>user</api:username>
                 <api:password>password</api:password>
                 <api:applicationKey>key</api:applicationKey>
              </api:ClientLogin>
          </soapenv:Body>
</soapenv:Envelope>

I get this beautiful 500:

<?xml version="1.0"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Body>
    <s:Fault>
      <faultcode>s:Security.Authentication.UserPassIncorrect</faultcode>
      <faultstring xml:lang="en-US">The username, password or application key is incorrect.</faultstring>
    </s:Fault>
  </s:Body>
</s:Envelope>

Have you tried ?

Read more

Twig ternary operator, Shorthand if-then-else

You can use shorthand syntax as of Twig 1.12.0

{{ foo ?: 'no' }} is the same as {{ foo ? foo : 'no' }}
{{ foo ? 'yes' }} is the same as {{ foo ? 'yes' : '' }}

Generate sql insert script from excel worksheet

Depending on the database, you can export to CSV and then use an import method.

MySQL - http://dev.mysql.com/doc/refman/5.1/en/load-data.html

PostgreSQL - http://www.postgresql.org/docs/8.2/static/sql-copy.html

Calculating and printing the nth prime number

You are trying to do too much in the main method. You need to break this up into more manageable parts. Write a method boolean isPrime(int n) that returns true if a number is prime, and false otherwise. Then modify the main method to use isPrime.

Escape double quotes in parameter

As none of the answers above are straight forward:

Backslash escape \ is what you need:

myscript \"test\"

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Python base64 data decode

Python 3 (and 2)

import base64
a = 'eW91ciB0ZXh0'
base64.b64decode(a)

Python 2

A quick way to decode it without importing anything:

'eW91ciB0ZXh0'.decode('base64')

or more descriptive

>>> a = 'eW91ciB0ZXh0'
>>> a.decode('base64')
'your text'

How to search all loaded scripts in Chrome Developer Tools?

Open a new Search pane in Developer Tools by:

  • pressing Ctrl+Shift+F (Cmd+Option+I on mac)
  • clicking the overflow menu (?) in DevTools, DevTools overflow menu
  • clicking the overflow menu in the Console (?) and choosing the Search option

You can search across all your scripts with support for regular expressions and case sensitivity.

Click any match to load that file/section in the scripts panel.

Search all files - results

Make sure 'Search in anonymous and content scripts' is checked in the DevTools Preferences (F1). This will return results from within iframes and HTML inline scripts:

Search in anonymous and content scripts DevTools Settings Preferences

Add Favicon with React and Webpack

Replace the favicon.ico in your public folder with yours, that should get you going.

Replace comma with newline in sed on MacOS?

$ echo $PATH | sed -e $'s/:/\\\n/g' 
/usr/local/sbin
/Library/Oracle/instantclient_11_2/sdk
/usr/local/bin

...

Works for me on Mojave

insert datetime value in sql database with c#

The following should work and is my recommendation (parameterized query):

DateTime dateTimeVariable = //some DateTime value, e.g. DateTime.Now;
SqlCommand cmd = new SqlCommand("INSERT INTO <table> (<column>) VALUES (@value)", connection);
cmd.Parameters.AddWithValue("@value", dateTimeVariable);

cmd.ExecuteNonQuery();

How to import functions from different js file in a Vue+webpack+vue-loader project

I was trying to organize my vue app code, and came across this question , since I have a lot of logic in my component and can not use other sub-coponents , it makes sense to use many functions in a separate js file and call them in the vue file, so here is my attempt

1)The Component (.vue file)

//MyComponent.vue file
<template>
  <div>
  <div>Hello {{name}}</div>
  <button @click="function_A">Read Name</button>
  <button @click="function_B">Write Name</button>
  <button @click="function_C">Reset</button>
  <div>{{message}}</div>
  </div>
 </template>


<script>
import Mylib from "./Mylib"; // <-- import
export default {
  name: "MyComponent",
  data() {
    return {
      name: "Bob",
      message: "click on the buttons"
    };
  },
  methods: {
    function_A() {
      Mylib.myfuncA(this); // <---read data
    },
    function_B() {
      Mylib.myfuncB(this); // <---write data
    },
    function_C() {
      Mylib.myfuncC(this); // <---write data
    }
  }
};
</script>

2)The External js file

//Mylib.js
let exports = {};

// this (vue instance) is passed as that , so we
// can read and write data from and to it as we please :)
exports.myfuncA = (that) => {
  that.message =
  "you hit ''myfuncA'' function that is located in Mylib.js  and data.name = " +
    that.name;
};

exports.myfuncB = (that) => {
  that.message =
  "you hit ''myfuncB'' function that is located in Mylib.js and now I will change the name to Nassim";
  that.name = "Nassim"; // <-- change name to Nassim
};

exports.myfuncC = (that) => {
  that.message =
  "you hit ''myfuncC'' function that is located in Mylib.js and now I will change the name back to Bob";
  that.name = "Bob"; // <-- change name to Bob
};

export default exports;

enter image description here 3)see it in action : https://codesandbox.io/s/distracted-pare-vuw7i?file=/src/components/MyComponent.vue


edit

after getting more experience with Vue , I found out that you could use mixins too to split your code into different files and make it easier to code and maintain see https://vuejs.org/v2/guide/mixins.html

How to combine two lists in R

We can use append

append(l1, l2)

It also has arguments to insert element at a particular location.

How to force ViewPager to re-instantiate its items

Had the same problem. For me it worked to call

viewPage.setAdapter( adapter );

again which caused reinstantiating the pages again.

Dynamically fill in form values with jQuery

If you need to hit the database, you need to hit the web server again (for the most part).

What you can do is use AJAX, which makes a request to another script on your site to retrieve data, gets the data, and then updates the input fields you want.

AJAX calls can be made in jquery with the $.ajax() function call, so this will happen

User's browser enters input that fires a trigger that makes an AJAX call

$('input .callAjax').bind('change', function() { 
  $.ajax({ url: 'script/ajax', 
           type: json
           data: $foo,  
           success: function(data) {
             $('input .targetAjax').val(data.newValue);
           });
  );

Now you will need to point that AJAX call at script (sounds like you're working PHP) that will do the query you want and send back data.

You will probably want to use the JSON object call so you can pass back a javascript object, that will be easier to use than return XML etc.

The php function json_encode($phpobj); will be useful.

Firebase Storage How to store and Retrieve images

You can also use a service called Filepicker which will store your image to their servers and Filepicker which is now called Filestack, will provide you with a url to the image. You can than store the url to Firebase.

Unzipping files in Python

import zipfile
with zipfile.ZipFile(path_to_zip_file, 'r') as zip_ref:
    zip_ref.extractall(directory_to_extract_to)

That's pretty much it!

How to add List<> to a List<> in asp.net

Use .AddRange to append any Enumrable collection to the list.

how to remove the dotted line around the clicked a element in html

To remove all doted outline, including those in bootstrap themes.

a, a:active, a:focus, 
button, button:focus, button:active, 
.btn, .btn:focus, .btn:active:focus, .btn.active:focus, .btn.focus, .btn.focus:active, .btn.active.focus {
    outline: none;
    outline: 0;
}

input::-moz-focus-inner {
    border: 0;
}

Note: You should add link href for bootstrap css before the main css, so bootstrap doesn't override your style.

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

Another developer use case: If the WindowManager or getWindow() is being called on onCreate() or onStart() or onResume(), a BadTokenException is thrown. You will need to wait until the view is prepared and attached.

Moving the code to onAttachedToWindow() solves it. It may not be a permanent solution, but as much as I could test, it always worked.

In my case, there was a need to increase the screen brightness when the activity became visible. The line getWindow().getAttributes().screenBrightness in the onResume() resulted in an exception. Moving the code to onAttachedToWindow() worked.

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

Bootswatch is a good alternative, but you can also find multiple types of free templates made for ASP.NET MVC that use MDBootstrap (a front-end framework built on top of Bootstrap) here:

ASP.NET MVC MDB Templates

How to determine the Schemas inside an Oracle Data Pump Export file

Update (2008-09-19 10:05) - Solution:

My Solution: Social engineering, I dug real hard and found someone who knew the schema name.
Technical Solution: Searching the .dmp file did yield the schema name.
Once I knew the schema name, I searched the dump file and learned where to find it.

Places the Schemas name were seen, in the .dmp file:

  • <OWNER_NAME>SOURCE_SCHEMA</OWNER_NAME> This was seen before each table name/definition.

  • SCHEMA_LIST 'SOURCE_SCHEMA' This was seen near the end of the .dmp.

Interestingly enough, around the SCHEMA_LIST 'SOURCE_SCHEMA' section, it also had the command line used to create the dump, directories used, par files used, windows version it was run on, and export session settings (language, date formats).

So, problem solved :)

What is the meaning of @_ in Perl?

All Perl's "special variables" are listed in the perlvar documentation page.

How do I install the OpenSSL libraries on Ubuntu?

You want the openssl-devel package. At least I think it's -devel on Ubuntu. Might be -dev. It's one of the two.

get the margin size of an element with jquery

Exemple, for :

<div id="myBlock" style="margin: 10px 0px 15px 5px:"></div>

In this js code :

var myMarginTop = $("#myBlock").css("marginBottom");

The var becomes "15px", a string.

If you want an Integer, to avoid NaN (Not a Number), there is multiple ways.

The fastest is to use native js method :

var myMarginTop = parseInt( $("#myBlock").css("marginBottom") );

Android: making a fullscreen application

According to this document, add the following code to onCreate

getWindow().getDecorView().setSystemUiVisibility(SYSTEM_UI_FLAG_IMMERSIVE_STICKY |
        SYSTEM_UI_FLAG_FULLSCREEN | SYSTEM_UI_FLAG_HIDE_NAVIGATION   | 
        SYSTEM_UI_FLAG_LAYOUT_STABLE | SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

Understanding .get() method in Python

To understand what is going on, let's take one letter(repeated more than once) in the sentence string and follow what happens when it goes through the loop.

Remember that we start off with an empty characters dictionary

characters = {}

I will pick the letter 'e'. Let's pass the character 'e' (found in the word The) for the first time through the loop. I will assume it's the first character to go through the loop and I'll substitute the variables with their values:

for 'e' in "The quick brown fox jumped over the lazy dog.":
    {}['e'] = {}.get('e', 0) + 1 

characters.get('e', 0) tells python to look for the key 'e' in the dictionary. If it's not found it returns 0. Since this is the first time 'e' is passed through the loop, the character 'e' is not found in the dictionary yet, so the get method returns 0. This 0 value is then added to the 1 (present in the characters[character] = characters.get(character,0) + 1 equation). After completion of the first loop using the 'e' character, we now have an entry in the dictionary like this: {'e': 1}

The dictionary is now:

characters = {'e': 1}

Now, let's pass the second 'e' (found in the word jumped) through the same loop. I'll assume it's the second character to go through the loop and I'll update the variables with their new values:

for 'e' in "The quick brown fox jumped over the lazy dog.":
    {'e': 1}['e'] = {'e': 1}.get('e', 0) + 1

Here the get method finds a key entry for 'e' and finds its value which is 1. We add this to the other 1 in characters.get(character, 0) + 1 and get 2 as result.

When we apply this in the characters[character] = characters.get(character, 0) + 1 equation:

characters['e'] = 2

It should be clear that the last equation assigns a new value 2 to the already present 'e' key. Therefore the dictionary is now:

characters = {'e': 2}

Eclipse CDT: Symbol 'cout' could not be resolved

If all else fails, like it did in my case, then just disable annotations. I started a c++11 project with own makefile but couldn't fix all the problems. Even if you disable annotations, eclipse will still be able to help you do some autocompletion. Most importantly, the debugger still works!

How to truncate milliseconds off of a .NET DateTime

I know the answer is quite late, but the best way to get rid of milliseconds is

var currentDateTime = DateTime.Now.ToString("s");

Try printing the value of the variable, it will show the date time, without milliseconds.

Recommended way to save uploaded files in a servlet application

Store it anywhere in an accessible location except of the IDE's project folder aka the server's deploy folder, for reasons mentioned in the answer to Uploaded image only available after refreshing the page:

  1. Changes in the IDE's project folder does not immediately get reflected in the server's work folder. There's kind of a background job in the IDE which takes care that the server's work folder get synced with last updates (this is in IDE terms called "publishing"). This is the main cause of the problem you're seeing.

  2. In real world code there are circumstances where storing uploaded files in the webapp's deploy folder will not work at all. Some servers do (either by default or by configuration) not expand the deployed WAR file into the local disk file system, but instead fully in the memory. You can't create new files in the memory without basically editing the deployed WAR file and redeploying it.

  3. Even when the server expands the deployed WAR file into the local disk file system, all newly created files will get lost on a redeploy or even a simple restart, simply because those new files are not part of the original WAR file.

It really doesn't matter to me or anyone else where exactly on the local disk file system it will be saved, as long as you do not ever use getRealPath() method. Using that method is in any case alarming.

The path to the storage location can in turn be definied in many ways. You have to do it all by yourself. Perhaps this is where your confusion is caused because you somehow expected that the server does that all automagically. Please note that @MultipartConfig(location) does not specify the final upload destination, but the temporary storage location for the case file size exceeds memory storage threshold.

So, the path to the final storage location can be definied in either of the following ways:

  • Hardcoded:

      File uploads = new File("/path/to/uploads");
    
  • Environment variable via SET UPLOAD_LOCATION=/path/to/uploads:

      File uploads = new File(System.getenv("UPLOAD_LOCATION"));
    
  • VM argument during server startup via -Dupload.location="/path/to/uploads":

      File uploads = new File(System.getProperty("upload.location"));
    
  • *.properties file entry as upload.location=/path/to/uploads:

      File uploads = new File(properties.getProperty("upload.location"));
    
  • web.xml <context-param> with name upload.location and value /path/to/uploads:

      File uploads = new File(getServletContext().getInitParameter("upload.location"));
    
  • If any, use the server-provided location, e.g. in JBoss AS/WildFly:

      File uploads = new File(System.getProperty("jboss.server.data.dir"), "uploads");
    

Either way, you can easily reference and save the file as follows:

File file = new File(uploads, "somefilename.ext");

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath());
}

Or, when you want to autogenerate an unique file name to prevent users from overwriting existing files with coincidentally the same name:

File file = File.createTempFile("somefilename-", ".ext", uploads);

try (InputStream input = part.getInputStream()) {
    Files.copy(input, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
}

How to obtain part in JSP/Servlet is answered in How to upload files to server using JSP/Servlet? and how to obtain part in JSF is answered in How to upload file using JSF 2.2 <h:inputFile>? Where is the saved File?

Note: do not use Part#write() as it interprets the path relative to the temporary storage location defined in @MultipartConfig(location).

See also:

Change fill color on vector asset in Android Studio

Android studio now supports vectors pre-lollipop. No PNG conversion. You can still change your fill color and it will work.

In you ImageView, use

 app:srcCompat="@drawable/ic_more_vert_24dp"

In your gradle file,

 // Gradle Plugin 2.0+  
 android {  
   defaultConfig {  
     vectorDrawables.useSupportLibrary = true  
   }  
 }  

 compile 'com.android.support:design:23.4.0'

How do I clear this setInterval inside a function?

the_int=window.clearInterval(the_int);

JavaScript loop through json array?

Well, all I can see there is that you have two JSON objects, seperated by a comma. If both of them were inside an array ([...]) it would make more sense.

And, if they ARE inside of an array, then you would just be using the standard "for var i = 0..." type of loop. As it is, I think it's going to try to retrieve the "id" property of the string "1", then "id" of "hi", and so on.

Python dictionary replace values

via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({'key1': 'value1', 'key2': 'value2'})

or like this:

my_dict.update(key1='value1', key2='value2')

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {'key1': 'value1', 'key2': 'value2'}

SQL Server Script to create a new user

Full admin rights for the whole server, or a specific database? I think the others answered for a database, but for the server:

USE [master];
GO
CREATE LOGIN MyNewAdminUser 
    WITH PASSWORD    = N'abcd',
    CHECK_POLICY     = OFF,
    CHECK_EXPIRATION = OFF;
GO
EXEC sp_addsrvrolemember 
    @loginame = N'MyNewAdminUser', 
    @rolename = N'sysadmin';

You may need to leave off the CHECK_ parameters depending on what version of SQL Server Express you are using (it is almost always useful to include this information in your question).

Get google map link with latitude/longitude

None of the above answers worked for me, but I got it working with the following:

src="'https://maps.google.com/maps?q=' + lat + ',' + long + '&t=&z=15&ie=UTF8&iwloc=&output=embed'"

How to check if string input is a number?

If you specifically need an int or float, you could try "is not int" or "is not float":

user_input = ''
while user_input is not int:
    try:
        user_input = int(input('Enter a number: '))
        break
    except ValueError:
        print('Please enter a valid number: ')

print('You entered {}'.format(a))

If you only need to work with ints, then the most elegant solution I've seen is the ".isdigit()" method:

a = ''
while a.isdigit() == False:
    a = input('Enter a number: ')

print('You entered {}'.format(a))

Targeting only Firefox with CSS

First of all, a disclaimer. I don't really advocate for the solution I present below. The only browser specific CSS I write is for IE (especially IE6), although I wish it wasn't the case.

Now, the solution. You asked it to be elegant so I don't know how elegant is it but it's sure going to target Gecko platforms only.

The trick is only working when JavaScript is enabled and makes use of Mozilla bindings (XBL), which are heavily used internally in Firefox and all other Gecko-based products. For a comparison, this is like the behavior CSS property in IE, but much more powerful.

Three files are involved in my solution:

  1. ff.html: the file to style
  2. ff.xml: the file containg the Gecko bindings
  3. ff.css: Firefox specific styling

ff.html

<!DOCTYPE html>

<html>
<head>
<style type="text/css">
body {
 -moz-binding: url(ff.xml#load-mozilla-css);
}
</style>
</head>
<body>

<h1>This should be red in FF</h1>

</body>
</html>

ff.xml

<?xml version="1.0"?>

<bindings xmlns="http://www.mozilla.org/xbl">
    <binding id="load-mozilla-css">
        <implementation>
            <constructor>
            <![CDATA[
                var link = document.createElement("link");
                    link.setAttribute("rel", "stylesheet");
                    link.setAttribute("type", "text/css");
                    link.setAttribute("href", "ff.css");

                document.getElementsByTagName("head")[0]
                        .appendChild(link);
            ]]>
            </constructor>
        </implementation>
    </binding>
</bindings>

ff.css

h1 {
 color: red;
}

Update: The above solution is not that good. It would be better if instead of appending a new LINK element it will add that "firefox" class on the BODY element. And it's possible, just by replacing the above JS with the following:

this.className += " firefox";

The solution is inspired by Dean Edwards' moz-behaviors.

How to Change Font Size in drawString Java

code example below:

g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

OpenCV with Network Cameras

rtsp protocol did not work for me. mjpeg worked first try. I assume it is built into my camera (Dlink DCS 900).

Syntax found here: http://answers.opencv.org/question/133/how-do-i-access-an-ip-camera/

I did not need to compile OpenCV with ffmpg support.

Using C++ base class constructors?

You'll need to declare constructors in each of the derived classes, and then call the base class constructor from the initializer list:

class D : public A
{
public:
    D(const string &val) : A(0) {}
    D( int val ) : A( val ) {}
};

D variable1( "Hello" );
D variable2( 10 );

C++11 allows you to use the using A::A syntax you use in your decleration of D, but C++11 features aren't supported by all compilers just now, so best to stick with the older C++ methods until this feature is implemented in all the compilers your code will be used with.

Java: method to get position of a match in a String?

Use string.indexOf to get the starting index.

Swift Bridging Header import issue

Add a temporary Objective-C file to your project. You may give it any name you like.

Select Yes to configure an Objective-C bridging header.

Delete the temporary Objective-C file you just created.

In the projectName-Bridging-Header.h file just created, add this line:

'#import < GoogleMaps/GoogleMaps.h >'

Edit the AppDelegate.swift file:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    GMSServices.provideAPIKey("AIza....") //iOS API key

    return true
}

Follow the link for full sample

MATLAB, Filling in the area between two sets of data, lines in one figure

You can accomplish this using the function FILL to create filled polygons under the sections of your plots. You will want to plot the lines and polygons in the order you want them to be stacked on the screen, starting with the bottom-most one. Here's an example with some sample data:

x = 1:100;             %# X range
y1 = rand(1,100)+1.5;  %# One set of data ranging from 1.5 to 2.5
y2 = rand(1,100)+0.5;  %# Another set of data ranging from 0.5 to 1.5
baseLine = 0.2;        %# Baseline value for filling under the curves
index = 30:70;         %# Indices of points to fill under

plot(x,y1,'b');                              %# Plot the first line
hold on;                                     %# Add to the plot
h1 = fill(x(index([1 1:end end])),...        %# Plot the first filled polygon
          [baseLine y1(index) baseLine],...
          'b','EdgeColor','none');
plot(x,y2,'g');                              %# Plot the second line
h2 = fill(x(index([1 1:end end])),...        %# Plot the second filled polygon
          [baseLine y2(index) baseLine],...
          'g','EdgeColor','none');
plot(x(index),baseLine.*ones(size(index)),'r');  %# Plot the red line

And here's the resulting figure:

enter image description here

You can also change the stacking order of the objects in the figure after you've plotted them by modifying the order of handles in the 'Children' property of the axes object. For example, this code reverses the stacking order, hiding the green polygon behind the blue polygon:

kids = get(gca,'Children');        %# Get the child object handles
set(gca,'Children',flipud(kids));  %# Set them to the reverse order

Finally, if you don't know exactly what order you want to stack your polygons ahead of time (i.e. either one could be the smaller polygon, which you probably want on top), then you could adjust the 'FaceAlpha' property so that one or both polygons will appear partially transparent and show the other beneath it. For example, the following will make the green polygon partially transparent:

set(h2,'FaceAlpha',0.5);

starting file download with JavaScript

If this is your own server application then i suggest using the following header

Content-disposition: attachment; filename=fname.ext

This will force any browser to download the file and not render it in the browser window.

Getting the name of a variable as a string

For constants, you can use an enum, which supports retrieving its name.

What is difference between INNER join and OUTER join

This is the best and simplest way to understand joins:

enter image description here

Credits go to the writer of this article HERE

What is the difference between a cer, pvk, and pfx file?

Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.

Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.

Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.

You should never disclose your private key. These are contained in .pfx and .pvk files.

Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.

What is the default font of Sublime Text?

To add to MattDMo's answer, you can get the exact font that's used on Linux like so (the example is from Xubuntu 14.04):

$ fc-match Monospace
DejaVuSansMono.ttf: "DejaVu Sans Mono" "Book"

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

Please note that PrimeFaces supports the standard JSF 2.0+ keywords:

  • @this Current component.
  • @all Whole view.
  • @form Closest ancestor form of current component.
  • @none No component.

and the standard JSF 2.3+ keywords:

  • @child(n) nth child.
  • @composite Closest composite component ancestor.
  • @id(id) Used to search components by their id ignoring the component tree structure and naming containers.
  • @namingcontainer Closest ancestor naming container of current component.
  • @parent Parent of the current component.
  • @previous Previous sibling.
  • @next Next sibling.
  • @root UIViewRoot instance of the view, can be used to start searching from the root instead the current component.

But, it also comes with some PrimeFaces specific keywords:

  • @row(n) nth row.
  • @widgetVar(name) Component with given widgetVar.

And you can even use something called "PrimeFaces Selectors" which allows you to use jQuery Selector API. For example to process all inputs in a element with the CSS class myClass:

process="@(.myClass :input)"

See:

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

show loading icon until the page is load?

HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.

So in CSS consider adding

pointer-events: none;
cursor: default;

Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html

<i class="fa fa-spinner fa-spin">

phpmyadmin "Not Found" after install on Apache, Ubuntu

sudo ln -s /etc/phpmyadmin/apache.conf /etc/apache2/conf-available/phpmyadmin.conf

sudo ln -s /usr/share/phpmyadmin /var/www/html/phpmyadmin

sudo service apache2 restart

Run above commands issue will be resolved.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Link statically to libstdc++ with -static-libstdc++ gcc option.

box-shadow on bootstrap 3 container

Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.

Example: http://jsfiddle.net/SHLu4/2/

It'll be something like:

<div class="container drop-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-8">Main Area</div>
            <div class="col-md-4">Side Area</div>
        </div>
    </div>
</div>

And your CSS:

<style>
    .drop-shadow {
        -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
        box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
    }
    .container.drop-shadow {
        padding-left:0;
        padding-right:0;
    }
</style>

Create a Cumulative Sum Column in MySQL

You could also create a trigger that will calculate the sum before each insert

delimiter |

CREATE TRIGGER calCumluativeSum  BEFORE INSERT ON someTable
  FOR EACH ROW BEGIN

  SET cumulative_sum = (
     SELECT SUM(x.count)
        FROM someTable x
        WHERE x.id <= NEW.id
    )

    set  NEW.cumulative_sum = cumulative_sum;
  END;
|

I have not tested this

How do I use NSTimer?

Something like this:

NSTimer *timer;

    timer = [NSTimer scheduledTimerWithTimeInterval: 0.5
                     target: self
                     selector: @selector(handleTimer:)
                     userInfo: nil
                     repeats: YES];

pandas dataframe columns scaling with sklearn

Like this?

dfTest = pd.DataFrame({
           'A':[14.00,90.20,90.95,96.27,91.21],
           'B':[103.02,107.26,110.35,114.23,114.68], 
           'C':['big','small','big','small','small']
         })
dfTest[['A','B']] = dfTest[['A','B']].apply(
                           lambda x: MinMaxScaler().fit_transform(x))
dfTest

    A           B           C
0   0.000000    0.000000    big
1   0.926219    0.363636    small
2   0.935335    0.628645    big
3   1.000000    0.961407    small
4   0.938495    1.000000    small

CORS: credentials mode is 'include'

Just add Axios.defaults.withCredentials=true instead of ({credentials: true}) in client side, and change app.use(cors()) to

app.use(cors(
  {origin: ['your client side server'],
  methods: ['GET', 'POST'],
  credentials:true,
}
))

How do you set, clear, and toggle a single bit?

For the beginner I would like to explain a bit more with an example:

Example:

value is 0x55;
bitnum : 3rd.

The & operator is used check the bit:

0101 0101
&
0000 1000
___________
0000 0000 (mean 0: False). It will work fine if the third bit is 1 (then the answer will be True)

Toggle or Flip:

0101 0101
^
0000 1000
___________
0101 1101 (Flip the third bit without affecting other bits)

| operator: set the bit

0101 0101
|
0000 1000
___________
0101 1101 (set the third bit without affecting other bits)

Adding a column to a dataframe in R

Even if that's a 7 years old question, people new to R should consider using the data.table, package.

A data.table is a data.frame so all you can do for/to a data.frame you can also do. But many think are ORDERS of magnitude faster with data.table.

vec <- 1:10
library(data.table)
DT <- data.table(start=c(1,3,5,7), end=c(2,6,7,9))
DT[,new:=apply(DT,1,function(row) mean(vec[ row[1] : row[2] ] ))]

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Separate your rules with a semi colon in a single declaration:

<span style="color:blue;font-style:italic">Test</span>

How to insert a string which contains an "&"

If you are doing it from SQLPLUS use

SET DEFINE OFF  

to stop it treading & as a special case

how to fetch data from database in Hibernate

Let me quote this:

Hibernate created a new language named Hibernate Query Language (HQL), the syntax is quite similar to database SQL language. The main difference between is HQL uses class name instead of table name, and property names instead of column name.

As far as I can see you are using the table name.

So it should be like this:

Query query = session.createQuery("from Employee");

time delayed redirect?

You can include this directly in your buttun. It works very well. I hope it'll be useful for you. onclick="setTimeout('location.href = ../../dashboard.xhtml;', 7000);"

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

Laravel 5.2 redirect back with success message

You can use laravel MessageBag to add our own messages to existing messages.

To use MessageBag you need to use:

use Illuminate\Support\MessageBag;

In the controller:

MessageBag $message_bag

$message_bag->add('message', trans('auth.confirmation-success'));

return redirect('login')->withSuccess($message_bag);

Hope it will help some one.

  • Adi