Programs & Examples On #Mysql error 1451

MySql error #1451 - Cannot delete or update a parent row: a foreign key constraint fails

org.apache.jasper.JasperException: Unable to compile class for JSP:

Please remove the servlet jar from web project,as any how, the application/web server already had.

How do I add a simple jQuery script to WordPress?

In WordPress, the correct way to include the scripts in your website is by using the following functions.

wp_register_script( $handle, $src )
wp_enqueue_script( $handle, $src )

These functions are called inside the hook wp_enqueue_script.

For more details and examples, you can check Adding JS files in Wordpress using wp_register_script & wp_enqueue_script

Example:

function webolute_theme_scripts() {
    wp_register_script( 'script-name', get_template_directory_uri() . '/js/example.js', array('jquery'), '1.0.0', true );
    wp_enqueue_script( 'script-name' );
}
add_action( 'wp_enqueue_scripts', 'webolute_theme_scripts' );

In Visual Studio C++, what are the memory allocation representations?

Regarding 0xCC and 0xCD in particular, these are relics from the Intel 8088/8086 processor instruction set back in the 1980s. 0xCC is a special case of the software interrupt opcode INT 0xCD. The special single-byte version 0xCC allows a program to generate interrupt 3.

Although software interrupt numbers are, in principle, arbitrary, INT 3 was traditionally used for the debugger break or breakpoint function, a convention which remains to this day. Whenever a debugger is launched, it installs an interrupt handler for INT 3 such that when that opcode is executed the debugger will be triggered. Typically it will pause the currently running programming and show an interactive prompt.

Normally, the x86 INT opcode is two bytes: 0xCD followed by the desired interrupt number from 0-255. Now although you could issue 0xCD 0x03 for INT 3, Intel decided to add a special version--0xCC with no additional byte--because an opcode must be only one byte in order to function as a reliable 'fill byte' for unused memory.

The point here is to allow for graceful recovery if the processor mistakenly jumps into memory that does not contain any intended instructions. Multi-byte instructions aren't suited this purpose since an erroneous jump could land at any possible byte offset where it would have to continue with a properly formed instruction stream.

Obviously, one-byte opcodes work trivially for this, but there can also be quirky exceptions: for example, considering the fill sequence 0xCDCDCDCD (also mentioned on this page), we can see that it's fairly reliable since no matter where the instruction pointer lands (except perhaps the last filled byte), the CPU can resume executing a valid two-byte x86 instruction CD CD, in this case for generating software interrupt 205 (0xCD).

Weirder still, whereas CD CC CD CC is 100% interpretable--giving either INT 3 or INT 204--the sequence CC CD CC CD is less reliable, only 75% as shown, but generally 99.99% when repeated as an int-sized memory filler.

page from contemporaneous 8088/8086 instruction set manual showing INT instruction
Macro Assembler Reference, 1987

onNewIntent() lifecycle and registered listeners

Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.

OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.

You can invoke onNewIntent always by putting it into onCreate method like

@Override
public void onCreate(Bundle savedState){
    super.onCreate(savedState);
    onNewIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
  super.onNewIntent(intent);
  //code
}

Select unique values with 'select' function in 'dplyr' library

Just to add to the other answers, if you would prefer to return a vector rather than a dataframe, you have the following options:

dplyr < 0.7.0

Enclose the dplyr functions in a parentheses and combine it with $ syntax:

(mtcars %>% distinct(cyl))$cyl

dplyr >= 0.7.0

Use the pull verb:

mtcars %>% distinct(cyl) %>% pull()

How to pass data from 2nd activity to 1st activity when pressed back? - android

Start Activity2 with startActivityForResult and use setResult method for sending data back from Activity2 to Activity1. In Activity1 you will need to override onActivityResult for updating TextView with EditText data from Activity2.

For example:

In Activity1, start Activity2 as:

Intent i = new Intent(this, Activity2.class);
startActivityForResult(i, 1);

In Activity2, use setResult for sending data back:

Intent intent = new Intent();
intent.putExtra("editTextValue", "value_here")
setResult(RESULT_OK, intent);        
finish();

And in Activity1, receive data with onActivityResult:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 1) {
         if(resultCode == RESULT_OK) {
             String strEditText = data.getStringExtra("editTextValue");
         }     
    }
} 

If you can, also use SharedPreferences for sharing data between Activities.

Can I change the fill color of an svg path with CSS?

It's possible to change the path fill color of the svg. See below for the CSS snippet:

  1. To apply the color for all the path: svg > path{ fill: red }

  2. To apply for the first d path: svg > path:nth-of-type(1){ fill: green }

  3. To apply for the second d path: svg > path:nth-of-type(2){ fill: green}

  4. To apply for the different d path, change only the path number:
    svg > path:nth-of-type(${path_number}){ fill: green}

  5. To support the CSS in Angular 2 to 8, use the encapsulation concept:

:host::ng-deep svg path:nth-of-type(1){
        fill:red;
    }

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

How do I delete an entity from symfony2

DELETE FROM ... WHERE id=...;

protected function templateRemove($id){
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));

            if ($entity != null){
                $em->remove($entity);
                $em->flush();
            }
        }

Extract a substring using PowerShell

Since the string is not complex, no need to add RegEx strings. A simple match will do the trick

$line = "----start----Hello World----end----"
$line -match "Hello World"
$matches[0]
Hello World

$result = $matches[0]
$result
Hello World

Short circuit Array.forEach like calling break

I use nullhack for that purpose, it tries to access property of null, which is an error:

try {
  [1,2,3,4,5]
  .forEach(
    function ( val, idx, arr ) {
      if ( val == 3 ) null.NULLBREAK;
    }
  );
} catch (e) {
  // e <=> TypeError: null has no properties
}
//

What is dynamic programming?

Dynamic programming is a technique used to avoid computing multiple times the same subproblem in a recursive algorithm.

Let's take the simple example of the Fibonacci numbers: finding the n th Fibonacci number defined by

Fn = Fn-1 + Fn-2 and F0 = 0, F1 = 1

Recursion

The obvious way to do this is recursive:

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1

    return fibonacci(n - 1) + fibonacci(n - 2)

Dynamic Programming

  • Top Down - Memoization

The recursion does a lot of unnecessary calculations because a given Fibonacci number will be calculated multiple times. An easy way to improve this is to cache the results:

cache = {}

def fibonacci(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    if n in cache:
        return cache[n]

    cache[n] = fibonacci(n - 1) + fibonacci(n - 2)

    return cache[n]
  • Bottom-Up

A better way to do this is to get rid of the recursion all-together by evaluating the results in the right order:

cache = {}

def fibonacci(n):
    cache[0] = 0
    cache[1] = 1

    for i in range(2, n + 1):
        cache[i] = cache[i - 1] +  cache[i - 2]

    return cache[n]

We can even use constant space and store only the necessary partial results along the way:

def fibonacci(n):
  fi_minus_2 = 0
  fi_minus_1 = 1

  for i in range(2, n + 1):
      fi = fi_minus_1 + fi_minus_2
      fi_minus_1, fi_minus_2 = fi, fi_minus_1

  return fi
  • How apply dynamic programming?

    1. Find the recursion in the problem.
    2. Top-down: store the answer for each subproblem in a table to avoid having to recompute them.
    3. Bottom-up: Find the right order to evaluate the results so that partial results are available when needed.

Dynamic programming generally works for problems that have an inherent left to right order such as strings, trees or integer sequences. If the naive recursive algorithm does not compute the same subproblem multiple times, dynamic programming won't help.

I made a collection of problems to help understand the logic: https://github.com/tristanguigue/dynamic-programing

Format a JavaScript string using placeholders and an object of substitutions?

Here is another way of doing this by using es6 template literals dynamically at runtime.

_x000D_
_x000D_
const str = 'My name is ${name} and my age is ${age}.'_x000D_
const obj = {name:'Simon', age:'33'}_x000D_
_x000D_
_x000D_
const result = new Function('const {' + Object.keys(obj).join(',') + '} = this.obj;return `' + str + '`').call({obj})_x000D_
_x000D_
document.body.innerHTML = result
_x000D_
_x000D_
_x000D_

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

It might be obvious, but make sure that you are sending to the parser URL object not a String containing www adress. This will not work:

    ObjectMapper mapper = new ObjectMapper();
    String www = "www.sample.pl";
    Weather weather = mapper.readValue(www, Weather.class);

But this will:

    ObjectMapper mapper = new ObjectMapper();
    URL www = new URL("http://www.oracle.com/");
    Weather weather = mapper.readValue(www, Weather.class);

ubuntu "No space left on device" but there is tons of space

It's possible that you've run out of memory or some space elsewhere and it prompted the system to mount an overflow filesystem, and for whatever reason, it's not going away.

Try unmounting the overflow partition:

umount /tmp

or

umount overflow

pull access denied repository does not exist or may require docker login

I solved this by inserting a language at the front of the docker image

FROM python:3.7-alpine

Accessing UI (Main) Thread safely in WPF

You can use

Dispatcher.Invoke(Delegate, object[])

on the Application's (or any UIElement's) dispatcher.

You can use it for example like this:

Application.Current.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

or

someControl.Dispatcher.Invoke(new Action(() => { /* Your code here */ }));

Gradle sync failed: failed to find Build Tools revision 24.0.0 rc1

Another thing is that all libraries from google (e.g. support lib, CardView and etc.) should have identical versions

Create a folder inside documents folder in iOS apps

This works fine for me,

NSFileManager *fm = [NSFileManager defaultManager];
NSArray *appSupportDir = [fm URLsForDirectory:NSDocumentsDirectory inDomains:NSUserDomainMask];
NSURL* dirPath = [[appSupportDir objectAtIndex:0] URLByAppendingPathComponent:@"YourFolderName"];

NSError*    theError = nil; //error setting
if (![fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES
                           attributes:nil error:&theError])
{
   NSLog(@"not created");
}

Is it possible to refresh a single UITableViewCell in a UITableView?

I need the upgrade cell but I want close the keyboard. If I use

let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()

the keyboard disappear

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Working solution for heroku is here http://kennethjiang.blogspot.com/2014/07/set-up-cors-in-cloudfront-for-custom.html (quotes follow):

Below is exactly what you can do if you are running your Rails app in Heroku and using Cloudfront as your CDN. It was tested on Ruby 2.1 + Rails 4, Heroku Cedar stack.

Add CORS HTTP headers (Access-Control-*) to font assets

  • Add gem font_assets to Gemfile .
  • bundle install
  • Add config.font_assets.origin = '*' to config/application.rb . If you want more granular control, you can add different origin values to different environment, e.g., config/config/environments/production.rb
  • curl -I http://localhost:3000/assets/your-custom-font.ttf
  • Push code to Heroku.

Configure Cloudfront to forward CORS HTTP headers

In Cloudfront, select your distribution, under "behavior" tab, select and edit the entry that controls your fonts delivery (for most simple Rails app you only have 1 entry here). Change Forward Headers from "None" to "Whilelist". And add the following headers to whitelist:

Access-Control-Allow-Origin
Access-Control-Allow-Methods
Access-Control-Allow-Headers
Access-Control-Max-Age

Save it and that's it!

Caveat: I found that sometimes Firefox wouldn't not refresh the fonts even if CORS error is gone. In this case keep refreshing the page a few times to convince Firefox that you are really determined.

How can I pass arguments to anonymous functions in JavaScript?

<input type="button" value="Click me" id="myButton" />

<script type="text/javascript">
    var myButton = document.getElementById("myButton");

    myButton.myMessage = "it's working";

    myButton.onclick = function() { alert(this.myMessage); };


</script>

This works in my test suite which includes everything from IE6+. The anonymous function is aware of the object which it belongs to therefore you can pass data with the object that's calling it ( in this case myButton ).

How to switch databases in psql?

\l for databases \c DatabaseName to switch to db \df for procedures stored in particular database

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

jQuery OR Selector?

If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:

element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');

which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:

element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];

which will return the first found element.

I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:

element = $('ul#someList').find('li.active, li:first')[0] 

which will return any li with a class of active or, should there be none, will just return the last li.

Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.

How to deal with "data of class uneval" error from ggplot2?

This could also occur if you refer to a variable in the data.frame that doesn't exist. For example, recently I forgot to tell ddply to summarize by one of my variables that I used in geom_line to specify line color. Then, ggplot didn't know where to find the variable I hadn't created in the summary table, and I got this error.

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

How to add items into a numpy array

Appending a single scalar could be done a bit easier as already shown (and also without converting to float) by expanding the scalar to a python-list-type:

import numpy as np
a = np.array([[1,3,4],[1,2,3],[1,2,1]])
x = 10

b = np.hstack ((a, [[x]] * len (a) ))

returns b as:

array([[ 1,  3,  4, 10],
       [ 1,  2,  3, 10],
       [ 1,  2,  1, 10]])

Appending a row could be done by:

c = np.vstack ((a, [x] * len (a[0]) ))

returns c as:

array([[ 1,  3,  4],
       [ 1,  2,  3],
       [ 1,  2,  1],
       [10, 10, 10]])

How to empty (clear) the logcat buffer in Android

For anyone coming to this question wondering how to do this in Eclipse, You can remove the displayed text from the logCat using the button provided (often has a red X on the icon)

Replace the single quote (') character from a string

As for how to represent a single apostrophe as a string in Python, you can simply surround it with double quotes ("'") or you can escape it inside single quotes ('\'').

To remove apostrophes from a string, a simple approach is to just replace the apostrophe character with an empty string:

>>> "didn't".replace("'", "")
'didnt'

Sending JSON object to Web API

Change:

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

To:

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

And in your controller you do this:

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

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

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

Tomcat: java.lang.IllegalArgumentException: Invalid character found in method name. HTTP method names must be tokens

I received this exception unrelated to any TLS issues. In my case the Content-Length header value did not match the body length.

How to create a new schema/new user in Oracle Database 11g?

It's a working example:

CREATE USER auto_exchange IDENTIFIED BY 123456;
GRANT RESOURCE TO auto_exchange;
GRANT CONNECT TO auto_exchange;
GRANT CREATE VIEW TO auto_exchange;
GRANT CREATE SESSION TO auto_exchange;
GRANT UNLIMITED TABLESPACE TO auto_exchange;

How to get the type of T from a member of a generic class or method?

Consider this: I use it to export 20 typed list by same way:

private void Generate<T>()
{
    T item = (T)Activator.CreateInstance(typeof(T));

    ((T)item as DemomigrItemList).Initialize();

    Type type = ((T)item as DemomigrItemList).AsEnumerable().FirstOrDefault().GetType();
    if (type == null) return;
    if (type != typeof(account)) //account is listitem in List<account>
    {
        ((T)item as DemomigrItemList).CreateCSV(type);
    }
}

Android API 21 Toolbar Padding

A combination of

android:padding="0dp" In the xml for the Toolbar

and

mToolbar.setContentInsetsAbsolute(0, 0) In the code

This worked for me.

C++ string to double conversion

#include <string>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.')) // if is equal
n/=pow(10,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]-48) * pow(10,s.size()-1-x - y) );
return n;
}

or

//In case you want to convert from different bases.
#include <string>
#include <iostream>
#include <cmath>
double _string_to_double(std::string s,unsigned short radix){
double n = 0;
for (unsigned short x = s.size(), y = 0;x>0;)
if(!(s[--x] ^ '.'))
n/=pow(radix,s.size()-1-x), y+= s.size()-x;
else
    n+=( (s[x]- (s[x]<='9' ? '0':'0'+7)   ) * pow(radix,s.size()-1-x - y) );
return n;
}
int main(){
std::cout<<_string_to_double("10.A",16)<<std::endl;//Prints 16.625
std::cout<<_string_to_double("1001.1",2)<<std::endl;//Prints 9.5
std::cout<<_string_to_double("123.4",10)<<std::endl;//Prints 123.4
return 0;
}

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

SQL Server convert select a column and convert it to a string

SELECT  CAST(<COLUMN Name> AS VARCHAR(3)) + ','
FROM    <TABLE Name>
FOR     XML PATH('')

Create normal zip file programmatically

You should look into Zip Packages

They are a more structured version of normal ZIP archives, requiring some meta stuff in the root. So other ZIP tools can open a package, but the Sysytem.IO.Packaging API can not open all ZIP files.

Access iframe elements in JavaScript

You should access frames from window and not document

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

Simplest way to detect a pinch

Think about what a pinch event is: two fingers on an element, moving toward or away from each other. Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:

(ontouchstart event)

if (e.touches.length === 2) {
    scaling = true;
    pinchStart(e);
}

(ontouchmove event)

if (scaling) {
    pinchMove(e);
}

(ontouchend event)

if (scaling) {
    pinchEnd(e);
    scaling = false;
}

To get the distance between the two fingers, use the hypot function:

var dist = Math.hypot(
    e.touches[0].pageX - e.touches[1].pageX,
    e.touches[0].pageY - e.touches[1].pageY);

What is correct media query for IPad Pro?

/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.

Request format is unrecognized for URL unexpectedly ending in

Found a solution on this website

All you need is to add the following to your web.config

<configuration>
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
        <add name="HttpPost"/>
      </protocols>
    </webServices>
  </system.web>
</configuration>

More info from Microsoft

can't start MySql in Mac OS 10.6 Snow Leopard

Have you considered installing MacPorts 1.8.0 (release candidate), and keeping MySQL up-to-date that way? That will build MySQL for the architecture and OS that you're using, rather than installing a 10.5 version on 10.6.

How do I execute a stored procedure once for each row returned by query?

You can do it with a dynamic query.

declare @cadena varchar(max) = ''
select @cadena = @cadena + 'exec spAPI ' + ltrim(id) + ';'
from sysobjects;
exec(@cadena);

MySQL WHERE: how to write "!=" or "not equals"?

The != operator most certainly does exist! It is an alias for the standard <> operator.

Perhaps your fields are not actually empty strings, but instead NULL?

To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

Which Radio button in the group is checked?

If you want to get the index of the selected radio button inside a control you can use this method:

public static int getCheckedRadioButton(Control c)
{
    int i;
    try
    {
        Control.ControlCollection cc = c.Controls;
        for (i = 0; i < cc.Count; i++)
        {
            RadioButton rb = cc[i] as RadioButton;
            if (rb.Checked)
            {
                return i;
            }
        }
    }
    catch
    {
        i = -1;
    }
    return i;
}

Example use:

int index = getCheckedRadioButton(panel1);

The code isn't that well tested, but it seems the index order is from left to right and from top to bottom, as when reading a text. If no radio button is found, the method returns -1.

Update: It turned out my first attempt didn't work if there's no radio button inside the control. I added a try and catch block to fix that, and the method now seems to work.

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

How to write to a file, using the logging Python module?

import sys
import logging

from util import reducer_logfile
logging.basicConfig(filename=reducer_logfile, format='%(message)s',
                    level=logging.INFO, filemode='w')

syntax error: unexpected token <

Removing this line from my code solved my problem.

header("Content-Type: application/json; charset=UTF-8"); 

How to add element in List while iterating in java?

To help with this I created a function to make this more easy to achieve it.

public static <T> void forEachCurrent(List<T> list, Consumer<T> action) {
    final int size = list.size();
    for (int i = 0; i < size; i++) {
        action.accept(list.get(i));
    }
}

Example

    List<String> l = new ArrayList<>();
    l.add("1");
    l.add("2");
    l.add("3");
    forEachCurrent(l, e -> {
        l.add(e + "A");
        l.add(e + "B");
        l.add(e + "C");
    });
    l.forEach(System.out::println);

Do you recommend using semicolons after every statement in JavaScript?

Yes, you should use semicolons after every statement in JavaScript.

Making a triangle shape using xml definitions?

I provide this customView below if you don't want to hack xml. Please have a try.


/**
 * TriangleView
 *
 * @author Veer
 * @date 2020-09-03
 */
class TriangleView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {
    private var triangleColor: Int = 0
    private var direction = Direction.Bottom

    private val paint by lazy {
        Paint().apply {
            isAntiAlias = true
            style = Paint.Style.FILL
            color = triangleColor
        }
    }

    init {
        initStyle(context, attrs, defStyleAttr)
    }

    private fun initStyle(
        context: Context,
        attrs: AttributeSet?,
        defStyleAttr: Int
    ) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.TriangleView, defStyleAttr, 0)
        with(ta) {
            triangleColor =
                getColor(R.styleable.TriangleView_triangle_background, Color.parseColor("#000000"))

            val directionValue =
                getInt(R.styleable.TriangleView_triangle_direction, Direction.Bottom.value)
            direction = when (directionValue) {
                Direction.Top.value -> Direction.Top
                Direction.Bottom.value -> Direction.Bottom
                Direction.Left.value -> Direction.Left
                Direction.Right.value -> Direction.Right
                else -> Direction.Bottom
            }

            recycle()
        }
    }

    override fun onDraw(canvas: Canvas) {
        calculatePath(direction).let {
            canvas.drawPath(it, paint)
        }
    }

    private fun calculatePath(direction: Direction): Path {
        var p1: Point? = null
        var p2: Point? = null
        var p3: Point? = null

        val width = width
        val height = height

        when (direction) {
            Direction.Top -> {
                p1 = Point(0, height)
                p2 = Point(width / 2, 0)
                p3 = Point(width, height)
            }
            Direction.Bottom -> {
                p1 = Point(0, 0)
                p2 = Point(width / 2, height)
                p3 = Point(width, 0)
            }
            Direction.Left -> {
                p1 = Point(width, 0)
                p2 = Point(0, height / 2)
                p3 = Point(width, height)
            }
            Direction.Right -> {
                p1 = Point(0, 0)
                p2 = Point(width, height / 2)
                p3 = Point(0, height)
            }
        }

        val path = Path()
        path.moveTo(p1.x.toFloat(), p1.y.toFloat())
        path.lineTo(p2.x.toFloat(), p2.y.toFloat())
        path.lineTo(p3.x.toFloat(), p3.y.toFloat())
        return path
    }

    private enum class Direction(val value: Int) {
        Top(0),
        Bottom(1),
        Left(2),
        Right(3)
    }
}

<declare-styleable name="TriangleView">
    <attr name="triangle_direction" format="enum">
        <enum name="top" value="0" />
        <enum name="bottom" value="1" />
        <enum name="left" value="2" />
        <enum name="right" value="3" />
    </attr>
    <attr name="triangle_background" format="reference|color" />
</declare-styleable>

How to URL encode a string in Ruby

I was originally trying to escape special characters in a file name only, not on the path, from a full URL string.

ERB::Util.url_encode didn't work for my use:

helper.send(:url_encode, "http://example.com/?a=\11\15")
# => "http%3A%2F%2Fexample.com%2F%3Fa%3D%09%0D"

Based on two answers in "Why is URI.escape() marked as obsolete and where is this REGEXP::UNSAFE constant?", it looks like URI::RFC2396_Parser#escape is better than using URI::Escape#escape. However, they both are behaving the same to me:

URI.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"
URI::Parser.new.escape("http://example.com/?a=\11\15")
# => "http://example.com/?a=%09%0D"

Before and After Suite execution hook in jUnit 4.x

Provided that all your tests may extend a "technical" class and are in the same package, you can do a little trick :

public class AbstractTest {
  private static int nbTests = listClassesIn(<package>).size();
  private static int curTest = 0;

  @BeforeClass
  public static void incCurTest() { curTest++; }

  @AfterClass
  public static void closeTestSuite() {
      if (curTest == nbTests) { /*cleaning*/ }             
  }
}

public class Test1 extends AbstractTest {
   @Test
   public void check() {}
}
public class Test2 extends AbstractTest {
   @Test
   public void check() {}
}

Be aware that this solution has a lot of drawbacks :

  • must execute all tests of the package
  • must subclass a "techincal" class
  • you can not use @BeforeClass and @AfterClass inside subclasses
  • if you execute only one test in the package, cleaning is not done
  • ...

For information: listClassesIn() => How do you find all subclasses of a given class in Java?

Python Script Uploading files via FTP

You can use the below function. I haven't tested it yet, but it should work fine. Remember the destination is a directory path where as source is complete file path.

import ftplib
import os

def uploadFileFTP(sourceFilePath, destinationDirectory, server, username, password):
    myFTP = ftplib.FTP(server, username, password)
    if destinationDirectory in [name for name, data in list(remote.mlsd())]:
        print "Destination Directory does not exist. Creating it first"
        myFTP.mkd(destinationDirectory)
    # Changing Working Directory
    myFTP.cwd(destinationDirectory)
    if os.path.isfile(sourceFilePath):
        fh = open(sourceFilePath, 'rb')
        myFTP.storbinary('STOR %s' % f, fh)
        fh.close()
    else:
        print "Source File does not exist"

Should IBOutlets be strong or weak under ARC?

WARNING, OUTDATED ANSWER: this answer is not up to date as per WWDC 2015, for the correct answer refer to the accepted answer (Daniel Hall) above. This answer will stay for record.


Summarized from the developer library:

From a practical perspective, in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak, except for those from File’s Owner to top-level objects in a nib file (or, in iOS, a storyboard scene) which should be strong. Outlets that you create will therefore typically be weak by default, because:

  • Outlets that you create to, for example, subviews of a view controller’s view or a window controller’s window, are arbitrary references between objects that do not imply ownership.

  • The strong outlets are frequently specified by framework classes (for example, UIViewController’s view outlet, or NSWindowController’s window outlet).

    @property (weak) IBOutlet MyView *viewContainerSubview;
    @property (strong) IBOutlet MyOtherClass *topLevelObject;
    

No restricted globals

Try adding window before location (i.e. window.location).

CS0234: Mvc does not exist in the System.Web namespace

I tried all these answers, even closed Visual Studio and deleted all bin directories.

After starting it up again the MVC reference appeared to have a yellow exclamation mark on it, so I removed it and added it again.

Now it works, without copy local.

"The POM for ... is missing, no dependency information available" even though it exists in Maven Repository

In my case the reason was since the remote repo artifact (non-central) had dependencies from the Maven Central in the .pom file, and the older version of mvn (older than 3.6.0) was used. So, it tried to check the Maven Central artifacts mentioned in the remote repo's .pom for the specific artifact I've added to my dependencies and faced the Maven Central http access issue behind the scenes (I believe the same as described there: Maven dependencies are failing with a 501 error - that is about using https access to Maven Central by default and prohibiting the http access).

Using more recent Maven (from 3.1 to 3.6.0) made it use https to check Maven Central repo dependencies mentioned in the .pom files of the remote repositories and I no longer face the issue.

Selenium Error - The HTTP request to the remote WebDriver timed out after 60 seconds

I had a similar issue using the Chrome driver (v2.23) / running the tests thru TeamCity. I was able to fix the issue by adding the "no-sandbox" flag to the Chrome options:

var options = new ChromeOptions();
options.AddArgument("no-sandbox");

I'm not sure if there is a similar option for the FF driver. From what I understand the issue has something to do with TeamCity running Selenium under the SYSTEM account.

Set drawable size programmatically

Specify the size with setBounds(), ie for a 50x50 size use

drawable.setBounds(0, 0, 50, 50);

public void setBounds (int left, int top, int right, int bottom)

Find character position and update file name

I know this thread is a bit old but, I was looking for something similar and could not find it. Here's what I came up with. I create a string object using the .Net String class to expose all the methods normally found if using C#

[System.String]$myString
 $myString = "237801_201011221155.xml"
 $startPos = $myString.LastIndexOf("_") + 1 # Do not include the "_" character
 $subString = $myString.Substring($startPos,$myString.Length - $startPos)

Result: 201011221155.xml

DataTables: Cannot read property style of undefined

POSSIBLE CAUSES

  • Number of th elements in the table header or footer differs from number of columns in the table body or defined using columns option.
  • Attribute colspan is used for th element in the table header.
  • Incorrect column index specified in columnDefs.targets option.

SOLUTIONS

  • Make sure that number of th elements in the table header or footer matches number of columns defined in the columns option.
  • If you use colspan attribute in the table header, make sure you have at least two header rows and one unique th element for each column. See Complex header for more information.
  • If you use columnDefs.targets option, make sure that zero-based column index refers to existing columns.

LINKS

See jQuery DataTables: Common JavaScript console errors - TypeError: Cannot read property ‘style’ of undefined for more information.

Add (insert) a column between two columns in a data.frame

You can use the append() function to insert items into vectors or lists (dataframes are lists). Simply:

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))

df <- as.data.frame(append(df, list(d=df$b+df$c), after=2))

Or, if you want to specify the position by name use which:

df <- as.data.frame(append(df, list(d=df$b+df$c), after=which(names(df)=="b")))

How does the Python's range function work?

range(x) returns a list of numbers from 0 to x - 1.

>>> range(1)
[0]
>>> range(2)
[0, 1]
>>> range(3)
[0, 1, 2]
>>> range(4)
[0, 1, 2, 3]

for i in range(x): executes the body (which is print i in your first example) once for each element in the list returned by range(). i is used inside the body to refer to the “current” item of the list. In that case, i refers to an integer, but it could be of any type, depending on the objet on which you loop.

Using LIKE in an Oracle IN clause

Just to add on @Lukas Eder answer.

An improvement to avoid creating tables and inserting values (we could use select from dual and unpivot to achieve the same result "on the fly"):

with all_likes as  
(select * from 
    (select '%val1%' like_1, '%val2%' like_2, '%val3%' like_3, '%val4%' as like_4, '%val5%' as like_5 from dual)
    unpivot (
     united_columns for subquery_column in ("LIKE_1", "LIKE_2", "LIKE_3", "LIKE_4", "LIKE_5"))
  )
    select * from tbl
    where exists (select 1 from all_likes where tbl.my_col like all_likes.united_columns)

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

How can I see normal print output created during pytest run?

pytest --capture=tee-sys was recently added (v5.4.0). You can capture as well as see the output on stdout/err.

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

SQL: how to select a single id ("row") that meets multiple criteria from a single column

Try this:

Select user_id
from yourtable
where ancestry in ('England', 'France', 'Germany')
group by user_id
having count(user_id) = 3

The last line means the user's ancestry has all 3 countries.

Unable to establish SSL connection, how do I fix my SSL cert?

This problem happened for me only in special cases, when I called website from some internet providers,

I've configured only ip v4 in VirtualHost configuration of apache, but some of router use ip v6, and when I added ip v6 to apache config the problem solved.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

What is the difference between UTF-8 and ISO-8859-1?

My reason for researching this question was from the perspective, is in what way are they compatible. Latin1 charset (iso-8859) is 100% compatible to be stored in a utf8 datastore. All ascii & extended-ascii chars will be stored as single-byte.

Going the other way, from utf8 to Latin1 charset may or may not work. If there are any 2-byte chars (chars beyond extended-ascii 255) they will not store in a Latin1 datastore.

Get the time of a datetime using T-SQL?

You can try the following code to get time as HH:MM format:

 SELECT CONVERT(VARCHAR(5),getdate(),108)

What is the difference between YAML and JSON?

I find YAML to be easier on the eyes: less parenthesis, "" etc. Although there is the annoyance of tabs in YAML... but one gets the hang of it.

In terms of performance/resources, I wouldn't expect big differences between the two.

Futhermore, we are talking about configuration files and so I wouldn't expect a high frequency of encode/decode activity, no?

How to specify a local file within html using the file: scheme?

The file: URL scheme refers to a file on the client machine. There is no hostname in the file: scheme; you just provide the path of the file. So, the file on your local machine would be file:///~User/2ndFile.html. Notice the three slashes; the hostname part of the URL is empty, so the slash at the beginning of the path immediately follows the double slash at the beginning of the URL. You will also need to expand the user's path; ~ does no expand in a file: URL. So you would need file:///home/User/2ndFile.html (on most Unixes), file:///Users/User/2ndFile.html (on Mac OS X), or file:///C:/Users/User/2ndFile.html (on Windows).

Many browsers, for security reasons, do not allow linking from a file that is loaded from a server to a local file. So, you may not be able to do this from a page loaded via HTTP; you may only be able to link to file: URLs from other local pages.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

  1. delete the build/ folder in ios/ and rerun if that doesn't do any change then
  2. File -> Project Settings (or WorkSpace Settings) -> Build System -> Legacy Build System
  3. Rerun and voilà!

In case this doesn't work, don't be sad, there is another solution to deeply clean project

  1. Delete ios/ and android/ folders.

  2. Run react-native eject

  3. Run react-native link

  4. react-native run-ios

This will bring a whole new resurrection for your project

how to destroy an object in java?

Here is the code:

public static void main(String argso[]) {
int big_array[] = new int[100000];

// Do some computations with big_array and get a result. 
int result = compute(big_array);

// We no longer need big_array. It will get garbage collected when there
// are no more references to it. Since big_array is a local variable,
// it refers to the array until this method returns. But this method
// doesn't return. So we've got to explicitly get rid of the reference
// ourselves, so the garbage collector knows it can reclaim the array. 
big_array = null;

// Loop forever, handling the user's input
for(;;) handle_input(result);
}

How do I assert equality on two classes without an equals method?

I generally implement this usecase using org.apache.commons.lang3.builder.EqualsBuilder

Assert.assertTrue(EqualsBuilder.reflectionEquals(expected,actual));

Running Windows batch file commands asynchronously

Using the START command to run each program should get you what you need:

START "title" [/D path] [options] "command" [parameters]

Every START invocation runs the command given in its parameter and returns immediately, unless executed with a /WAIT switch.

That applies to command-line apps. Apps without command line return immediately anyway, so to be sure, if you want to run all asynchronously, use START.

How to force div to appear below not next to another?

#similar { 
float:left; 
width:200px; 
background:#000; 
clear:both;
}

Regular cast vs. static_cast vs. dynamic_cast

FYI, I believe Bjarne Stroustrup is quoted as saying that C-style casts are to be avoided and that you should use static_cast or dynamic_cast if at all possible.

Barne Stroustrup's C++ style FAQ

Take that advice for what you will. I'm far from being a C++ guru.

Where is nodejs log file?

For nodejs log file you can use winston and morgan and in place of your console.log() statement user winston.log() or other winston methods to log. For working with winston and morgan you need to install them using npm. Example: npm i -S winston npm i -S morgan

Then create a folder in your project with name winston and then create a config.js in that folder and copy this code given below.

const appRoot = require('app-root-path');
const winston = require('winston');

// define the custom settings for each transport (file, console)
const options = {
  file: {
    level: 'info',
    filename: `${appRoot}/logs/app.log`,
    handleExceptions: true,
    json: true,
    maxsize: 5242880, // 5MB
    maxFiles: 5,
    colorize: false,
  },
  console: {
    level: 'debug',
    handleExceptions: true,
    json: false,
    colorize: true,
  },
};

// instantiate a new Winston Logger with the settings defined above
let logger;
if (process.env.logging === 'off') {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
} else {
  logger = winston.createLogger({
    transports: [
      new winston.transports.File(options.file),
      new winston.transports.Console(options.console),
    ],
    exitOnError: false, // do not exit on handled exceptions
  });
}

// create a stream object with a 'write' function that will be used by `morgan`
logger.stream = {
  write(message) {
    logger.info(message);
  },
};

module.exports = logger;

After copying the above code make make a folder with name logs parallel to winston or wherever you want and create a file app.log in that logs folder. Go back to config.js and set the path in the 5th line "filename: ${appRoot}/logs/app.log, " to the respective app.log created by you.

After this go to your index.js and include the following code in it.

const morgan = require('morgan');
const winston = require('./winston/config');
const express = require('express');
const app = express();
app.use(morgan('combined', { stream: winston.stream }));

winston.info('You have successfully started working with winston and morgan');

C# Macro definitions in Preprocessor

You can use a C preprocessor (like mcpp) and rig it into your .csproj file. Then you chnage "build action" on your source file from Compile to Preprocess or whatever you call it. Just add BeforBuild to your .csproj like this:

  <Target Name="BeforeBuild" Inputs="@(Preprocess)" Outputs="@(Preprocess->'%(Filename)_P.cs')">
<Exec Command="..\Bin\cpp.exe @(Preprocess) -P -o %(RelativeDir)%(Filename)_P.cs" />
<CreateItem Include="@(Preprocess->'%(RelativeDir)%(Filename)_P.cs')">
  <Output TaskParameter="Include" ItemName="Compile" />
</CreateItem>

You may have to manually change Compile to Preprocess on at least one file (in a text editor) - then the "Preprocess" option should be available for selection in Visual Studio.

I know that macros are heavily overused and misused but removing them completely is equally bad if not worse. A classic example of macro usage would be NotifyPropertyChanged. Every programmer who had to rewrite this code by hand thousands of times knows how painful it is without macros.

Subset of rows containing NA (missing) values in a chosen column of a data frame

NA is a special value in R, do not mix up the NA value with the "NA" string. Depending on the way the data was imported, your "NA" and "NULL" cells may be of various type (the default behavior is to convert "NA" strings to NA values, and let "NULL" strings as is).

If using read.table() or read.csv(), you should consider the "na.strings" argument to do clean data import, and always work with real R NA values.

An example, working in both cases "NULL" and "NA" cells :

DF <- read.csv("file.csv", na.strings=c("NA", "NULL"))
new_DF <- subset(DF, is.na(DF$Var2))

Unable to create Android Virtual Device

This can happen when:

  • You have multiple copies of the Android SDK installed on your machine. You may be updating the available images and devices for one copy of the Android SDK, and trying to debug or run your application in another.

    If you're using Eclipse, take a look at your "Preferences | Android | SDK Location". Make sure it's the path you expect. If not, change the path to point to where you think the Android SDK is installed.

  • You don't have an Android device setup in your emulator as detailed in other answers on this page.

How do I pass environment variables to Docker containers?

If you have the environment variables in an env.sh locally and want to set it up when the container starts, you could try

COPY env.sh /env.sh
COPY <filename>.jar /<filename>.jar
ENTRYPOINT ["/bin/bash" , "-c", "source /env.sh && printenv && java -jar /<filename>.jar"]

This command would start the container with a bash shell (I want a bash shell since source is a bash command), sources the env.sh file(which sets the environment variables) and executes the jar file.

The env.sh looks like this,

#!/bin/bash
export FOO="BAR"
export DB_NAME="DATABASE_NAME"

I added the printenv command only to test that actual source command works. You should probably remove it when you confirm the source command works fine or the environment variables would appear in your docker logs.

Redirect in Spring MVC

For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

return "redirect:/index.html";  

should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

Here is the source code of the method of RedirectView of Spring

protected void renderMergedOutputModel(  
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
throws IOException {  
  // Prepare target URL.  
  StringBuilder targetUrl = new StringBuilder();  
  if (this.contextRelative && getUrl().startsWith("/")) {  
    // Do not apply context path to relative URLs.  
    targetUrl.append(request.getContextPath());  
  }  
  targetUrl.append(getUrl());  

  // ...  

  sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  
}  

how to merge 200 csv files in Python

Use accepted StackOverflow answer to create a list of csv files that you want to append and then run this code:

import pandas as pd
combined_csv = pd.concat( [ pd.read_csv(f) for f in filenames ] )

And if you want to export it to a single csv file, use this:

combined_csv.to_csv( "combined_csv.csv", index=False )

How to run batch file from network share without "UNC path are not supported" message?

This is the RegKey I used:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Command Processor]
"DisableUNCCheck"=dword:00000001

How to remove all options from a dropdown using jQuery / JavaScript

function removeElements(){
  $('#models').html('');
}

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

Two Divs on the same row and center align both of them

You could do this

<div style="text-align:center;">
    <div style="border:1px solid #000; display:inline-block;">Div 1</div>
    <div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>  

http://jsfiddle.net/jasongennaro/MZrym/

  1. wrap it in a div with text-align:center;
  2. give the innder divs a display:inline-block; instead of a float

Best also to put that css in a stylesheet.

Compiler error "archive for required library could not be read" - Spring Tool Suite

In my case I had to manually delete all the files in .m2\repository folder and then open command prompt and run mvn -install command in my project directory.

From an array of objects, extract value of a property as array

Using Array.prototype.map:

function getFields(input, field) {
    return input.map(function(o) {
        return o[field];
    });
}

See the above link for a shim for pre-ES5 browsers.

Eclipse: Frustration with Java 1.7 (unbound library)

Most of the time after the installation of Eclipse eclipse.ini is changed. If you change the jdk in eclipse.ini then eclipse will use this jdk by default.

Let's say you install a new version of Eclipse and you have forgotten to change the eclipse.ini related to the jdk. Then Eclipse finds a jdk for you. Let's say it is java 1.6 that was automatically discovered (you did nothing).

If you use maven (M2E) and you reference a 1.7 jdk then you will see the frustrating message. But normally it is not displayed because you configure the correct jdk in eclipse.ini.

That was my case. I made reference into the pom to a jdk that was not configured into Eclipse.

In the screenshot you can see that 1.7 is configured and seen by Eclipse. In this case, you should make reference into the pom to a jre that is compatible with 1.7! If not -> frustrating message!

jdk 1.7 configured in eclipse.ini and retrieved in installed jre

Merge 2 DataTables and store in a new one

Instead of dtAll = dtOne.Copy(); in Jeromy Irvine's answer you can start with an empty DataTable and merge one-by-one iteratively:

dtAll = new DataTable();
...
dtAll.Merge(dtOne);
dtAll.Merge(dtTwo);
dtAll.Merge(dtThree);
...

and so on.

This technique is useful in a loop where you want to iteratively merge data tables:

DataTable dtAllCountries = new DataTable();

foreach(String strCountry in listCountries)
{
    DataTable dtCountry = getData(strCountry); //Some function that returns a data table
    dtAllCountries.Merge(dtCountry);
}

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

Change UITableView height dynamically

create your cell by xib or storyboard. give it's outlet's contents. now call it in CellForRowAtIndexPath. eg. if you want to set cell height according to Comment's label text. enter image description here

so set you commentsLbl.numberOfLine=0;enter image description here

so set you commentsLbl.numberOfLine=0;

then in ViewDidLoad

 self.table.estimatedRowHeight = 44.0 ;
self.table.rowHeight = UITableViewAutomaticDimension;

and now

-(float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
return UITableViewAutomaticDimension;}

EOFError: end of file reached issue with Net::HTTP

After doing some research, this was happening in Ruby's XMLRPC::Client library - which uses NET::HTTP. The client uses the start() method in NET::HTTP which keeps the connection open for future requests.

This happened precisely at 30 seconds after the last requests - so my assumption here is that the server it's hitting is closing requests after that time. I'm not sure what the default is for NET::HTTP to keep the request open - but I'm about to test with 60 seconds to see if that solves the issue.

How to printf long long

  • Your scanf() statement needs to use %lld too.
  • Your loop does not have a terminating condition.
  • There are far too many parentheses and far too few spaces in the expression

    pi += pow(-1.0, e) / (2.0*e + 1.0);
    
  • You add one on the first iteration of the loop, and thereafter zero to the value of 'pi'; this does not change the value much.
  • You should use an explicit return type of int for main().
  • On the whole, it is best to specify int main(void) when it ignores its arguments, though that is less of a categorical statement than the rest.
  • I dislike the explicit licence granted in C99 to omit the return from the end of main() and don't use it myself; I write return 0; to be explicit.

I think the whole algorithm is dubious when written using long long; the data type probably should be more like long double (with %Lf for the scanf() format, and maybe %19.16Lf for the printf() formats.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

If any one is interested here is what query is executed by psql on postgres 9.1:

SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE
  WHEN p.proisagg THEN 'agg'
  WHEN p.proiswindow THEN 'window'
  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
  ELSE 'normal'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;

You can get what psql runs for a backslash command by running psql with the -E flag.

How to find out the server IP address (using JavaScript) that the browser is connected to?

You cannot get this in general. From Javascript, you can only get the HTTP header, which may or may not have an IP address (typically only has the host name). Part of the browser's program is to abstract the TCP/IP address away and only allow you to deal with a host name.

Pass a data.frame column name to a function

As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call() could be useful as well in this case, as an alternative to deparse(substitute()):

df <- data.frame(A = 1:10, B = 2:11)

fun <- function(x, column){
  arg <- match.call()
  max(x[[arg$column]])
}

fun(df, A)
#> [1] 10

fun(df, B)
#> [1] 11

If there is a typo in the column name, then would be safer to stop with an error:

fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf

# Stop with error in case of typo
fun <- function(x, column){
  arg <- match.call()
  if (is.null(x[[arg$column]])) stop("Wrong column name")
  max(x[[arg$column]])
}

fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10

Created on 2019-01-11 by the reprex package (v0.2.1)

I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.

How can I get the order ID in WooCommerce?

it worked. Just modified it

global $woocommerce, $post;

$order = new WC_Order($post->ID);

//to escape # from order id 

$order_id = trim(str_replace('#', '', $order->get_order_number()));

What causes imported Maven project in Eclipse to use Java 1.5 instead of Java 1.6 by default and how can I ensure it doesn't?

In case anyone's wondering why Eclipse still puts a J2SE-1.5 library on the Java Build Path in a Maven project even if a Java version >= 9 is specified by the maven.compiler.release property (as of October 2020, that is Eclipse version 2020-09 including Maven version 3.6.3): Maven by default uses version 3.1 of the Maven compiler plugin, while the release property has been introduced only in version 3.6.

So don't forget to include a current version of the Maven compiler plugin in your pom.xml when using the release property:

<properties>
    <maven.compiler.release>15</maven.compiler.release>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
        </plugin>
    </plugins>
</build>

Or alternatively but possibly less prominent, specify the Java version directly in the plugin configuration:

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.8.1</version>
            <configuration>
                <release>15</release>
            </configuration>
        </plugin>
    </plugins>
</build>

This picks up Line's comment on the accepted answer which, had I seen it earlier, would have saved me another hour of searching.

Set database timeout in Entity Framework

I extended Ronnie's answer with a fluent implementation so you can use it like so:

dm.Context.SetCommandTimeout(120).Database.SqlQuery...

public static class EF
{
    public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
    {
        ((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;

        return db;
    }

    public static DbContext SetCommandTimeout(this DbContext db, int seconds)
    {
        return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
    } 
}

How to include vars file in a vars file with ansible?

Unfortunately, vars files do not have include statements.

You can either put all the vars into the definitions dictionary, or add the variables as another dictionary in the same file.

If you don't want to have them in the same file, you can include them at the playbook level by adding the vars file at the start of the play:

---
- hosts: myhosts

  vars_files:
    - default_step.yml

or in a task:

---
- hosts: myhosts

  tasks:
    - name: include default step variables
      include_vars: default_step.yml

Opacity of div's background without affecting contained element in IE 8?

Use RGBA or if you hex code then change it into rgba. No need to do some presodu element css.

function hexaChangeRGB(hex, alpha) {
    var r = parseInt(hex.slice(1, 3), 16),
        g = parseInt(hex.slice(3, 5), 16),
        b = parseInt(hex.slice(5, 7), 16);

    if (alpha) {
        return "rgba(" + r + ", " + g + ", " + b + ", " + alpha + ")";
    } else {
        return "rgb(" + r + ", " + g + ", " + b + ")";
    }
}

hexaChangeRGB('#FF0000', 0.2);

css ---------

background-color: #fff;
opacity: 0.8;

OR

mycolor = hexaChangeRGB('#FF0000', 0.2);
document.getElementById("myP").style.background-color = mycolor;

Proper usage of .net MVC Html.CheckBoxFor

By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:

@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });

Instead, in your GET Action method, the following needs to be done:

model.SomeBooleanProperty = true;

The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).

However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.

 @Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });

UPDATE

//Get Method
   public ActionResult CreateUser(int id)
   {
        model.SomeBooleanProperty = true;         
   }

Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.

How can I use mySQL replace() to replace strings in multiple records?

At a very generic level

UPDATE MyTable

SET StringColumn = REPLACE (StringColumn, 'SearchForThis', 'ReplaceWithThis')

WHERE SomeOtherColumn LIKE '%PATTERN%'

In your case you say these were escaped but since you don't specify how they were escaped, let's say they were escaped to GREATERTHAN

UPDATE MyTable

SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')

WHERE articleItem LIKE '%GREATERTHAN%'

Since your query is actually going to be working inside the string, your WHERE clause doing its pattern matching is unlikely to improve any performance - it is actually going to generate more work for the server. Unless you have another WHERE clause member that is going to make this query perform better, you can simply do an update like this:

UPDATE MyTable
SET StringColumn = REPLACE (StringColumn, 'GREATERTHAN', '>')

You can also nest multiple REPLACE calls

UPDATE MyTable
SET StringColumn = REPLACE (REPLACE (StringColumn, 'GREATERTHAN', '>'), 'LESSTHAN', '<')

You can also do this when you select the data (as opposed to when you save it).

So instead of :

SELECT MyURLString From MyTable

You could do

SELECT REPLACE (MyURLString, 'GREATERTHAN', '>') as MyURLString From MyTable

Why is my Button text forced to ALL CAPS on Lollipop?

I don't have idea why it is happening but there 3 trivial attempts to make:

  1. Use android:textAllCaps="false" in your layout-v21

  2. Programmatically change the transformation method of the button. mButton.setTransformationMethod(null);

  3. Check your style for Allcaps

Note: public void setAllCaps(boolean allCaps), android:textAllCaps are available from API version 14.

Rank function in MySQL

A tweak of Daniel's version to calculate percentile along with rank. Also two people with same marks will get the same rank.

set @totalStudents = 0;
select count(*) into @totalStudents from marksheets;
SELECT id, score, @curRank := IF(@prevVal=score, @curRank, @studentNumber) AS rank, 
@percentile := IF(@prevVal=score, @percentile, (@totalStudents - @studentNumber + 1)/(@totalStudents)*100),
@studentNumber := @studentNumber + 1 as studentNumber, 
@prevVal:=score
FROM marksheets, (
SELECT @curRank :=0, @prevVal:=null, @studentNumber:=1, @percentile:=100
) r
ORDER BY score DESC

Results of the query for a sample data -

+----+-------+------+---------------+---------------+-----------------+
| id | score | rank | percentile    | studentNumber | @prevVal:=score |
+----+-------+------+---------------+---------------+-----------------+
| 10 |    98 |    1 | 100.000000000 |             2 |              98 |
|  5 |    95 |    2 |  90.000000000 |             3 |              95 |
|  6 |    91 |    3 |  80.000000000 |             4 |              91 |
|  2 |    91 |    3 |  80.000000000 |             5 |              91 |
|  8 |    90 |    5 |  60.000000000 |             6 |              90 |
|  1 |    90 |    5 |  60.000000000 |             7 |              90 |
|  9 |    84 |    7 |  40.000000000 |             8 |              84 |
|  3 |    83 |    8 |  30.000000000 |             9 |              83 |
|  4 |    72 |    9 |  20.000000000 |            10 |              72 |
|  7 |    60 |   10 |  10.000000000 |            11 |              60 |
+----+-------+------+---------------+---------------+-----------------+

How to trim whitespace from a Bash variable?

I created the following functions. I am not sure how portable printf is, but the beauty of this solution is you can specify exactly what is "white space" by adding more character codes.

    iswhitespace()
    {
        n=`printf "%d\n" "'$1'"`
        if (( $n != "13" )) && (( $n != "10" )) && (( $n != "32" )) && (( $n != "92" )) && (( $n != "110" )) && (( $n != "114" )); then
            return 0
        fi
        return 1
    }

    trim()
    {
        i=0
        str="$1"
        while (( i < ${#1} ))
        do
            char=${1:$i:1}
            iswhitespace "$char"
            if [ "$?" -eq "0" ]; then
                str="${str:$i}"
                i=${#1}
            fi
            (( i += 1 ))
        done
        i=${#str}
        while (( i > "0" ))
        do
            (( i -= 1 ))
            char=${str:$i:1}
            iswhitespace "$char"
            if [ "$?" -eq "0" ]; then
                (( i += 1 ))
                str="${str:0:$i}"
                i=0
            fi
        done
        echo "$str"
    }

#Call it like so
mystring=`trim "$mystring"`

Create Table from View

If you just want to snag the schema and make an empty table out of it, use a false predicate, like so:

SELECT * INTO myNewTable FROM myView WHERE 1=2

Scripting Language vs Programming Language

In Scripting languages like (JavaScript and old PHP versions) we use existing fundamental functions and method for performing our job. Lets take an example in JavaScript we can use ajax or web-sockets only if they are supported by browser or methods exist or them in browser. But in languages like C or C++ , Java we can write that feature from scratch even if any library for that feature is not available but we can't do so in JavaScript.

can you support web-sockets in Internet Explorer 8 or prior with the help of JavaScript But you can write a plugin in C or C++ or Java which may add a feature of web-socket to Internet Explorer 8.

Basically in Scripting languages we write a code in a sequence which execute existing methods in a sequence to complete our job. Entering numbers and formula in a digital calculator to do a operation is also a very example of scripting language.We should note that the compiler/run-time-environment of every scripting language is always written in programming language in which we can add more features and methods and can write new libraries.

PHP This is language which is somewhat b/w programming and scripting. We can add new methods by adding compiled extensions written in another High Level Language. We can't add high level features of networking or creating image processing libraries directly in PHP.

P.S. I am really sorry for revolving my answer around PHP JavaScript only but I use these two because I have a considerable experience in these two.

Struct with template variables in C++

You can template a struct as well as a class. However you can't template a typedef. So template<typename T> struct array {...}; works, but template<typename T> typedef struct {...} array; does not. Note that there is no need for the typedef trick in C++ (you can use structs without the struct modifier just fine in C++).

Android MediaPlayer Stop and Play

According to the MediaPlayer life cycle, which you can view in the Android API guide, I think that you have to call reset() instead of stop(), and after that prepare again the media player (use only one) to play the sound from the beginning. Take also into account that the sound may have finished. So I would also recommend to implement setOnCompletionListener() to make sure that if you try to play again the sound it doesn't fail.

Maintain/Save/Restore scroll position when returning to a ListView

To clarify the excellent answer of Ryan Newsom and to adjust it for fragments and for the usual case that we want to navigate from a "master" ListView fragment to a "details" fragment and then back to the "master"

    private View root;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
           if(root == null){
             root = inflater.inflate(R.layout.myfragmentid,container,false);
             InitializeView(); 
           } 
           return root; 
        }

    public void InitializeView()
    {
        ListView listView = (ListView)root.findViewById(R.id.listviewid);
        BaseAdapter adapter = CreateAdapter();//Create your adapter here
        listView.setAdpater(adapter);
        //other initialization code
    }

The "magic" here is that when we navigate back from the details fragment to the ListView fragment, the view is not recreated, we don't set the ListView's adapter, so everything stays as we left it!

How do you read CSS rule values with JavaScript?

I created a version that searches all stylesheets and returns matches as a key/value object. You can also specify startsWith to match child styles.

getStylesBySelector('.pure-form-html', true);

returns:

{
    ".pure-form-html body": "padding: 0; margin: 0; font-size: 14px; font-family: tahoma;",
    ".pure-form-html h1": "margin: 0; font-size: 18px; font-family: tahoma;"
}

from:

.pure-form-html body {
    padding: 0;
    margin: 0;
    font-size: 14px;
    font-family: tahoma;
}

.pure-form-html h1 {
    margin: 0;
    font-size: 18px;
    font-family: tahoma;
}

The code:

/**
 * Get all CSS style blocks matching a CSS selector from stylesheets
 * @param {string} className - class name to match
 * @param {boolean} startingWith - if true matches all items starting with selector, default = false (exact match only)
 * @example getStylesBySelector('pure-form .pure-form-html ')
 * @returns {object} key/value object containing matching styles otherwise null
 */
function getStylesBySelector(className, startingWith) {

    if (!className || className === '') throw new Error('Please provide a css class name');

    var styleSheets = window.document.styleSheets;
    var result = {};

    // go through all stylesheets in the DOM
    for (var i = 0, l = styleSheets.length; i < l; i++) {

        var classes = styleSheets[i].rules || styleSheets[i].cssRules || [];

        // go through all classes in each document
        for (var x = 0, ll = classes.length; x < ll; x++) {

            var selector = classes[x].selectorText || '';
            var content = classes[x].cssText || classes[x].style.cssText || '';

            // if the selector matches
            if ((startingWith && selector.indexOf(className) === 0) || selector === className) {

                // create an object entry with selector as key and value as content
                result[selector] = content.split(/(?:{|})/)[1].trim();
            }
        }
    }

    // only return object if we have values, otherwise null
    return Object.keys(result).length > 0 ? result : null;
}

I'm using this in production as part of the pure-form project. Hope it helps.

Search text in fields in every table of a MySQL database

You could do an SQLDump of the database (and its data) then search that file.

How to add days to the current date?

Dateadd(datepart,number,date)

You should use it like this:

select DATEADD(day,360,getdate())

Then you will find the same date but different year.

How are cookies passed in the HTTP protocol?

The server sends the following in its response header to set a cookie field.

Set-Cookie:name=value

If there is a cookie set, then the browser sends the following in its request header.

Cookie:name=value

See the HTTP Cookie article at Wikipedia for more information.

CKEditor, Image Upload (filebrowserUploadUrl)

My latest issue was how to integrate CKFinder for image upload in CKEditor. Here the solution.

  1. Download CKEditor and extract in your web folder root.

  2. Download CKFinder and extract withing ckeditor folder.

  3. Then add references to the CKEditor, CKFinder and put

     <CKEditor:CKEditorControl ID="CKEditorControl1" runat="server"></CKEditor:CKEditorControl>
    

    to your aspx page.

  4. In code behind page OnLoad event add this code snippet

    protected override void OnLoad(EventArgs e)
    {
      CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
      _FileBrowser.BasePath = "ckeditor/ckfinder/";
      _FileBrowser.SetupCKEditor(CKEditorControl1);
    }
    
  5. Edit Confic.ascx file.

    public override bool CheckAuthentication()
    {
      return true;
    }
    
    // Perform additional checks for image files.
    SecureImageUploads = true;
    

(source)

INNER JOIN in UPDATE sql for DB2

The reference documentation for the UPDATE statement on DB2 LUW 9.7 gives the following example:

   UPDATE (SELECT EMPNO, SALARY, COMM,
     AVG(SALARY) OVER (PARTITION BY WORKDEPT),
     AVG(COMM) OVER (PARTITION BY WORKDEPT)
     FROM EMPLOYEE E) AS E(EMPNO, SALARY, COMM, AVGSAL, AVGCOMM)
   SET (SALARY, COMM) = (AVGSAL, AVGCOMM)
   WHERE EMPNO = '000120'

The parentheses after UPDATE can contain a full-select, meaning any valid SELECT statement can go there.

Based on that, I would suggest the following:

UPDATE (
  SELECT
    f1.firstfield,
    f2.anotherfield,
    f2.something
  FROM file1 f1
  WHERE f1.firstfield like 'BLAH%' 
  INNER JOIN file2 f2
  ON substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
AS my_files(firstfield, anotherfield, something)
SET
  firstfield = ( 'BIT OF TEXT' || something )

Edit: Ian is right. My first instinct was to try subselects instead:

UPDATE file1 f1
SET f1.firstfield = ( 'BIT OF TEXT' || (
  SELECT f2.something
  FROM file2 f2
  WHERE substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
))
WHERE f1.firstfield LIKE 'BLAH%' 
AND substr(f1.firstfield,10,20) IN (
  SELECT substr(f2.anotherfield,1,10)
  FROM file2 f2
)

But I'm not sure if the concatenation would work. It also assumes that there's a 1:1 mapping between the substrings. If there are multiple rows that match, it wouldn't work.

Get the value of a dropdown in jQuery

This has worked for me!

$('#selected-option option:selected').val()

Hope this helps someone!

Simple WPF RadioButton Binding?

I've come up with solution using Binding.DoNothing returned from converter which doesn't break two-way binding.

public class EnumToCheckedConverter : IValueConverter
{
    public Type Type { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value.GetType() == Type)
        {
            try
            {
                var parameterFlag = Enum.Parse(Type, parameter as string);

                if (Equals(parameterFlag, value))
                {
                    return true;
                }
            }
            catch (ArgumentNullException)
            {
                return false;
            }
            catch (ArgumentException)
            {
                throw new NotSupportedException();
            }

            return false;
        }
        else if (value == null)
        {
            return false;
        }

        throw new NotSupportedException();
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value != null && value is bool check)
        {
            if (check)
            {
                try
                {
                    return Enum.Parse(Type, parameter as string);
                }
                catch(ArgumentNullException)
                {
                    return Binding.DoNothing;
                }
                catch(ArgumentException)
                {
                    return Binding.DoNothing;
                }
            }

            return Binding.DoNothing;
        }

        throw new NotSupportedException();
    }
}

Usage:

<converters:EnumToCheckedConverter x:Key="SourceConverter" Type="{x:Type monitor:VariableValueSource}" />

Radio button bindings:

<RadioButton GroupName="ValueSource" 
             IsChecked="{Binding Source, Converter={StaticResource SourceConverter}, ConverterParameter=Function}">Function</RadioButton>

How to extract multiple JSON objects from one file?

Added streaming support based on the answer of @dunes:

import re
from json import JSONDecoder, JSONDecodeError

NOT_WHITESPACE = re.compile(r"[^\s]")


def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
    buf = ""
    ex = None
    while True:
        block = file_obj.read(buf_size)
        if not block:
            break
        buf += block
        pos = 0
        while True:
            match = NOT_WHITESPACE.search(buf, pos)
            if not match:
                break
            pos = match.start()
            try:
                obj, pos = decoder.raw_decode(buf, pos)
            except JSONDecodeError as e:
                ex = e
                break
            else:
                ex = None
                yield obj
        buf = buf[pos:]
    if ex is not None:
        raise ex

Text not wrapping inside a div element

That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all; to your .title rules to force a break.

#calendar_container > #events_container > .event_block > .title {
    width:400px;
    font-size:12px;
    word-break:break-all;
}

jsFiddle example

How do I open a new window using jQuery?

It's not really something you need jQuery to do. There is a very simple plain old javascript method for doing this:

window.open('http://www.google.com','GoogleWindow', 'width=800, height=600');

That's it.

The first arg is the url, the second is the name of the window, this should be specified because IE will throw a fit about trying to use window.opener later if there was no window name specified (just a little FYI), and the last two params are width/height.

EDIT: Full specification can be found in the link mmmshuddup provided.

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

http://php.about.com/od/advancedphp/p/html_php.htm

Extracting numbers from vectors of strings

Using the package unglue we can do :

# install.packages("unglue")
library(unglue)

years<-c("20 years old", "1 years old")
unglue_vec(years, "{x} years old", convert = TRUE)
#> [1] 20  1

Created on 2019-11-06 by the reprex package (v0.3.0)

More info: https://github.com/moodymudskipper/unglue/blob/master/README.md

CSS - Syntax to select a class within an id

#navigation .navigationLevel2 li
{
    color: #f00;
}

How to check whether a string is a valid HTTP URL?

After Uri.TryCreate you can check Uri.Scheme to see if it HTTP(s).

Stopping a JavaScript function when a certain condition is met

use return for this

if(i==1) { 
    return; //stop the execution of function
}

//keep on going

Cygwin - Makefile-error: recipe for target `main.o' failed

You see the two empty -D entries in the g++ command line? They're causing the problem. You must have values in the -D items e.g. -DWIN32

if you're insistent on using something like -D$(SYSTEM) -D$(ENVIRONMENT) then you can use something like:

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

<command-line>:0:1: error: macro names must be identifiers
<command-line>:0:1: error: macro names must be identifiers

just to clarify, what actually got sent to g++ was -D -DWindows_NT, i.e. define a preprocessor macro called -DWindows_NT; which is of course not a valid identifier (similarly for -D -I.)

Windows batch file file download from a URL

There's a utility (resides with CMD) on Windows which can be run from CMD (if you have write access):

set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
echo Done.

Built in Windows application. No need for external downloads.

Tested on Win 10

VBA - Run Time Error 1004 'Application Defined or Object Defined Error'

Your cells object is not fully qualified. You need to add a DOT before the cells object. For example

With Worksheets("Cable Cards")
    .Range(.Cells(RangeStartRow, RangeStartColumn), _
           .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues

Similarly, fully qualify all your Cells object.

How to get values from selected row in DataGrid for Windows Form Application?

You could just use

DataGridView1.CurrentRow.Cells["ColumnName"].Value

malloc for struct and pointer in C

You could actually do this in a single malloc by allocating for the Vector and the array at the same time. Eg:

struct Vector y = (struct Vector*)malloc(sizeof(struct Vector) + 10*sizeof(double));
y->x = (double*)((char*)y + sizeof(struct Vector));
y->n = 10;

This allocates Vector 'y', then makes y->x point to the extra allocated data immediate after the Vector struct (but in the same memory block).

If resizing the vector is required, you should do it with the two allocations as recommended. The internal y->x array would then be able to be resized while keeping the vector struct 'y' intact.

contenteditable change events

non jQuery quick and dirty answer:

function setChangeListener (div, listener) {

    div.addEventListener("blur", listener);
    div.addEventListener("keyup", listener);
    div.addEventListener("paste", listener);
    div.addEventListener("copy", listener);
    div.addEventListener("cut", listener);
    div.addEventListener("delete", listener);
    div.addEventListener("mouseup", listener);

}

var div = document.querySelector("someDiv");

setChangeListener(div, function(event){
    console.log(event);
});

How to set Java classpath in Linux?

Can you provide some more details like which linux you are using? Are you loged in as root? On linux you have to run export CLASSPATH = %path%;LOG4J_HOME/og4j-1.2.16.jar If you want it permanent then you can add above lines in ~/.bashrc file.

How to forcefully set IE's Compatibility Mode off from the server-side?

Changing my header to the following solve the problem:

<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

How to create multiple class objects with a loop in python?

This question is asked every day in some variation. The answer is: keep your data out of your variable names, and this is the obligatory blog post.

In this case, why not make a list of objs?

objs = [MyClass() for i in range(10)]
for obj in objs:
    other_object.add(obj)

objs[0].do_sth()

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

It is used in transaction management to ensure that any errors result in the transaction being rolled back.

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Replacing accented characters php

You can try this one

class Diacritic
{
    public function replaceDiacritic($input)
    {
        $input = iconv('UTF-8','ASCII//TRANSLIT',$input);
        $input = preg_replace("/['|^|`|~|]/","",$input);
        $input = preg_replace('/["]/','',$input);
        return preg_replace('/[" "]/','_',$input);
    }
}

How to print to console using swift playground?

you need to enable the Show Assistant Editor:

enter image description here

Forward request headers from nginx proxy server

The problem is that '_' underscores are not valid in header attribute. If removing the underscore is not an option you can add to the server block:

underscores_in_headers on;

This is basically a copy and paste from @kishorer747 comment on @Fleshgrinder answer, and solution is from: https://serverfault.com/questions/586970/nginx-is-not-forwarding-a-header-value-when-using-proxy-pass/586997#586997

I added it here as in my case the application behind nginx was working perfectly fine, but as soon ngix was between my flask app and the client, my flask app would not see the headers any longer. It was kind of time consuming to debug.

getaddrinfo: nodename nor servname provided, or not known

In my config/application.yml I have changed this

redis:
    url: "redis://redis:6379/0"

to this

redis:
    url: "redis://localhost:6379/0"

and it works for me

DataTable: How to get item value with row name and column name? (VB)

'Create a class to hold the pair...

        Public Class ColumnValue
            Public ColumnName As String
            Public ColumnValue As New Object
        End Class

    'Build the pair...

        For Each row In [YourDataTable].Rows

              For Each item As DataColumn In row.Table.Columns
                Dim rowValue As New ColumnValue
                rowValue.ColumnName = item.Caption
                rowValue.ColumnValue = row.item(item.Ordinal)
                RowValues.Add(rowValue)
                rowValue = Nothing
              Next

        ' Now you can grab the value by the column name...

        Dim results = (From p In RowValues Where p.ColumnName = "MyColumn" Select  p.ColumnValue).FirstOrDefault    

        Next

MySQL OPTIMIZE all tables?

The MySQL Administrator (part of the MySQL GUI Tools) can do that for you on a database level.

Just select your schema and press the Maintenance button in the bottom right corner.

Since the GUI Tools have reached End-of-life status they are hard to find on the mysql page. Found them via Google: http://dev.mysql.com/downloads/gui-tools/5.0.html

I don't know if the new MySQL Workbench can do that, too.

And you can use the mysqlcheck command line tool which should be able to do that, too.

Full width image with fixed height

#image {
  width: 100%;
  height: 100px; //static
  object-fit: cover;
}

Android Completely transparent Status Bar?

This should work

// In Activity's onCreate() for instance

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    Window w = getWindow();
    w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
}

How do I split a string with multiple separators in JavaScript?

a = "a=b,c:d"

array = ['=',',',':'];

for(i=0; i< array.length; i++){ a= a.split(array[i]).join(); }

this will return the string without a special charecter.

How to solve could not create the virtual machine error of Java Virtual Machine Launcher?

I had the same issue today when running the ancient software Dundjinni, a mapping tool, on Windows 10. (Dundjinni requires a rather old installation of Java; I haven’t tried updating Java, for fear the programme will fail.) My method was to simply run Dundjinni in administrator mode. Here is how:

Click Start or press the Start key, navigate down to the software, rightclick the programme, choose More, then choose Run as administrator. Note that this option is not available if you simply type the name of the software.

enter image description here

How do I send a JSON string in a POST request in Go

I'm not familiar with napping, but using Golang's net/http package works fine (playground):

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)

    var jsonStr = []byte(`{"title":"Buy cheese and bread for breakfast."}`)
    req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
    req.Header.Set("X-Custom-Header", "myvalue")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        panic(err)
    }
    defer resp.Body.Close()

    fmt.Println("response Status:", resp.Status)
    fmt.Println("response Headers:", resp.Header)
    body, _ := ioutil.ReadAll(resp.Body)
    fmt.Println("response Body:", string(body))
}

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

Are arrays passed by value or passed by reference in Java?

Kind of a trick realty... Even references are passed by value in Java, hence a change to the reference itself being scoped at the called function level. The compiler and/or JVM will often turn a value type into a reference.

Testing web application on Mac/Safari when I don't own a Mac

Meanwhile, MacOS High Sierra can be run in VirtualBox (on a PC) for Free. It's not really fast but it works for general browser testing.

How to setup see here: https://www.howtogeek.com/289594/how-to-install-macos-sierra-in-virtualbox-on-windows-10/

I'm using this for a while now and it works quite well

asp.net mvc3 return raw html to view

There's no much point in doing that, because View should be generating html, not the controller. But anyways, you could use Controller.Content method, which gives you ability to specify result html, also content-type and encoding

public ActionResult Index()
{
    return Content("<html></html>");
}

Or you could use the trick built in asp.net-mvc framework - make the action return string directly. It will deliver string contents into users's browser.

public string Index()
{
    return "<html></html>";
}

In fact, for any action result other than ActionResult, framework tries to serialize it into string and write to response.

How do I measure execution time of a command on the Windows command line?

If you have a command window open and call the commands manually, you can display a timestamp on each prompt, e.g.

prompt $d $t $_$P$G

It gives you something like:

23.03.2009 15:45:50,77

C:\>

If you have a small batch script that executes your commands, have an empty line before each command, e.g.

(empty line)

myCommand.exe

(next empty line)

myCommand2.exe

You can calculate the execution time for each command by the time information in the prompt. The best would probably be to pipe the output to a textfile for further analysis:

MyBatchFile.bat > output.txt

ERROR 1067 (42000): Invalid default value for 'created_at'

Just convert it by this line :

for the new table :

CREATE TABLE t1 (
  ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

for Existing Table:

Alter ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP

Source :

https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html

Input button target="_blank" isn't causing the link to load in a new window/tab

Another solution, using JQUERY, would be to write a function that is invoked when the user clicks the button. This function creates a new <A> element, with target='blank', appends this to the document, 'clicks' it then removes it.

So as far as the user is concerned, they clicked a button, but behind the scenes, an <A> element with target='_blank' was clicked.

<input type="button" id='myButton' value="facebook">

$(document).on('ready', function(){
     $('#myButton').on('click',function(){
         var link = document.createElement("a");
         link.href = 'http://www.facebook.com/';
         link.style = "visibility:hidden";
         link.target = "_blank";
         document.body.appendChild(link);
         link.click();
         document.body.removeChild(link); 
     });
});

JsFiddle : https://jsfiddle.net/ragDaniel/tf991u4g/2/

How to change RGB color to HSV?

This is the VB.net version which works fine for me ported from the C code in BlaM's post.

There's a C implementation here:

http://www.cs.rit.edu/~ncs/color/t_convert.html

Should be very straightforward to convert to C#, as almost no functions are called - just > calculations.


Public Sub HSVtoRGB(ByRef r As Double, ByRef g As Double, ByRef b As Double, ByVal h As Double, ByVal s As Double, ByVal v As Double)
    Dim i As Integer
    Dim f, p, q, t As Double

    If (s = 0) Then
        ' achromatic (grey)
        r = v
        g = v
        b = v
        Exit Sub
    End If

    h /= 60 'sector 0 to 5
    i = Math.Floor(h)
    f = h - i 'factorial part of h
    p = v * (1 - s)
    q = v * (1 - s * f)
    t = v * (1 - s * (1 - f))

    Select Case (i)
        Case 0
            r = v
            g = t
            b = p
            Exit Select
        Case 1
            r = q
            g = v
            b = p
            Exit Select
        Case 2
            r = p
            g = v
            b = t
            Exit Select
        Case 3
            r = p
            g = q
            b = v
            Exit Select
        Case 4
            r = t
            g = p
            b = v
            Exit Select
        Case Else   'case 5:
            r = v
            g = p
            b = q
            Exit Select
    End Select
End Sub

Sending cookies with postman

You can enable Interceptor in browser and in Postman separately. For send/recieve cookies you should enable Interceptor in Postman. So if you enable interceptor only in browser - it will not work. Actually you don't need enable Interceptor in browser at all - if you don't want to flood your postman history with unnecessary requests.

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here

Redirect Windows cmd stdout and stderr to a single file

Anders Lindahl's answer is correct, but it should be noted that if you are redirecting stdout to a file and want to redirect stderr as well then you MUST ensure that 2>&1 is specified AFTER the 1> redirect, otherwise it will not work.

REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt

Getting a "This application is modifying the autolayout engine from a background thread" error?

For me, this error message originated from a banner from Admob SDK.

I was able to track the origin to "WebThread" by setting a conditional breakpoint.

conditional breakpoint to find who is updating ui from background thread

Then I was able to get rid of the issue by encapsulating the Banner creation with:

dispatch_async(dispatch_get_main_queue(), ^{
   _bannerForTableFooter = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
   ...
}

I don't know why this helped as I cannot see how this code was called from a non-main-thread.

Hope it can help anyone.

sql query with multiple where statements

You need to consider that GROUP BY happens after the WHERE clause conditions have been evaluated. And the WHERE clause always considers only one row, meaning that in your query, the meta_key conditions will always prevent any records from being selected, since one column cannot have multiple values for one row.

And what about the redundant meta_value checks? If a value is allowed to be both smaller and greater than a given value, then its actual value doesn't matter at all - the check can be omitted.

According to one of your comments you want to check for places less than a certain distance from a given location. To get correct distances, you'd actually have to use some kind of proper distance function (see e.g. this question for details). But this SQL should give you an idea how to start:

SELECT items.* FROM items i, meta_data m1, meta_data m2
    WHERE i.item_id = m1.item_id and i.item_id = m2.item_id
    AND m1.meta_key = 'lat' AND m1.meta_value >= 55 AND m1.meta_value <= 65
    AND m2.meta_key = 'lng' AND m2.meta_value >= 20 AND m2.meta_value <= 30

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

Flutter: Setting the height of the AppBar

Use toolbarHeight:

enter image description here


There's no longer a need to use PreferredSize. Use toolbarHeight with flexibleSpace.

AppBar(
  toolbarHeight: 120, // Set this height
  flexibleSpace: Container(
    color: Colors.orange,
    child: Column(
      children: [
        Text('1'),
        Text('2'),
        Text('3'),
        Text('4'),
      ],
    ),
  ),
)

Android and Facebook share intent

This solution works aswell. If there is no Facebook installed, it just runs the normal share-dialog. If there is and you are not logged in, it goes to the login screen. If you are logged in, it will open the share dialog and put in the "Share url" from the Intent Extra.

Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Share url");
intent.setType("text/plain");

List<ResolveInfo> matches = getMainFragmentActivity().getPackageManager().queryIntentActivities(intent, 0);
for (ResolveInfo info : matches) {
    if (info.activityInfo.packageName.toLowerCase().contains("facebook")) {
        intent.setPackage(info.activityInfo.packageName);
    }
}

startActivity(intent);

How to add 10 minutes to my (String) time?

I would recommend storing the time as integers and regulate it through the division and modulo operators, once that is done convert the integers into the string format you require.

How Do I Uninstall Yarn

ng set --global packageManager=npm OR ng set --global packageManager=yarn

How to export database schema in Oracle to a dump file

It depends on which version of Oracle? Older versions require exp (export), newer versions use expdp (data pump); exp was deprecated but still works most of the time.

Before starting, note that Data Pump exports to the server-side Oracle "directory", which is an Oracle symbolic location mapped in the database to a physical location. There may be a default directory (DATA_PUMP_DIR), check by querying DBA_DIRECTORIES:

  SQL> select * from dba_directories;

... and if not, create one

  SQL> create directory DATA_PUMP_DIR as '/oracle/dumps';
  SQL> grant all on directory DATA_PUMP_DIR to myuser;    -- DBAs dont need this grant

Assuming you can connect as the SYSTEM user, or another DBA, you can export any schema like so, to the default directory:

 $ expdp system/manager schemas=user1 dumpfile=user1.dpdmp

Or specifying a specific directory, add directory=<directory name>:

 C:\> expdp system/manager schemas=user1 dumpfile=user1.dpdmp directory=DUMPDIR

With older export utility, you can export to your working directory, and even on a client machine that is remote from the server, using:

 $ exp system/manager owner=user1 file=user1.dmp

Make sure the export is done in the correct charset. If you haven't setup your environment, the Oracle client charset may not match the DB charset, and Oracle will do charset conversion, which may not be what you want. You'll see a warning, if so, then you'll want to repeat the export after setting NLS_LANG environment variable so the client charset matches the database charset. This will cause Oracle to skip charset conversion.

Example for American UTF8 (UNIX):

 $ export NLS_LANG=AMERICAN_AMERICA.AL32UTF8

Windows uses SET, example using Japanese UTF8:

 C:\> set NLS_LANG=Japanese_Japan.AL32UTF8

More info on Data Pump here: http://docs.oracle.com/cd/B28359_01/server.111/b28319/dp_export.htm#g1022624

Display a message in Visual Studio's output window when not debug mode?

This whole thread confused the h#$l out of me until I realized you have to be running the debugger to see ANY trace or debug output. I needed a debug output (outside of the debugger) because my WebApp runs fine when I debug it but not when the debugger isn't running (SqlDataSource is instantiated correctly when running through the debugger).

Just because debug output can be seen when you're running in release mode doesn't mean you'll see anything if you're not running the debugger. Careful reading of Writing to output window of Visual Studio? gave me DebugView as an alternative. Extremely useful!

Hopefully this helps anyone else confused by this.

/etc/apt/sources.list" E212: Can't open file for writing

for me worked changing the filesystem from Read-Only before running vim:

bash-3.2# mount -o remount rw /

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

Laravel: Auth::user()->id trying to get a property of a non-object

Do a Auth::check() before to be sure that you are well logged in :

if (Auth::check())
{
    // The user is logged in...
}

Include CSS and Javascript in my django template

First, create staticfiles folder. Inside that folder create css, js, and img folder.

settings.py

import os

PROJECT_DIR = os.path.dirname(__file__)

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.sqlite3', 
         'NAME': os.path.join(PROJECT_DIR, 'myweblabdev.sqlite'),                        
         'USER': '',
         'PASSWORD': '',
         'HOST': '',                      
         'PORT': '',                     
    }
}

MEDIA_ROOT = os.path.join(PROJECT_DIR, 'media')

MEDIA_URL = '/media/'

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(PROJECT_DIR, 'staticfiles'),
)

main urls.py

from django.conf.urls import patterns, include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from myweblab import settings

admin.autodiscover()

urlpatterns = patterns('',
    .......
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += staticfiles_urlpatterns()

template

{% load static %}

<link rel="stylesheet" href="{% static 'css/style.css' %}">

There is already an object named in the database

I faced the same bug as below. Then I fixed it as below:

  1. Check current databases in your project:
    • dotnet ef migrations list
  2. If the newest is what you've added, then remove it:
    • dotnet ef migrations remove
  3. Guarantee outputs of this database must be deteled in source code: .cs/.Designer.cs files

4.Now it is fine. Try to re-add: dotnet ef migrations add [new_dbo_name]

5.Finally, try to update again, in arrangement base on migration list:

  • dotnet ef database update [First]
  • dotnet ef database update [Second]
  • ...
  • dotnet ef database update [new_dbo_name]

Hope it is helpful for you. ^^

Set custom HTML5 required field validation message

You can do this setting up an event listener for the 'invalid' across all the inputs of the same type, or just one, depending on what you need, and then setting up the proper message.

[].forEach.call( document.querySelectorAll('[type="email"]'), function(emailElement) {
    emailElement.addEventListener('invalid', function() {
        var message = this.value + 'is not a valid email address';
        emailElement.setCustomValidity(message)
    }, false);

    emailElement.addEventListener('input', function() {
        try{emailElement.setCustomValidity('')}catch(e){}
    }, false);
    });

The second piece of the script, the validity message will be reset, since otherwise won't be possible to submit the form: for example this prevent the message to be triggered even when the email address has been corrected.

Also you don't have to set up the input field as required, since the 'invalid' will be triggered once you start typing in the input.

Here is a fiddle for that: http://jsfiddle.net/napy84/U4pB7/2/ Hope that helps!

Creating multiple log files of different content with log4j

Demo link: https://github.com/RazvanSebastian/spring_multiple_log_files_demo.git

My solution is based on XML configuration using spring-boot-starter-log4j. The example is a basic example using spring-boot-starter and the two Loggers writes into different log files.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

you have to use echo before base_url() function. otherwise it woudn't print the base url.

How to disable clicking inside div

How to disable clicking another div click until first one popup div close

Image of the example

 <p class="btn1">One</p>
 <div id="box1" class="popup">
 Test Popup Box One
 <span class="close">X</span>
 </div>

 <!-- Two -->
 <p class="btn2">Two</p>
 <div id="box2" class="popup">
 Test Popup Box Two
 <span class="close">X</span>
  </div>

<style>
.disabledbutton {
 pointer-events: none;
 }

.close {
cursor: pointer;
}

</style>
<script>
$(document).ready(function(){
//One
$(".btn1").click(function(){
  $("#box1").css('display','block');
  $(".btn2,.btn3").addClass("disabledbutton");

});
$(".close").click(function(){
  $("#box1").css('display','none');
  $(".btn2,.btn3").removeClass("disabledbutton");
});
</script>

How to get resources directory path programmatically

Just use com.google.common.io.Resources class. Example:

 URL url = Resources.getResource("file name")

After that you have methods like: .getContent(), .getFile(), .getPath() etc

How to specify font attributes for all elements on an html web page?

you can set them in the body tag

body
{
    font-size:xxx;
    font-family:yyyy;
}

Remove multiple items from a Python list in just one statement

You Can use this -

Suppose we have a list, l = [1,2,3,4,5]

We want to delete last two items in a single statement

del l[3:]

We have output:

l = [1,2,3]

Keep it Simple

How do I check if file exists in jQuery or pure JavaScript?

So long as you're testing files on the same domain this should work:

function fileExists(url) {
    if(url){
        var req = new XMLHttpRequest();
        req.open('GET', url, false);
        req.send();
        return req.status==200;
    } else {
        return false;
    }
}

Please note, this example is using a GET request, which besides getting the headers (all you need to check weather the file exists) gets the whole file. If the file is big enough this method can take a while to complete.

The better way to do this would be changing this line: req.open('GET', url, false); to req.open('HEAD', url, false);

How to get a variable from a file to another file in Node.js

File FileOne.js:

module.exports = { ClientIDUnsplash : 'SuperSecretKey' };

File FileTwo.js:

var { ClientIDUnsplash } = require('./FileOne');

This example works best for React.

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

For null values in the dataframe of pyspark

Dict_Null = {col:df.filter(df[col].isNull()).count() for col in df.columns}
Dict_Null

# The output in dict where key is column name and value is null values in that column

{'#': 0,
 'Name': 0,
 'Type 1': 0,
 'Type 2': 386,
 'Total': 0,
 'HP': 0,
 'Attack': 0,
 'Defense': 0,
 'Sp_Atk': 0,
 'Sp_Def': 0,
 'Speed': 0,
 'Generation': 0,
 'Legendary': 0}

OnClickListener in Android Studio

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         int id = item.getItemId();
         if (id == R.id.standingsButton) {
            startActivity(new Intent(MainActivity.this,StandingsActivity.class));
            return true;
        }
        return super.onOptionsItemSelected(item);
    }