Programs & Examples On #Itemizedoverlay

Hibernate openSession() vs getCurrentSession()

If we talk about SessionFactory.openSession()

  • It always creates a new Session object.
  • You need to explicitly flush and close session objects.
  • In single threaded environment it is slower than getCurrentSession().
  • You do not need to configure any property to call this method.

And If we talk about SessionFactory.getCurrentSession()

  • It creates a new Session if not exists, else uses same session which is in current hibernate context.
  • You do not need to flush and close session objects, it will be automatically taken care by Hibernate internally.
  • In single threaded environment it is faster than openSession().
  • You need to configure additional property. "hibernate.current_session_context_class" to call getCurrentSession() method, otherwise it will throw an exception.

How to get current time in python and break up into year, month, day, hour, minute?

By unpacking timetuple of datetime object, you should get what you want:

from datetime import datetime

n = datetime.now()
t = n.timetuple()
y, m, d, h, min, sec, wd, yd, i = t

How do I convert from a string to an integer in Visual Basic?

Convert.ToIntXX doesn't like being passed strings of decimals.

To be safe use

Convert.ToInt32(Convert.ToDecimal(txtPrice.Text))

How can I use onItemSelected in Android?

Joseph: spinner.setOnItemSelectedListener(this) should be below Spinner firstSpinner = (Spinner) findViewById(R.id.spinner1); on onCreate

Print newline in PHP in single quotes

If you are echoing to a browser, you can use <br/> with your statement:

echo 'Will print a newline<br/>';
echo 'But this wont!';

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

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

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

Difference between \n and \r?

Two different characters for different Operating Systems. Also this plays a role in data transmitted over TCP/IP which requires the use of \r\n.

\n Unix

\r Mac

\r\n Windows and DOS.

Adding :default => true to boolean in existing Rails column

change_column is a method of ActiveRecord::Migration, so you can't call it like that in the console.

If you want to add a default value for this column, create a new migration:

rails g migration add_default_value_to_show_attribute

Then in the migration created:

# That's the more generic way to change a column
def up
  change_column :profiles, :show_attribute, :boolean, default: true
end

def down
  change_column :profiles, :show_attribute, :boolean, default: nil
end

OR a more specific option:

def up
    change_column_default :profiles, :show_attribute, true
end

def down
    change_column_default :profiles, :show_attribute, nil
end

Then run rake db:migrate.

It won't change anything to the already created records. To do that you would have to create a rake task or just go in the rails console and update all the records (which I would not recommend in production).

When you added t.boolean :show_attribute, :default => true to the create_profiles migration, it's expected that it didn't do anything. Only migrations that have not already been ran are executed. If you started with a fresh database, then it would set the default to true.

How to scale a UIImageView proportionally?

This works fine for me Swift 2.x:

imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true;

How Best to Compare Two Collections in Java and Act on Them?

For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.

How to list the files in current directory?

You should verify that new File(".") is really pointing to where you think it is pointing - .classpath suggests the root of some Eclipse project....

Open multiple Eclipse workspaces on the Mac

2018 Update since many answers are no longer valid

OS X Heigh Sierra (10.13) with Eclipse Oxygen

Go to wherever your Eclipse is installed. Right-click -> Show Package Contents -> Contents -> MacOS -> Double-click the executable called eclipse

A terminal window will open and a new instance of eclipse will start.

Note that if you close the terminal window, the new Eclipse instance will be closed also.

enter image description here

To make your life easier, you can drag the executable to your dock for easy access

enter image description here

How can I merge two commits into one if I already started rebase?

Assuming you were in your own topic branch. If you want to merge the last 2 commits into one and look like a hero, branch off the commit just before you made the last two commits (specified with the relative commit name HEAD~2).

git checkout -b temp_branch HEAD~2

Then squash commit the other branch in this new branch:

git merge branch_with_two_commits --squash

That will bring in the changes but not commit them. So just commit them and you're done.

git commit -m "my message"

Now you can merge this new topic branch back into your main branch.

Installing Java 7 on Ubuntu

Oracle Java 1.7.0 from .deb packages

wget https://raw.github.com/flexiondotorg/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

Workaround for 1.7.0_51

There is an Issue 123 currently in OAB and a pull request

Here is the patched vesion:

wget https://raw.github.com/ladios/oab-java6/master/oab-java.sh
chmod +x oab-java.sh
sudo ./oab-java.sh -7
sudo apt-get update
sudo sudo apt-get install oracle-java7-jdk oracle-java7-fonts oracle-java7-source 
sudo apt-get dist-upgrade

How to change the default charset of a MySQL table?

Change table's default charset:

ALTER TABLE etape_prospection
  CHARACTER SET utf8,
  COLLATE utf8_general_ci;

To change string column charset exceute this query:

ALTER TABLE etape_prospection
  CHANGE COLUMN etape_prosp_comment etape_prosp_comment TEXT CHARACTER SET utf8 COLLATE utf8_general_ci;

Getting hold of the outer class object from the inner class object

Here's the example:

// Test
public void foo() {
    C c = new C();
    A s;
    s = ((A.B)c).get();
    System.out.println(s.getR());
}

// classes
class C {}

class A {
   public class B extends C{
     A get() {return A.this;}
   }
   public String getR() {
     return "This is string";
   }
}

Check if a variable is a string in JavaScript

Performance

Today 2020.09.17 I perform tests on MacOs HighSierra 10.13.6 on Chrome v85, Safari v13.1.2 and Firefox v80 for chosen solutions.

Results

For all browsers (and both test cases)

  • solutions typeof||instanceof (A, I) and x===x+'' (H) are fast/fastest
  • solution _.isString (lodash lib) is medium/fast
  • solutions B and K are slowest

enter image description here

Update: 2020.11.28 I update results for x=123 Chrome column - for solution I there was probably an error value before (=69M too low) - I use Chrome 86.0 to repeat tests.

Details

I perform 2 tests cases for solutions A B C D E F G H I J K L

  • when variable is string - you can run it HERE
  • when variable is NOT string - you can run it HERE

Below snippet presents differences between solutions

_x000D_
_x000D_
// https://stackoverflow.com/a/9436948/860099
function A(x) {
  return (typeof x == 'string') || (x instanceof String)
}

// https://stackoverflow.com/a/17772086/860099
function B(x) {
  return Object.prototype.toString.call(x) === "[object String]"
}

// https://stackoverflow.com/a/20958909/860099
function C(x) {
  return _.isString(x);
}

// https://stackoverflow.com/a/20958909/860099
function D(x) {
  return $.type(x) === "string";
}

// https://stackoverflow.com/a/16215800/860099
function E(x) {
  return x?.constructor === String;
}

// https://stackoverflow.com/a/42493631/860099
function F(x){
  return x?.charAt != null
}


// https://stackoverflow.com/a/57443488/860099
function G(x){
  return String(x) === x
}

// https://stackoverflow.com/a/19057360/860099
function H(x){
  return x === x + ''
}

// https://stackoverflow.com/a/4059166/860099
function I(x) {
  return typeof x == 'string'
}

// https://stackoverflow.com/a/28722301/860099
function J(x){
  return x === x?.toString()
}

// https://stackoverflow.com/a/58892465/860099
function K(x){
  return x && typeof x.valueOf() === "string"
}

// https://stackoverflow.com/a/9436948/860099
function L(x) {
  return x instanceof String
}

// ------------------
//     PRESENTATION
// ------------------

console.log('Solutions results for different inputs \n\n');
console.log("'abc' Str  ''  ' ' '1' '0'  1   0   {} [] true false null undef");

let tests = [ 'abc', new String("abc"),'',' ','1','0',1,0,{},[],true,false,null,undefined];

[A,B,C,D,E,F,G,H,I,J,K,L].map(f=> {  
console.log(
  `${f.name}   ` + tests.map(v=> (1*!!f(v)) ).join`   `
)})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>


This shippet only presents functions used in performance tests - it not perform tests itself!
_x000D_
_x000D_
_x000D_

And here are example results for chrome

enter image description here

Laravel Blade html image

you can Using asset() you can directly access to the image folder.

<img src="{{asset('img/stuvi-logo.png')}}" alt="logo" class="img-size-50 mr-3 img-circle">

How to set HttpResponse timeout for Android in Java

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}

How do I get the entity that represents the current user in Symfony2?

$this->container->get('security.token_storage')->getToken()->getUser();

How to reduce a huge excel file

I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.

jquery how to use multiple ajax calls one after the end of the other

Place them inside of the success: of the one it relies on.

$.ajax({
    url: 'http://www.xxxxxxxxxxxxx',
    data: {name: 'xxxxxx'},
    dataType: 'jsonp',
    success: function(data){

        // do stuff

        // call next ajax function
        $.ajax({ xxx });
    }
});

How to force ViewPager to re-instantiate its items

I have found a solution. It is just a workaround to my problem but currently the only solution.

ViewPager PagerAdapter not updating the View

public int getItemPosition(Object object) {
   return POSITION_NONE;
}

Does anyone know whether this is a bug or not?

React - Display loading screen while DOM is rendering?

I'm using react-progress-2 npm package, which is zero-dependency and works great in ReactJS.

https://github.com/milworm/react-progress-2

Installation:

npm install react-progress-2

Include react-progress-2/main.css to your project.

import "node_modules/react-progress-2/main.css";

Include react-progress-2 and put it somewhere in the top-component, for example:

import React from "react";
import Progress from "react-progress-2";

var Layout = React.createClass({
render: function() {
    return (
        <div className="layout">
            <Progress.Component/>
                {/* other components go here*/}
            </div>
        );
    }
});

Now, whenever you need to show an indicator, just call Progress.show(), for example:

loadFeed: function() {
    Progress.show();
    // do your ajax thing.
},

onLoadFeedCallback: function() {
    Progress.hide();
    // render feed.
}

Please note, that show and hide calls are stacked, so after n-consecutive show calls, you need to do n hide calls to hide an indicator or you can use Progress.hideAll().

Remove or adapt border of frame of legend using matplotlib

When plotting a plot using matplotlib:

How to remove the box of the legend?

plt.legend(frameon=False)

How to change the color of the border of the legend box?

leg = plt.legend()
leg.get_frame().set_edgecolor('b')

How to remove only the border of the box of the legend?

leg = plt.legend()
leg.get_frame().set_linewidth(0.0)

Fast check for NaN in NumPy

If you're comfortable with it allows to create a fast short-circuit (stops as soon as a NaN is found) function:

import numba as nb
import math

@nb.njit
def anynan(array):
    array = array.ravel()
    for i in range(array.size):
        if math.isnan(array[i]):
            return True
    return False

If there is no NaN the function might actually be slower than np.min, I think that's because np.min uses multiprocessing for large arrays:

import numpy as np
array = np.random.random(2000000)

%timeit anynan(array)          # 100 loops, best of 3: 2.21 ms per loop
%timeit np.isnan(array.sum())  # 100 loops, best of 3: 4.45 ms per loop
%timeit np.isnan(array.min())  # 1000 loops, best of 3: 1.64 ms per loop

But in case there is a NaN in the array, especially if it's position is at low indices, then it's much faster:

array = np.random.random(2000000)
array[100] = np.nan

%timeit anynan(array)          # 1000000 loops, best of 3: 1.93 µs per loop
%timeit np.isnan(array.sum())  # 100 loops, best of 3: 4.57 ms per loop
%timeit np.isnan(array.min())  # 1000 loops, best of 3: 1.65 ms per loop

Similar results may be achieved with Cython or a C extension, these are a bit more complicated (or easily avaiable as bottleneck.anynan) but ultimatly do the same as my anynan function.

How can I listen to the form submit event in javascript?

Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?

var ele = /*Your Form Element*/;
if(ele.addEventListener){
    ele.addEventListener("submit", callback, false);  //Modern browsers
}else if(ele.attachEvent){
    ele.attachEvent('onsubmit', callback);            //Old IE
}

callback is a function that you want to call when the form is being submitted.

About EventTarget.addEventListener, check out this documentation on MDN.

To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,

document.querySelector("#myForm").addEventListener("submit", function(e){
    if(!isValid){
        e.preventDefault();    //stop form from submitting
    }
});

Listening to the submit event with libraries

If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:

  1. jQuery

    $(ele).submit(callback);
    

    Where ele is the form element reference, and callback being the callback function reference. Reference

_x000D_
_x000D_
    <iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
_x000D_
_x000D_
_x000D_

  1. AngularJS (1.x)

    <form ng-submit="callback()">
    
    $scope.callback = function(){ /*...*/ };
    

    Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference

  2. React

    <form onSubmit={this.handleSubmit}>
    
    class YourComponent extends Component {
        // stuff
    
        handleSubmit(event) {
            // do whatever you need here
    
            // if you need to stop the submit event and 
            // perform/dispatch your own actions
            event.preventDefault();
        }
    
        // more stuff
    }
    

    Simply pass in a handler to the onSubmit prop. Reference

  3. Other frameworks/libraries

    Refer to the documentation of your framework.


Validation

You can always do your validation in JavaScript, but with HTML5 we also have native validation.

<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">

You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.

Demo: http://jsfiddle.net/DerekL/L23wmo1L/

Which characters are valid in CSS class names/selectors?

You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(az), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

In short, the previous rule translates to the following, extracted from the W3C spec.:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

1 It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).

2 Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. --indent1, is invalid. However, I'm pretty sure I've seen this in practice.

How do you Sort a DataTable given column and direction?

I assume "direction" is "ASC" or "DESC" and dt contains a column named "colName"

public static DataTable resort(DataTable dt, string colName, string direction)
{
    DataTable dtOut = null;
    dt.DefaultView.Sort = colName + " " + direction;
    dtOut = dt.DefaultView.ToTable();
    return dtOut;
}

OR without creating dtOut

public static DataTable resort(DataTable dt, string colName, string direction)
{
    dt.DefaultView.Sort = colName + " " + direction;
    dt = dt.DefaultView.ToTable();
    return dt;
}

How to get Tensorflow tensor dimensions (shape) as int values?

Another simple solution is to use map() as follows:

tensor_shape = map(int, my_tensor.shape)

This converts all the Dimension objects to int

How do I trim a file extension from a String in Java?

 private String trimFileExtension(String fileName)
  {
     String[] splits = fileName.split( "\\." );
     return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
  }

Fatal error: Call to a member function query() on null

First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:

global $db;

And I guess, when you wrote:

if($result->num_rows){
        return (mysqli_result($query, 0) == 1) ? true : false;

what you really wanted was:

if ($result->num_rows==1) { return true; } else { return false; }

Google Maps Android API v2 Authorization failure

I faced the same issue.

If you issued an api for your release version of the application. Then that api will only work for the release version not for the debug version. So make sure you are using the release version in your phone or emulator .

How to use android emulator for testing bluetooth application?

You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

  • No support for placing or receiving actual phone calls. However, You can simulate phone calls (placed and received) through the emulator console
  • No support for USB
  • No support for device-attached headphones
  • No support for determining SD card insert/eject
  • No support for WiFi, Bluetooth, NFC

Refer to the documentation

Find objects between two dates MongoDB

Use this code to find the record between two dates using $gte and $lt:

db.CollectionName.find({"whenCreated": {
    '$gte': ISODate("2018-03-06T13:10:40.294Z"),
    '$lt': ISODate("2018-05-06T13:10:40.294Z")
}});

How to fix homebrew permissions?

As a first option to whomever lands here like I did, follow whatever this suggests you to do:

brew doctor

It's the safest path, and amongst other things, it suggested me to:

sudo chown -R $(whoami) /usr/local

which solved that permissions issue.

The OP did just that but apparently didn't get the above suggestion; you might, and it's always better to start there, and only then look for non trivial solutions if it didn't help.

Hibernate: get entity by id

use get instead of load

// ...
        try {
            session = HibernateUtil.getSessionFactory().openSession();
            user =  (User) session.get(User.class, user_id);
        } catch (Exception e) {
 // ...

VC++ fatal error LNK1168: cannot open filename.exe for writing

The Reason is that your previous build is still running in the background. I solve this problem by following these steps:

  • Open Task Manager
  • Goto Details Tab
  • Find Your Application
  • End Task it by right clicking on it
  • Done!

Tomcat manager/html is not available?

Your website is blank because ROOT directory is missing from your ../webapps folder. Refer to tomcat documentation for the specific location on where it should be.

Adding custom radio buttons in android

In order to hide the default radio button, I'd suggest to remove the button instead of making it transparent as all visual feedback is handled by the drawable background :

android:button="@null"

Also it would be better to use styles as there are several radio buttons :

<RadioButton style="@style/RadioButtonStyle" ... />

<style name="RadioButtonStyle" parent="@android:style/Widget.CompoundButton">
    <item name="android:background">@drawable/customButtonBackground</item>
    <item name="android:button">@null</item>
</style>

You'll need the Seslyn customButtonBackground drawable too.

Get a list of all functions and procedures in an Oracle database

 SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
 and owner = 'Schema_name' order by object_name

here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be

SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE') 
and owner = 'PMIS' order by object_name

enter image description here

Ref: https://www.plsql.co/list-all-procedures-from-a-schema-of-oracle-database.html

Javascript event handler with parameters

let obj = MyObject();

elem.someEvent( function(){ obj.func(param) } );

//calls the MyObject.func, passing the param.

Waiting for another flutter command to release the startup lock

There are some action to do:

1- in pubspec.yaml press "packages get" or in terminal type " flutter packages get" and wait seconds.

if this doesn't work :

2-type flutter clean then do step(1)

if this doesn't work too :

3-type killtask /f /im dart.exe

if this doesn't work too :

4- close android studio and then restart your pc.

CS0120: An object reference is required for the nonstatic field, method, or property 'foo'

For this case, where you want to get a Control of a Form and are receiving this error, then I have a little bypass for you.

Go to your Program.cs and change

Application.Run(new Form1());

to

public static Form1 form1 = new Form1(); // Place this var out of the constructor
Application.Run(form1);

Now you can access a control with

Program.form1.<Your control>

Also: Don't forget to set your Control-Access-Level to Public.

And yes I know, this answer does not fit to the question caller, but it fits to googlers who have this specific issue with controls.

How can I clear the Scanner buffer in Java?

Other people have suggested using in.nextLine() to clear the buffer, which works for single-line input. As comments point out, however, sometimes System.in input can be multi-line.

You can instead create a new Scanner object where you want to clear the buffer if you are using System.in and not some other InputStream.

in = new Scanner(System.in);

If you do this, don't call in.close() first. Doing so will close System.in, and so you will get NoSuchElementExceptions on subsequent calls to in.nextInt(); System.in probably shouldn't be closed during your program.

(The above approach is specific to System.in. It might not be appropriate for other input streams.)

If you really need to close your Scanner object before creating a new one, this StackOverflow answer suggests creating an InputStream wrapper for System.in that has its own close() method that doesn't close the wrapped System.in stream. This is overkill for simple programs, though.

Namenode not getting started

After deleting a resource managers' data folder, the problem is gone.
Even if you have formatting cannot solve this problem.

Volatile boolean vs AtomicBoolean

You can't do compareAndSet, getAndSet as atomic operation with volatile boolean (unless of course you synchronize it).

jQuery .each() index?

jQuery takes care of this for you. The first argument to your .each() callback function is the index of the current iteration of the loop. The second being the current matched DOM element So:

$('#list option').each(function(index, element){
  alert("Iteration: " + index)
});

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

How to make a HTML Page in A4 paper size page(s)?

PPI and DPI make absolutely no difference to how a document will print off a browser. the printer takes no information on screen dot pitch or the DPI of the images etc. if you are printing images they would print at a size similar in proportion to how they are displayed on screen. the print processor of the browser would increase the DPI of the images from something rather low like 72dpi to whatever DPI the rest of the document is. say the image displays as half a page wide, then its about 4" wide physically. the pixel width of the image would be approx 300px to display correctly in the browser. by the time it prints at a nominal 300DPI, the processor has added pixels and the image will grow to around 1200px which at 300 DPI is 4".

when it comes to vector or non pixel based elements like text, the printer chooses its own DPI from the driver which doesnt relate to screen dot pitch or browser width etc. if the browser is 3000px wide, the print processor will wrap text as appropriate.

heres what makes it hard about creating print displays: each browser and printer will interpret text sizes (pt, em, px) and spacing in its own way. depending on what printer, browser and maybe even OS you use, you will get a different amount of lines and characters per page. so even if you test on your computer using your browser and printer and figure out that you can display the text in a box at 640x900px and its perfect on print, the next guy who tries to print will possibly get it printing differently. there really is no way to force each printer and browser to get it identical each time.

forget pixels and moreso forget DPI, the only thing you could use pixels for is setting a table width that simulates the width of a printable area on your printer. in that case i found that 640px wide is close.

CSS Border Not Working

Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.

Converting int to bytes in Python 3

The behaviour comes from the fact that in Python prior to version 3 bytes was just an alias for str. In Python3.x bytes is an immutable version of bytearray - completely new type, not backwards compatible.

How to pad zeroes to a string?

Just use the rjust method of the string object.

This example will make a string of 10 characters long, padding as necessary.

>>> t = 'test'
>>> t.rjust(10, '0')
>>> '000000test'

Exporting the values in List to excel

Exporting values List to Excel

  1. Install in nuget next reference
  2. Install-Package Syncfusion.XlsIO.Net.Core -Version 17.2.0.35
  3. Install-Package ClosedXML -Version 0.94.2
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClosedXML;
using ClosedXML.Excel;
using Syncfusion.XlsIO;

namespace ExporteExcel
{
    class Program
    {
        public class Auto
        {
            public string Marca { get; set; }

            public string Modelo { get; set; }
            public int Ano { get; set; }

            public string Color { get; set; }
            public int Peronsas { get; set; }
            public int Cilindros { get; set; }
        }
        static void Main(string[] args)
        {
            //Lista Estatica
            List<Auto> Auto = new List<Program.Auto>()
            {
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2019, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2018, Color= "Azul", Cilindros=6, Peronsas= 4 },
                new Auto{Marca = "Chevrolet", Modelo = "Sport", Ano = 2017, Color= "Azul", Cilindros=6, Peronsas= 4 }
            };
            //Inizializar Librerias
            var workbook = new XLWorkbook();
            workbook.AddWorksheet("sheetName");
            var ws = workbook.Worksheet("sheetName");
            //Recorrer el objecto
            int row = 1;
            foreach (var c in Auto)
            {
                //Escribrie en Excel en cada celda
                ws.Cell("A" + row.ToString()).Value = c.Marca;
                ws.Cell("B" + row.ToString()).Value = c.Modelo;
                ws.Cell("C" + row.ToString()).Value = c.Ano;
                ws.Cell("D" + row.ToString()).Value = c.Color;
                ws.Cell("E" + row.ToString()).Value = c.Cilindros;
                ws.Cell("F" + row.ToString()).Value = c.Peronsas;
                row++;

            }
            //Guardar Excel 
            //Ruta = Nombre_Proyecto\bin\Debug
            workbook.SaveAs("Coches.xlsx");
        }
    }
}

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Looks like maven is not present in your PATH. Add the absolute maven home\bin location to your PATH.

JPA: unidirectional many-to-one and cascading delete

I have seen in unidirectional @ManytoOne, delete don't work as expected. When parent is deleted, ideally child should also be deleted, but only parent is deleted and child is NOT deleted and is left as orphan

Technology used are Spring Boot/Spring Data JPA/Hibernate

Sprint Boot : 2.1.2.RELEASE

Spring Data JPA/Hibernate is used to delete row .eg

parentRepository.delete(parent)

ParentRepository extends standard CRUD repository as shown below ParentRepository extends CrudRepository<T, ID>

Following are my entity class

@Entity(name = “child”)
public class Child  {

    @Id
    @GeneratedValue
    private long id;

    @ManyToOne( fetch = FetchType.LAZY, optional = false)
    @JoinColumn(name = “parent_id", nullable = false)
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;
}

@Entity(name = “parent”)
public class Parent {

    @Id
    @GeneratedValue
    private long id;

    @Column(nullable = false, length = 50)
    private String firstName;


}

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

How to do encryption using AES in Openssl

My suggestion is to run

openssl enc -aes-256-cbc -in plain.txt -out encrypted.bin

under debugger and see what exactly what it is doing. openssl.c is the only real tutorial/getting started/reference guide OpenSSL has. All other documentation is just an API reference.

U1: My guess is that you are not setting some other required options, like mode of operation (padding).

U2: this is probably a duplicate of this question: AES CTR 256 Encryption Mode of operation on OpenSSL and answers there will likely help.

How do I remove blank elements from an array?

Use reject:

>> cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"].reject{ |e| e.empty? }
=> ["Kathmandu", "Pokhara", "Dharan", "Butwal"]

Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support

I don't know if this will be helpful for someone, but I had the same problem. I wrote pip install xlrd in the anaconda prompt while in the specific environment and it said it was installed, but when I looked at the installed packages it wasn't there. What solved the problem was "moving" (I don't know the terminology for it) into the Scripts folder of the specific environment and do the pip install xlrd there. Hope this is useful for someone :D

How to compare character ignoring case in primitive types

The Character class of Java API has various functions you can use.

You can convert your char to lowercase at both sides:

Character.toLowerCase(name1.charAt(i)) == Character.toLowerCase(name2.charAt(j))

There are also a methods you can use to verify if the letter is uppercase or lowercase:

Character.isUpperCase('P')
Character.isLowerCase('P') 

How to format a numeric column as phone number in SQL

I do not recommend keeping bad data in the database and then only correcting it on the output. We have a database where phone numbers are entered in variously as :

  • (555) 555-5555
  • 555+555+5555
  • 555.555.5555
  • (555)555-5555
  • 5555555555

Different people in an organization may write various retrieval functions and updates to the database, and therefore it would be harder to set in place formatting and retrieval rules. I am therefore correcting the data in the database first and foremost and then setting in place rules and form validations that protect the integrity of this database going forward.

I see no justification for keeping bad data unless as suggested a duplicate column be added with corrected formatting and the original data kept around for redundancy and reference, and YES I consider badly formatted data as BAD data.

Removing empty lines in Notepad++

An easy alternative for removing white space from empty lines:

  1. TextFX>TextFX Edit> Trim Trailing Spaces

This will remove all trailing spaces, including trailing spaces in blank lines. Make sure, no trailing spaces are significant.

How to make the checkbox unchecked by default always

An easy way , only HTML, no javascript, no jQuery

<input name="box1" type="hidden"   value="0" />
<input name="box1" type="checkbox" value="1" />

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

When would you use the different git merge strategies?

I'm not familiar with resolve, but I've used the others:

Recursive

Recursive is the default for non-fast-forward merges. We're all familiar with that one.

Octopus

I've used octopus when I've had several trees that needed to be merged. You see this in larger projects where many branches have had independent development and it's all ready to come together into a single head.

An octopus branch merges multiple heads in one commit as long as it can do it cleanly.

For illustration, imagine you have a project that has a master, and then three branches to merge in (call them a, b, and c).

A series of recursive merges would look like this (note that the first merge was a fast-forward, as I didn't force recursion):

series of recursive merges

However, a single octopus merge would look like this:

commit ae632e99ba0ccd0e9e06d09e8647659220d043b9
Merge: f51262e... c9ce629... aa0f25d...

octopus merge

Ours

Ours == I want to pull in another head, but throw away all of the changes that head introduces.

This keeps the history of a branch without any of the effects of the branch.

(Read: It is not even looked at the changes between those branches. The branches are just merged and nothing is done to the files. If you want to merge in the other branch and every time there is the question "our file version or their version" you can use git merge -X ours)

Subtree

Subtree is useful when you want to merge in another project into a subdirectory of your current project. Useful when you have a library you don't want to include as a submodule.

Trim string in JavaScript?

Here's a very simple way:

function removeSpaces(string){
return string.split(' ').join('');
}

In DB2 Display a table's definition

Try the following:

DESCRIBE SELECT * FROM TABLE_name

sed command with -i option failing on Mac, but works on Linux

Sinetris' answer is right, but I use this with find command to be more specific about what files I want to change. In general this should work (tested on osx /bin/bash):

find . -name "*.smth" -exec sed -i '' 's/text1/text2/g' {} \;

In general when using sed without find in complex projects is less efficient.

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

What does the symbol \0 mean in a string-literal?

char str[]= "Hello\0";

That would be 7 bytes.

In memory it'd be:

48 65 6C 6C 6F 00 00
H  e  l  l  o  \0 \0

Edit:

  • What does the \0 symbol mean in a C string?
    It's the "end" of a string. A null character. In memory, it's actually a Zero. Usually functions that handle char arrays look for this character, as this is the end of the message. I'll put an example at the end.

  • What is the length of str array? (Answered before the edit part)
    7

  • and with how much 0s it is ending?
    You array has two "spaces" with zero; str[5]=str[6]='\0'=0

Extra example:
Let's assume you have a function that prints the content of that text array. You could define it as:

char str[40];

Now, you could change the content of that array (I won't get into details on how to), so that it contains the message: "This is just a printing test" In memory, you should have something like:

54 68 69 73 20 69 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

So you print that char array. And then you want a new message. Let's say just "Hello"

48 65 6c 6c 6f 00 73 20 6a 75 73 74 20 61 20 70 72 69 6e 74
69 6e 67 20 74 65 73 74 00 00 00 00 00 00 00 00 00 00 00 00

Notice the 00 on str[5]. That's how the print function will know how much it actually needs to send, despite the actual longitude of the vector and the whole content.

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

Sharing a variable between multiple different threads

You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".

Please refer the below the code :

public class EvenOdd {

    static int a = 0;

    public static void main(String[] args) {

        EvenOdd eo = new EvenOdd();

        A aobj = eo.new A();
        B bobj = eo.new B();

        aobj.a = Lock.lock1;
        aobj.b = Lock.lock2;

        bobj.a = Lock.lock2;
        bobj.b = Lock.lock1;

        Thread t1 = new Thread(aobj);
        Thread t2 = new Thread(bobj);

        t1.start();
        t2.start();
    }

    static class Lock {
        final static Object lock1 = new Object();
        final static Object lock2 = new Object();
    }

    class A implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {
                try {
                    System.out.println(++EvenOdd.a + " A ");
                    synchronized (a) {
                        a.notify();
                    }
                    synchronized (b) {
                        b.wait();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class B implements Runnable {

        Object a;
        Object b;

        public void run() {
            while (EvenOdd.a < 10) {

                try {
                    synchronized (b) {
                        b.wait();
                        System.out.println(++EvenOdd.a + " B ");
                    }
                    synchronized (a) {
                        a.notify();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

OUTPUT :

1 A 
2 B 
3 A 
4 B 
5 A 
6 B 
7 A 
8 B 
9 A 
10 B 

How do I get the application exit code from a Windows command line?

At one point I needed to accurately push log events from Cygwin to the Windows Event log. I wanted the messages in WEVL to be custom, have the correct exit code, details, priorities, message, etc. So I created a little Bash script to take care of this. Here it is on GitHub, logit.sh.

Some excerpts:

usage: logit.sh [-h] [-p] [-i=n] [-s] <description>
example: logit.sh -p error -i 501 -s myscript.sh "failed to run the mount command"

Here is the temporary file contents part:

LGT_TEMP_FILE="$(mktemp --suffix .cmd)"
cat<<EOF>$LGT_TEMP_FILE
    @echo off
    set LGT_EXITCODE="$LGT_ID"
    exit /b %LGT_ID%
EOF
unix2dos "$LGT_TEMP_FILE"

Here is a function to to create events in WEVL:

__create_event () {
    local cmd="eventcreate /ID $LGT_ID /L Application /SO $LGT_SOURCE /T $LGT_PRIORITY /D "
    if [[ "$1" == *';'* ]]; then
        local IFS=';'
        for i in "$1"; do
            $cmd "$i" &>/dev/null
        done
    else
        $cmd "$LGT_DESC" &>/dev/null
    fi
}

Executing the batch script and calling on __create_event:

cmd /c "$(cygpath -wa "$LGT_TEMP_FILE")"
__create_event

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

Set value of hidden input with jquery

var test = $('input[name="testing"]:hidden');
test.val('work!');

How to Access Hive via Python?

The easiest way is to use PyHive.

To install you'll need these libraries:

pip install sasl
pip install thrift
pip install thrift-sasl
pip install PyHive

After installation, you can connect to Hive like this:

from pyhive import hive
conn = hive.Connection(host="YOUR_HIVE_HOST", port=PORT, username="YOU")

Now that you have the hive connection, you have options how to use it. You can just straight-up query:

cursor = conn.cursor()
cursor.execute("SELECT cool_stuff FROM hive_table")
for result in cursor.fetchall():
  use_result(result)

...or to use the connection to make a Pandas dataframe:

import pandas as pd
df = pd.read_sql("SELECT cool_stuff FROM hive_table", conn)

jQuery keypress() event not firing?

e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.

See http://unixpapa.com/js/key.html for more information.

Verifying that a string contains only letters in C#

If You are a newbie then you can take reference from my code .. what i did was to put on a check so that i could only get the Alphabets and white spaces! You can Repeat the for loop after the second if statement to validate the string again

       bool check = false;

       Console.WriteLine("Please Enter the Name");
       name=Console.ReadLine();

       for (int i = 0; i < name.Length; i++)
       {
           if (name[i]>='a' && name[i]<='z' || name[i]==' ')
           {
               check = true;
           }
           else
           {
               check = false;
               break;
           }

       }

       if (check==false)
       {
           Console.WriteLine("Enter Valid Value");
           name = Console.ReadLine();
       }

What MIME type should I use for CSV?

My users are allowed to upload CSV files and text/csv and application/csv did not appear by now. These are the ones identified through finfo():

text/plain
text/x-csv

And these are the ones transmitted through the browser:

text/plain
application/vnd.ms-excel
text/x-csv

The following types did not appear, but could:

application/csv
application/x-csv
text/csv
text/comma-separated-values
text/x-comma-separated-values
text/tab-separated-values

Change the Bootstrap Modal effect

 body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}

    <div class="container">
    <form class="form-inline" style="position:absolute; top:40%; left:50%; transform:translateX(-50%);">
        <div class="form-group">
        <label>Entrances</label>
          <select class="form-control" id="entrance">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Entrances">
              <option value="bounceIn" selected>bounceIn</option>
              <option value="bounceInDown">bounceInDown</option>
              <option value="bounceInLeft">bounceInLeft</option>
              <option value="bounceInRight">bounceInRight</option>
              <option value="bounceInUp">bounceInUp</option>
            </optgroup>
            <optgroup label="Fading Entrances">
              <option value="fadeIn">fadeIn</option>
              <option value="fadeInDown">fadeInDown</option>
              <option value="fadeInDownBig">fadeInDownBig</option>
              <option value="fadeInLeft">fadeInLeft</option>
              <option value="fadeInLeftBig">fadeInLeftBig</option>
              <option value="fadeInRight">fadeInRight</option>
              <option value="fadeInRightBig">fadeInRightBig</option>
              <option value="fadeInUp">fadeInUp</option>
              <option value="fadeInUpBig">fadeInUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipInX">flipInX</option>
              <option value="flipInY">flipInY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedIn">lightSpeedIn</option>
            </optgroup>
            <optgroup label="Rotating Entrances">
              <option value="rotateIn">rotateIn</option>
              <option value="rotateInDownLeft">rotateInDownLeft</option>
              <option value="rotateInDownRight">rotateInDownRight</option>
              <option value="rotateInUpLeft">rotateInUpLeft</option>
              <option value="rotateInUpRight">rotateInUpRight</option>
            </optgroup>
            <optgroup label="Sliding Entrances">
              <option value="slideInUp">slideInUp</option>
              <option value="slideInDown">slideInDown</option>
              <option value="slideInLeft">slideInLeft</option>
              <option value="slideInRight">slideInRight</option>
            </optgroup>
            <optgroup label="Zoom Entrances">
              <option value="zoomIn">zoomIn</option>
              <option value="zoomInDown">zoomInDown</option>
              <option value="zoomInLeft">zoomInLeft</option>
              <option value="zoomInRight">zoomInRight</option>
              <option value="zoomInUp">zoomInUp</option>
            </optgroup>

            <optgroup label="Specials">
              <option value="rollIn">rollIn</option>
            </optgroup>
          </select>
       </div>
        <div class="form-group">
        <label>Exits</label>
          <select class="form-control" id="exit">
            <optgroup label="Attention Seekers">
              <option value="bounce">bounce</option>
              <option value="flash">flash</option>
              <option value="pulse">pulse</option>
              <option value="rubberBand">rubberBand</option>
              <option value="shake">shake</option>
              <option value="swing">swing</option>
              <option value="tada">tada</option>
              <option value="wobble">wobble</option>
              <option value="jello">jello</option>
            </optgroup>
            <optgroup label="Bouncing Exits">
              <option value="bounceOut">bounceOut</option>
              <option value="bounceOutDown">bounceOutDown</option>
              <option value="bounceOutLeft">bounceOutLeft</option>
              <option value="bounceOutRight">bounceOutRight</option>
              <option value="bounceOutUp">bounceOutUp</option>
            </optgroup>
            <optgroup label="Fading Exits">
              <option value="fadeOut">fadeOut</option>
              <option value="fadeOutDown">fadeOutDown</option>
              <option value="fadeOutDownBig">fadeOutDownBig</option>
              <option value="fadeOutLeft">fadeOutLeft</option>
              <option value="fadeOutLeftBig">fadeOutLeftBig</option>
              <option value="fadeOutRight">fadeOutRight</option>
              <option value="fadeOutRightBig">fadeOutRightBig</option>
              <option value="fadeOutUp">fadeOutUp</option>
              <option value="fadeOutUpBig">fadeOutUpBig</option>
            </optgroup>
            <optgroup label="Flippers">
              <option value="flipOutX" selected>flipOutX</option>
              <option value="flipOutY">flipOutY</option>
            </optgroup>
            <optgroup label="Lightspeed">
              <option value="lightSpeedOut">lightSpeedOut</option>
            </optgroup>
            <optgroup label="Rotating Exits">
              <option value="rotateOut">rotateOut</option>
              <option value="rotateOutDownLeft">rotateOutDownLeft</option>
              <option value="rotateOutDownRight">rotateOutDownRight</option>
              <option value="rotateOutUpLeft">rotateOutUpLeft</option>
              <option value="rotateOutUpRight">rotateOutUpRight</option>
            </optgroup>
            <optgroup label="Sliding Exits">
              <option value="slideOutUp">slideOutUp</option>
              <option value="slideOutDown">slideOutDown</option>
              <option value="slideOutLeft">slideOutLeft</option>
              <option value="slideOutRight">slideOutRight</option>
            </optgroup>        
            <optgroup label="Zoom Exits">
              <option value="zoomOut">zoomOut</option>
              <option value="zoomOutDown">zoomOutDown</option>
              <option value="zoomOutLeft">zoomOutLeft</option>
              <option value="zoomOutRight">zoomOutRight</option>
              <option value="zoomOutUp">zoomOutUp</option>
            </optgroup>
            <optgroup label="Specials">
              <option value="rollOut">rollOut</option>
            </optgroup>

          </select>
       </div>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
      Launch demo modal
    </button>
    </form>

      <a class="btn btn-black " href="http://demo.nhembram.com/bootstrap-modal-animation-with-animate-css/index.html" target="_blank">View FullPage</a>
    </div>
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
            <h4 class="modal-title" id="myModalLabel">Modal title</h4>
          </div>
          <div class="modal-body">
            ...
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            <button type="button" class="btn btn-primary">Save changes</button>
          </div>
        </div>
      </div>
    </div>

    <script>
    function testAnim(x) {
        $('.modal .modal-dialog').attr('class', 'modal-dialog  ' + x + '  animated');
    };
    $('#myModal').on('show.bs.modal', function (e) {
      var anim = $('#entrance').val();
          testAnim(anim);
    });
    $('#myModal').on('hide.bs.modal', function (e) {
      var anim = $('#exit').val();
          testAnim(anim);
    });
    </script>

<style>
body{
  text-align:center;
  padding:50px;
}
.modal.fade{
  opacity:1;
}
.modal.fade .modal-dialog {
   -webkit-transform: translate(0);
   -moz-transform: translate(0);
   transform: translate(0);
}
.btn-black{
  position:absolute;
  bottom:50px;
  transform:translateX(-50%);
  background:#222;
  padding:10px 20px;
  text-transform:uppercase;
  letter-spacing:1px;
  font-size:14px;
  font-weight:bold;
}
</style>

Is log(n!) = T(n·log(n))?

I realize this is a very old question with an accepted answer, but none of these answers actually use the approach suggested by the hint.

It is a pretty simple argument:

n! (= 1*2*3*...*n) is a product of n numbers each less than or equal to n. Therefore it is less than the product of n numbers all equal to n; i.e., n^n.

Half of the numbers -- i.e. n/2 of them -- in the n! product are greater than or equal to n/2. Therefore their product is greater than the product of n/2 numbers all equal to n/2; i.e. (n/2)^(n/2).

Take logs throughout to establish the result.

What does the star operator mean, in a function call?

The single star * unpacks the sequence/collection into positional arguments, so you can do this:

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

values = (1, 2)

s = sum(*values)

This will unpack the tuple so that it actually executes as:

s = sum(1, 2)

The double star ** does the same, only using a dictionary and thus named arguments:

values = { 'a': 1, 'b': 2 }
s = sum(**values)

You can also combine:

def sum(a, b, c, d):
    return a + b + c + d

values1 = (1, 2)
values2 = { 'c': 10, 'd': 15 }
s = sum(*values1, **values2)

will execute as:

s = sum(1, 2, c=10, d=15)

Also see section 4.7.4 - Unpacking Argument Lists of the Python documentation.


Additionally you can define functions to take *x and **y arguments, this allows a function to accept any number of positional and/or named arguments that aren't specifically named in the declaration.

Example:

def sum(*values):
    s = 0
    for v in values:
        s = s + v
    return s

s = sum(1, 2, 3, 4, 5)

or with **:

def get_a(**values):
    return values['a']

s = get_a(a=1, b=2)      # returns 1

this can allow you to specify a large number of optional parameters without having to declare them.

And again, you can combine:

def sum(*values, **options):
    s = 0
    for i in values:
        s = s + i
    if "neg" in options:
        if options["neg"]:
            s = -s
    return s

s = sum(1, 2, 3, 4, 5)            # returns 15
s = sum(1, 2, 3, 4, 5, neg=True)  # returns -15
s = sum(1, 2, 3, 4, 5, neg=False) # returns 15

remove empty lines from text file with PowerShell

file

PS /home/edward/Desktop> Get-Content ./copy.txt

[Desktop Entry]

Name=calibre Exec=~/Apps/calibre/calibre

Icon=~/Apps/calibre/resources/content-server/calibre.png

Type=Application*


Start by get the content from file and trim the white spaces if any found in each line of the text document. That becomes the object passed to the where-object to go through the array looking at each member of the array with string length greater then 0. That object is passed to replace the content of the file you started with. It would probably be better to make a new file... Last thing to do is reads back the newly made file's content and see your awesomeness.

(Get-Content ./copy.txt).Trim() | Where-Object{$_.length -gt 0} | Set-Content ./copy.txt

Get-Content ./copy.txt

Composer: how can I install another dependency without updating old ones?

My use case is simpler, and fits simply your title but not your further detail.

That is, I want to install a new package which is not yet in my composer.json without updating all the other packages.

The solution here is composer require x/y

ReferenceError: document is not defined (in plain JavaScript)

Try adding the script element just before the /body tag like that

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/quiz.css" />
</head>
<body>

    <div id="divid">Next</div>
    <script type="text/javascript" src="js/quiz.js"></script>
</body>
</html>

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Try this code it work fine

assign the post variable to the variable

   $username = $_POST['uname'];

   $password = $_POST['pass'];

  $result = mysql_query('SELECT * FROM userData WHERE UserName LIKE $username');

if(!empty($result)){

    while($row = mysql_fetch_array($result)){
        echo $row['FirstName'];
     }
}

SQL Server r2 installation error .. update Visual Studio 2008 to SP1

Finally, I solved it. Even though the solution is a bit lengthy, I think its the simplest. The solution is as follows:

  1. Install Visual Studio 2008
  2. Install the service Package 1 (SP1)
  3. Install SQL Server 2008 r2

creating json object with variables

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

Sql Query to list all views in an SQL Server 2005 database

SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views

How do I import a .sql file in mysql database using PHP?

I Thing you can Try this Code, It's Run for my Case:

_x000D_
_x000D_
<?php_x000D_
_x000D_
$con = mysqli_connect('localhost', 'root', 'NOTSHOWN', 'test');_x000D_
_x000D_
$filename = 'dbbackupmember.sql';_x000D_
$handle = fopen($filename, 'r+');_x000D_
$contents = fread($handle, filesize($filename));_x000D_
_x000D_
$sql = explode(";", $contents);_x000D_
foreach ($sql as $query) {_x000D_
 $result = mysqli_query($con, $query);_x000D_
 if ($result) {_x000D_
  echo "<tr><td><br></td></tr>";_x000D_
  echo "<tr><td>".$query."</td></tr>";_x000D_
  echo "<tr><td><br></td></tr>";_x000D_
 }_x000D_
}_x000D_
_x000D_
fclose($handle);_x000D_
echo "success";_x000D_
_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

unsigned APK can not be installed

I did not know that even with the "Allow Installation of non-Marked application", I still needed to sign the application.

I self-signed my application, following this link self-sign and release application, It only took 5 minutes, then I emailed the signed-APK file to myself and downloaded it to SD-card and then installed it without any problem.

changing kafka retention period during runtime

log.retention.hours is a property of a broker which is used as a default value when a topic is created. When you change configurations of currently running topic using kafka-topics.sh, you should specify a topic-level property.

A topic-level property for log retention time is retention.ms.

From Topic-level configuration in Kafka 0.8.1 documentation:

  • Property: retention.ms
  • Default: 7 days
  • Server Default Property: log.retention.minutes
  • Description: This configuration controls the maximum time we will retain a log before we will discard old log segments to free up space if we are using the "delete" retention policy. This represents an SLA on how soon consumers must read their data.

So the correct command depends on the version. Up to 0.8.2 (although docs still show its use up to 0.10.1) use kafka-topics.sh --alter and after 0.10.2 (or perhaps from 0.9.0 going forward) use kafka-configs.sh --alter

$ bin/kafka-topics.sh --zookeeper zk.yoursite.com --alter --topic as-access --config retention.ms=86400000
 

You can check whether the configuration is properly applied with the following command.

$ bin/kafka-topics.sh --describe --zookeeper zk.yoursite.com --topic as-access

Then you will see something like below.

Topic:as-access  PartitionCount:3  ReplicationFactor:3  Configs:retention.ms=86400000

Measuring execution time of a function in C++

I recommend using steady_clock which is guarunteed to be monotonic, unlike high_resolution_clock.

#include <iostream>
#include <chrono>

using namespace std;

unsigned int stopwatch()
{
    static auto start_time = chrono::steady_clock::now();

    auto end_time = chrono::steady_clock::now();
    auto delta    = chrono::duration_cast<chrono::microseconds>(end_time - start_time);

    start_time = end_time;

    return delta.count();
}

int main() {
  stopwatch(); //Start stopwatch
  std::cout << "Hello World!\n";
  cout << stopwatch() << endl; //Time to execute last line
  for (int i=0; i<1000000; i++)
      string s = "ASDFAD";
  cout << stopwatch() << endl; //Time to execute for loop
}

Output:

Hello World!
62
163514

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

Difference between rake db:migrate db:reset and db:schema:load

Rails 5

db:create - Creates the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:create:all - Creates the database for all environments.

db:drop - Drops the database for the current RAILS_ENV environment. If RAILS_ENV is not specified it defaults to the development and test databases.

db:drop:all - Drops the database for all environments.

db:migrate - Runs migrations for the current environment that have not run yet. By default it will run migrations only in the development environment.

db:migrate:redo - Runs db:migrate:down and db:migrate:up or db:migrate:rollback and db:migrate:up depending on the specified migration.

db:migrate:up - Runs the up for the given migration VERSION.

db:migrate:down - Runs the down for the given migration VERSION.

db:migrate:status - Displays the current migration status.

db:migrate:rollback - Rolls back the last migration.

db:version - Prints the current schema version.

db:forward - Pushes the schema to the next version.

db:seed - Runs the db/seeds.rb file.

db:schema:load Recreates the database from the schema.rb file. Deletes existing data.

db:schema:dump Dumps the current environment’s schema to db/schema.rb.

db:structure:load - Recreates the database from the structure.sql file.

db:structure:dump - Dumps the current environment’s schema to db/structure.sql. (You can specify another file with SCHEMA=db/my_structure.sql)

db:setup Runs db:create, db:schema:load and db:seed.

db:reset Runs db:drop and db:setup. db:migrate:reset - Runs db:drop, db:create and db:migrate.

db:test:prepare - Check for pending migrations and load the test schema. (If you run rake without any arguments it will do this by default.)

db:test:clone - Recreate the test database from the current environment’s database schema.

db:test:clone_structure - Similar to db:test:clone, but it will ensure that your test database has the same structure, including charsets and collations, as your current environment’s database.

db:environment:set - Set the current RAILS_ENV environment in the ar_internal_metadata table. (Used as part of the protected environment check.)

db:check_protected_environments - Checks if a destructive action can be performed in the current RAILS_ENV environment. Used internally when running a destructive action such as db:drop or db:schema:load.

Removing all line breaks and adding them after certain text

You can also go to Notepad++ and do the following steps:

Edit->LineOperations-> Remove Empty Lines or Remove Empty Lines(Containing blank characters)

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

I had the same issue. In my home folder I've got a script named sqlplus.sh that takes care of this for me, containing:

ORACLE_HOME=/usr/lib/oracle/xe/app/oracle/product/10.2.0/server
export ORACLE_HOME
ORACLE_SID=XE
export ORACLE_SID
NLS_LANG=`$ORACLE_HOME/bin/nls_lang.sh`
export NLS_LANG
PATH=$ORACLE_HOME/bin:$PATH
export PATH
sqlplus /nolog

Find non-ASCII characters in varchar columns using SQL Server

This script searches for non-ascii characters in one column. It generates a string of all valid characters, here code point 32 to 127. Then it searches for rows that don't match the list:

declare @str varchar(128)
declare @i int
set @str = ''
set @i = 32
while @i <= 127
    begin
    set @str = @str + '|' + char(@i)
    set @i = @i + 1
    end

select  col1
from    YourTable
where   col1 like '%[^' + @str + ']%' escape '|'

How do DATETIME values work in SQLite?

One of the powerful features of SQLite is allowing you to choose the storage type. Advantages/disadvantages of each of the three different possibilites:

  • ISO8601 string

    • String comparison gives valid results
    • Stores fraction seconds, up to three decimal digits
    • Needs more storage space
    • You will directly see its value when using a database browser
    • Need for parsing for other uses
    • "default current_timestamp" column modifier will store using this format
  • Real number

    • High precision regarding fraction seconds
    • Longest time range
  • Integer number

    • Lowest storage space
    • Quick operations
    • Small time range
    • Possible year 2038 problem

If you need to compare different types or export to an external application, you're free to use SQLite's own datetime conversion functions as needed.

PHP split alternative?

You can use the easier function preg_match instead, It's better and faster than all of the other ones.

$var = "<tag>Get this var</tag>";
preg_match("/<tag>(.*)<\/tag>/", $var , $new_var);
echo $new_var['1']; 

Output: Get this var

What are the uses of the exec command in shell scripts?

Just to augment the accepted answer with a brief newbie-friendly short answer, you probably don't need exec.

If you're still here, the following discussion should hopefully reveal why. When you run, say,

sh -c 'command'

you run a sh instance, then start command as a child of that sh instance. When command finishes, the sh instance also finishes.

sh -c 'exec command'

runs a sh instance, then replaces that sh instance with the command binary, and runs that instead.

Of course, both of these are useless in this limited context; you simply want

command

There are some fringe situations where you want the shell to read its configuration file or somehow otherwise set up the environment as a preparation for running command. This is pretty much the sole situation where exec command is useful.

#!/bin/sh
ENVIRONMENT=$(some complex task)
exec command

This does some stuff to prepare the environment so that it contains what is needed. Once that's done, the sh instance is no longer necessary, and so it's a (minor) optimization to simply replace the sh instance with the command process, rather than have sh run it as a child process and wait for it, then exit as soon as it finishes.

Similarly, if you want to free up as much resources as possible for a heavyish command at the end of a shell script, you might want to exec that command as an optimization.

If something forces you to run sh but you really wanted to run something else, exec something else is of course a workaround to replace the undesired sh instance (like for example if you really wanted to run your own spiffy gosh instead of sh but yours isn't listed in /etc/shells so you can't specify it as your login shell).

The second use of exec to manipulate file descriptors is a separate topic. The accepted answer covers that nicely; to keep this self-contained, I'll just defer to the manual for anything where exec is followed by a redirect instead of a command name.

Parser Error when deploy ASP.NET application

Very old question here, but I ran into the same error and none of the provided answers solved the issue.

My issue occurred because I manually changed the namespace and assembly names of the project after initial creation. Took me a little bit to notice that the namespace in the Inherits attribute didn't match the updated namespace.

Updating that namespace in the Global.asax markup to match the apps namespace fixed the error for me.

./xx.py: line 1: import: command not found

When you see "import: command not found" on the very first import, it is caused by the parser not using the character encoding matching your py file. Especially when you are not using ASCII encoding in your py file.

The way to get it right is to specify the correct encoding on top of your py file to match your file character encoding.

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

window.location (JS) vs header() (PHP) for redirection

The first case will fail when JS is off. It's also a little bit slower since JS must be parsed first (DOM must be loaded). However JS is safer since the destination doesn't know the referer and your redirect might be tracked (referers aren't reliable in general yet this is something).

You can also use meta refresh tag. It also requires DOM to be loaded.

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

How to split CSV files as per number of rows specified?

Made it into a function. You can now call splitCsv <Filename> [chunkSize]

splitCsv() {
    HEADER=$(head -1 $1)
    if [ -n "$2" ]; then
        CHUNK=$2
    else 
        CHUNK=1000
    fi
    tail -n +2 $1 | split -l $CHUNK - $1_split_
    for i in $1_split_*; do
        sed -i -e "1i$HEADER" "$i"
    done
}

Found on: http://edmondscommerce.github.io/linux/linux-split-file-eg-csv-and-keep-header-row.html

How to make a query with group_concat in sql server

Query:

SELECT
      m.maskid
    , m.maskname
    , m.schoolid
    , s.schoolname
    , maskdetail = STUFF((
          SELECT ',' + md.maskdetail
          FROM dbo.maskdetails md
          WHERE m.maskid = md.maskid
          FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
FROM dbo.tblmask m
JOIN dbo.school s ON s.ID = m.schoolid
ORDER BY m.maskname

Additional information:

String Aggregation in the World of SQL Server

Convert Unicode to ASCII without errors in Python

2018 Update:

As of February 2018, using compressions like gzip has become quite popular (around 73% of all websites use it, including large sites like Google, YouTube, Yahoo, Wikipedia, Reddit, Stack Overflow and Stack Exchange Network sites).
If you do a simple decode like in the original answer with a gzipped response, you'll get an error like or similar to this:

UnicodeDecodeError: 'utf8' codec can't decode byte 0x8b in position 1: unexpected code byte

In order to decode a gzpipped response you need to add the following modules (in Python 3):

import gzip
import io

Note: In Python 2 you'd use StringIO instead of io

Then you can parse the content out like this:

response = urlopen("https://example.com/gzipped-ressource")
buffer = io.BytesIO(response.read()) # Use StringIO.StringIO(response.read()) in Python 2
gzipped_file = gzip.GzipFile(fileobj=buffer)
decoded = gzipped_file.read()
content = decoded.decode("utf-8") # Replace utf-8 with the source encoding of your requested resource

This code reads the response, and places the bytes in a buffer. The gzip module then reads the buffer using the GZipFile function. After that, the gzipped file can be read into bytes again and decoded to normally readable text in the end.

Original Answer from 2010:

Can we get the actual value used for link?

In addition, we usually encounter this problem here when we are trying to .encode() an already encoded byte string. So you might try to decode it first as in

html = urllib.urlopen(link).read()
unicode_str = html.decode(<source encoding>)
encoded_str = unicode_str.encode("utf8")

As an example:

html = '\xa0'
encoded_str = html.encode("utf8")

Fails with

UnicodeDecodeError: 'ascii' codec can't decode byte 0xa0 in position 0: ordinal not in range(128)

While:

html = '\xa0'
decoded_str = html.decode("windows-1252")
encoded_str = decoded_str.encode("utf8")

Succeeds without error. Do note that "windows-1252" is something I used as an example. I got this from chardet and it had 0.5 confidence that it is right! (well, as given with a 1-character-length string, what do you expect) You should change that to the encoding of the byte string returned from .urlopen().read() to what applies to the content you retrieved.

Another problem I see there is that the .encode() string method returns the modified string and does not modify the source in place. So it's kind of useless to have self.response.out.write(html) as html is not the encoded string from html.encode (if that is what you were originally aiming for).

As Ignacio suggested, check the source webpage for the actual encoding of the returned string from read(). It's either in one of the Meta tags or in the ContentType header in the response. Use that then as the parameter for .decode().

Do note however that it should not be assumed that other developers are responsible enough to make sure the header and/or meta character set declarations match the actual content. (Which is a PITA, yeah, I should know, I was one of those before).

What is the difference between LATERAL and a subquery in PostgreSQL?

One thing no one has pointed out is that you can use LATERAL queries to apply a user-defined function on every selected row.

For instance:

CREATE OR REPLACE FUNCTION delete_company(companyId varchar(255))
RETURNS void AS $$
    BEGIN
        DELETE FROM company_settings WHERE "company_id"=company_id;
        DELETE FROM users WHERE "company_id"=companyId;
        DELETE FROM companies WHERE id=companyId;
    END; 
$$ LANGUAGE plpgsql;

SELECT * FROM (
    SELECT id, name, created_at FROM companies WHERE created_at < '2018-01-01'
) c, LATERAL delete_company(c.id);

That's the only way I know how to do this sort of thing in PostgreSQL.

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

CORS is a browser feature. Servers need to opt into CORS to allow browsers to bypass same-origin policy. Your server would not have that same restriction and be able to make requests to any server with a public API. https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Create an endpoint on your server with CORS enabled that can act as a proxy for your web app.

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

Make the current Git branch a master branch

One can also checkout all files from the other branch into master:

git checkout master
git checkout better_branch -- .

and then commit all changes.

Truncating a table in a stored procedure

You should know that it is not possible to directly run a DDL statement like you do for DML from a PL/SQL block because PL/SQL does not support late binding directly it only support compile time binding which is fine for DML. hence to overcome this type of problem oracle has provided a dynamic SQL approach which can be used to execute the DDL statements.The dynamic sql approach is about parsing and binding of sql string at the runtime. Also you should rememder that DDL statements are by default auto commit hence you should be careful about any of the DDL statement using the dynamic SQL approach incase if you have some DML (which needs to be commited explicitly using TCL) before executing the DDL in the stored proc/function.

You can use any of the following dynamic sql approach to execute a DDL statement from a pl/sql block.

1) Execute immediate

2) DBMS_SQL package

3) DBMS_UTILITY.EXEC_DDL_STATEMENT (parse_string IN VARCHAR2);

Hope this answers your question with explanation.

Standard Android menu icons, for example refresh

Maybe a bit late. Completing the other answers, you have the hdpi refresh icon in:

"android_sdk"\platforms\"android_api_level"\data\res\drawable-hdpi\ic_menu_refresh.png

Remove Identity from a column in a table

Bellow code working as fine, when we don't know identity column name.

Need to copy data into new temp table like Invoice_DELETED. and next time we using:

insert into Invoice_DELETED select * from Invoice where ...


SELECT t1.*
INTO Invoice_DELETED
FROM Invoice t1
LEFT JOIN Invoice ON 1 = 0
--WHERE t1.InvoiceID = @InvoiceID

For more explanation see: https://dba.stackexchange.com/a/138345/101038

accessing a variable from another class

I had the same problem. In order to modify variables from different classes, I made them extend the class they were to modify. I also made the super class's variables static so they can be changed by anything that inherits them. I also made them protected for more flexibility.

Source: Bad experiences. Good lessons.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Why am I suddenly getting a "Blocked loading mixed active content" issue in Firefox?

I found if you have issues with including or mixing your page with something like http://www.example.com, you can fix that by putting //www.example.com instead

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

# is better than javascript:anything, but the following is even better:

HTML:

<a href="/gracefully/degrading/url/with/same/functionality.ext" class="some-selector">For great justice</a>

JavaScript:

$(function() {
    $(".some-selector").click(myJsFunc);
});

You should always strive for graceful degradation (in the event that the user doesn't have JavaScript enabled...and when it is with specs. and budget). Also, it is considered bad form to use JavaScript attributes and protocol directly in HTML.

Case-insensitive search in Rails model

There are lots of great answers here, particularly @oma's. But one other thing you could try is to use custom column serialization. If you don't mind everything being stored lowercase in your db then you could create:

# lib/serializers/downcasing_string_serializer.rb
module Serializers
  class DowncasingStringSerializer
    def self.load(value)
      value
    end

    def self.dump(value)
      value.downcase
    end
  end
end

Then in your model:

# app/models/my_model.rb
serialize :name, Serializers::DowncasingStringSerializer
validates_uniqueness_of :name, :case_sensitive => false

The benefit of this approach is that you can still use all the regular finders (including find_or_create_by) without using custom scopes, functions, or having lower(name) = ? in your queries.

The downside is that you lose casing information in the database.

Warning "Do not Access Superglobal $_POST Array Directly" on Netbeans 7.4 for PHP

filter_input(INPUT_POST, 'var_name') instead of $_POST['var_name']
filter_input_array(INPUT_POST) instead of $_POST

How to write "not in ()" sql query using join

I would opt for NOT EXISTS in this case.

SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
    (SELECT 'X'
     FROM Domain2 D2
     WHERE D2.ShortCode = D1.ShortCode
    )

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

I think the easiest trick is:

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR API KEY&callback=initMap">google.maps.event.addDomListener(window,'load', initMap);</script>

It will init the map when your app is ready.

Check this.

CSS two div width 50% in one line with line break in file

<div id="wrapper" style="width: 400px">
    <div id="left" style="float: left; width: 200px;">Left</div>
    <div id="right" style="float: right; width: 200px;">Left</div>
    <div style="clear: both;"></div>
</div>

I know this question wanted inline block, but try to view http://jsfiddle.net/N9mzE/1/ in IE 7 (the oldest browser supported where I work). The divs are not side by side.

OP said he did not want to use floats because he did not like them. Well...in my opinion, making good webpages that does not look weird in any browsers should be the maingoal, and you do this by using floats.

Honestly, I can see the problem. Floats are fantastic.

jQuery: Change button text on click

This should work for you:

    $('.SeeMore2').click(function(){
        var $this = $(this);
        $this.toggleClass('SeeMore2');
        if($this.hasClass('SeeMore2')){
            $this.text('See More');         
        } else {
            $this.text('See Less');
        }
});

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

Make code in LaTeX look *nice*

The listings package is quite nice and very flexible (e.g. different sizes for comments and code).

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

its work for me SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(new Date));

Combining a class selector and an attribute selector with jQuery

Combine them. Literally combine them; attach them together without any punctuation.

$('.myclass[reference="12345"]')

Your first selector looks for elements with the attribute value, contained in elements with the class.
The space is being interpreted as the descendant selector.

Your second selector, like you said, looks for elements with either the attribute value, or the class, or both.
The comma is being interpreted as the multiple selector operator — whatever that means (CSS selectors don't have a notion of "operators"; the comma is probably more accurately known as a delimiter).

Can I use tcpdump to get HTTP requests, response header and response body?

Here is another choice: Chaosreader

So I need to debug an application which posts xml to a 3rd party application. I found a brilliant little perl script which does all the hard work – you just chuck it a tcpdump output file, and it does all the manipulation and outputs everything you need...

The script is called chaosreader0.94. See http://www.darknet.org.uk/2007/11/chaosreader-trace-tcpudp-sessions-from-tcpdump/

It worked like a treat, I did the following:

tcpdump host www.blah.com -s 9000 -w outputfile; perl chaosreader0.94 outputfile

Moving uncommitted changes to a new branch

Just move to the new branch. The uncommited changes get carried over.

git checkout -b ABC_1

git commit -m <message>

How to find the socket connection state in C?

I had a similar problem. I wanted to know whether the server is connected to client or the client is connected to server. In such circumstances the return value of the recv function can come in handy. If the socket is not connected it will return 0 bytes. Thus using this I broke the loop and did not have to use any extra threads of functions. You might also use this same if experts feel this is the correct method.

C# ASP.NET MVC Return to Previous Page

Here is just another option you couold apply for ASP NET MVC.

Normally you shoud use BaseController class for each Controller class.

So inside of it's constructor method do following.

public class BaseController : Controller
{
        public BaseController()
        {
            // get the previous url and store it with view model
            ViewBag.PreviousUrl = System.Web.HttpContext.Current.Request.UrlReferrer;
        }
}

And now in ANY view you can do like

<button class="btn btn-success mr-auto" onclick="  window.location.href = '@ViewBag.PreviousUrl'; " style="width:2.5em;"><i class="fa fa-angle-left"></i></button>

Enjoy!

How do you get the length of a string?

A somewhat important distinction is if the element is an input or not. If an input you can use:

$('#selector').val().length;

otherwise if the element is a different html element like a paragraph or list item div etc, you must use

$('#selector').text().length;

Mocha / Chai expect.to.throw not catching thrown errors

I have found a nice way around it:

// The test, BDD style
it ("unsupported site", () => {
    The.function(myFunc)
    .with.arguments({url:"https://www.ebay.com/"})
    .should.throw(/unsupported/);
});


// The function that does the magic: (lang:TypeScript)
export const The = {
    'function': (func:Function) => ({
        'with': ({
            'arguments': function (...args:any) {
                return () => func(...args);
            }
        })
    })
};

It's much more readable then my old version:

it ("unsupported site", () => {
    const args = {url:"https://www.ebay.com/"}; //Arrange
    function check_unsupported_site() { myFunc(args) } //Act
    check_unsupported_site.should.throw(/unsupported/) //Assert
});

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

On the basic question of why openssl is not found: Short answer:Some installation packages for openssl have a default openssl.cnf pre-included. Other packages do not. In the latter case you will include one from the link shown below; You can enter additional user-specifics --DN name,etc-- as needed.

From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:

"OPENSSL LIBRARY CONFIGURATION

Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.

To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.

The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"

So it appears one must self configure openssl.cnf according to your Distinguished Name (DN), along with other entries specific to your use.

Here is the template file from which you can generate openssl.cnf with your specific entries.

One Application actually has a demo installation that includes a demo .cnf file.

Additionally, if you need to programmatically access .cnf files, you can include appropriate headers --openssl/conf.h-- and parse your .cnf files using

CONF_modules_load_file(const char *filename, const char *appname,
                            unsigned long flags);

Here are docs for "CONF_modules_load_file";

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I faced the same problem when after installing Viber. It had all required qt libraries in /opt/viber/plugins/. I checked dependencies of /opt/viber/plugins/platforms/libqxcb.so and found missing dependencies. They were libxcb-render.so.0, libxcb-image.so.0, libxcb-icccm.so.4, libxcb-xkb.so.1 So I resolved my issue by installing missing packages with this libraries:

apt-get install libxcb-xkb1 libxcb-icccm4 libxcb-image0 libxcb-render-util0

Check if an HTML input element is empty or has no value entered by user

The getElementById method returns an Element object that you can use to interact with the element. If the element is not found, null is returned. In case of an input element, the value property of the object contains the string in the value attribute.

By using the fact that the && operator short circuits, and that both null and the empty string are considered "falsey" in a boolean context, we can combine the checks for element existence and presence of value data as follows:

var myInput = document.getElementById("customx");
if (myInput && myInput.value) {
  alert("My input has a value!");
}

How to redirect to another page using AngularJS?

If you want to use a link then: in the html have:

<button type="button" id="btnOpenLine" class="btn btn-default btn-sm" ng-click="orderMaster.openLineItems()">Order Line Items</button>

in the typescript file

public openLineItems() {
if (this.$stateParams.id == 0) {
    this.Flash.create('warning', "Need to save order!", 3000);
    return
}
this.$window.open('#/orderLineitems/' + this.$stateParams.id);

}

I hope you see this example helpful as it was for me along with the other answers.

pip3: command not found but python3-pip is already installed

On Windows 10 install Python from Python.org Once installed add these two paths to PATH env variable C:\Users<your user>\AppData\Local\Programs\Python\Python38 C:\Users<your user>\AppData\Local\Programs\Python\Python38\Scripts

Open command prompt and following command should be working python --version pip --version

Could not open ServletContext resource

Put the things like /src/main/resources/foo/bar.properties and then reference them as classpath:/foo/bar.properties.

How to import a bak file into SQL Server Express

To do this via TSQL (ssms query window or sqlcmd.exe) just run:

RESTORE DATABASE MyDatabase FROM DISK='c:\backups\MyDataBase1.bak'

To do it via GUI - open SSMS, right click on Databases and follow the steps below

enter image description here enter image description here

How to check if running in Cygwin, Mac or Linux?

Ok, here is my way.

osis()
{
    local n=0
    if [[ "$1" = "-n" ]]; then n=1;shift; fi

    # echo $OS|grep $1 -i >/dev/null
    uname -s |grep -i "$1" >/dev/null

    return $(( $n ^ $? ))
}

e.g.

osis Darwin &&
{
    log_debug Detect mac osx
}
osis Linux &&
{
    log_debug Detect linux
}
osis -n Cygwin &&
{
    log_debug Not Cygwin
}

I use this in my dotfiles

Delaying AngularJS route change until model loaded to prevent flicker

Here's a minimal working example which works for Angular 1.0.2

Template:

<script type="text/ng-template" id="/editor-tpl.html">
    Editor Template {{datasets}}
</script>

<div ng-view>

</div>

JavaScript:

function MyCtrl($scope, datasets) {    
    $scope.datasets = datasets;
}

MyCtrl.resolve = {
    datasets : function($q, $http) {
        var deferred = $q.defer();

        $http({method: 'GET', url: '/someUrl'})
            .success(function(data) {
                deferred.resolve(data)
            })
            .error(function(data){
                //actually you'd want deffered.reject(data) here
                //but to show what would happen on success..
                deferred.resolve("error value");
            });

        return deferred.promise;
    }
};

var myApp = angular.module('myApp', [], function($routeProvider) {
    $routeProvider.when('/', {
        templateUrl: '/editor-tpl.html',
        controller: MyCtrl,
        resolve: MyCtrl.resolve
    });
});?
?

http://jsfiddle.net/dTJ9N/3/

Streamlined version:

Since $http() already returns a promise (aka deferred), we actually don't need to create our own. So we can simplify MyCtrl. resolve to:

MyCtrl.resolve = {
    datasets : function($http) {
        return $http({
            method: 'GET', 
            url: 'http://fiddle.jshell.net/'
        });
    }
};

The result of $http() contains data, status, headers and config objects, so we need to change the body of MyCtrl to:

$scope.datasets = datasets.data;

http://jsfiddle.net/dTJ9N/5/

How to include libraries in Visual Studio 2012?

Typically you need to do 5 things to include a library in your project:

1) Add #include statements necessary files with declarations/interfaces, e.g.:

#include "library.h"

2) Add an include directory for the compiler to look into

-> Configuration Properties/VC++ Directories/Include Directories (click and edit, add a new entry)

3) Add a library directory for *.lib files:

-> project(on top bar)/properties/Configuration Properties/VC++ Directories/Library Directories (click and edit, add a new entry)

4) Link the lib's *.lib files

-> Configuration Properties/Linker/Input/Additional Dependencies (e.g.: library.lib;

5) Place *.dll files either:

-> in the directory you'll be opening your final executable from or into Windows/system32

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

"com.jcraft.jsch.JSchException: Auth fail" with working passwords

Example case, when I get file from remote server and save it in local machine
package connector;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

public class Main {

    public static void main(String[] args) throws JSchException, SftpException, IOException {
        // TODO Auto-generated method stub
        String username = "XXXXXX";
        String host = "XXXXXX";
        String passwd = "XXXXXX";
        JSch conn = new JSch();
        Session session = null;
        session = conn.getSession(username, host, 22);
        session.setPassword(passwd);
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        ChannelSftp channel = null;
        channel = (ChannelSftp)session.openChannel("sftp");
        channel.connect();

        channel.cd("/tmp/qtmp");

        InputStream in = channel.get("testScp");
        String lf = "OBJECT_FILE";
        FileOutputStream tergetFile = new FileOutputStream(lf);

        int c;
        while ( (c= in.read()) != -1 ) {
            tergetFile.write(c);
        } 

        in.close();
        tergetFile.close();

        channel.disconnect();
        session.disconnect();   

    }

}

[] and {} vs list() and dict(), which is better?

In the case of difference between [] and list(), there is a pitfall that I haven't seen anyone else point out. If you use a dictionary as a member of the list, the two will give entirely different results:

In [1]: foo_dict = {"1":"foo", "2":"bar"}

In [2]: [foo_dict]
Out [2]: [{'1': 'foo', '2': 'bar'}]

In [3]: list(foo_dict)
Out [3]: ['1', '2'] 

Bootstrap 3 Carousel fading to new slide instead of sliding to new slide

You can achieve a fade effect (instead of sticking with the default slide) using css only. Add these to your stylesheet

.carousel .item {
    -webkit-transition: opacity 3s; 
    -moz-transition: opacity 3s; 
    -ms-transition: opacity 3s; 
    -o-transition: opacity 3s; 
    transition: opacity 3s;
}
.carousel .active.left {
    left:0;opacity:0;z-index:2;
}
.carousel .next {
    left:0;opacity:1;z-index:1;
}

How to set background color of a button in Java GUI?

for(int i=1;i<=9;i++) {
    p3.add(new JButton(""+i) {{
        // initialize the JButton directly
        setBackground(Color.BLACK);
        setForeground(Color.GRAY);
    }});
}

How to split a list by comma not space

I think the canonical method is:

while IFS=, read field1 field2 field3 field4 field5 field6; do 
  do stuff
done < CSV.file

If you don't know or don't care about how many fields there are:

IFS=,
while read line; do
  # split into an array
  field=( $line )
  for word in "${field[@]}"; do echo "$word"; done

  # or use the positional parameters
  set -- $line
  for word in "$@"; do echo "$word"; done

done < CSV.file

How to get my project path?

var requiredPath = Path.GetDirectoryName(Path.GetDirectoryName(
System.IO.Path.GetDirectoryName( 
      System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase )));

redirect to current page in ASP.Net

http://en.wikipedia.org/wiki/Post/Redirect/Get

The most common way to implement this pattern in ASP.Net is to use Response.Redirect(Request.RawUrl)

Consider the differences between Redirect and Transfer. Transfer really isn't telling the browser to forward to a clear form, it's simply returning a cleared form. That may or may not be what you want.

Response.Redirect() does not a waste round trip. If you post to a script that clears the form by Server.Transfer() and reload you will be asked to repost by most browsers since the last action was a HTTP POST. This may cause your users to unintentionally repeat some action, eg. place a second order which will have to be voided later.

Move branch pointer to different commit without checkout

git branch -f <branch-name> [<new-tip-commit>]

If new-tip-commit is omitted it defaults to the current commit.

How do negative margins in CSS work and why is (margin-top:-5 != margin-bottom:5)?

Just to phrase things differently from the great answers above, as that has helped me get an intuitive understanding of negative margins:

A negative margin on an element allows it to eat up the space of its parent container.

Adding a (positive) margin on the bottom doesn't allow the element to do that - it only pushes back whatever element is below.

How to get week numbers from dates?

Base package

Using the function strftime passing the argument %V to obtain the week of the year as decimal number (01–53) as defined in ISO 8601. (More details in the documentarion: ?strftime)

strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V")

Output:

[1] "11" "12" "12" "01"

How do I strip all spaces out of a string in PHP?

If you want to remove all whitespace:

$str = preg_replace('/\s+/', '', $str);

See the 5th example on the preg_replace documentation. (Note I originally copied that here.)

Edit: commenters pointed out, and are correct, that str_replace is better than preg_replace if you really just want to remove the space character. The reason to use preg_replace would be to remove all whitespace (including tabs, etc.).

How to return value from Action()?

You can also take advantage of the fact that a lambda or anonymous method can close over variables in its enclosing scope.

MyType result;

SimpleUsing.DoUsing(db => 
{
  result = db.SomeQuery(); //whatever returns the MyType result
}); 

//do something with result

Best way to structure a tkinter application?

I personally do not use the objected oriented approach, mostly because it a) only get in the way; b) you will never reuse that as a module.

but something that is not discussed here, is that you must use threading or multiprocessing. Always. otherwise your application will be awful.

just do a simple test: start a window, and then fetch some URL or anything else. changes are your UI will not be updated while the network request is happening. Meaning, your application window will be broken. depend on the OS you are on, but most times, it will not redraw, anything you drag over the window will be plastered on it, until the process is back to the TK mainloop.

How to pass variable from jade template file to a script file?

#{} is for escaped string interpolation which automatically escapes the input and is thus more suitable for plain strings rather than JS objects:

script var data = #{JSON.stringify(data)}
<script>var data = {&quot;foo&quot;:&quot;bar&quot;} </script>

!{} is for unescaped code interpolation, which is more suitable for objects:

script var data = !{JSON.stringify(data)}
<script>var data = {"foo":"bar"} </script>

CAUTION: Unescaped code can be dangerous. You must be sure to sanitize any user inputs to avoid cross-site scripting (XSS).

E.g.:

{ foo: 'bar </script><script> alert("xss") //' }

will become:

<script>var data = {"foo":"bar </script><script> alert("xss") //"}</script>

Possible solution: Use .replace(/<\//g, '<\\/')

script var data = !{JSON.stringify(data).replace(/<\//g, '<\\/')}
<script>var data = {"foo":"bar<\/script><script>alert(\"xss\")//"}</script>

The idea is to prevent the attacker to:

  1. Break out of the variable: JSON.stringify escapes the quotes
  2. Break out of the script tag: if the variable contents (which you might not be able to control if comes from the database for ex.) has a </script> string, the replace statement will take care of it

https://github.com/pugjs/pug/blob/355d3dae/examples/dynamicscript.pug

jQuery $(document).ready and UpdatePanels?

Upgrade to jQuery 1.3 and use:

$(function() {

    $('div._Foo').live("mouseover", function(e) {
        // Do something exciting
    });

});

Note: live works with most events, but not all. There is a complete list in the documentation.

How to close <img> tag properly?

Unfortunately the above solutions did not work in my case - maybe because a put the button inside a form-tag. This code ...

<input class="button" type="submit" value=" ">
    <img src="../assets/logo.png" alt="test" />
</input>

... always leads to error (with or without the closing slash of the img tag):

error  Parsing error: x-invalid-end-tag  vue/no-parsing-error

? 1 problem (1 error, 0 warnings)

A kind of workaround that did work was to define the image as background-image by means of css.

The html snippet describes the button only. The value attribute contains a single blank in order to suppress some browsers presenting unwanted default text.

<input class="button" type="submit" value=" " />

the CSS defines the button's background image:

.button {
  display: block;
  width: 6em;
  height: 6em;
  color: white;
  background-color: #639f59;
  padding: 0.4em 1.2em;
  box-shadow: inset 0 -0.6em 1em -0.35em rgba(5, 122, 11, 0.30),
    inset 0 0.6em 2em -0.3em rgba(255, 255, 255, 0.30),
    inset 0 0 0em 0.05em rgba(255, 255, 255, 0.30);
  cursor: pointer;
  background: url("../assets/logo.png") ;
  background-repeat: no-repeat;
  background-size: 6em;
  background-position: center;
  border: 0;
  border-radius: 3em;
}

Delete topic in Kafka 0.8.1.1

Adding to above answers one has to delete the meta data associated with that topic in zookeeper consumer offset path.

bin/zookeeper-shell.sh zookeeperhost:port

rmr /consumers/<sample-consumer-1>/offsets/<deleted-topic>

Otherwise the lag will be negative in kafka-monitoring tools based on zookeeper.

Different names of JSON property during serialization and deserialization

I would bind two different getters/setters pair to one variable:

class Coordinates{
    int red;

    @JsonProperty("red")
    public byte getRed() {
      return red;
    }

    public void setRed(byte red) {
      this.red = red;
    }

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    public void setR(byte red) {
      this.red = red;
    }
}

How does one Display a Hyperlink in React Native App?

Import Linking the module from React Native

import { TouchableOpacity, Linking } from "react-native";

Try it:-

<TouchableOpacity onPress={() => Linking.openURL('http://Facebook.com')}>
     <Text> Facebook </Text>     
</TouchableOpacity>

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in the end of your Index.js need to add this Code:

_x000D_
_x000D_
import React from 'react';_x000D_
import ReactDOM from 'react-dom';_x000D_
import { BrowserRouter  } from 'react-router-dom';_x000D_
_x000D_
import './index.css';_x000D_
import App from './App';_x000D_
_x000D_
import { Provider } from 'react-redux';_x000D_
import { createStore, applyMiddleware, compose, combineReducers } from 'redux';_x000D_
import thunk from 'redux-thunk';_x000D_
_x000D_
///its your redux ex_x000D_
import productReducer from './redux/reducer/admin/product/produt.reducer.js'_x000D_
_x000D_
const rootReducer = combineReducers({_x000D_
    adminProduct: productReducer_x000D_
   _x000D_
})_x000D_
const composeEnhancers = window._REDUX_DEVTOOLS_EXTENSION_COMPOSE_ || compose;_x000D_
const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));_x000D_
_x000D_
_x000D_
const app = (_x000D_
    <Provider store={store}>_x000D_
        <BrowserRouter   basename='/'>_x000D_
            <App />_x000D_
        </BrowserRouter >_x000D_
    </Provider>_x000D_
);_x000D_
ReactDOM.render(app, document.getElementById('root'));
_x000D_
_x000D_
_x000D_

How to get the first and last date of the current year?

In Microsoft SQL Server (T-SQL) this can be done as follows

--beginning of year
select '01/01/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

--end of year
select '12/31/' + LTRIM(STR(YEAR(CURRENT_TIMESTAMP)))

CURRENT_TIMESTAMP - returns the sql server date at the time of execution of the query.

YEAR - gets the year part of the current time stamp.

STR , LTRIM - these two functions are applied so that we can convert this into a varchar that can be concatinated with our desired prefix (in this case it's either first date of the year or the last date of the year). For whatever reason the result generated by the YEAR function has prefixing spaces. To fix them we use the LTRIM function which is left trim.

H2 database error: Database may be already in use: "Locked by another process"

H2 is still running (I can guarantee it). You need to use a TCP connection for multiple users such as ->

<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/C:\Database\Data\production;"/>

OR

DriverManager.getConnection("jdbc:h2:tcp://localhost/server~/dbname","username","password");

It also means you need to start the server in TCP mode. Honesetly, it is pretty straight forward in the documentation.

Force kill the process (javaw.exe for Windows), and make sure that any application that might have started it is shut down. You have an active lock.

Uncaught TypeError: Cannot assign to read only property

When you use Object.defineProperties, by default writable is set to false, so _year and edition are actually read only properties.

Explicitly set them to writable: true:

_year: {
    value: 2004,
    writable: true
},

edition: {
    value: 1,
    writable: true
},

Check out MDN for this method.

writable
true if and only if the value associated with the property may be changed with an assignment operator.
Defaults to false.

Getting value from JQUERY datepicker

You can also try this.

$('#datepickerID').val();

This is the simplest way.

Center fixed div with dynamic width (CSS)

This approach will not limit element's width when using margins in flexbox

top: 0; left: 0;
transform: translate(calc(50vw - 50%));

Also for centering it vertically

top: 0; left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

INSTALL_FAILED_UPDATE_INCOMPATIBLE when I try to install compiled .apk on device

This might be Raised When the Application installed in you device as Different Signature then the Application(apk) you are Trying to install.(in easy words, earlier application is build by "System-A " and now build a Application By "System-B" and trying to install) You can solve this Issues in one or the other ways as showed Below.

Option 1:

   Uninstall the Application in your Device and install the New APK

Option 2:

Note: this option is applicable only if you have the Access to both old and new Systems via which Apk are build respecitively

if you don't want to Remove the APk or its not Allowed then you can get the Debug key, System-A and the same Debug to System-B

steps to take the Debug Key form "System-A"

Go to Terminal enter

./gradlew signingReport

you will get to know your results as Below

Variant: debug Config:
debug Store: /home/user/debug.keystore
Alias: AndroidDebugKey
MD5: CS:7B:E3:51:C5:2E:36:AA:3F:66:BA:ED:40:DB:86:25
SHA1: 2A:BB:C5:4E:64:4E:FE:12:4C:4E:2B:4E:4E:42:4E:4E:4E:4E:63:83
Valid until: Wednesday, May 6, 2048

get the "debug.keystore" file from the location showed above and transfer it to "System-B" then goto

    Android studio >> File >> Project Structure >> SigningConfigs
    set the location of the "debug.keystore" to Store File and then ok

Now build the Apk in your "System-B" and Run it will work

'this' vs $scope in AngularJS controllers

The reason 'addPane' is assigned to this is because of the <pane> directive.

The pane directive does require: '^tabs', which puts the tabs controller object from a parent directive, into the link function.

addPane is assigned to this so that the pane link function can see it. Then in the pane link function, addPane is just a property of the tabs controller, and it's just tabsControllerObject.addPane. So the pane directive's linking function can access the tabs controller object and therefore access the addPane method.

I hope my explanation is clear enough.. it's kind of hard to explain.

Assign format of DateTime with data annotations?

Did you try this?

[DataType(DataType.Date)]

How do I turn off Oracle password expiration?

I will suggest its not a good idea to turn off the password expiration as it can lead to possible threats to confidentiality, integrity and availability of data.

However if you want so.

If you have proper access use following SQL

SELECT username, account_status FROM dba_users;

This should give you result like this.

   USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

SYSTEM                         OPEN
SYS                            OPEN
SDMADM                         OPEN
MARKETPLACE                    OPEN
SCHEMAOWNER                    OPEN
ANONYMOUS                      OPEN
SCHEMAOWNER2                   OPEN
SDMADM2                        OPEN
SCHEMAOWNER1                   OPEN
SDMADM1                        OPEN
HR                             EXPIRED(GRACE)

USERNAME                       ACCOUNT_STATUS
------------------------------ -----------------

APEX_PUBLIC_USER               LOCKED
APEX_040000                    LOCKED
FLOWS_FILES                    LOCKED
XS$NULL                        EXPIRED & LOCKED
OUTLN                          EXPIRED & LOCKED
XDB                            EXPIRED & LOCKED
CTXSYS                         EXPIRED & LOCKED
MDSYS                          EXPIRED & LOCKED

Now you can use Pedro Carriço answer https://stackoverflow.com/a/6777079/2432468

Insertion sort vs Bubble Sort Algorithms

well bubble sort is better than insertion sort only when someone is looking for top k elements from a large list of number i.e. in bubble sort after k iterations you'll get top k elements. However after k iterations in insertion sort, it only assures that those k elements are sorted.

Html.RenderPartial() syntax with Razor

@Html.Partial("NameOfPartialView")

How to change text transparency in HTML/CSS?

Easy! after your:

    <font color=\"black\" face=\"arial\" size=\"4\">

add this one:

    <font style="opacity:.6"> 

you just have to change the ".6" for a decimal number between 1 and 0

What is the difference between char array and char pointer in C?

char p[3] = "hello" ? should be char p[6] = "hello" remember there is a '\0' char in the end of a "string" in C.

anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.

Bootstrap date time picker

In order to run the bootstrap date time picker you need to include Moment.js as well. Here is the working code sample in your case.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
    <html lang="en">_x000D_
    <head>_x000D_
      <meta charset="utf-8">_x000D_
      <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
      <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    _x000D_
    _x000D_
      <!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
      <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
      <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
    _x000D_
    </head>_x000D_
    _x000D_
    _x000D_
    <body>_x000D_
    _x000D_
       <div class="container">_x000D_
          <div class="row">_x000D_
            <div class='col-sm-6'>_x000D_
                <div class="form-group">_x000D_
                    <div class='input-group date' id='datetimepicker1'>_x000D_
                        <input type='text' class="form-control" />_x000D_
                        <span class="input-group-addon">_x000D_
                            <span class="glyphicon glyphicon-calendar"></span>_x000D_
                        </span>_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
            <script type="text/javascript">_x000D_
                $(function () {_x000D_
                    $('#datetimepicker1').datetimepicker();_x000D_
                });_x000D_
            </script>_x000D_
          </div>_x000D_
       </div>_x000D_
    _x000D_
    _x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Spring boot Security Disable security

What also seems to work fine is creating a file application-dev.properties that contains:

security.basic.enabled=false
management.security.enabled=false

If you then start your Spring Boot app with the dev profile, you don't need to log on.

Explicit vs implicit SQL joins

Performance wise, they are exactly the same (at least in SQL Server).

PS: Be aware that the IMPLICIT OUTER JOIN syntax is deprecated since SQL Server 2005. (The IMPLICIT INNER JOIN syntax as used in the question is still supported)

Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing

How to convert a single char into an int

Any problems with the following way of doing it?

int CharToInt(const char c)
{
    switch (c)
    {
    case '0':
        return 0;
    case '1':
        return 1;
    case '2':
        return 2;
    case '3':
        return 3;
    case '4':
        return 4;
    case '5':
        return 5;
    case '6':
        return 6;
    case '7':
        return 7;
    case '8':
        return 8;
    case '9':
        return 9;
    default:
        return 0;
    }
}

List of all users that can connect via SSH

Any user with a valid shell in /etc/passwd can potentially login. If you want to improve security, set up SSH with public-key authentication (there is lots of info on the web on doing this), install a public key in one user's ~/.ssh/authorized_keys file, and disable password-based authentication. This will prevent anybody except that one user from logging in, and will require that the user have in their possession the matching private key. Make sure the private key has a decent passphrase.

To prevent bots from trying to get in, run SSH on a port other than 22 (i.e. 3456). This doesn't improve security but prevents script-kiddies and bots from cluttering up your logs with failed attempts.

Pytorch reshape tensor dimension

you might use

a.view(1,5)
Out: 

 1  2  3  4  5
[torch.FloatTensor of size 1x5]

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

Here is the one of methods to avoid duplicates into javascript array...and it supports for strings and numbers...

 var unique = function(origArr) {
    var newArray = [],
        origLen = origArr.length,
        found,
        x = 0; y = 0;

    for ( x = 0; x < origLen; x++ ) {
        found = undefined;
        for ( y = 0; y < newArray.length; y++ ) {
            if ( origArr[x] === newArray[y] ) found = true;
        }
        if ( !found) newArray.push( origArr[x] );    
    }
   return newArray;
}

check this fiddle..

Current Subversion revision command

Nobody mention for Windows world SubWCRev, which, properly used, can substitute needed data into the needed places automagically, if script call SubWCRev in form SubWCRev WC_PATH TPL-FILE READY-FILE

Sample of my post-commit hook (part of)

SubWCRev.exe CustomLocations Builder.tpl  z:\Builder.bat
...
call z:\Builder.bat

where my Builder.tpl is

svn.exe export trunk z:\trunk$WCDATE=%Y%m%d$-r$WCREV$

as result, I have every time bat-file with variable part - name of dir - which corresponds to the metadata of Working Copy

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

The problem here involves type casting.

When you add int and long,

  1. The int object is casted to long & both are added and you get long object.
  2. but long object cannot be implicitly casted to int. So, you have to do that explicitly.

But += is coded in such a way that it does type casting. i=(int)(i+m)

Google Map API - Removing Markers

You can try this

    markers[markers.length-1].setMap(null);

Hope it works.