Programs & Examples On #Page curl

page-curl refers to the effect of flipping through digital documents

check for null date in CASE statement, where have I gone wrong?

select Id, StartDate,
Case IsNull (StartDate , '01/01/1800')
When '01/01/1800' then
  'Awaiting'
Else
  'Approved'
END AS StartDateStatus
From MyTable

Find index of a value in an array

This solution helped me more, from msdn microsoft:

var result =  query.AsEnumerable().Select((x, index) =>
              new { index,x.Id,x.FirstName});

query is your toList() query.

How to append to the end of an empty list?

use my_list.append(...) and do not use and other list to append as list are mutable.

Reading an Excel file in python using pandas

I think this should satisfy your need:

import pandas as pd

# Read the excel sheet to pandas dataframe
df = pd.read_excel("PATH\FileName.xlsx", sheetname=0)

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

Rotate an image in image source in html

If your rotation angles are fairly uniform, you can use CSS:

<img id="image_canv" src="/image.png" class="rotate90">

CSS:

.rotate90 {
    -webkit-transform: rotate(90deg);
    -moz-transform: rotate(90deg);
    -o-transform: rotate(90deg);
    -ms-transform: rotate(90deg);
    transform: rotate(90deg);
}

Otherwise, you can do this by setting a data attribute in your HTML, then using Javascript to add the necessary styling:

<img id="image_canv" src="/image.png" data-rotate="90">

Sample jQuery:

$('img').each(function() {
    var deg = $(this).data('rotate') || 0;
    var rotate = 'rotate(' + deg + 'deg)';
    $(this).css({ 
        '-webkit-transform': rotate,
        '-moz-transform': rotate,
        '-o-transform': rotate,
        '-ms-transform': rotate,
        'transform': rotate 
    });
});

Demo:

http://jsfiddle.net/verashn/6rRnd/5/

How to pass a single object[] to a params object[]

new[] { (object) 0, (object) null, (object) false }

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

JavaScript string and number conversion

These questions come up all the time due to JavaScript's typing system. People think they are getting a number when they're getting the string of a number.

Here are some things you might see that take advantage of the way JavaScript deals with strings and numbers. Personally, I wish JavaScript had used some symbol other than + for string concatenation.

Step (1) Concatenate "1", "2", "3" into "123"

result = "1" + "2" + "3";

Step (2) Convert "123" into 123

result = +"123";

Step (3) Add 123 + 100 = 223

result = 123 + 100;

Step (4) Convert 223 into "223"

result = "" + 223;

If you know WHY these work, you're less likely to get into trouble with JavaScript expressions.

Gradle error: Minimum supported Gradle version is 3.3. Current version is 3.2

you need to download the latest version from https://gradle.org/releases after that go to file/project structure/project and put the new version in gradle version

Using sed and grep/egrep to search and replace

Honestly, much as I love sed for appropriate tasks, this is definitely a task for perl -- it's truly more powerful for this kind of one-liners, especially to "write it back to where it comes from" (perl's -i switch does it for you, and optionally also lets you keep the old version around e.g. with a .bak appended, just use -i.bak instead).

perl -i.bak -pe 's/\.jpg|\.png|\.gif/.jpg/

rather than intricate work in sed (if even possible there) or awk...

Looping each row in datagridview

I used the solution below to export all datagrid values to a text file, rather than using the column names you can use the column index instead.

foreach (DataGridViewRow row in xxxCsvDG.Rows)
{
    File.AppendAllText(csvLocation, row.Cells[0].Value + "," + row.Cells[1].Value + "," + row.Cells[2].Value + "," + row.Cells[3].Value + Environment.NewLine);
}

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

How to style child components from parent component's CSS file?

I have solved it outside Angular. I have defined a shared scss that I'm importing to my children.

shared.scss

%cell {
  color: #333333;
  background: #eee;
  font-size: 13px;
  font-weight: 600;
}

child.scss

@import 'styles.scss';
.cell {
  @extend %cell;
}

My proposed approach is a way how to solve the problem the OP has asked about. As mentioned at multiple occasions, ::ng-deep, :ng-host will get depreciated and disabling encapsulation is just too much of a code leakage, in my view.

C99 stdint.h header and MS Visual Studio

Microsoft do not support C99 and haven't announced any plans to. I believe they intend to track C++ standards but consider C as effectively obsolete except as a subset of C++.

New projects in Visual Studio 2003 and later have the "Compile as C++ Code (/TP)" option set by default, so any .c files will be compiled as C++.

TextView Marquee not working

I have created a custom class AlwaysMarqueTextView

public class AlwaysMarqueeTextView extends TextView
{
    protected boolean a;

    public AlwaysMarqueeTextView(Context context)
    {
        super(context);
        a = false;
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset)
    {
        super(context, attributeset);
        a = false;
    }

    public AlwaysMarqueeTextView(Context context, AttributeSet attributeset, int i)
    {
        super(context, attributeset, i);
        a = false;
    }

    public boolean isFocused()
    {
        return a || super.isFocused();
    }

    public void setAlwaysMarquee(boolean flag)
    {
        setSelected(flag);
        setSingleLine(flag);
        if(flag)
        setEllipsize(TruncateAt.MARQUEE);
        a = flag;
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) 
    {
        if(focused)

            super.onFocusChanged(focused, direction, previouslyFocusedRect);
    }

    @Override
    public void onWindowFocusChanged(boolean focused)
    {
        if(focused)
            super.onWindowFocusChanged(focused);
    }
}

And you can startMarquee when desire.. like

//textView.setSelected(true); No need of Selection..
textview.setAlwaysMarquee(true); 

Creating a constant Dictionary in C#

There does not seem to be any standard immutable interface for dictionaries, so creating a wrapper seems like the only reasonable option, unfortunately.

Edit: Marc Gravell found the ILookup that I missed - that will allow you to at least avoid creating a new wrapper, although you still need to transform the Dictionary with .ToLookup().

If this is a need constrained to a specific scenario, you might be better off with a more business-logic-oriented interface:

interface IActiveUserCountProvider
{
    int GetMaxForServer(string serverName);
}

How to prevent XSS with HTML/PHP?

Many frameworks help handle XSS in various ways. When rolling your own or if there's some XSS concern, we can leverage filter_input_array (available in PHP 5 >= 5.2.0, PHP 7.) I typically will add this snippet to my SessionController, because all calls go through there before any other controller interacts with the data. In this manner, all user input gets sanitized in 1 central location. If this is done at the beginning of a project or before your database is poisoned, you shouldn't have any issues at time of output...stops garbage in, garbage out.

/* Prevent XSS input */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
/* I prefer not to use $_REQUEST...but for those who do: */
$_REQUEST = (array)$_POST + (array)$_GET + (array)$_REQUEST;

The above will remove ALL HTML & script tags. If you need a solution that allows safe tags, based on a whitelist, check out HTML Purifier.


If your database is already poisoned or you want to deal with XSS at time of output, OWASP recommends creating a custom wrapper function for echo, and using it EVERYWHERE you output user-supplied values:

//xss mitigation functions
function xssafe($data,$encoding='UTF-8')
{
   return htmlspecialchars($data,ENT_QUOTES | ENT_HTML401,$encoding);
}
function xecho($data)
{
   echo xssafe($data);
}

Using getopts to process long and short command line options

I have been working on that subject for quite a long time... and made my own library which you will need to source in your main script. See libopt4shell and cd2mpc for an example. Hope it helps !

What should I do when 'svn cleanup' fails?

I've tried to do svn cleanup via the console and got an error like:

svn: E720002: Can't open file '..\.svn\pristine\40\40d53d69871f4ff622a3fbb939b6a79932dc7cd4.svn-base':
The system cannot find the file specified.

So I created this file manually (empty) and did svn cleanup again. This time it was done OK.

Android Layout Animations from bottom to top and top to bottom on ImageView click

Try this :

Create anim folder inside your res folder and copy this four files :

slide_in_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>  

slide_out_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0" 
android:duration="@android:integer/config_longAnimTime" /> 

slide_in_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />

slide_out_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />

When you click on image view call:

overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);

When you click on original place call:

overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);

Main Activity :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);


    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, test.class));

        }
    });


}
    }

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

test.java :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class test extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    btn1 = (Button) findViewById(R.id.btn1);

    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         finish();
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);
            startActivity(new Intent(test.this, MainActivity.class));


        }
    });
}

    }

test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

Hope this helps.

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

Mi helped: windows defender settings >> device security >> core insulation (details) >> Memory integrity >> Disable (OFF) SYSTEM RESTART !

What is "Linting"?

Interpreted languages like Python and JavaScript benefit greatly from linting, as these languages don’t have a compiling phase to display errors before execution.

Linters are also useful for code formatting and/or adhering to language specific best practices.

Lately I have been using ESLint for JS/React and will occasionally use it with an airbnb-config file.

Update multiple columns in SQL

here is one that works:

UPDATE  `table_1`
INNER JOIN 
 `table_2` SET  col1= value, col2= val,col3= val,col4= val;

value is the column from table_2

How do I make a <div> move up and down when I'm scrolling the page?

using position:fixed alone is just fine when you don't have a header or logo at the top of your page. This solution will take into account the how far the window has scrolled, and moves the div when you scrolled past your header. It will then lock it back into place when you get to the top again.

if($(window).scrollTop() > Height_of_Header){
    //begin to scroll
    $("#div").css("position","fixed");
    $("#div").css("top",0);
}
else{
    //lock it back into place
    $("#div").css("position","relative");
}

Why doesn't Git ignore my specified file?

.gitignore will only ignore files that you haven't already added to your repository.

If you did a git add ., and the file got added to the index, .gitignore won't help you. You'll need to do git rm sites/default/settings.php to remove it, and then it will be ignored.

Java reverse an int value without using array

int aa=456;
int rev=Integer.parseInt(new StringBuilder(aa+"").reverse());

How to create a Custom Dialog box in android?

Import custom alert :

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dse_location_list_filter, null);
final Dialog dialog = new Dialog(Acitvity_name.this);
dialog.setContentView(view);
dialog.setCancelable(true);
dialog.setCanceledOnTouchOutside(true);
dialog.show();

Is it bad practice to use break to exit a loop in Java?

break and continue breaks the readability for the reader, although it's often useful. Not as much as "goto" concept, but almost.

Besides, if you take some new languages like Scala (inspired by Java and functional programming languages like Ocaml), you will notice that break and continue simply disappeared.

Especially in functional programming, this style of code is avoided:

Why scala doesn't support break and continue?

To sum up: break and continueare widely used in Java for an imperative style, but for any coders that used to practice functional programming, it might be.. weird.

svn cleanup: sqlite: database disk image is malformed

no need to worry for a directory lock guys.

Just you need to do is, If sqllite3 is not installed, type below command,

>sudo apt-get install sqlite3

Open SVN database by typing this command,

>sqlite3 .svn/wc.db 

Now just you need to do is to remove locks entries from SVN DB.

sqlite>  select * from wc_lock;
1|-1           
sqlite>  delete from wc_lock;
sqlite>  select * from wc_lock;
sqlite>  .q

Process Completed. You can work on your SVN repository, do commit, update, add, remove operations without issue.

:-)

add item to dropdown list in html using javascript

i think you have only defined the function. you are not triggering it anywhere.

please do

window.onload = addList();

or trigger it on some other event

after its definition

see this fiddle

Convert XLS to CSV on command line

Scott F's answer is the best I have found on the internet. I did add on to his code to meet my needs. I added:

On Error Resume Next <- To account for a missing xls files in my batch processing at the top. oBook.Application.Columns("A:J").NumberFormat = "@" <- Before the SaveAs line to make sure my data is saved formatted as text to keep excel from deleting leading zero's and eliminating commas in number strings in my data i.e. (1,200 to 1200). The column range should be adjusted to meet your neeeds (A:J).

I also removed the Echo "done" to make it non interactive.

I then added the script into a cmd batch file for processing automated data on an hourly basis via a task.

Node.js/Express routing with get params

For Query parameters like domain.com/test?format=json&type=mini format, then you can easily receive it via - req.query.

app.get('/test', function(req, res){
  var format = req.query.format,
      type = req.query.type;
});

How to state in requirements.txt a direct github source

requirements.txt allows the following ways of specifying a dependency on a package in a git repository as of pip 7.0:1

[-e] git+git://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+https://git.myproject.org/SomeProject#egg=SomeProject
[-e] git+ssh://git.myproject.org/SomeProject#egg=SomeProject
-e [email protected]:SomeProject#egg=SomeProject (deprecated as of Jan 2020)

For Github that means you can do (notice the omitted -e):

git+git://github.com/mozilla/elasticutils.git#egg=elasticutils

Why the extra answer?
I got somewhat confused by the -e flag in the other answers so here's my clarification:

The -e or --editable flag means that the package is installed in <venv path>/src/SomeProject and thus not in the deeply buried <venv path>/lib/pythonX.X/site-packages/SomeProject it would otherwise be placed in.2

Documentation

Alert after page load

Why can't you use it in MVC?

Rather than using the body load method use jQuery and wait for the the document onready function to complete.

Determine device (iPhone, iPod Touch) with iOS

More usable

#include <sys/types.h>
#include <sys/sysctl.h>

@interface UIDevice(Hardware)

- (NSString *) platform;

- (BOOL)hasRetinaDisplay;

- (BOOL)hasMultitasking;

- (BOOL)hasCamera;

@end

@implementation UIDevice(Hardware)

- (NSString *) platform{
    int mib[2];
size_t len;
char *machine;

mib[0] = CTL_HW;
mib[1] = HW_MACHINE;
sysctl(mib, 2, NULL, &len, NULL, 0);
machine = malloc(len);
sysctl(mib, 2, machine, &len, NULL, 0);

    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
return platform;
}

- (BOOL)hasRetinaDisplay {
    NSString *platform = [self platform];
    BOOL ret = YES;
    if ([platform isEqualToString:@"iPhone1,1"]) {
        ret = NO;
    }
    else
        if ([platform isEqualToString:@"iPhone1,2"])    ret = NO;
    else 
        if ([platform isEqualToString:@"iPhone2,1"])    ret = NO;
    else 
        if ([platform isEqualToString:@"iPod1,1"])      ret = NO;
    else
        if ([platform isEqualToString:@"iPod2,1"])      ret = NO;
    else
        if ([platform isEqualToString:@"iPod3,1"])      ret = NO;
    return ret;
}

- (BOOL)hasMultitasking {
    if ([self respondsToSelector:@selector(isMultitaskingSupported)]) {
        return [self isMultitaskingSupported];
    }
    return NO;
}

- (BOOL)hasCamera {
   BOOL ret = NO;
   // check camera availability
   return ret;
}

@end

you can reading properties with

NSLog(@"platform %@, retita %@, multitasking %@", [[UIDevice currentDevice] platform], [[UIDevice currentDevice] hasRetinaDisplay] ? @"YES" : @"NO" , [[UIDevice currentDevice] hasMultitasking] ? @"YES" : @"NO");

Call to undefined function oci_connect()

Alright, folks.

First, use

<?php 
phpinfo();
?> 

and determine your PHP Version (located at the very top, e.g. 7.0.xxx) and also, your PHP Version architecture: x64 or x86 and also, Thread Safe or Not THread Safe (located in the first table as "Thread Safety".) "Disabled" obviously means "Not Thread Safe".

It is absolutely critical that the following three pieces of software that you will need are:

  1. for the same major version of PHP (7.0 for 7.0.xxx)
  2. same version of Oracle as the version you are accessing (11g, 12g, etc)
  3. the same Not Thread Safe / Thread Safe version of PHP
  4. all for the same architecture.

If any of the following are for a different architecture, Not Thread Safe/Thread Safe version, PHP major version number, or database version, you'll get errors:

 1. PHP for Windows
 2. OCI8 PECL Drivers for PHP (https://pecl.php.net/package/oci8)
 3. Oracle Instant Client

Remember: If you are connecting to an 11g Oracle instance, you need an 11g driver.

Second, install the correct PHP, OCI8 PECL Driver, and instant client.

I chose:

d:\php\ for php
d:\oci\ for instant client
unzip the contents of the OCI8 PECL Driver into d:\php\ext\

Third, modify d:\php\php.ini according the instructions given by Oracle:

1. set the extension directory
2. set only one of the following:
  a. for 11g drivers, use extension=php_oci8_11g.dll
  b. for 12c drivers, use extension=php_oci8_12c.dll
  c. for other oracle DB drivers, use the correct oracle extension.

Fourth: Add d:\oci\ (or whatever your instant client install location is) to your system PATH.

Fifth: reboot your PC.

Sixth, on a command prompt, type "where oci*" and verify that your Instant Client install path version of oci.dll is present.

Seventh, go to d:\php\ and type "php -m" and you should see OCI8 in the list.

If you do not see OCI8 in the list of modules after typing "php -m", open up d:\php\errorlog.txt

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_11g.dll' - %1 is not a valid Win32 application.

then either instant client or your PECL driver download is not the same architecture as your PHP version.

If you see something like:

PHP Warning:  PHP Startup: Unable to load dynamic library 'ext\php_oci8_12c.dll' - The specified procedure could not be found.

then you are using the wrong OCI8 PECL driver for your version of instant client.

Hope this helps.

How to use the switch statement in R functions?

I hope this example helps. You ca use the curly braces to make sure you've got everything enclosed in the switcher changer guy (sorry don't know the technical term but the term that precedes the = sign that changes what happens). I think of switch as a more controlled bunch of if () {} else {} statements.

Each time the switch function is the same but the command we supply changes.

do.this <- "T1"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
#########################################################
do.this <- "T2"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)
########################################################
do.this <- "T3"

switch(do.this,
    T1={X <- t(mtcars)
        colSums(mtcars)%*%X
    },
    T2={X <- colMeans(mtcars)
        outer(X, X)
    },
    stop("Enter something that switches me!")
)

Here it is inside a function:

FUN <- function(df, do.this){
    switch(do.this,
        T1={X <- t(df)
            P <- colSums(df)%*%X
        },
        T2={X <- colMeans(df)
            P <- outer(X, X)
        },
        stop("Enter something that switches me!")
    )
    return(P)
}

FUN(mtcars, "T1")
FUN(mtcars, "T2")
FUN(mtcars, "T3")

What's the scope of a variable initialized in an if statement?

you're executing this code from command line therefore if conditions is true and x is set. Compare:

>>> if False:
    y = 42


>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y
NameError: name 'y' is not defined

How to do jquery code AFTER page loading?

And if you want to run a second function after the first one finishes, see this stackoverflow answer.

Including dependencies in a jar with Maven

http://fiji.sc/Uber-JAR provides an excellent explanation of the alternatives:

There are three common methods for constructing an uber-JAR:

  1. Unshaded. Unpack all JAR files, then repack them into a single JAR.
    • Pro: Works with Java's default class loader.
    • Con: Files present in multiple JAR files with the same path (e.g., META-INF/services/javax.script.ScriptEngineFactory) will overwrite one another, resulting in faulty behavior.
    • Tools: Maven Assembly Plugin, Classworlds Uberjar
  2. Shaded. Same as unshaded, but rename (i.e., "shade") all packages of all dependencies.
    • Pro: Works with Java's default class loader. Avoids some (not all) dependency version clashes.
    • Con: Files present in multiple JAR files with the same path (e.g., META-INF/services/javax.script.ScriptEngineFactory) will overwrite one another, resulting in faulty behavior.
    • Tools: Maven Shade Plugin
  3. JAR of JARs. The final JAR file contains the other JAR files embedded within.
    • Pro: Avoids dependency version clashes. All resource files are preserved.
    • Con: Needs to bundle a special "bootstrap" classloader to enable Java to load classes from the wrapped JAR files. Debugging class loader issues becomes more complex.
    • Tools: Eclipse JAR File Exporter, One-JAR.

ORA-01652 Unable to extend temp segment by in tablespace

You don't need to create a new datafile; you can extend your existing tablespace data files.

Execute the following to determine the filename for the existing tablespace:

  SELECT * FROM DBA_DATA_FILES;

Then extend the size of the datafile as follows (replace the filename with the one from the previous query):

  ALTER DATABASE DATAFILE 'D:\ORACLEXE\ORADATA\XE\SYSTEM.DBF' RESIZE 2048M; 

Run react-native on android emulator

On macOs I manage to fix this by adding:

export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$PATH:$ANDROID_HOME/emulator
export PATH=$PATH:$ANDROID_HOME/tools
export PATH=$PATH:$ANDROID_HOME/tools/bin
export PATH=$PATH:$ANDROID_HOME/platform-tools

to ~/.zsh_profile file.

and than type to your terminal

source $HOME/.zsh_profile

The issue was caused by using iTerm2 shell so it's required to edit its own config instead of default $HOME/.bash_profile as described in the official documentation https://reactnative.dev/docs/environment-setup

Convert string to integer type in Go?

If you control the input data, you can use the mini version

package main

import (
    "testing"
    "strconv"
)

func Atoi (s string) int {
    var (
        n uint64
        i int
        v byte
    )   
    for ; i < len(s); i++ {
        d := s[i]
        if '0' <= d && d <= '9' {
            v = d - '0'
        } else if 'a' <= d && d <= 'z' {
            v = d - 'a' + 10
        } else if 'A' <= d && d <= 'Z' {
            v = d - 'A' + 10
        } else {
            n = 0; break        
        }
        n *= uint64(10) 
        n += uint64(v)
    }
    return int(n)
}

func BenchmarkAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in := Atoi("9999")
        _ = in
    }   
}

func BenchmarkStrconvAtoi(b *testing.B) {
    for i := 0; i < b.N; i++ {
        in, _ := strconv.Atoi("9999")
        _ = in
    }   
}

the fastest option (write your check if necessary). Result :

Path>go test -bench=. atoi_test.go
goos: windows
goarch: amd64
BenchmarkAtoi-2                 100000000               14.6 ns/op
BenchmarkStrconvAtoi-2          30000000                51.2 ns/op
PASS
ok      path     3.293s

Converting JSON String to Dictionary Not List

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Using multiple delimiters in awk

Good news! awk field separator can be a regular expression. You just need to use -F"<separator1>|<separator2>|...":

awk -F"/|=" -vOFS='\t' '{print $3, $5, $NF}' file

Returns:

tc0001  tomcat7.1  demo.example.com
tc0001  tomcat7.2  quest.example.com
tc0001  tomcat7.5  www.example.com

Here:

  • -F"/|=" sets the input field separator to either / or =. Then, it sets the output field separator to a tab.

  • -vOFS='\t' is using the -v flag for setting a variable. OFS is the default variable for the Output Field Separator and it is set to the tab character. The flag is necessary because there is no built-in for the OFS like -F.

  • {print $3, $5, $NF} prints the 3rd, 5th and last fields based on the input field separator.


See another example:

$ cat file
hello#how_are_you
i#am_very#well_thank#you

This file has two fields separators, # and _. If we want to print the second field regardless of the separator being one or the other, let's make both be separators!

$ awk -F"#|_" '{print $2}' file
how
am

Where the files are numbered as follows:

hello#how_are_you           i#am_very#well_thank#you
^^^^^ ^^^ ^^^ ^^^           ^ ^^ ^^^^ ^^^^ ^^^^^ ^^^
  1    2   3   4            1  2   3    4    5    6

Should IBOutlets be strong or weak under ARC?

I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign, as they're already retained by their superviews. If you make them weak, you shouldn't have to nil them out in viewDidUnload, as you point out.

One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak, so you'd have to make them assign, in which case you'd still want to nil the reference in viewDidUnload to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:

A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation {
    Class geocoderClass = NSClassFromString(@"CLGeocoder");
    if (geocoderClass && IsEmpty(self.zip.text)) {
        id geocoder = [[geocoderClass alloc] init];
        [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
            if (self.zip && IsEmpty(self.zip.text)) {
                self.zip.text = [[placemarks objectAtIndex:0] postalCode];
            }
        }];    
    }
    [self.locationManager stopUpdatingLocation];
}

I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload, the delegate callback could throw a bad access exception on self.zip.text.

Centering a Twitter Bootstrap button

If you have more than one button, then you can do the following.

<div class="center-block" style="max-width:400px">
  <a href="#" class="btn btn-success">Accept</a>
  <a href="#" class="btn btn-danger"> Reject</a>
</div>

Display loading image while post with ajax

$.ajax(
{
    type: 'post',
    url: 'mail.php',
    data: form.serialize(),
    beforeSend: function()
    {
        $('.content').html('loading...');
    },
    success: function(data)
    {
        $('.content').html(data);
    },
    error: function()
    {
        $('.content').html('error');
    }
});

have fun playing arround!

if you should have quick loading times which prevent te loading showing, you can add a timeout of some sort.

Git pull - Please move or remove them before you can merge

If there are too many files to delete, which is actually a case for me. You can also try the following solution:

1) fetch

2) merge with a strategy. For instance this one works for me:

git.exe merge --strategy=ours master

Can't connect to Postgresql on port 5432

This has bitten me a second time so I thought might be worth mentioning. The line listen_addresses = '*' in the postgresql.conf is by default commented. Be sure to uncomment (remove the pound sign, # at the beginning) it after updating otherwise, remote connections will continue to be blocked.

C compile error: Id returned 1 exit status

My solution is to try to open another file that you can successfully run that you do at another PC, open that file and run it, after that copy that file and make a new file. Try to run it.

How to get previous month and year relative to today, using strtotime and date?

date("m-Y", strtotime("-1 months")); 

would solve this

How do I make an HTTP request in Swift?

You can use Just, a python-requests style HTTP library.

Some example of sending HTTP request with Just:

// synchronous GET request with URL query a=1
let r = Just.get("https://httpbin.org/get", params:["a":1])

// asynchronous POST request with form value and file uploads
Just.post(
    "http://justiceleauge.org/member/register",
    data: ["username": "barryallen", "password":"ReverseF1ashSucks"],
    files: ["profile_photo": .URL(fileURLWithPath:"flash.jpeg", nil)]
) { (r)
    if (r.ok) { /* success! */ }
}

In both cases, the result of a request r can be accessed in ways similar to python-request:

r.ok            // is the response successful?
r.statusCode    // status code of response
r.content       // response body as NSData?
r.text          // response body as text?
r.json          // response body parsed by NSJSONSerielization

You can find more examples in this playground

Using this library in synchronous mode in a playground is the closest thing to cURL one can get in Swift.

Creating a procedure in mySql with parameters

I figured it out now. Here's the correct answer

CREATE PROCEDURE checkUser 
(
   brugernavn1 varchar(64),
   password varchar(64)
) 
BEGIN 
   SELECT COUNT(*) FROM bruger 
   WHERE bruger.brugernavn=brugernavn1 
   AND bruger.pass=password; 
END; 

@ points to a global var in mysql. The above syntax is correct.

Java - How do I make a String array with values?

Another way is with Arrays.setAll, or Arrays.fill:

String[] v = new String[1000];
Arrays.setAll(v, i -> Integer.toString(i * 30));
//v => ["0", "30", "60", "90"... ]

Arrays.fill(v, "initial value");
//v => ["initial value", "initial value"... ]

This is more usefull for initializing (possibly large) arrays where you can compute each element from its index.

Convert integer to hex and hex to integer

Actually, the built-in function is named master.dbo.fn_varbintohexstr.

So, for example:

SELECT 100, master.dbo.fn_varbintohexstr(100)

Gives you

100 0x00000064

How to fix date format in ASP .NET BoundField (DataFormatString)?

I had the same problem, only need to show shortdate (without the time), moreover it was needed to have multi-language settings, so depends of the language, show dd-mm-yyyy or mm-dd-yyyy.

Finally using DataFormatString="{0:d}, all works fine and show only the date with culture format.

What is "406-Not Acceptable Response" in HTTP?

In my case for a API in .NET-Core, the api is set to work with XML (by default is set to response with JSON), so I add this annotation in my Controller :

[Produces("application/xml")]
public class MyController : ControllerBase {...}

Thank you for putting me on the path !

CSS: how do I create a gap between rows in a table?

All you need:

table {
    border-collapse: separate;
    border-spacing: 0 1em;
}

That assumes you want a 1em vertical gap, and no horizontal gap. If you're doing this, you should probably also look at controlling your line-height.

Sort of weird that some of the answers people gave involve border-collapse: collapse, whose effect is the exact opposite of what the question asked for.

Query an object array using linq

Add:

using System.Linq;

to the top of your file.

And then:

Car[] carList = ...
var carMake = 
    from item in carList
    where item.Model == "bmw" 
    select item.Make;

or if you prefer the fluent syntax:

var carMake = carList
    .Where(item => item.Model == "bmw")
    .Select(item => item.Make);

Things to pay attention to:

  • The usage of item.Make in the select clause instead if s.Make as in your code.
  • You have a whitespace between item and .Model in your where clause

How to get the current plugin directory in WordPress?

Why not use the WordPress core function that's designed specifically for that purpose?

<?php plugin_dir_path( __FILE__ ); ?>

See Codex documentation here.

You also have

<?php plugin_dir_url( __FILE__ ); ?>

if what you're looking for is a URI as opposed to a server path.

See Codex documentation here.

IMO it's always best to use the highest-level method that's available in core, and this is it. It makes your code more future proof.

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

This exception comes when the service of docker is not running or the logged in user dont have the permission to access docker and generally it comes in RedHat

Using below command should resolve the issue

sudo service docker start

enter image description here

pySerial write() won't take my string

You have found the root cause. Alternately do like this:

ser.write(bytes(b'your_commands'))

How to implement an android:background that doesn't stretch?

Use draw9patch... included within Android Studio's SDK tools. You can define the stretchable areas of your image. Important parts are constrained and the image doesn't look all warped. A good demo on dra9patch is HERE

Use draw9patch to change your existing splash.png into new_splash.9.png, drag new_splash.9.png into the drawable-hdpi project folder ensure the AndroidManifest and styles.xml are proper as below:

AndroidManifest.xml:

<application
...
        android:theme="@style/splashScreenStyle"
>

styles.xml:

<style name="splashScreenStyle" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowBackground">@drawable/new_splash</item>
</style>

sudo service mongodb restart gives "unrecognized service error" in ubuntu 14.0.4

Try this:

Write mongodb instead of mongod

sudo service mongodb status

Integrating the ZXing library directly into my Android application

Why use an external lib, when google play services (since version 7.8.0) includes a barcode decoder.

Running a command in a new Mac OS X Terminal window

Here's my awesome script, it creates a new terminal window if needed and switches to the directory Finder is in if Finder is frontmost. It has all the machinery you need to run commands.

on run
    -- Figure out if we want to do the cd (doIt)
    -- Figure out what the path is and quote it (myPath)
    try
        tell application "Finder" to set doIt to frontmost
        set myPath to finder_path()
        if myPath is equal to "" then
            set doIt to false
        else
            set myPath to quote_for_bash(myPath)
        end if
    on error
        set doIt to false
    end try

    -- Figure out if we need to open a window
    -- If Terminal was not running, one will be opened automatically
    tell application "System Events" to set isRunning to (exists process "Terminal")

    tell application "Terminal"
        -- Open a new window
        if isRunning then do script ""
        activate
        -- cd to the path
        if doIt then
            -- We need to delay, terminal ignores the second do script otherwise
            delay 0.3
            do script " cd " & myPath in front window
        end if
    end tell
end run

on finder_path()
    try
        tell application "Finder" to set the source_folder to (folder of the front window) as alias
        set thePath to (POSIX path of the source_folder as string)
    on error -- no open folder windows
        set thePath to ""
    end try

    return thePath
end finder_path

-- This simply quotes all occurrences of ' and puts the whole thing between 's
on quote_for_bash(theString)
    set oldDelims to AppleScript's text item delimiters
    set AppleScript's text item delimiters to "'"
    set the parsedList to every text item of theString
    set AppleScript's text item delimiters to "'\\''"
    set theString to the parsedList as string
    set AppleScript's text item delimiters to oldDelims
    return "'" & theString & "'"
end quote_for_bash

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

How can I create a dropdown menu from a List in Tkinter?

To create a "drop down menu" you can use OptionMenu in tkinter

Example of a basic OptionMenu:

from Tkinter import *

master = Tk()

variable = StringVar(master)
variable.set("one") # default value

w = OptionMenu(master, variable, "one", "two", "three")
w.pack()

mainloop()

More information (including the script above) can be found here.


Creating an OptionMenu of the months from a list would be as simple as:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

mainloop()

In order to retrieve the value the user has selected you can simply use a .get() on the variable that we assigned to the widget, in the below case this is variable:

from tkinter import *

OPTIONS = [
"Jan",
"Feb",
"Mar"
] #etc

master = Tk()

variable = StringVar(master)
variable.set(OPTIONS[0]) # default value

w = OptionMenu(master, variable, *OPTIONS)
w.pack()

def ok():
    print ("value is:" + variable.get())

button = Button(master, text="OK", command=ok)
button.pack()

mainloop()

I would highly recommend reading through this site for further basic tkinter information as the above examples are modified from that site.

file_put_contents(meta/services.json): failed to open stream: Permission denied

I had the same issue and the below steps helped me fix the issue.

  1. Find out the apache user - created a test.php file in the public folder with the code

<?php echo exec('whoami'); ?>

And run the file from the web browser. It would give the apache user. In my case, it is ec2-user as I was using the aws with cronjob installed in /etc/cron.d/. It could be different user for others.

  1. Run the below command on the command line.

sudo chown -R ec2-user:<usergroup> /app-path/public

You need to identify and use the right "user" and "usergroup" here.

How to find which version of TensorFlow is installed in my system?

If you're using anaconda distribution of Python,

$ conda list | grep tensorflow
tensorflow    1.0.0       py35_0    conda-forge

To check it using Jupyter Notebook (IPython Notebook)

In [1]: import tensorflow as tf
In [2]: tf.__version__
Out[2]: '1.0.0'

Is it possible to convert char[] to char* in C?

It sounds like you're confused between pointers and arrays. Pointers and arrays (in this case char * and char []) are not the same thing.

  • An array char a[SIZE] says that the value at the location of a is an array of length SIZE
  • A pointer char *a; says that the value at the location of a is a pointer to a char. This can be combined with pointer arithmetic to behave like an array (eg, a[10] is 10 entries past wherever a points)

In memory, it looks like this (example taken from the FAQ):

 char a[] = "hello";  // array

   +---+---+---+---+---+---+
a: | h | e | l | l | o |\0 |
   +---+---+---+---+---+---+

 char *p = "world"; // pointer

   +-----+     +---+---+---+---+---+---+
p: |  *======> | w | o | r | l | d |\0 |
   +-----+     +---+---+---+---+---+---+

It's easy to be confused about the difference between pointers and arrays, because in many cases, an array reference "decays" to a pointer to it's first element. This means that in many cases (such as when passed to a function call) arrays become pointers. If you'd like to know more, this section of the C FAQ describes the differences in detail.

One major practical difference is that the compiler knows how long an array is. Using the examples above:

char a[] = "hello";  
char *p =  "world";  

sizeof(a); // 6 - one byte for each character in the string,
           // one for the '\0' terminator
sizeof(p); // whatever the size of the pointer is
           // probably 4 or 8 on most machines (depending on whether it's a 
           // 32 or 64 bit machine)

Without seeing your code, it's hard to recommend the best course of action, but I suspect changing to use pointers everywhere will solve the problems you're currently having. Take note that now:

  • You will need to initialise memory wherever the arrays used to be. Eg, char a[10]; will become char *a = malloc(10 * sizeof(char));, followed by a check that a != NULL. Note that you don't actually need to say sizeof(char) in this case, because sizeof(char) is defined to be 1. I left it in for completeness.

  • Anywhere you previously had sizeof(a) for array length will need to be replaced by the length of the memory you allocated (if you're using strings, you could use strlen(), which counts up to the '\0').

  • You will need a make a corresponding call to free() for each call to malloc(). This tells the computer you are done using the memory you asked for with malloc(). If your pointer is a, just write free(a); at a point in the code where you know you no longer need whatever a points to.

As another answer pointed out, if you want to get the address of the start of an array, you can use:

char* p = &a[0] 

You can read this as "char pointer p becomes the address of element [0] of a".

Printing 1 to 1000 without loop or conditionals

Easy as pie:

int main(int argc, char* argv[])
{
    printf(argv[0]);
}

method of execution:

printer.exe "1;2;3;4;5;6;7;8;9;10;11;12;13;14;15;16;17;18;19;20;21;22;23;24;25;26;27;28;29;30;31;32;33;34;35;36;37;38;39;40;41;42;43;44;45;46;47;48;49;50;51;52;53;54;55;56;57;58;59;60;61;62;63;64;65;66;67;68;69;70;71;72;73;74;75;76;77;78;79;80;81;82;83;84;85;86;87;88;89;90;91;92;93;94;95;96;97;98;99;100;101;102;103;104;105;106;107;108;109;110;111;112;113;114;115;116;117;118;119;120;121;122;123;124;125;126;127;128;129;130;131;132;133;134;135;136;137;138;139;140;141;142;143;144;145;146;147;148;149;150;151;152;153;154;155;156;157;158;159;160;161;162;163;164;165;166;167;168;169;170;171;172;173;174;175;176;177;178;179;180;181;182;183;184;185;186;187;188;189;190;191;192;193;194;195;196;197;198;199;200;201;202;203;204;205;206;207;208;209;210;211;212;213;214;215;216;217;218;219;220;221;222;223;224;225;226;227;228;229;230;231;232;233;234;235;236;237;238;239;240;241;242;243;244;245;246;247;248;249;250;251;252;253;254;255;256;257;258;259;260;261;262;263;264;265;266;267;268;269;270;271;272;273;274;275;276;277;278;279;280;281;282;283;284;285;286;287;288;289;290;291;292;293;294;295;296;297;298;299;300;301;302;303;304;305;306;307;308;309;310;311;312;313;314;315;316;317;318;319;320;321;322;323;324;325;326;327;328;329;330;331;332;333;334;335;336;337;338;339;340;341;342;343;344;345;346;347;348;349;350;351;352;353;354;355;356;357;358;359;360;361;362;363;364;365;366;367;368;369;370;371;372;373;374;375;376;377;378;379;380;381;382;383;384;385;386;387;388;389;390;391;392;393;394;395;396;397;398;399;400;401;402;403;404;405;406;407;408;409;410;411;412;413;414;415;416;417;418;419;420;421;422;423;424;425;426;427;428;429;430;431;432;433;434;435;436;437;438;439;440;441;442;443;444;445;446;447;448;449;450;451;452;453;454;455;456;457;458;459;460;461;462;463;464;465;466;467;468;469;470;471;472;473;474;475;476;477;478;479;480;481;482;483;484;485;486;487;488;489;490;491;492;493;494;495;496;497;498;499;500;501;502;503;504;505;506;507;508;509;510;511;512;513;514;515;516;517;518;519;520;521;522;523;524;525;526;527;528;529;530;531;532;533;534;535;536;537;538;539;540;541;542;543;544;545;546;547;548;549;550;551;552;553;554;555;556;557;558;559;560;561;562;563;564;565;566;567;568;569;570;571;572;573;574;575;576;577;578;579;580;581;582;583;584;585;586;587;588;589;590;591;592;593;594;595;596;597;598;599;600;601;602;603;604;605;606;607;608;609;610;611;612;613;614;615;616;617;618;619;620;621;622;623;624;625;626;627;628;629;630;631;632;633;634;635;636;637;638;639;640;641;642;643;644;645;646;647;648;649;650;651;652;653;654;655;656;657;658;659;660;661;662;663;664;665;666;667;668;669;670;671;672;673;674;675;676;677;678;679;680;681;682;683;684;685;686;687;688;689;690;691;692;693;694;695;696;697;698;699;700;701;702;703;704;705;706;707;708;709;710;711;712;713;714;715;716;717;718;719;720;721;722;723;724;725;726;727;728;729;730;731;732;733;734;735;736;737;738;739;740;741;742;743;744;745;746;747;748;749;750;751;752;753;754;755;756;757;758;759;760;761;762;763;764;765;766;767;768;769;770;771;772;773;774;775;776;777;778;779;780;781;782;783;784;785;786;787;788;789;790;791;792;793;794;795;796;797;798;799;800;801;802;803;804;805;806;807;808;809;810;811;812;813;814;815;816;817;818;819;820;821;822;823;824;825;826;827;828;829;830;831;832;833;834;835;836;837;838;839;840;841;842;843;844;845;846;847;848;849;850;851;852;853;854;855;856;857;858;859;860;861;862;863;864;865;866;867;868;869;870;871;872;873;874;875;876;877;878;879;880;881;882;883;884;885;886;887;888;889;890;891;892;893;894;895;896;897;898;899;900;901;902;903;904;905;906;907;908;909;910;911;912;913;914;915;916;917;918;919;920;921;922;923;924;925;926;927;928;929;930;931;932;933;934;935;936;937;938;939;940;941;942;943;944;945;946;947;948;949;950;951;952;953;954;955;956;957;958;959;960;961;962;963;964;965;966;967;968;969;970;971;972;973;974;975;976;977;978;979;980;981;982;983;984;985;986;987;988;989;990;991;992;993;994;995;996;997;998;999;1000"

The specification does not say that the sequence must be generated inside the code :)

MySQL error #1054 - Unknown column in 'Field List'

You have an error in your OrderQuantity column. It is named "OrderQuantity" in the INSERT statement and "OrderQantity" in the table definition.

Also, I don't think you can use NOW() as default value in OrderDate. Try to use the following:

 OrderDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP

Example Fiddle

How to add image in Flutter

Create your assets directory the same as lib level

like this

projectName
 -android
 -ios
 -lib
 -assets
 -pubspec.yaml

then your pubspec.yaml like

  flutter:
  assets:
    - assets/images/

now you can use Image.asset("/assets/images/")

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

To address the question more generally...

Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):

synchronized static void foo() {
    ...
}

is the same as

static void foo() {
    synchronized(SomeClass.class) {
        ...
    }
}

and

synchronized void foo() {
    ...
}

is the same as

void foo() {
    synchronized(this) {
        ...
    }
}

You can use any object as the lock. If you want to lock subsets of static methods, you can

class SomeClass {
    private static final Object LOCK_1 = new Object() {};
    private static final Object LOCK_2 = new Object() {};
    static void foo() {
        synchronized(LOCK_1) {...}
    }
    static void fee() {
        synchronized(LOCK_1) {...}
    }
    static void fie() {
        synchronized(LOCK_2) {...}
    }
    static void fo() {
        synchronized(LOCK_2) {...}
    }
}

(for non-static methods, you would want to make the locks be non-static fields)

How to handle a single quote in Oracle SQL

I found the above answer giving an error with Oracle SQL, you also must use square brackets, below;

SQL> SELECT Q'[Paddy O'Reilly]' FROM DUAL;


Result: Paddy O'Reilly

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

How to discard local changes and pull latest from GitHub repository

To push over old repo. git push -u origin master --force

I think the --force would work for a pull as well.

How to find specified name and its value in JSON-string from Java?

I agree that Google's Gson is clear and easy to use. But you should create a result class for getting an instance from JSON string. If you can't clarify the result class, use json-simple:

// import static org.hamcrest.CoreMatchers.is;
// import static org.junit.Assert.assertThat;
// import org.json.simple.JSONObject;
// import org.json.simple.JSONValue;
// import org.junit.Test;

@Test
public void json2Object() {
    // given
    String jsonString = "{\"name\" : \"John\",\"age\" : \"20\","
            + "\"address\" : \"some address\","
            + "\"someobject\" : {\"field\" : \"value\"}}";

    // when
    JSONObject object = (JSONObject) JSONValue.parse(jsonString);

    // then
    @SuppressWarnings("unchecked")
    Set<String> keySet = object.keySet();
    for (String key : keySet) {
        Object value = object.get(key);
        System.out.printf("%s=%s (%s)\n", key, value, value.getClass()
                .getSimpleName());
    }

    assertThat(object.get("age").toString(), is("20"));
}

Pros and cons of Gson and json-simple is pretty much like pros and cons of user-defined Java Object and Map. The object you define is clear for all fields (name and type), but less flexible than Map.

ReportViewer Client Print Control "Unable to load client print control"?

Our Server environment : SQL2008 x64 SP2 Reporting Services on Windows Server 2008 x64,

Client PC environment: Windows XP SP2 with IE6 or higher, all users are login to Active Directory, users are not members of local Administrator or power user group.

Error: When a user printing a report getting an error as "Unable to load client print control"

Solution that work for us: replace following files in sql 2008 with SQL 2008 R2

Program Files\Microsoft SQL Server\MSRS10.MSSQLSERVER\Reporting Services\ReportServer\bin RSClientPrint-x86.cab RSClientPrint-x64.cab RSClientPrint-ia64.cab

Once you replace the files one server users wont get above error and they do not required local power user or admin right to download Active X. Recommending to add report server URL as a trusted site (add to Trusted sites) via Active Directory GP.

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

These are two ways of using a DLL file in Windows:

  1. There is a stub library (.lib) with associated header files. When you link your executable with the lib-file it will automatically load the DLL file when starting the program.

  2. Loading the DLL manually. This is typically what you want to do if you are developing a plugin system where there are many DLL files implementing a common interface. Check out the documentation for LoadLibrary and GetProcAddress for more information on this.

For Qt I would suspect there are headers and a static library available that you can include and link in your project.

How can I print variable and string on same line in Python?

On a current python version you have to use parenthesis, like so :

print ("If there was a birth every 7 seconds", X)

SQL Server: Get table primary key using sql query

Keep in mind that if you want to get exact primary field you need to put TABLE_NAME and TABLE_SCHEMA into the condition.

this solution should work:

select COLUMN_NAME from information_schema.KEY_COLUMN_USAGE 
where CONSTRAINT_NAME='PRIMARY' AND TABLE_NAME='TABLENAME' 
AND TABLE_SCHEMA='DATABASENAME'

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How to URL encode a string in Ruby

Code:

str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded

Result:

http://localhost/with%20spaces%20and%20spaces

Cookies on localhost with explicit domain

If you're setting a cookie from another domain (ie you set the cookie by making an XHR cross origin request), then you need to make sure you set the withCredentials attribute to true on the XMLHttpRequest you use to fetch the cookie as described here

Reading a date using DataReader

Try as given below:

while (MyReader.Read())
{
    TextBox1.Text = Convert.ToDateTime(MyReader["DateField"]).ToString("dd/MM/yyyy");
}

in ToString() method you can change data format as per your requirement.

What is the difference between i++ & ++i in a for loop?

The way for loop is processed is as follows

1 First, initialization is performed (i=0)

2 the check is performed (i < n)

3 the code in the loop is executed.

4 the value is incremented

5 Repeat steps 2 - 4

This is the reason why, there is no difference between i++ and ++i in the for loop which has been used.

How to list physical disks?

Might want to include the old A: and B: drives as you never know who might be using them! I got tired of USB drives bumping my two SDHC drives that are just for Readyboost. I had been assigning them to High letters Z: Y: with a utility that will assign drive letters to devices as you wish. I wondered.... Can I make a Readyboost drive letter A: ? YES! Can I put my second SDHC drive letter as B: ? YES!

I've used Floppy Drives back in the day, never thought that A: or B: would come in handy for Readyboost.

My point is, don't assume A: & B: will not be used by anyone for anything You might even find the old SUBST command being used!

How to copy multiple files in one layer using a Dockerfile?

It might be worth mentioning that you can also create a .dockerignore file, to exclude the files that you don't want to copy:

https://docs.docker.com/engine/reference/builder/#dockerignore-file

Before the docker CLI sends the context to the docker daemon, it looks for a file named .dockerignore in the root directory of the context. If this file exists, the CLI modifies the context to exclude files and directories that match patterns in it. This helps to avoid unnecessarily sending large or sensitive files and directories to the daemon and potentially adding them to images using ADD or COPY.

How to sort a list of objects based on an attribute of the objects?

It looks much like a list of Django ORM model instances.

Why not sort them on query like this:

ut = Tag.objects.order_by('-count')

How do I ignore files in Subversion?

If you are using TortoiseSVN, right-click on a file and then select TortoiseSVN / Add to ignore list. This will add the file/wildcard to the svn:ignore property.

svn:ignore will be checked when you are checking in files, and matching files will be ignored. I have the following ignore list for a Visual Studio .NET project:

bin obj
*.exe
*.dll
_ReSharper
*.pdb
*.suo

You can find this list in the context menu at TortoiseSVN / Properties.

What is the difference between a deep copy and a shallow copy?

I haven't seen a short, easy to understand answer here--so I'll give it a try.

With a shallow copy, any object pointed to by the source is also pointed to by the destination (so that no referenced objects are copied).

With a deep copy, any object pointed to by the source is copied and the copy is pointed to by the destination (so there will now be 2 of each referenced object). This recurses down the object tree.

jQuery function to open link in new window

$(document).ready(function() {
$('.popup').click(function(event) {
    window.open($(this).attr("href"), "popupWindow", "width=600,height=600,scrollbars=yes");
 });
});

How to read strings from a Scanner in a Java console application?

You are entering a null value to nextInt, it will fail if you give a null value...

i have added a null check to the piece of code

Try this code:

import java.util.Scanner;
class MyClass
{
     public static void main(String args[]){

                Scanner scanner = new Scanner(System.in);
                int eid,sid;
                String ename;
                System.out.println("Enter Employeeid:");
                     eid=(scanner.nextInt());
                System.out.println("Enter EmployeeName:");
                     ename=(scanner.next());
                System.out.println("Enter SupervisiorId:");
                    if(scanner.nextLine()!=null&&scanner.nextLine()!=""){//null check
                     sid=scanner.nextInt();
                     }//null check
        }
}

To draw an Underline below the TextView in Android

Its works for me.

tv.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);

Responsive css background images

If you want the same image to scale based on the size of the browser window:

background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size:contain;
background-position:center;

Do not set width, height, or margins.

EDIT: The previous line about not setting width, height or margin refers to OP's original question about scaling with the window size. In other use cases, you may want to set width/height/margins if necessary.

How to set fake GPS location on IOS real device

There are one solution for fake GPS in ios simulator and real device. we can use GPX file for fake GPS and simulation.

I followed the step by step guidelines of GPX file use in Xcode with simulation. Here is full step by step guidelines of GPX file use. And also you can download the GPX file Demo from github.

How long to brute force a salted SHA-512 hash? (salt provided)

In your case, breaking the hash algorithm is equivalent to finding a collision in the hash algorithm. That means you don't need to find the password itself (which would be a preimage attack), you just need to find an output of the hash function that is equal to the hash of a valid password (thus "collision"). Finding a collision using a birthday attack takes O(2^(n/2)) time, where n is the output length of the hash function in bits.

SHA-2 has an output size of 512 bits, so finding a collision would take O(2^256) time. Given there are no clever attacks on the algorithm itself (currently none are known for the SHA-2 hash family) this is what it takes to break the algorithm.

To get a feeling for what 2^256 actually means: currently it is believed that the number of atoms in the (entire!!!) universe is roughly 10^80 which is roughly 2^266. Assuming 32 byte input (which is reasonable for your case - 20 bytes salt + 12 bytes password) my machine takes ~0,22s (~2^-2s) for 65536 (=2^16) computations. So 2^256 computations would be done in 2^240 * 2^16 computations which would take

2^240 * 2^-2 = 2^238 ~ 10^72s ~ 3,17 * 10^64 years

Even calling this millions of years is ridiculous. And it doesn't get much better with the fastest hardware on the planet computing thousands of hashes in parallel. No human technology will be able to crunch this number into something acceptable.

So forget brute-forcing SHA-256 here. Your next question was about dictionary words. To retrieve such weak passwords rainbow tables were used traditionally. A rainbow table is generally just a table of precomputed hash values, the idea is if you were able to precompute and store every possible hash along with its input, then it would take you O(1) to look up a given hash and retrieve a valid preimage for it. Of course this is not possible in practice since there's no storage device that could store such enormous amounts of data. This dilemma is known as memory-time tradeoff. As you are only able to store so many values typical rainbow tables include some form of hash chaining with intermediary reduction functions (this is explained in detail in the Wikipedia article) to save on space by giving up a bit of savings in time.

Salts were a countermeasure to make such rainbow tables infeasible. To discourage attackers from precomputing a table for a specific salt it is recommended to apply per-user salt values. However, since users do not use secure, completely random passwords, it is still surprising how successful you can get if the salt is known and you just iterate over a large dictionary of common passwords in a simple trial and error scheme. The relationship between natural language and randomness is expressed as entropy. Typical password choices are generally of low entropy, whereas completely random values would contain a maximum of entropy.

The low entropy of typical passwords makes it possible that there is a relatively high chance of one of your users using a password from a relatively small database of common passwords. If you google for them, you will end up finding torrent links for such password databases, often in the gigabyte size category. Being successful with such a tool is usually in the range of minutes to days if the attacker is not restricted in any way.

That's why generally hashing and salting alone is not enough, you need to install other safety mechanisms as well. You should use an artificially slowed down entropy-enducing method such as PBKDF2 described in PKCS#5 and you should enforce a waiting period for a given user before they may retry entering their password. A good scheme is to start with 0.5s and then doubling that time for each failed attempt. In most cases users don't notice this and don't fail much more often than three times on average. But it will significantly slow down any malicious outsider trying to attack your application.

$on and $broadcast in angular

//Your broadcast in service

(function () { 
    angular.module('appModule').factory('AppService', function ($rootScope, $timeout) {

    function refreshData() {  
        $timeout(function() {         
            $rootScope.$broadcast('refreshData');
        }, 0, true);      
    }

    return {           
        RefreshData: refreshData
    };
}); }());

//Controller Implementation
 (function () {
    angular.module('appModule').controller('AppController', function ($rootScope, $scope, $timeout, AppService) {            

       //Removes Listeners before adding them 
       //This line will solve the problem for multiple broadcast call                             
       $scope.$$listeners['refreshData'] = [];

       $scope.$on('refreshData', function() {                                                    
          $scope.showData();             
       });

       $scope.onSaveDataComplete = function() { 
         AppService.RefreshData();
       };
    }); }());

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

Another tip to remember: Since v7.0 OpenSSH disables DSS/DSA SSH keys by default due to their inherit weakness. So if you have OpenSSH v7.0+, make sure your key is not ssh-dss.

If you are stuck with DSA keys, you can re-enable support locally by updating your sshd_config and ~/.ssh/config files with lines like so: PubkeyAcceptedKeyTypes=+ssh-dss

Codeigniter $this->db->order_by(' ','desc') result is not complete

Put the line $this->db->order_by("course_name","desc"); at top of your query. Like

$this->db->order_by("course_name","desc");$this->db->select('*');
$this->db->where('tennant_id',$tennant_id);
$this->db->from('courses');
$query=$this->db->get();
return $query->result();

How to change button color with tkinter

When you do self.button = Button(...).grid(...), what gets assigned to self.button is the result of the grid() command, not a reference to the Button object created.

You need to assign your self.button variable before packing/griding it. It should look something like this:

self.button = Button(self,text="Click Me",command=self.color_change,bg="blue")
self.button.grid(row = 2, column = 2, sticky = W)

How can I hide select options with JavaScript? (Cross browser)

Hiding an <option> element is not in the spec. But you can disable them, which should work cross-browser.

$('option.hide').prop('disabled', true);

http://www.w3.org/TR/html401/interact/forms.html#h-17.6

Turning off hibernate logging console output

Try to set more reasonable logging level. Setting logging level to info means that only log event at info or higher level (warn, error and fatal) are logged, that is debug logging events are ignored.

log4j.logger.org.hibernate=info

or in XML version of log4j config file:

<logger name="org.hibernate">
  <level value="info"/> 
</logger>

See also log4j manual.

How do I replace all the spaces with %20 in C#?

I found useful System.Web.HttpUtility.UrlPathEncode(string str);

It replaces spaces with %20 and not with +.

What EXACTLY is meant by "de-referencing a NULL pointer"?

From wiki

A null pointer has a reserved value, often but not necessarily the value zero, indicating that it refers to no object
..

Since a null-valued pointer does not refer to a meaningful object, an attempt to dereference a null pointer usually causes a run-time error.

int val =1;
int *p = NULL;
*p = val; // Whooosh!!!! 

"Fatal error: Cannot redeclare <function>"

I'd recommend using get_included_files - as Pascal says you're either looking at the wrong file somehow or this function is already defined in a file that's been included.

require_once is also useful if the file you're attempting to include is essential.

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

How do I turn a C# object into a JSON string in .NET?

You can achieve this by using Newtonsoft.json. Install Newtonsoft.json from NuGet. And then:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

If you install the application on your device via adb install you should look for the reinstall option which should be -r. So if you do adb install -r you should be able to install without uninstalling before.

How to calculate age in T-SQL with years, months, and days

Here is some T-SQL that gives you the number of years, months, and days since the day specified in @date. It takes into account the fact that DATEDIFF() computes the difference without considering what month or day it is (so the month diff between 8/31 and 9/1 is 1 month) and handles that with a case statement that decrements the result where appropriate.

DECLARE @date datetime, @tmpdate datetime, @years int, @months int, @days int
SELECT @date = '2/29/04'

SELECT @tmpdate = @date

SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE WHEN (MONTH(@date) > MONTH(GETDATE())) OR (MONTH(@date) = MONTH(GETDATE()) AND DAY(@date) > DAY(GETDATE())) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate)
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE WHEN DAY(@date) > DAY(GETDATE()) THEN 1 ELSE 0 END
SELECT @tmpdate = DATEADD(m, @months, @tmpdate)
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE())

SELECT @years, @months, @days

Find all files with a filename beginning with a specified string?

If you want to restrict your search only to files you should consider to use -type f in your search

try to use also -iname for case-insensitive search

Example:

find /path -iname 'yourstring*' -type f

You could also perform some operations on results without pipe sign or xargs

Example:

Search for files and show their size in MB

find /path -iname 'yourstring*' -type f -exec du -sm {} \;

How to move mouse cursor using C#?

Take a look at the Cursor.Position Property. It should get you started.

private void MoveCursor()
{
   // Set the Current cursor, move the cursor's Position,
   // and set its clipping rectangle to the form. 

   this.Cursor = new Cursor(Cursor.Current.Handle);
   Cursor.Position = new Point(Cursor.Position.X - 50, Cursor.Position.Y - 50);
   Cursor.Clip = new Rectangle(this.Location, this.Size);
}

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

Is it possible to Turn page programmatically in UIPageViewController?

Yes it is possible with the method:

- (void)setViewControllers:(NSArray *)viewControllers 
                 direction:(UIPageViewControllerNavigationDirection)direction 
                  animated:(BOOL)animated 
                completion:(void (^)(BOOL finished))completion;`

That is the same method used for setting up the first view controller on the page. Similar, you can use it to go to other pages.

Wonder why viewControllers is an array, and not a single view controller?

That's because a page view controller could have a "spine" (like in iBooks), displaying 2 pages of content at a time. If you display 1 page of content at a time, then just pass in a 1-element array.

An example in Swift:

pageContainer.setViewControllers([displayThisViewController], direction: .Forward, animated: true, completion: nil)

Extract hostname name from string

import URL from 'url';

const pathname = URL.parse(url).path;
console.log(url.replace(pathname, ''));

this takes care of both the protocol.

How to enable relation view in phpmyadmin

Change your storage engine to InnoDB by going to Operation

How to cast ArrayList<> from List<>

import java.util.List;
import java.util.Arrays;
import java.util.*;

public class Merge
{  
  public static void main(String[] args) {
  // This is normal way
  // List<Integer> l1 = new ArrayList<Integer>(); l1.add(2); l1.add(5); l1.add(10); l1.add(22); 
  // List<Integer> l2 = new ArrayList<Integer>(); l2.add(3); l2.add(8); l2.add(15); 

 //Array.asList only have the list interface, but ArrayList is inherited from List Interface with few more property like ArrayList.remove()
 List<Integer> templ1 = Arrays.asList(2,5,10,22); 
 List<Integer> templ2 =  Arrays.asList(3,8,12);
//So creation of ArrayList with the given list is required, then only ArrayList.remove function works. 
 List<Integer> l1 = new ArrayList<Integer>(templ1);
 List<Integer> l2 = new ArrayList<Integer>(templ2);
 List<Integer> l3 = new ArrayList<Integer>();

 Iterator itr1 = l1.iterator();
 while(itr1.hasNext()){
    int x = (Integer) itr1.next();
    Iterator itr2 = l2.iterator();
    while(itr2.hasNext()) {
      int y = (Integer) itr2.next(); 
      if(x < y) {
        l3.add(x);
        break;
      }
      else{
        l3.add(y);
        itr2.remove();
         
      }
    }
 }
 
 Iterator it = l1.iterator(); 
 while (it.hasNext()){
  int k = (Integer) it.next();
  if (l3.contains(k)){
     continue;
  }
  else{
     l3.add(k);
     System.out.println(k);
  }
 }
 
 Iterator itr2 = l2.iterator();
 while (itr2.hasNext()){
  int k = (Integer) itr2.next();
  l3.add(k);
 }
 
 System.out.println(l3);
 }
}

SQL string value spanning multiple lines in query

I prefer to use the @ symbol so I see the query exactly as I can copy and paste into a query file:

string name = "Joe";
string gender = "M";
string query = String.Format(@"
SELECT
   *
FROM
   tableA
WHERE
   Name = '{0}' AND
   Gender = '{1}'", name, gender);

It's really great with long complex queries. Nice thing is it keeps tabs and line feeds so pasting into a query browser retains the nice formatting

How can I iterate through a string and also know the index (current position)?

A good practice would be based on readability, e.g.:

string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it)
   cout << index++ << *it;

Or:

string str ("Test string");
for (int index = 0, auto it = str.begin(); it < str.end(); ++it, ++index)
   cout << index << *it;

Or your original:

string str ("Test string");
int index = 0;
for (auto it = str.begin() ; it < str.end(); ++it, ++index)
   cout << index << *it;

Etc. Whatever is easiest and cleanest to you.

It's not clear there is any one best practice as you'll need a counter variable somewhere. The question seems to be whether where you define it and how it is incremented works well for you.

How do I add target="_blank" to a link within a specified div?

/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
  $('#link_other a').attr('target', '_blank');
});

// not using jquery
window.onload = function(){
  var anchors = document.getElementById('link_other').getElementsByTagName('a');
  for (var i=0; i<anchors.length; i++){
    anchors[i].setAttribute('target', '_blank');
  }
}
// jquery is prettier. :-)

You could also add a title tag to notify the user that you are doing this, to warn them, because as has been pointed out, it's not what users expect:

$('#link_other a').attr('target', '_blank').attr('title','This link will open in a new window.');

How to run shell script on host from docker container?

To expand on user2915097's response:

The idea of isolation is to be able to restrict what an application/process/container (whatever your angle at this is) can do to the host system very clearly. Hence, being able to copy and execute a file would really break the whole concept.

Yes. But it's sometimes necessary.

No. That's not the case, or Docker is not the right thing to use. What you should do is declare a clear interface for what you want to do (e.g. updating a host config), and write a minimal client/server to do exactly that and nothing more. Generally, however, this doesn't seem to be very desirable. In many cases, you should simply rethink your approach and eradicate that need. Docker came into an existence when basically everything was a service that was reachable using some protocol. I can't think of any proper usecase of a Docker container getting the rights to execute arbitrary stuff on the host.

Angular: Can't find Promise, Map, Set and Iterator

I found the reference in boot.ts wasn't the correct path. Updating that path to /// <reference path=">../../../node_modules/angular2/typings/browser.d.ts" /> resolved the Promise errors.

How to compare two columns in Excel and if match, then copy the cell next to it

It might be easier with vlookup. Try this:

=IFERROR(VLOOKUP(D2,G:H,2,0),"")

The IFERROR() is for no matches, so that it throws "" in such cases.

VLOOKUP's first parameter is the value to 'look for' in the reference table, which is column G and H.

VLOOKUP will thus look for D2 in column G and return the value in the column index 2 (column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.

The last parameter is 0 (or equivalently FALSE) to mean an exact match. That's what you need as opposed to approximate match.

How to expand 'select' option width after the user wants to select an option

I fixed my problem with the following code:

_x000D_
_x000D_
<div style="width: 180px; overflow: hidden;">_x000D_
   <select style="width: auto;" name="abc" id="10">_x000D_
     <option value="-1">AAAAAAAAAAA</option>_x000D_
     <option value="123">123</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope it helps!

Adding a caption to an equation in LaTeX

You may want to look at http://tug.ctan.org/tex-archive/macros/latex/contrib/float/ which allows you to define new floats using \newfloat

I say this because captions are usually applied to floats.

Straight ahead equations (those written with $ ... $, $$ ... $$, begin{equation}...) are in-line objects that do not support \caption.

This can be done using the following snippet just before \begin{document}

\usepackage{float}
\usepackage{aliascnt}
\newaliascnt{eqfloat}{equation}
\newfloat{eqfloat}{h}{eqflts}
\floatname{eqfloat}{Equation}

\newcommand*{\ORGeqfloat}{}
\let\ORGeqfloat\eqfloat
\def\eqfloat{%
  \let\ORIGINALcaption\caption
  \def\caption{%
    \addtocounter{equation}{-1}%
    \ORIGINALcaption
  }%
  \ORGeqfloat
}

and when adding an equation use something like

\begin{eqfloat}
\begin{equation}
f( x ) = ax + b
\label{eq:linear}
\end{equation}
\caption{Caption goes here}
\end{eqfloat}

How to "inverse match" with regex?

In perl you can do

process($line) if ($line =~ !/Andrea/);

Replace \n with <br />

For some reason using python3 I had to escape the "\"-sign

somestring.replace('\\n', '')

Hope this helps someone else!

Get size of an Iterable in Java

java 8 and above

StreamSupport.stream(data.spliterator(), false).count();

How to get current screen width in CSS?

this can be achieved with the css calc() operator

@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
        zoom:calc(100% / 480);
    }
}

Android translate animation - permanently move View to new position using AnimationListener

You should rather use ViewPropertyAnimator. This animates the view to its future position and you don't need to force any layout params on the view after the animation ends. And it's rather simple.

myView.animate().x(50f).y(100f);

myView.animate().translateX(pixelInScreen) 

Note: This pixel is not relative to the view. This pixel is the pixel position in the screen.

ImportError: cannot import name

When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a

import importlib

and

importlib.reload (*module*)

likely to solve your problem

Mockito : doAnswer Vs thenReturn

doAnswer and thenReturn do the same thing if:

  1. You are using Mock, not Spy
  2. The method you're stubbing is returning a value, not a void method.

Let's mock this BookService

public interface BookService {
    String getAuthor();
    void queryBookTitle(BookServiceCallback callback);
}

You can stub getAuthor() using doAnswer and thenReturn.

BookService service = mock(BookService.class);
when(service.getAuthor()).thenReturn("Joshua");
// or..
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        return "Joshua";
    }
}).when(service).getAuthor();

Note that when using doAnswer, you can't pass a method on when.

// Will throw UnfinishedStubbingException
doAnswer(invocation -> "Joshua").when(service.getAuthor());

So, when would you use doAnswer instead of thenReturn? I can think of two use cases:

  1. When you want to "stub" void method.

Using doAnswer you can do some additionals actions upon method invocation. For example, trigger a callback on queryBookTitle.

BookServiceCallback callback = new BookServiceCallback() {
    @Override
    public void onSuccess(String bookTitle) {
        assertEquals("Effective Java", bookTitle);
    }
};
doAnswer(new Answer() {
    @Override
    public Object answer(InvocationOnMock invocation) throws Throwable {
        BookServiceCallback callback = (BookServiceCallback) invocation.getArguments()[0];
        callback.onSuccess("Effective Java");
        // return null because queryBookTitle is void
        return null;
    }
}).when(service).queryBookTitle(callback);
service.queryBookTitle(callback);
  1. When you are using Spy instead of Mock

When using when-thenReturn on Spy Mockito will call real method and then stub your answer. This can cause a problem if you don't want to call real method, like in this sample:

List list = new LinkedList();
List spy = spy(list);
// Will throw java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
when(spy.get(0)).thenReturn("java");
assertEquals("java", spy.get(0));

Using doAnswer we can stub it safely.

List list = new LinkedList();
List spy = spy(list);
doAnswer(invocation -> "java").when(spy).get(0);
assertEquals("java", spy.get(0));

Actually, if you don't want to do additional actions upon method invocation, you can just use doReturn.

List list = new LinkedList();
List spy = spy(list);
doReturn("java").when(spy).get(0);
assertEquals("java", spy.get(0));

"Retrieving the COM class factory for component.... error: 80070005 Access is denied." (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))

Came across this issue two days back, spent whole complete two days, So I found that I need to give the access to IUSR user group at DCOMCNFG --> My Computer Properties --> Com Security --> Launch and Activation Permissions --> Edit defaults and give all rights to IUSR.

hope it will help someone....

Java error: Comparison method violates its general contract

The exception message is actually pretty descriptive. The contract it mentions is transitivity: if A > B and B > C then for any A, B and C: A > C. I checked it with paper and pencil and your code seems to have few holes:

if (card1.getRarity() < card2.getRarity()) {
  return 1;

you do not return -1 if card1.getRarity() > card2.getRarity().


if (card1.getId() == card2.getId()) {
  //...
}
return -1;

You return -1 if ids aren't equal. You should return -1 or 1 depending on which id was bigger.


Take a look at this. Apart from being much more readable, I think it should actually work:

if (card1.getSet() > card2.getSet()) {
    return 1;
}
if (card1.getSet() < card2.getSet()) {
    return -1;
};
if (card1.getRarity() < card2.getRarity()) {
    return 1;
}
if (card1.getRarity() > card2.getRarity()) {
    return -1;
}
if (card1.getId() > card2.getId()) {
    return 1;
}
if (card1.getId() < card2.getId()) {
    return -1;
}
return cardType - item.getCardType();  //watch out for overflow!

What do parentheses surrounding an object/function/class declaration mean?

The first parentheses are for, if you will, order of operations. The 'result' of the set of parentheses surrounding the function definition is the function itself which, indeed, the second set of parentheses executes.

As to why it's useful, I'm not enough of a JavaScript wizard to have any idea. :P

Performance of Arrays vs. Lists

The measurements are nice, but you are going to get significantly different results depending on what you're doing exactly in your inner loop. Measure your own situation. If you're using multi-threading, that alone is a non-trivial activity.

Unprotect workbook without password

Try the below code to unprotect the workbook. It works for me just fine in excel 2010 but I am not sure if it will work in 2013.

Sub PasswordBreaker()
    'Breaks worksheet password protection.
    Dim i As Integer, j As Integer, k As Integer
    Dim l As Integer, m As Integer, n As Integer
    Dim i1 As Integer, i2 As Integer, i3 As Integer
    Dim i4 As Integer, i5 As Integer, i6 As Integer
    On Error Resume Next
    For i = 65 To 66: For j = 65 To 66: For k = 65 To 66
    For l = 65 To 66: For m = 65 To 66: For i1 = 65 To 66
    For i2 = 65 To 66: For i3 = 65 To 66: For i4 = 65 To 66
    For i5 = 65 To 66: For i6 = 65 To 66: For n = 32 To 126
    ThisWorkbook.Unprotect Chr(i) & Chr(j) & Chr(k) & _
        Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & Chr(i3) & _
        Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
    If ThisWorkbook.ProtectStructure = False Then
        MsgBox "One usable password is " & Chr(i) & Chr(j) & _
            Chr(k) & Chr(l) & Chr(m) & Chr(i1) & Chr(i2) & _
            Chr(i3) & Chr(i4) & Chr(i5) & Chr(i6) & Chr(n)
         Exit Sub
    End If
    Next: Next: Next: Next: Next: Next
    Next: Next: Next: Next: Next: Next
End Sub

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

Deleting Objects in JavaScript

I stumbled across this article in my search for this same answer. What I ended up doing is just popping out obj.pop() all the stored values/objects in my object so I could reuse the object. Not sure if this is bad practice or not. This technique came in handy for me testing my code in Chrome Dev tools or FireFox Web Console.

How do you unit test private methods?

You could also declare it as public or internal (with InternalsVisibleToAttribute) while building in debug-Mode:

    /// <summary>
    /// This Method is private.
    /// </summary>
#if DEBUG
    public
#else
    private
#endif
    static string MyPrivateMethod()
    {
        return "false";
    }

It bloats the code, but it will be private in a release build.

How to make a div center align in HTML

it depends if your div is in position: absolute / fixed or relative / static

for position: absolute & fixed

<div style="position: absolute; /*or fixed*/;
width: 50%;
height: 300px;
left: 50%;
top:100px;
margin: 0 0 0 -25%">blblablbalba</div>

The trick here is to have a negative margin half the width of the object

for position: relative & static

<div style="position: relative; /*or static*/;
width: 50%;
height: 300px;
margin: 0 auto">blblablbalba</div>

for both techniques, it is imperative to set the width.

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

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

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

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

enter image description here

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

Execute command without keeping it in history

In any given Bash session, set the history file to /dev/null by typing:

export HISTFILE=/dev/null

Note that, as pointed out in the comments, this will not write any commands in that session to the history!

Just don't mess with your system administrator's hard work, please ;)

Doodad's solution is more elegant. Simply unset the variable: unset HISTFILE (thanks!)

Any easy way to use icons from resources?

  1. Add the icon to the project resources and rename to icon.

  2. Open the designer of the form you want to add the icon to.

  3. Append the InitializeComponent function.

  4. Add this line in the top:

    this.Icon = PROJECTNAME.Properties.Resources.icon;
    

    repeat step 4 for any forms in your project you want to update

Repeat command automatically in Linux

Running commands periodically without cron is possible when we go with while.

As a command:

while true ; do command ; sleep 100 ; done &
[ ex: # while true;  do echo `date` ; sleep 2 ; done & ]

Example:

while true
do echo "Hello World"
sleep 100
done &

Do not forget the last & as it will put your loop in the background. But you need to find the process id with command "ps -ef | grep your_script" then you need to kill it. So kindly add the '&' when you running the script.

# ./while_check.sh &

Here is the same loop as a script. Create file "while_check.sh" and put this in it:

#!/bin/bash
while true; do 
    echo "Hello World" # Substitute this line for whatever command you want.
    sleep 100
done

Then run it by typing bash ./while_check.sh &

What techniques can be used to speed up C++ compilation times?

I had an idea about using a RAM drive. It turned out that for my projects it doesn't make that much of a difference after all. But then they are pretty small still. Try it! I'd be interested in hearing how much it helped.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

To be absolutely correct you should put all the names into the SAN field.

The CN field should contain a Subject Name not a domain name, but when the Netscape found out this SSL thing, they missed to define its greatest market. Simply there was not certificate field defined for the Server URL.

This was solved to put the domain into the CN field, and nowadays usage of the CN field is deprecated, but still widely used. The CN can hold only one domain name.

The general rules for this: CN - put here your main URL (for compatibility) SAN - put all your domain here, repeat the CN because its not in right place there, but its used for that...

If you found a correct implementation, the answers for your questions will be the followings:

  • Has this setup a special meaning, or any [dis]advantages over setting both CNs? You cant set both CNs, because CN can hold only one name. You can make with 2 simple CN certificate instead one CN+SAN certificate, but you need 2 IP addresses for this.

  • What happens on server-side if the other one, host.domain.tld, is being requested? It doesn't matter whats happen on server side.

In short: When a browser client connects to this server, then the browser sends encrypted packages, which are encrypted with the public key of the server. Server decrypts the package, and if server can decrypt, then it was encrypted for the server.

The server doesn't know anything from the client before decrypt, because only the IP address is not encrypted trough the connection. This is why you need 2 IPs for 2 certificates. (Forget SNI, there is too much XP out there still now.)

On client side the browser gets the CN, then the SAN until all of the are checked. If one of the names matches for the site, then the URL verification was done by the browser. (im not talking on the certificate verification, of course a lot of ocsp, crl, aia request and answers travels on the net every time.)

Gridview row editing - dynamic binding to a DropDownList

Quite easy... You're doing it wrong, because by that event the control is not there:

protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow && 
        (e.Row.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
    { 
        // Here you will get the Control you need like:
        DropDownList dl = (DropDownList)e.Row.FindControl("ddlPBXTypeNS");
    }
}

That is, it will only be valid for a DataRow (the actually row with data), and if it's in Edit mode... because you only edit one row at a time. The e.Row.FindControl("ddlPBXTypeNS") will only find the control that you want.

Multi-statement Table Valued Function vs Inline Table Valued Function

Another case to use a multi line function would be to circumvent sql server from pushing down the where clause.

For example, I have a table with a table names and some table names are formatted like C05_2019 and C12_2018 and and all tables formatted that way have the same schema. I wanted to merge all that data into one table and parse out 05 and 12 to a CompNo column and 2018,2019 into a year column. However, there are other tables like ACA_StupidTable which I cannot extract CompNo and CompYr and would get a conversion error if I tried. So, my query was in two part, an inner query that returned only tables formatted like 'C_______' then the outer query did a sub-string and int conversion. ie Cast(Substring(2, 2) as int) as CompNo. All looks good except that sql server decided to put my Cast function before the results were filtered and so I get a mind scrambling conversion error. A multi statement table function may prevent that from happening, since it is basically a "new" table.

Add Bootstrap Glyphicon to Input Box

Without Bootstrap:

We'll get to Bootstrap in a second, but here's the fundamental CSS concepts in play in order to do this yourself. As beard of prey points out, you can do this with CSS by absolutely positioning the icon inside of the input element. Then add padding to either side so the text doesn't overlap with the icon.

So for the following HTML:

<div class="inner-addon left-addon">
    <i class="glyphicon glyphicon-user"></i>
    <input type="text" class="form-control" />
</div>

You can use the following CSS to left and right align glyphs:

/* enable absolute positioning */
.inner-addon { 
    position: relative; 
}

/* style icon */
.inner-addon .glyphicon {
  position: absolute;
  padding: 10px;
  pointer-events: none;
}

/* align icon */
.left-addon .glyphicon  { left:  0px;}
.right-addon .glyphicon { right: 0px;}

/* add padding  */
.left-addon input  { padding-left:  30px; }
.right-addon input { padding-right: 30px; }

Demo in Plunker

css screenshot

Note: This presumes you're using glyphicons, but works equally well with font-awesome.
For FA, just replace .glyphicon with .fa


With Bootstrap:

As buffer points out, this can be accomplished natively within Bootstrap by using Validation States with Optional Icons. This is done by giving the .form-group element the class of .has-feedback and the icon the class of .form-control-feedback.

The simplest example would be something like this:

<div class="form-group has-feedback">
    <label class="control-label">Username</label>
    <input type="text" class="form-control" placeholder="Username" />
    <i class="glyphicon glyphicon-user form-control-feedback"></i>
</div>

Pros:

  • Includes support for different form types (Basic, Horizontal, Inline)
  • Includes support for different control sizes (Default, Small, Large)

Cons:

  • Doesn't include support for left aligning icons

To overcome the cons, I put together this pull-request with changes to support left aligned icons. As it is a relatively large change, it has been put off until a future release, but if you need these features today, here's a simple implementation guide:

Just include the these form changes in css (also inlined via hidden stack snippet at the bottom)
*LESS: alternatively, if you are building via less, here's the form changes in less

Then, all you have to do is include the class .has-feedback-left on any group that has the class .has-feedback in order to left align the icon.

Since there are a lot of possible html configurations over different form types, different control sizes, different icon sets, and different label visibilities, I created a test page that shows the correct set of HTML for each permutation along with a live demo.

Here's a demo in Plunker

feedback screenshot

P.S. frizi's suggestion of adding pointer-events: none; has been added to bootstrap

Didn't find what you were looking for? Try these similar questions:

Addition CSS for Left Aligned feedback icons

_x000D_
_x000D_
.has-feedback .form-control {_x000D_
  padding-right: 34px;_x000D_
}_x000D_
.has-feedback .form-control.input-sm,_x000D_
.has-feedback.form-group-sm .form-control {_x000D_
  padding-right: 30px;_x000D_
}_x000D_
.has-feedback .form-control.input-lg,_x000D_
.has-feedback.form-group-lg .form-control {_x000D_
  padding-right: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control {_x000D_
  padding-right: 12px;_x000D_
  padding-left: 34px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-sm,_x000D_
.has-feedback-left.form-group-sm .form-control {_x000D_
  padding-left: 30px;_x000D_
}_x000D_
.has-feedback-left .form-control.input-lg,_x000D_
.has-feedback-left.form-group-lg .form-control {_x000D_
  padding-left: 46px;_x000D_
}_x000D_
.has-feedback-left .form-control-feedback {_x000D_
  left: 0;_x000D_
}_x000D_
.form-control-feedback {_x000D_
  line-height: 34px !important;_x000D_
}_x000D_
.input-sm + .form-control-feedback,_x000D_
.form-horizontal .form-group-sm .form-control-feedback {_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  line-height: 30px !important;_x000D_
}_x000D_
.input-lg + .form-control-feedback,_x000D_
.form-horizontal .form-group-lg .form-control-feedback {_x000D_
  width: 46px;_x000D_
  height: 46px;_x000D_
  line-height: 46px !important;_x000D_
}_x000D_
.has-feedback label.sr-only ~ .form-control-feedback,_x000D_
.has-feedback label.sr-only ~ div .form-control-feedback {_x000D_
  top: 0;_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
  .form-inline .inline-feedback {_x000D_
    position: relative;_x000D_
    display: inline-block;_x000D_
  }_x000D_
  .form-inline .has-feedback .form-control-feedback {_x000D_
    top: 0;_x000D_
  }_x000D_
}_x000D_
.form-horizontal .has-feedback-left .form-control-feedback {_x000D_
  left: 15px;_x000D_
}
_x000D_
_x000D_
_x000D_

Store output of subprocess.Popen call in a string

In Python 3.7 a new keyword argument capture_output was introduced for subprocess.run. Enabling the short and simple:

import subprocess

p = subprocess.run("echo 'hello world!'", capture_output=True, shell=True, encoding="utf8")
assert p.stdout == 'hello world!\n'

This action could not be completed. Try Again (-22421)

I've tried to load archive nearly 10 times (with all kinds of cleans and reloads, with different versions and provisioning files), still received the same error. Then suddenly on my next attempt it showed me: "cannot proceed with delivery an existing transporter instance is currently uploading this package", I did the following and it helped:

Basically, you need to clear out the transport tokens. This can happen if you were to close out of Xcode while in the middle of submitting an app to iTunes Connect.

/Users/<username>/.itmstransporter/UploadTokens/

Delete any .token files in this directory. If you are unable to find the .token files, this is because they are hidden in Finder. To hide/show hidden files in Finder, use the following Terminal command (TRUE = UNHIDE, FALSE = HIDE):

defaults write com.apple.finder AppleShowAllFiles TRUE;killall Finder

How to make an inline element appear on new line, or block element not occupy the whole line?

Even though the question is quite fuzzy and the HTML snippet is quite limited, I suppose

.feature_desc {
    display: block;
}
.feature_desc:before {
    content: "";
    display: block;
}

might give you want you want to achieve without the <br/> element. Though it would help to see your CSS applied to these elements.

NOTE. The example above doesn't work in IE7 though.

Where can I download IntelliJ IDEA Color Schemes?

This is just a suggestion, but what I like to do while I'm coding sometimes is to Invert the colors of my Screen. On a Mac it's Ctrl-Cmd-Alt->8 and it inverts the colors.

Haven't personally tried these in Idea10, but it worked on Idea9. http://devnet.jetbrains.net/docs/DOC-1154

Automatically plot different colored lines

If all vectors have equal size, create a matrix and plot it. Each column is plotted with a different color automatically Then you can use legend to indicate columns:

data = randn(100, 5);

figure;
plot(data);

legend(cellstr(num2str((1:size(data,2))')))

Or, if you have a cell with kernels names, use

legend(names)

Why is System.Web.Mvc not listed in Add References?

This has changed for Visual Studio 2012 (I know the original question says VS2010, but the title will still hit on searches).

When you create a VS2012 MVC project, the system.web.mvc is placed in the packages folder which is peer to the solution. This will be referenced in the web project by default and you can find the exact path there).

If you want to reference this in a secondary project (say a supporting .dll with filters or other attributes), then you can reference it from there.

console.log showing contents of array object

The console object is available in Internet Explorer 8 or newer, but only if you open the Developer Tools window by pressing F12 or via the menu.

It stays available even if you close the Developer Tools window again until you close your IE.

Chorme and Opera always have an available console, at least in the current versions. Firefox has a console when using Firebug, but it may also provide one without Firebug.

In any case it is a save approach to make the use of console output optional. Here are some examples on how to do that:

if (console) {
    console.log('Hello World!');
}

if (console) console.debug('value of someVar: ' + someVar);

How do I determine the current operating system with Node.js

With Node.js v6 (and above) there is a dedicated os module, which provides a number of operating system-related utility methods.

On my Windows 10 machine it reports the following:

var os = require('os');

console.log(os.type()); // "Windows_NT"
console.log(os.release()); // "10.0.14393"
console.log(os.platform()); // "win32"

You can read it's full documentation here: https://nodejs.org/api/os.html#os_os_type

C Program to find day of week given date

A one-liner is unlikely, but the strptime function can be used to parse your date format and the struct tm argument can be queried for its tm_wday member on systems that modify those fields automatically (e.g. some glibc implementations).

int get_weekday(char * str) {
  struct tm tm;
  memset((void *) &tm, 0, sizeof(tm));
  if (strptime(str, "%d-%m-%Y", &tm) != NULL) {
    time_t t = mktime(&tm);
    if (t >= 0) {
      return localtime(&t)->tm_wday; // Sunday=0, Monday=1, etc.
    }
  }
  return -1;
}

Or you could encode these rules to do some arithmetic in a really long single line:

  • 1 Jan 1900 was a Monday.
  • Thirty days has September, April, June and November; all the rest have thirty-one, saving February alone, which has twenty-eight, rain or shine, and on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.

EDIT: note that this solution only works for dates after the UNIX epoch (1970-01-01T00:00:00Z).

SQL Server 2008- Get table constraints

I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.

SELECT 
    tab.name AS [Table]
    ,tab.id AS [Table Id]
    ,constr.name AS [Constraint Name]
    ,constr.xtype AS [Constraint Type]
    ,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
    ,i.index_id AS [Index ID]
    ,ic.column_id AS [Column ID]
    ,clmns.name AS [Column Name]
    ,clmns.max_length AS [Column Max Length]
    ,clmns.precision AS [Column Precision]
    ,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
    ,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) 
                                    AND (ic.index_id=CAST(i.index_id AS int) 
                                    AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name

Adding hours to JavaScript Date object?

The below code is to add 4 hours to date(example today's date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

How to fire an event on class change using jQuery?

There is no event raised when a class changes. The alternative is to manually raise an event when you programatically change the class:

$someElement.on('event', function() {
    $('#myDiv').addClass('submission-ok').trigger('classChange');
});

// in another js file, far, far away
$('#myDiv').on('classChange', function() {
     // do stuff
});

UPDATE

This question seems to be gathering some visitors, so here is an update with an approach which can be used without having to modify existing code using the new MutationObserver:

_x000D_
_x000D_
var $div = $("#foo");_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
  mutations.forEach(function(mutation) {_x000D_
    if (mutation.attributeName === "class") {_x000D_
      var attributeValue = $(mutation.target).prop(mutation.attributeName);_x000D_
      console.log("Class attribute changed to:", attributeValue);_x000D_
    }_x000D_
  });_x000D_
});_x000D_
observer.observe($div[0], {_x000D_
  attributes: true_x000D_
});_x000D_
_x000D_
$div.addClass('red');
_x000D_
.red { color: #C00; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="foo" class="bar">#foo.bar</div>
_x000D_
_x000D_
_x000D_

Be aware that the MutationObserver is only available for newer browsers, specifically Chrome 26, FF 14, IE 11, Opera 15 and Safari 6. See MDN for more details. If you need to support legacy browsers then you will need to use the method I outlined in my first example.

How do I collapse a table row in Bootstrap?

Which version of Bootstrap are you using? I was perplexed that I could get @Chad's solution to work in jsfiddle, but not locally. So, I checked the version of Bootstrap used by jsfiddle, and it's using a 3.0.0-rc1 release, while the default download on getbootstrap.com is version 2.3.2.

In 2.3.2 the collapse class wasn't getting replaced by the in class. The in class was simply getting appended when the button was clicked. In version 3.0.0-rc1, the collapse class correctly is removed, and the <tr> collapses.

Use @Chad's solution for the html, and try using these links for referencing Bootstrap:

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/css/bootstrap.min.css" rel="stylesheet">
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0-rc1/js/bootstrap.min.js"></script>

How to turn on front flash light programmatically in Android?

Android Lollipop introduced camera2 API and deprecated the previous camera API. However, using the deprecated API to turn on the flash still works and is much simpler than using the new API.

It seems that the new API is intended for use in dedicated full featured camera apps and that its architects didn't really consider simpler use cases such as turning on the flashlight. To do that now, one has to get a CameraManager, create a CaptureSession with a dummy Surface, and finally create and start a CaptureRequest. Exception handling, resource cleanup and long callbacks included!

To see how to turn the flashlight on Lollipop and newer, take a look at the FlashlightController in the AOSP project (try to find the newest as older use APIs that have been modified). Don't forget to set the needed permissions.


Android Marshmallow finally introduced a simple way to turn on the flash with setTorchMode.

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

How to know which is running in Jupyter notebook?

Assuming you have the wrong backend system you can change the backend kernel by creating a new or editing the existing kernel.json in the kernels folder of your jupyter data path jupyter --paths. You can have multiple kernels (R, Python2, Python3 (+virtualenvs), Haskell), e.g. you can create an Anaconda specific kernel:

$ <anaconda-path>/bin/python3 -m ipykernel install --user --name anaconda --display-name "Anaconda"

Should create a new kernel:

<jupyter-data-dir>/kernels/anaconda/kernel.json

{
    "argv": [ "<anaconda-path>/bin/python3", "-m", "ipykernel", "-f", "{connection_file}" ],
    "display_name": "Anaconda",
    "language": "python"
}

You need to ensure ipykernel package is installed in the anaconda distribution.

This way you can just switch between kernels and have different notebooks using different kernels.

JavaScript data grid for millions of rows

(Disclaimer: I am the author of w2ui)

I have recently written an article on how to implement JavaScript grid with 1 million records (http://w2ui.com/web/blog/7/JavaScript-Grid-with-One-Million-Records). I discovered that ultimately there are 3 restrictions that prevent from taking it highter:

  1. Height of the div has a limit (can be overcome by virtual scrolling)
  2. Operations such as sort and search start being slow after 1 million records or so
  3. RAM is limited because data is stored in JavaScript array

I have tested the grid with 1 million records (except IE) and it performs well. See article for demos and examples.

How to send a POST request in Go?

You have mostly the right idea, it's just the sending of the form that is wrong. The form belongs in the body of the request.

req, err := http.NewRequest("POST", url, strings.NewReader(form.Encode()))

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

install apt-get on linux Red Hat server

wget http://dag.wieers.com/packages/apt/apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

rpm -ivh apt-0.5.15lorg3.1-4.el4.rf.i386.rpm

wget http://dag.wieers.com/packages/rpmforge-release/rpmforge-release-0.3.4-1.el4.rf.i386.rpm

rpm -Uvh rpmforge-release-0.3.4-1.el4.rf.i386.rpm

maybe some URL is broken,please research it. Enjoy~~

Cannot run the macro... the macro may not be available in this workbook

This error also occurs if you create a sub or function in a 'Microsoft Excel Object' (like Sheet1, Sheet2, ...) instead to create it in a Module.

For example: you create with VBA a button and set .OnAction = 'btn_action' . And Sub btn_action you placed into the Sheet object instead into a Module.

Unmarshaling nested JSON objects

This is an example of how to unmarshall JSON responses from the Safebrowsing v4 API sbserver proxy server: https://play.golang.org/p/4rGB5da0Lt

// this example shows how to unmarshall JSON requests from the Safebrowsing v4 sbserver
package main

import (
    "fmt"
    "log"
    "encoding/json"
)

// response from sbserver POST request
type Results struct {
    Matches []Match     
}

// nested within sbserver response
type Match struct {
    ThreatType string 
    PlatformType string 
    ThreatEntryType string 
    Threat struct {
        URL string
    }
}

func main() {
    fmt.Println("Hello, playground")

    // sample POST request
    //   curl -X POST -H 'Content-Type: application/json' 
    // -d '{"threatInfo": {"threatEntries": [{"url": "http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}]}}' 
    // http://127.0.0.1:8080/v4/threatMatches:find

    // sample JSON response
    jsonResponse := `{"matches":[{"threatType":"MALWARE","platformType":"ANY_PLATFORM","threatEntryType":"URL","threat":{"url":"http://testsafebrowsing.appspot.com/apiv4/ANY_PLATFORM/MALWARE/URL/"}}]}`

    res := &Results{}
    err := json.Unmarshal([]byte(jsonResponse), res)
        if(err!=nil) {
            log.Fatal(err)
        }

    fmt.Printf("%v\n",res)
    fmt.Printf("\tThreat Type: %s\n",res.Matches[0].ThreatType)
    fmt.Printf("\tPlatform Type: %s\n",res.Matches[0].PlatformType)
    fmt.Printf("\tThreat Entry Type: %s\n",res.Matches[0].ThreatEntryType)
    fmt.Printf("\tURL: %s\n",res.Matches[0].Threat.URL)
}

How to reload current page?

A little bit tricky to do something so simple but had no luck trying to reload and recreate the entire parent & child components with current solution.

Angular Router now provides strategy configuration to tell the Router what to do in case you navigate to the same URL as this user suggests in this GitHub issue.

First of all you can configure what to do while setting up the Router (your router module).

@NgModule({
   imports: [RouterModule.forRoot(routes, { onSameUrlNavigation: 'reload' })],
   exports: [RouterModule]
})

Or, if you are like me and don't want to change the entire router module behaviour you can do it with a method/function like this:

reloadComponent() {
    this._router.routeReuseStrategy.shouldReuseRoute = () => false;
    this._router.onSameUrlNavigation = 'reload';
    this._router.navigate(['/same-route']);
}

Of course you have to first inject Router in your component's constructor:

// import { Router } from '@angular/router';
...
constructor(private _router: Router){}
...

Somehow and as pointed out by @Abhiz you have to set shouldReuseRoute, with just configuring the Router by itself the page reload doesn't work with this aproach.

I've used an arrow function for shouldReuseRoutebecause new TSLint rules won't allow non-arrow functions.

Jquery select this + class

Maybe something like: $(".subclass", this);

How to catch all exceptions in c# using try and catch?

Both ways are correct.

If you need to do something with the Exception object in the catch block then you should use

try {
    // code....
}
catch (Exception ex){}

and then use ex in the catch block.

Anyway, it is not always a good practice to catch the Exception class, it is a better practice to catch a more specific exception - an exception which you expect.

How to use (install) dblink in PostgreSQL?

On linux, find dblink.sql, then execute in the postgresql console something like this to create all required functions:

\i /usr/share/postgresql/8.4/contrib/dblink.sql 

you might need to install the contrib packages: sudo apt-get install postgresql-contrib

How to make MySQL handle UTF-8 properly

Was able to find a solution. Ran the following as specified at http://technoguider.com/2015/05/utf8-set-up-in-mysql/

SET NAMES UTF8;
set collation_server = utf8_general_ci;
set default-character-set = utf8;
set init_connect = ’SET NAMES utf8';
set character_set_server = utf8;
set character_set_client = utf8;

Escape a string in SQL Server so that it is safe to use in LIKE expression

Alternative escaping syntax:

LIKE Wildcard Literals

The JDBC driver supports the {escape 'escape character'} syntax for using LIKE clause wildcards as literals.

SELECT *
FROM tab
WHERE col LIKE 'a\_c' {escape '\'};

db<>fiddle demo

Doing HTTP requests FROM Laravel to an external API

Definitively, for any PHP project, you may want to use GuzzleHTTP for sending requests. Guzzle has very nice documentation you can check here. I just want to say that, you probably want to centralize the usage of the Client class of Guzzle in any component of your Laravel project (for example a trait) instead of being creating Client instances on several controllers and components of Laravel (as many articles and replies suggest).

I created a trait you can try to use, which allows you to send requests from any component of your Laravel project, just using it and calling to makeRequest.

namespace App\Traits;
use GuzzleHttp\Client;
trait ConsumesExternalServices
{
    /**
     * Send a request to any service
     * @return string
     */
    public function makeRequest($method, $requestUrl, $queryParams = [], $formParams = [], $headers = [], $hasFile = false)
    {
        $client = new Client([
            'base_uri' => $this->baseUri,
        ]);

        $bodyType = 'form_params';

        if ($hasFile) {
            $bodyType = 'multipart';
            $multipart = [];

            foreach ($formParams as $name => $contents) {
                $multipart[] = [
                    'name' => $name,
                    'contents' => $contents
                ];
            }
        }

        $response = $client->request($method, $requestUrl, [
            'query' => $queryParams,
            $bodyType => $hasFile ? $multipart : $formParams,
            'headers' => $headers,
        ]);

        $response = $response->getBody()->getContents();

        return $response;
    }
}

Notice this trait can even handle files sending.

If you want more details about this trait and some other stuff to integrate this trait to Laravel, check this article. Additionally, if interested in this topic or need major assistance, you can take my course which guides you in the whole process.

I hope it helps all of you.

Best wishes :)

Search a text file and print related lines in Python?

Note the potential for an out-of-range index with "i+3". You could do something like:

with open("file.txt", "r") as f:
    searchlines = f.readlines()
j=len(searchlines)-1
for i, line in enumerate(searchlines):
    if "searchphrase" in line: 
        k=min(i+3,j)
        for l in searchlines[i:k]: print l,
        print

Edit: maybe not necessary. I just tested some examples. x[y] will give errors if y is out of range, but x[y:z] doesn't seem to give errors for out of range values of y and z.

Visual Studio Code - Convert spaces to tabs

If you want to use tabs instead of spaces

Try this:

  1. Go to File ? Preferences ? Settings or just press Ctrl + ,
  2. In the Search settings bar on top insert editor.insertSpaces
  3. You will see something like this: Editor: Insert Spaces and it will be probably checked. Just uncheck it as show in image below

Editor: Insert Spaces

  1. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

If it doesn't worked try this:

It's probably because of installed plugin JS-CSS-HTML Formatter

(You can check it by going to File ? Preferences ? Extensions or just pressing Ctrl + Shift + X, in the Enabled list you will find JS-CSS-HTML Formatter)

If so you can modify this plugin:

  1. Press F1 ? type Formatter config ? press Enter (it will open the file formatter.json)
  2. Modify the file like this:
 4|    "indent_size": 1,
 5|    "indent_char": "\t"
——|
24|    "indent_size": 1,
25|    "indentCharacter": "\t",
26|    "indent_char": "\t",
——|
34|    "indent_size": 1,
35|    "indent_char": "\t",
36|    "indent_character": "\t"
  1. Save it (Go to File ? Save or just press Ctrl + S)
  2. Reload Visual Studio Code (Press F1 ? type reload window ? press Enter)

Display all items in array using jquery

for (var i = 0; i < array.length; i++) {
    $(".element").append('<span>' + array[i] + '</span>');
}

How to reliably open a file in the same directory as a Python script

I'd do it this way:

from os.path import abspath, exists

f_path = abspath("fooabar.txt")

if exists(f_path):
    with open(f_path) as f:
        print f.read()

The above code builds an absolute path to the file using abspath and is equivalent to using normpath(join(os.getcwd(), path)) [that's from the pydocs]. It then checks if that file actually exists and then uses a context manager to open it so you don't have to remember to call close on the file handle. IMHO, doing it this way will save you a lot of pain in the long run.

Install a Nuget package in Visual Studio Code

You can use the NuGet Package Manager extension.

After you've installed it, to add a package, press Ctrl+Shift+P, and type >nuget and press Enter:

enter image description here

Type a part of your package's name as search string:

enter image description here

Choose the package:

enter image description here

And finally the package version (you probably want the newest one):

enter image description here

In nodeJs is there a way to loop through an array without using array size?

To print 'item1' , 'item2', this code would work.

var myarray = ['hello', ' hello again'];

for (var item in myarray) {
    console.log(myarray[item])
}

What exactly should be set in PYTHONPATH?

Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:

% python3 -c "import sys;print(sys.path)"
['', 
'/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']

where the first path '' denotes the current dir., the 2nd path is via

%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite 

which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.

As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:

% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'

Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)

Note that if you start a Python script, the CWD will be the script's directory. For example:

username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages

You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:

username@bud:~/Documents/DjangoTutorial% python3 
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', 
'/home/username/Documents']
>>> from Python import Fibonacci as fibo

or via

% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['', 
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite', 
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', 
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo

Java - remove last known item from ArrayList

First error: You're casting a ClientThread as a String for some reason.

Second error: You're not calling remove on your List.

Is is homework? If so, you might want to use the tag.

Drop view if exists

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

eg1:
director:Settings - Editor - Inspections - Spring - Spring Core - Code - Autowiring for Bean Class 
operate:checkout ???
eg2:
1.impl class add @service
like this:
@Service
public class CityServiceImpl implements CityService{
@Autowired
private CityDao cityDao;

like this
2.dao file class add @Repository
@Repository
public interface CityDao {

Does Python have a string 'contains' substring method?

So apparently there is nothing similar for vector-wise comparison. An obvious Python way to do so would be:

names = ['bob', 'john', 'mike']
any(st in 'bob and john' for st in names) 
>> True

any(st in 'mary and jane' for st in names) 
>> False

PHP Fatal error: Class 'PDO' not found

This error is caused by PDO not being available to PHP.

If you are getting the error on the command line, or not via the same interface your website uses for PHP, you are potentially invoking a different version of PHP, or utlising a different php.ini configuration file when checking phpinfo().

Ensure PDO is loaded, and the PDO drivers for your database are also loaded.