Programs & Examples On #Multiview

How Can I Remove “public/index.php” in the URL Generated Laravel?

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^(.*)/(public)/(index.php)/$ $1/$4 [L]
</IfModule>

Apache 2.4 - Request exceeded the limit of 10 internal redirects due to probable configuration error

You're getting into looping most likely due to these rules:

RewriteRule ^(.*\.php)$ $1 [L]
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]

Just comment it out and try again in a new browser.

Laravel blank white screen

This changes works for my localhost Ubuntu server 14.xx setting

# Apply all permission to the laravel 5.x site folders     
$ sudo chmod -R 777 mysite

Also made changes on site-available httpd setting Apache2 settings

Add settings:

Options +Indexes +FollowSymLinks +MultiViews
Require all granted

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

I ran into this exact issue upon a new install of Apache 2.4. After a few hours of googling and testing I finally found out that I also had to allow access to the directory that contains the (non-existent) target of the Alias directive. That is, this worked for me:

# File: /etc/apache2/conf-available/php5-fpm.conf
<IfModule mod_fastcgi.c>
    AddHandler php5-fcgi .php
    Action php5-fcgi /php5-fcgi
    Alias /php5-fcgi /usr/lib/cgi-bin/php5-fcgi
    FastCgiExternalServer /usr/lib/cgi-bin/php5-fcgi -socket /var/run/php5-fpm.sock -pass-header Authorization

    # NOTE: using '/usr/lib/cgi-bin/php5-cgi' here does not work,
    #   it doesn't exist in the filesystem!
    <Directory /usr/lib/cgi-bin>
        Require all granted
    </Directory>
</Ifmodule>

Apache2: 'AH01630: client denied by server configuration'

This drove me absolutely nuts for a day and a half but I found a solution if all other solutions have been tried unsuccessfully.

This is for macOS.

  • Go to activity Monitor (spotlight search for: activity)
  • In activity monitor search for httpd which is the Apache service
  • Select the one that belongs to root and click X on the top left to close it.

At that point I immediately stopped getting 403 errors and everything started working as expected. Weird thing is i didn't even have to restart apache it just worked, i guess it restarted itself when i went to my localhost, I honestly don't know but I guess the problem is Apache not actually restarting when using apachectl restart, or stop or start. Hope this helps someone.

Error message "Forbidden You don't have permission to access / on this server"

I was getting the same error and couldn't figure out the problem for ages. If you happen to be on a Linux distribution that includes SELinux such as CentOS, you need to make sure SELinux permissions are set correctly for your document root files or you will get this error. This is a completely different set of permissions to the standard file system permissions.

I happened to use the tutorial Apache and SELinux, but there seems to be plenty around once you know what to look for.

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

In your apache config file (../bin/apachex.y.z/cong/httpd.conf)

Just change

< Directory "c:/wamp/www/" > ...
...

"Require local" ===> "Require all granted"
< /Directory >

This allows other pc's to access (to read) your web folder.

Apache won't follow symlinks (403 Forbidden)

First disable selinux (vim /etc/selinux/config)

vim /etc/httpd/conf/httpd.conf edit following lines for symlinks and directory indexing:

documentroot /var/www/html
<directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride None
</directory>

If .htaccess file then AllowOverride all

How to debug an apache virtual host configuration?

First check out config files for syntax errors with apachectl configtest and then look into apache error logs.

Better way to find control in ASP.NET

Recursively find all controls matching the specified predicate (do not include root Control):

    public static IEnumerable<Control> FindControlsRecursive(this Control control, Func<Control, bool> predicate)
    {
        var results = new List<Control>();

        foreach (Control child in control.Controls)
        {
            if (predicate(child))
            {
                results.Add(child);
            }
            results.AddRange(child.FindControlsRecursive(predicate));
        }

        return results;
    }

Usage:

myControl.FindControlsRecursive(c => c.ID == "findThisID");

How to use .htaccess in WAMP Server?

if it related to hosting site then ask to your hosting to enable url writing or if you want to enable it in local machine then check this youtube step by step tutorial related to enabling rewrite module in wamp apache https://youtu.be/xIspOX9FuVU?t=1m43s
Wamp server icon -> Apache -> Apache Modules and check the rewrite module option it should be checked Note its very important that after enable rewrite module you should require to restart all services of wamp server

How to open maximized window with Javascript?

var params = [
    'height='+screen.height,
    'width='+screen.width,
    'fullscreen=yes' // only works in IE, but here for completeness
].join(',');
     // and any other options from
     // https://developer.mozilla.org/en/DOM/window.open

var popup = window.open('http://www.google.com', 'popup_window', params); 
popup.moveTo(0,0);

Please refrain from opening the popup unless the user really wants it, otherwise they will curse you and blacklist your site. ;-)

edit: Oops, as Joren Van Severen points out in a comment, this may not take into account taskbars and window decorations (in a possibly browser-dependent way). Be aware. It seems that ignoring height and width (only param is fullscreen=yes) seems to work on Chrome and perhaps Firefox too; the original 'fullscreen' functionality has been disabled in Firefox for being obnoxious, but has been replaced with maximization. This directly contradicts information on the same page of https://developer.mozilla.org/en/DOM/window.open which says that window-maximizing is impossible. This 'feature' may or may not be supported depending on the browser.

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

How to convert minutes to hours/minutes and add various time values together using jQuery?

Q1:

$(document).ready(function() {
    var totalMinutes = $('.totalMin').html();

    var hours = Math.floor(totalMinutes / 60);          
    var minutes = totalMinutes % 60;

    $('.convertedHour').html(hours);
    $('.convertedMin').html(minutes);    
});

Q2:

$(document).ready(function() {

    var minutes = 0;

    $('.min').each(function() {
        minutes = parseInt($(this).html()) + minutes;
    });

    var realmin = minutes % 60
    var hours = Math.floor(minutes / 60)

    $('.hour').each(function() {
        hours = parseInt($(this).html()) + hours;
    });


    $('.totalHour').html(hours);
    $('.totalMin').html(realmin);    

});

How to stop flask application without using ctrl-c

My method can be proceeded via bash terminal/console

1) run and get the process number

$ ps aux | grep yourAppKeywords

2a) kill the process

$ kill processNum

2b) kill the process if above not working

$ kill -9 processNum

Enter triggers button click

It is important to read the HTML specifications to truly understand what behavior is to be expected:

The HTML5 spec explicitly states what happens in implicit submissions:

A form element's default button is the first submit button in tree order whose form owner is that form element.

If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.

This was not made explicit in the HTML4 spec, however browsers have already been implementing what is described in the HTML5 spec (which is why it's included explicitly).

Edit to add:

The simplest answer I can think of is to put your submit button as the first [type="submit"] item in the form, add padding to the bottom of the form with css, and absolutely position the submit button at the bottom where you'd like it.

Spark - Error "A master URL must be set in your configuration" when submitting an app

If you are using following code

 val sc = new SparkContext(master, "WordCount", System.getenv("SPARK_HOME"))

Then replace with following lines

  val jobName = "WordCount";
  val conf = new SparkConf().setAppName(jobName);
  val sc = new SparkContext(conf)

In Spark 2.0 you can use following code

val spark = SparkSession
  .builder()
  .appName("Spark SQL basic example")
  .config("spark.some.config.option", "some-value")
  .master("local[*]")// need to add
  .getOrCreate()

You need to add .master("local[*]") if runing local here * means all node , you can say insted of 8 1,2 etc

You need to set Master URL if on cluster

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

How to read the shell variable in groovy / how to assign shell return value to groovy variable.

Requirement : Open a text file read the lines using shell and store the value in groovy and get the parameter for each line .

Here , is delimiter

Ex: releaseModule.txt

./APP_TSBASE/app/team/i-home/deployments/ip-cc.war/cs_workflowReport.jar,configurable-wf-report,94,23crb1,artifact



./APP_TSBASE/app/team/i-home/deployments/ip.war/cs_workflowReport.jar,configurable-temppweb-report,394,rvu3crb1,artifact

========================

Here want to get module name 2nd Parameter (configurable-wf-report) , build no 3rd Parameter (94), commit id 4th (23crb1)

def  module = sh(script: """awk -F',' '{ print \$2 "," \$3 "," \$4 }' releaseModules.txt  | sort -u """, returnStdout: true).trim()

echo module

List lines = module.split( '\n' ).findAll { !it.startsWith( ',' ) }

def buildid

def Modname

lines.each {

List det1 =  it.split(',')

buildid=det1[1].trim() 

Modname = det1[0].trim()

tag= det1[2].trim()

               

echo Modname               

echo buildid

                echo tag

                        

}

Change limit for "Mysql Row size too large"

If you can switch the ENGINE and use MyISAM instead of InnoDB, that should help:

ENGINE=MyISAM

There are two caveats with MyISAM (arguably more):

  1. You can't use transactions.
  2. You can't use foreign key constraints.

convert a JavaScript string variable to decimal/money

You can also use the Number constructor/function (no need for a radix and usable for both integers and floats):

Number('09'); /=> 9
Number('09.0987'); /=> 9.0987

Alternatively like Andy E said in the comments you can use + for conversion

+'09'; /=> 9
+'09.0987'; /=> 9.0987

JavaScript load a page on button click

The answers here work to open the page in the same browser window/tab.

However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)

So here is how it worked to open the page in new tab/window:

<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>

It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.

How to move (and overwrite) all files from one directory to another?

It's also possible by using rsync, for example:

rsync -va --delete-after src/ dst/

where:

  • -v, --verbose: increase verbosity
  • -a, --archive: archive mode; equals -rlptgoD (no -H,-A,-X)
  • --delete-after: delete files on the receiving side be done after the transfer has completed

If you've root privileges, prefix with sudo to override potential permission issues.

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT(firstName), ID, LastName from tableName GROUP BY firstName

Would be the best bet IMO

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

CSS3 selector to find the 2nd div of the same class

What exactly is the structure of your HTML?

The previous CSS will work if the HTML is as such:

CSS

.foo:nth-child(2)

HTML

<div>
 <div class="foo"></div>
 <div class="foo">Find me</div>
...
</div>

But if you have the following HTML it will not work.

<div>
 <div class="other"></div>
 <div class="foo"></div>
 <div class="foo">Find me</div>
 ...
</div>

Simple put, there is no selector for the getting the index of the matches from the rest of the selector before it.

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

Looks like you are using pandas dataframe (from the name df2).

You could also do the following:

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, 5].to_frame(), df2.iloc[1:1000, 2].to_frame())

NOTE: I have removed "values" as that converts the pandas Series to numpy.ndarray and numpy.ndarray does not have attribute to_frame().

Why doesn't height: 100% work to expand divs to the screen height?

If you absolutely position the elements inside the div, you can set the padding top and bottom to 50%.

So something like this:

#s7 {
    position: relative;
    width:100%;
    padding: 50% 0;
    margin:auto;
    overflow: hidden;
    z-index:1;
}

How to pass values between Fragments

step 1.to send data from fragment to activity

Intent intent = new Intent(getActivity().getBaseContext(),
                        TargetActivity.class);
                intent.putExtra("message", message);
                getActivity().startActivity(intent);

step 2.to receive this data in Activity:

Intent intent = getIntent();
String message = intent.getStringExtra("message");

step 3. to send data from activity to another activity follow normal approach

Intent intent = new Intent(MainActivity.this,
                        TargetActivity.class);
                intent.putExtra("message", message);
                startActivity(intent);

step 4 to receive this data in activity

     Intent intent = getIntent();
  String message = intent.getStringExtra("message");

Step 5. From Activity you can send data to Fragment with intent as:

Bundle bundle=new Bundle();
bundle.putString("message", "From Activity");
  //set Fragmentclass Arguments
Fragmentclass fragobj=new Fragmentclass();
fragobj.setArguments(bundle);

and to receive in fragment in Fragment onCreateView method:

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
    Bundle savedInstanceState) {
          String strtext=getArguments().getString("message");

    return inflater.inflate(R.layout.fragment, container, false);
    }

How to dynamically add a class to manual class names?

You can use this npm package. It handles everything and has options for static and dynamic classes based on a variable or a function.

// Support for string arguments
getClassNames('class1', 'class2');

// support for Object
getClassNames({class1: true, class2 : false});

// support for all type of data
getClassNames('class1', 'class2', ['class3', 'class4'], { 
    class5 : function() { return false; },
    class6 : function() { return true; }
});

<div className={getClassNames({class1: true, class2 : false})} />

Reading a .txt file using Scanner class in Java

You have to put file extension here

File file = new File("10_Random.txt");

Tomcat starts but home page cannot open with url http://localhost:8080

For *Unix based systems, you can check the ports used by a particular application by issueing the following command in the terminal

[~/.]$ netstat -tuplen

You will get the list of all the ports that are being currently held and used by their respective process ID's

Set and Get Methods in java?

It looks like you trying to do something similar to C# if you want setAge create method
setAge(int age){ this.age = age;}

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

Script to get the HTTP status code of a list of urls?

wget --spider -S "http://url/to/be/checked" 2>&1 | grep "HTTP/" | awk '{print $2}'

prints only the status code for you

How to start activity in another application?

If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:

Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);

Hope it helps.

How do I get first name and last name as whole name in a MYSQL query?

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

How do I get the total number of unique pairs of a set in the database?

What you're looking for is n choose k. Basically:

enter image description here

For every pair of 100 items, you'd have 4,950 combinations - provided order doesn't matter (AB and BA are considered a single combination) and you don't want to repeat (AA is not a valid pair).

Postgres error on insert - ERROR: invalid byte sequence for encoding "UTF8": 0x00

If you need to store null characters in text fields and don't want to change your data type other than text then you can follow my solution too:

Before insert:

myValue = myValue.replaceAll("\u0000", "SomeVerySpecialText")

After select:

myValue = myValue.replaceAll("SomeVerySpecialText","\u0000")

I've used "null" as my SomeVerySpecialText which I am sure that there will be no any "null" string in my values at all.

400 BAD request HTTP error code meaning?

As a complementary, for those who might meet the same issue as mine, I'm using $.ajax to post form data to server and I also got the 400 error at first.

Assume I have a javascript variable,

var formData = {
    "name":"Gearon",
    "hobby":"Be different"
    }; 

Do not use variable formData directly as the value of key data like below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: formData,
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Instead, use JSON.stringify to encapsulate the formData as below:

$.ajax({
    type: "post",
    dataType: "json",
    url: "http://localhost/user/add",
    contentType: "application/json",
    data: JSON.stringify(formData),
    success: function(data, textStatus){
        alert("Data: " + data + "\nStatus: " + status); 
    }
});

Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I'm just raising a instance at practice. Hope it would be helpful to someone.

Check if two unordered lists are equal

Assuming you already know lists are of equal size, the following will guarantee True if and only if two vectors are exactly the same (including order)

functools.reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, listA, ListB), True)

Example:

>>> from functools import reduce
>>> def compvecs(a,b):
...     return reduce(lambda b1,b2: b1 and b2, map(lambda e1,e2: e1==e2, a, b), True)
... 
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compvecs(a=[1,2,3,4], b=[1,2,3,4])
True
>>> compvecs(a=[1,2,3,4], b=[1,2,4,3])
False
>>> compare_vectors(a=[1,2,3,4], b=[1,2,2,4])
False
>>> 

AWS ssh access 'Permission denied (publickey)' issue

Canonical's releases use the user 'ubuntu' by default for anyone landing here with a ubuntu image that is coming up with the same problem.

Jquery validation plugin - TypeError: $(...).validate is not a function

I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:

require('jquery-validation');

Unity Scripts edited in Visual studio don't provide autocomplete

For some odd reason, the "Game development with Unity" tool can become disabled in Visual Studio.

To fix this..

  1. Open Visual Studio
  2. Go to Extensions ? "Manage Extensions" ? Installed
  3. Find "Visual Studio 2019 Tools for Unity"
  4. If it is disabled, enable it
  5. Restart VS

Credit to Yuli Levtov's answer on another Thread

C++ Best way to get integer division and remainder

You cannot trust g++ 4.6.3 here with 64 bit integers on a 32 bit intel platform. a/b is computed by a call to divdi3 and a%b is computed by a call to moddi3. I can even come up with an example that computes a/b and a-b*(a/b) with these calls. So I use c=a/b and a-b*c.

The div method gives a call to a function which computes the div structure, but a function call seems inefficient on platforms which have hardware support for the integral type (i.e. 64 bit integers on 64 bit intel/amd platforms).

CSS width of a <span> tag

Use the attribute 'display' as in the example:

<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>

Cocoa: What's the difference between the frame and the bounds?

The answers above have very well explained the difference between Bounds and Frames.

Bounds : A view Size and Location as per its own coordinate system.

Frame : A view size and Location relative to its SuperView.

Then there is confusion that in case of Bounds the X,Y will always be "0". This is not true. This can be understood in UIScrollView and UICollectionView as well.

When bounds' x, y are not 0.
Let's assume we have a UIScrollView. We have implemented pagination. The UIScrollView has 3 pages and its ContentSize's width is three times Screen Width (assume ScreenWidth is 320). The height is constant (assume 200).

scrollView.contentSize = CGSize(x:320*3, y : 200)

Add three UIImageViews as subViews and keep a close look at the x value of frame

let imageView0 = UIImageView.init(frame: CGRect(x:0, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView1 :  UIImageView.init( frame: CGRect(x:320, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
let imageView2 :  UIImageView.init(frame: CGRect(x:640, y: 0 , width : scrollView.frame.size.width, height : scrollView.frame.size.height))
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)
scrollView.addSubview(imageView0)
  1. Page 0: When the ScrollView is at 0 Page the Bounds will be (x:0,y:0, width : 320, height : 200)

  2. Page 1: Scroll and move to Page 1.
    Now the bounds will be (x:320,y:0, width : 320, height : 200) Remember we said with respect to its own coordinate System. So now the "Visible Part" of our ScrollView has its "x" at 320. Look at the frame of imageView1.

  3. Page 2: Scroll and move to Page 2 Bounds : (x:640,y:0, width : 320, height : 200) Again take a look at frame of imageView2

Same for the case of UICollectionView. The easiest way to look at collectionView is to scroll it and print/log its bounds and you will get the idea.

OpenCV in Android Studio

The below steps for using Android OpenCV sdk in Android Studio. This is a simplified version of this(1) SO answer.

  1. Download latest OpenCV sdk for Android from OpenCV.org and decompress the zip file.
  2. Import OpenCV to Android Studio, From File -> New -> Import Module, choose sdk/java folder in the unzipped opencv archive.
  3. Update build.gradle under imported OpenCV module to update 4 fields to match your project build.gradle a) compileSdkVersion b) buildToolsVersion c) minSdkVersion and d) targetSdkVersion.
  4. Add module dependency by Application -> Module Settings, and select the Dependencies tab. Click + icon at bottom, choose Module Dependency and select the imported OpenCV module.
    • For Android Studio v1.2.2, to access to Module Settings : in the project view, right-click the dependent module -> Open Module Settings
  5. Copy libs folder under sdk/native to Android Studio under app/src/main.
  6. In Android Studio, rename the copied libs directory to jniLibs and we are done.

Step (6) is since Android studio expects native libs in app/src/main/jniLibs instead of older libs folder. For those new to Android OpenCV, don't miss below steps

  • include static{ System.loadLibrary("opencv_java"); } (Note: for OpenCV version 3 at this step you should instead load the library opencv_java3.)
  • For step(5), if you ignore any platform libs like x86, make sure your device/emulator is not on that platform.

OpenCV written is in C/C++. Java wrappers are

  1. Android OpenCV SDK - OpenCV.org maintained Android Java wrapper. I suggest this one.
  2. OpenCV Java - OpenCV.org maintained auto generated desktop Java wrapper.
  3. JavaCV - Popular Java wrapper maintained by independent developer(s). Not Android specific. This library might get out of sync with OpenCV newer versions.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

How do you handle multiple submit buttons in ASP.NET MVC Framework?

You should be able to name the buttons and give them a value; then map this name as an argument to the action. Alternatively, use 2 separate action-links or 2 forms.

Apache Proxy: No protocol handler was valid

This can happen if you don't have mod_proxy_http enabled

sudo a2enmod proxy_http

For me to get my https based load balancer working, i had to enable the following:

sudo a2enmod ssl
sudo a2enmod proxy
sudo a2enmod proxy_balancer
sudo a2enmod proxy_http

What is the easiest way to get the current day of the week in Android?

Here is my simple approach to get Current day

public String getCurrentDay(){

    String daysArray[] = {"Sunday","Monday","Tuesday", "Wednesday","Thursday","Friday", "Saturday"};

    Calendar calendar = Calendar.getInstance();
    int day = calendar.get(Calendar.DAY_OF_WEEK);

    return daysArray[day];

}

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

Add all files to a commit except a single file?

Changes to be committed: (use "git reset HEAD ..." to unstage)

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Remove duplicate values from JS array

var lines = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
var uniqueNames = [];

for(var i=0;i<lines.length;i++)
{
    if(uniqueNames.indexOf(lines[i]) == -1)
        uniqueNames.push(lines[i]);
}
if(uniqueNames.indexOf(uniqueNames[uniqueNames.length-1])!= -1)
    uniqueNames.pop();
for(var i=0;i<uniqueNames.length;i++)
{
    document.write(uniqueNames[i]);
      document.write("<br/>");
}

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

I had an issue with Servlet instantiation. I cleaned the project and it worked for me. In eclipse menu, Go to Project->Clean. It should work.

Write HTML file using Java

if it is becoming repetitive work ; i think you shud do code reuse ! why dont you simply write functions that "write" small building blocks of HTML. get the idea? see Eg. you can have a function to which you could pass a string and it would automatically put that into a paragraph tag and present it. Of course you would also need to write some kind of a basic parser to do this (how would the function know where to attach the paragraph!). i dont think you are a beginner .. so i am not elaborating ... do tell me if you do not understand..

How to change a TextView's style at runtime

TextView tvCompany = (TextView)findViewById(R.layout.tvCompany);
tvCompany.setTypeface(null,Typeface.BOLD);

You an set it from code. Typeface

AngularJS: How to make angular load script inside ng-include?

Unfortunately all the answers in this post didn't work for me. I kept getting following error.

Failed to execute 'write' on 'Document': It isn't possible to write into a document from an asynchronously-loaded external script unless it is explicitly opened.

I found out that this happens if you use some 3rd party widgets (demandforce in my case) that also call additional external JavaScript files and try to insert HTML. Looking at the console and the JavaScript code, I noticed multiple lines like this:

document.write("<script type='text/javascript' "..."'></script>");

I used 3rd party JavaScript files (htmlParser.js and postscribe.js) from: https://github.com/krux/postscribe. That solved the problem in this post and fixed the above error at the same time.

(This was a quick and dirty way around under the tight deadline I have now. I am not comfortable with using 3rd party JavaScript library however. I hope someone can come up with a cleaner and better way.)

How does the "view" method work in PyTorch?

What is the meaning of parameter -1?

You can read -1 as dynamic number of parameters or "anything". Because of that there can be only one parameter -1 in view().

If you ask x.view(-1,1) this will output tensor shape [anything, 1] depending on the number of elements in x. For example:

import torch
x = torch.tensor([1, 2, 3, 4])
print(x,x.shape)
print("...")
print(x.view(-1,1), x.view(-1,1).shape)
print(x.view(1,-1), x.view(1,-1).shape)

Will output:

tensor([1, 2, 3, 4]) torch.Size([4])
...
tensor([[1],
        [2],
        [3],
        [4]]) torch.Size([4, 1])
tensor([[1, 2, 3, 4]]) torch.Size([1, 4])

How to count number of files in each directory?

Here's one way to do it, but probably not the most efficient.

find -type d -print0 | xargs -0 -n1 bash -c 'echo -n "$1:"; ls -1 "$1" | wc -l' --

Gives output like this, with directory name followed by count of entries in that directory. Note that the output count will also include directory entries which may not be what you want.

./c/fa/l:0
./a:4
./a/c:0
./a/a:1
./a/a/b:0

Extracting text from HTML file using Python

Here is a version of xperroni's answer which is a bit more complete. It skips script and style sections and translates charrefs (e.g., &#39;) and HTML entities (e.g., &amp;).

It also includes a trivial plain-text-to-html inverse converter.

"""
HTML <-> text conversions.
"""
from HTMLParser import HTMLParser, HTMLParseError
from htmlentitydefs import name2codepoint
import re

class _HTMLToText(HTMLParser):
    def __init__(self):
        HTMLParser.__init__(self)
        self._buf = []
        self.hide_output = False

    def handle_starttag(self, tag, attrs):
        if tag in ('p', 'br') and not self.hide_output:
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = True

    def handle_startendtag(self, tag, attrs):
        if tag == 'br':
            self._buf.append('\n')

    def handle_endtag(self, tag):
        if tag == 'p':
            self._buf.append('\n')
        elif tag in ('script', 'style'):
            self.hide_output = False

    def handle_data(self, text):
        if text and not self.hide_output:
            self._buf.append(re.sub(r'\s+', ' ', text))

    def handle_entityref(self, name):
        if name in name2codepoint and not self.hide_output:
            c = unichr(name2codepoint[name])
            self._buf.append(c)

    def handle_charref(self, name):
        if not self.hide_output:
            n = int(name[1:], 16) if name.startswith('x') else int(name)
            self._buf.append(unichr(n))

    def get_text(self):
        return re.sub(r' +', ' ', ''.join(self._buf))

def html_to_text(html):
    """
    Given a piece of HTML, return the plain text it contains.
    This handles entities and char refs, but not javascript and stylesheets.
    """
    parser = _HTMLToText()
    try:
        parser.feed(html)
        parser.close()
    except HTMLParseError:
        pass
    return parser.get_text()

def text_to_html(text):
    """
    Convert the given text to html, wrapping what looks like URLs with <a> tags,
    converting newlines to <br> tags and converting confusing chars into html
    entities.
    """
    def f(mo):
        t = mo.group()
        if len(t) == 1:
            return {'&':'&amp;', "'":'&#39;', '"':'&quot;', '<':'&lt;', '>':'&gt;'}.get(t)
        return '<a href="%s">%s</a>' % (t, t)
    return re.sub(r'https?://[^] ()"\';]+|[&\'"<>]', f, text)

Why is my JavaScript function sometimes "not defined"?

Use an anonymous function to protect your local symbol table. Something like:

(function() {
    function copyArray(pa) {
        // Details
    }

    Function.prototype.bind = function ( po ) {
        __args = copyArray( arguments );
    }
})();

This will create a closure that includes your function in the local symbol table, and you won't have to depend on it being available in the global namespace when you call the function.

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

Use formula in custom calculated field in Pivot Table

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

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

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

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

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

How to limit text width

I think what you are trying to do is to wrap long text without spaces.

look at this :Hyphenator.js and it's demo.

Java compile error: "reached end of file while parsing }"

You have to open and close your class with { ... } like:

public class mod_MyMod extends BaseMod
{
  public String Version()
  {
    return "1.2_02";
  }

  public void AddRecipes(CraftingManager recipes)
  {
     recipes.addRecipe(new ItemStack(Item.diamond), new Object[] {
        "#", Character.valueOf('#'), Block.dirt });
  }
}

Prevent wrapping of span or div

Particularly when using something like Twitter's Bootstrap, white-space: nowrap; doesn't always work in CSS when applying padding or margin to a child div. Instead however, adding an equivalent border: 20px solid transparent; style in place of padding/margin works more consistently.

Write output to a text file in PowerShell

Use the Out-File cmdlet

 Compare-Object ... | Out-File C:\filename.txt

Optionally, add -Encoding utf8 to Out-File as the default encoding is not really ideal for many uses.

Naming Conventions: What to name a boolean variable?

hasFollowingItems? or hasFollowingXXXXs where XXXX is whatever the item in your list is?

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

Ruby replace string with captured regex pattern

\1 in double quotes needs to be escaped. So you want either

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, "\\1")

or

"Z_sdsd: sdsd".gsub(/^(Z_.*): .*/, '\1')

see the docs on gsub where it says "If it is a double-quoted string, both back-references must be preceded by an additional backslash."

That being said, if you just want the result of the match you can do:

"Z_sdsd: sdsd".scan(/^Z_.*(?=:)/)

or

"Z_sdsd: sdsd"[/^Z_.*(?=:)/]

Note that the (?=:) is a non-capturing group so that the : doesn't show up in your match.

What is the use of hashCode in Java?

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

To show error message without alert box in Java Script

Try this code

<html>
<head>
 <script type="text/javascript">
 function validate() {
  if(myform.fname.value.length==0)
  {
document.getElementById('errfn').innerHTML="this is invalid name";
  }
 }
 </script>
</head>
<body>
 <form name="myform">
  First_Name
  <input type=text id=fname name=fname onblur="validate()"> </input><div id="errfn">   </div>

<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"> </input>

<br>
<input type=button value=check> 

</form>
</body>
</html>

Populate a datagridview with sql query results

String strConnection = Properties.Settings.Default.BooksConnectionString;
SqlConnection con = new SqlConnection(strConnection);

SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = con;
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "Select * from titles";
SqlDataAdapter sqlDataAdap = new SqlDataAdapter(sqlCmd);

DataTable dtRecord = new DataTable();
sqlDataAdap.Fill(dtRecord);
dataGridView1.DataSource = dtRecord;

What values for checked and selected are false?

Actually, the HTML 4.01 spec says that these attributes do not require values. I haven't personally encountered a situation where providing a value rendered these controls as unselected.

Here are the respective links to the spec document for selected and checked.

Edit: Firebug renders the checkbox as checked regardless of any values I put in quotes for the checked attribute (including just typing "checked" with no values whatsoever), and IE 8's Developer Tools forces checked="checked". I'm not sure if any similar tools exist for other browsers that might alter the rendered state of a checkbox, however.

Bind failed: Address already in use

You have a process that is already using that port. netstat -tulpn will enable one to find the process ID of that is using a particular port.

cd into directory without having permission

chmod +x openfire worked for me. It adds execution permission to the openfire folder.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Selecting multiple columns with linq query and lambda expression

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}

no need to declare the 'contact'

How to read one single line of csv data in Python?

You can use Pandas library to read the first few lines from the huge dataset.

import pandas as pd

data = pd.read_csv("names.csv", nrows=1)

You can mention the number of lines to be read in the nrows parameter.

Android Fragments and animation

I'd highly suggest you use this instead of creating the animation file because it's a much better solution. Android Studio already provides default animation you can use without creating any new XML file. The animations' names are android.R.anim.slide_in_left and android.R.anim.slide_out_right and you can use them as follows:

fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();              
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();

Output:

enter image description here

Is there an addHeaderView equivalent for RecyclerView?

If you want the header to be easily reused across multiple lists, take a look at the version 1.2.0 of recyclerview library. It introduces ConcatAdapter class which concatenates multiple adapters into a single one. So you can create a header adapter and easily combine it with any other adapter, like:

myRecyclerView.adapter = ConcatAdapter(headerAdapter, listAdapter)

The announcement article contains a sample how to display a loading progress in header and footer using ConcatAdapter.

For the moment when I post this answer the version 1.2.0 of the library is in alpha stage, so the api might change. You can check the status here.

AngularJS - Find Element with attribute

Rather than querying the DOM for elements (which isn't very angular see "Thinking in AngularJS" if I have a jQuery background?) you should perform your DOM manipulation within your directive. The element is available to you in your link function.

So in your myDirective

return {
    link: function (scope, element, attr) {
        element.html('Hello world');
    }
}

If you must perform the query outside of the directive then it would be possible to use querySelectorAll in modern browers

angular.element(document.querySelectorAll("[my-directive]"));

however you would need to use jquery to support IE8 and backwards

angular.element($("[my-directive]"));

or write your own method as demonstrated here Get elements by attribute when querySelectorAll is not available without using libraries?

Explain __dict__ attribute

Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes. Quoting from the documentation for __dict__

A dictionary or other mapping object used to store an object's (writable) attributes.

Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:

def func():
    pass

func.temp = 1

print(func.__dict__)

class TempClass:
    a = 1
    def temp_function(self):
        pass

print(TempClass.__dict__)

will output

{'temp': 1}
{'__module__': '__main__', 
 'a': 1, 
 'temp_function': <function TempClass.temp_function at 0x10a3a2950>, 
 '__dict__': <attribute '__dict__' of 'TempClass' objects>, 
 '__weakref__': <attribute '__weakref__' of 'TempClass' objects>, 
 '__doc__': None}

What exactly is a Maven Snapshot and why do we need it?

Snapshot Dependencies Snapshot dependencies are dependencies (JAR files) which are under development. Instead of constantly updating the version numbers to get the latest version, you can depend on a snapshot version of the project. Snapshot versions are always downloaded into your local repository for every build, even if a matching snapshot version is already located in your local repository. Always downloading the snapshot dependencies assures that you always have the latest version in your local repository, for every build.

your pom contains a lot of -SNAPSHOT dependencies and those -SNAPSHOT dependencies are a moving target enter image description here

enter image description here

https://dzone.com/articles/maven-release-plugin-in-the-enterprise https://javarevisited.blogspot.com/2019/03/top-5-course-to-learn-apache-maven-for.html https://www.mojohaus.org/versions-maven-plugin/examples/lock-snapshots.html http://tutorials.jenkov.com/maven/maven-tutorial.html

WARNING: Exception encountered during context initialization - cancelling refresh attempt

This was my stupidity, but a stupidity that was not easy to identify :).

Problem:

  1. My code is compiled on Jdk 1.8.
  2. My eclipse, had JDK 1.8 as the compiler.
  3. My tomcat in eclipse was using Java 1.7 for its container, hence it was not able to understand the .class files which were compiled using 1.8.
  4. To avoid the problem, ensure in your eclipse, double click on your server -> Open Launch configuration -> Classpath -> JRE System Library -> Give the JDK/JRE of the compiled version of java class, in my case, it had to be JDK 1.8
    1. Post this, clean the server, build and redeploy, start the tomcat.

If you are deploying manually into your server, ensure your JAVA_HOME, JDK_HOME points to the correct JDK which you used to compile the project and build the war.

If you do not like to change JAVA_HOME, JDK_HOME, you can always change the JAVA_HOME and JDK_HOME in catalina.bat(for tomcat server) and that'll enable your life to be easy!

How to merge remote master to local branch

I found out it was:

$ git fetch upstream
$ git merge upstream/master

Reload a DIV without reloading the whole page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js" />

<div class="View"><?php include 'Small.php'; ?></div>

<script type="text/javascript">
$(document).ready(function() {
$('.View').load('Small.php');
var auto_refresh = setInterval(
    function ()
    {
        $('.View').load('Small.php').fadeIn("slow");
    }, 15000); // refresh every 15000 milliseconds
        $.ajaxSetup({ cache: true });
    });
</script>

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

You'll need to decide how you'd like to handle exceptions thrown by the encrypt method.

Currently, encrypt is declared with throws Exception - however, in the body of the method, exceptions are caught in a try/catch block. I recommend you either:

  • remove the throws Exception clause from encrypt and handle exceptions internally (consider writing a log message at the very least); or,
  • remove the try/catch block from the body of encrypt, and surround the call to encrypt with a try/catch instead (i.e. in actionPerformed).

Regarding the compilation error you refer to: if an exception was thrown in the try block of encrypt, nothing gets returned after the catch block finishes. You could address this by initially declaring the return value as null:

public static byte[] encrypt(String toEncrypt) throws Exception{
  byte[] encrypted = null;
  try {
    // ...
    encrypted = ...
  }
  catch(Exception e){
    // ...
  }
  return encrypted;
}

However, if you can correct the bigger issue (the exception-handling strategy), this problem will take care of itself - particularly if you choose the second option I've suggested.

Is Visual Studio Community a 30 day trial?

For VS2019 I was able to signup with my github account:

enter image description here enter image description here enter image description here enter image description here

Then it will send password to your email and you will be able to sign.

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

The problem:

Microsoft Office 2010 products (or later) install updates that break compatibility of MSCOMCTL.ocx and COMCTL32.ocx. Unfortunately this affects many other programs such Visual Basic 6 SP6 and even Oracle Virtual Box v5. The actual problem is HKEY_CLASSES_ROOT\TypeLib\{831FDD16-0C5C-11D2-A9FC-0000F8754DA1}\2.0 registry key. You can find detailed background information about this problem here.

Here is another working solution:

The solution assumes you have not damaged your registry by deleting, replacing and re-registering MSCOMCTL.ocx and COMCTL32.ocx without unregistering the Office patch files.

Create a batch file called fix.cmd and place the following commands in it:

regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx
del /y %windir%\SysWOW64\comctl32.ocx
del /y %windir%\SysWOW64\mscomctl.ocx
msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi
regtlib %windir%\SysWOW64\msdatsrc.tlb

Download from Security update for Visual Basic 6.0 Service Pack 6: August 14, 2012 the msi file and rename it to KB2708437.msi.

Note: A direct link to the Service Pack 6 download is located HERE.

Run fix.cmd and the problem will be fixed!

What fix.cmd does is to properly unregister and then delete the current MSCOMCTL.ocx and COMCTL32.ocx files, and then apply the latest Visual Basic 6 SP6 rollup patch. In fact, the script enforces the patch to be installed and then re-installed by updating every file, regardless of version. Finally it registers msdatsrc.tlb type library.

Please let me know if this works for you.

======================================================================

Advanced Solution:

If however you have accidentally damaged your registry, you need to get as many versions of MSCOMCTL.ocx and COMCTL32.ocx you can find. Then you need to start from the newer version going back to the older and register and unregister the ocx files.

The latest version of MSCOMCTL.ocx is 6.1.98.39 (v2.1) of May 2012 which is more likely the one installed on your system and causing all your problems.

The oldest (legacy) version is that shipped with Visual Basic 6 on 1998 6.1.97.82 (v2.0), or the one shipped with an early service pack 6.1.97.86 on April 2005.

Example:

regsvr32 /s comctl32.6.0.98.34.ocx
regsvr32 /s /u comctl32.6.0.98.34.ocx

regsvr32 /s comctl32.6.0.81.6.ocx
regsvr32 /s /u comctl32.6.0.81.6.ocx 

regsvr32 /s comctl32.6.0.81.5.ocx
regsvr32 /s /u comctl32.6.0.81.5.ocx

regsvr32 /s mscomctl.6.1.98.39.(2.1).ocx
regsvr32 /s /u mscomctl.6.1.98.39.(2.1).ocx

regsvr32 /s mscomctl.6.1.98.34.ocx
regsvr32 /s /u mscomctl.6.1.98.34.ocx

regsvr32 /s mscomctl.6.1.97.86.ocx
regsvr32 /s /u mscomctl.6.1.97.86.ocx

regsvr32 /s mscomctl.6.1.97.82.(2.0).ocx
regsvr32 /s /u mscomctl.6.1.97.82.(2.0).ocx

regsvr32 /s /u %windir%\SysWOW64\comctl32.ocx
regsvr32 /s /u %windir%\SysWOW64\mscomctl.ocx

del /q %windir%\SysWOW64\comctl32.ocx
del /q %windir%\SysWOW64\mscomctl.ocx

msiexec /passive /norestart /i KB2708437.msi
msiexec /passive /a KB2708437.msi

regtlib %windir%\SysWOW64\msdatsrc.tlb   

WARNING:

Do not search the internet for those files. To find different version of the OCX files download and extract official Microsoft Installer packages such as the following:

2005 Apr - Microsoft KB896559

2008 Dec - Microsoft KB926857

2009 Apr - Microsoft KB957924

2012 May - Microsoft KB2708437

It is also recommended to run CCleaner version 4.0 or later to fix any other ActiveX related problems on your computer.

JavaScript - Use variable in string match

You have to use RegExp object if your pattern is string

var xxx = "victoria";
var yyy = "i";
var rgxp = new RegExp(yyy, "g");
alert(xxx.match(rgxp).length);

If pattern is not dynamic string:

var xxx = "victoria";
var yyy = /i/g;
alert(xxx.match(yyy).length);

Check if certain value is contained in a dataframe column in pandas

I think you need str.contains, if you need rows where values of column date contains string 07311954:

print df[df['date'].astype(str).str.contains('07311954')]

Or if type of date column is string:

print df[df['date'].str.contains('07311954')]

If you want check last 4 digits for string 1954 in column date:

print df[df['date'].astype(str).str[-4:].str.contains('1954')]

Sample:

print df['date']
0    8152007
1    9262007
2    7311954
3    2252011
4    2012011
5    2012011
6    2222011
7    2282011
Name: date, dtype: int64

print df['date'].astype(str).str[-4:].str.contains('1954')
0    False
1    False
2     True
3    False
4    False
5    False
6    False
7    False
Name: date, dtype: bool

print df[df['date'].astype(str).str[-4:].str.contains('1954')]
     cmte_id trans_typ entity_typ state  employer  occupation     date  \
2  C00119040       24K        CCM    MD       NaN         NaN  7311954   

   amount     fec_id    cand_id  
2    1000  C00140715  H2MD05155  

Laravel 5 Class 'form' not found

Use Form, not form. The capitalization counts.

Insert data to MySql DB and display if insertion is success or failure

if (mysql_query("INSERT INTO PEOPLE (NAME ) VALUES ('COLE')")or die(mysql_error())) {
  echo 'Success';
} else {
  echo 'Fail';
} 

Although since you have or die(mysql_error()) it will show the mysql_error() on the screen when it fails. You should probably remove that if it isnt the desired result

How to 'foreach' a column in a DataTable using C#?

int countRow = dt.Rows.Count;
int countCol = dt.Columns.Count;

for (int iCol = 0; iCol < countCol; iCol++)
{
     DataColumn col = dt.Columns[iCol];

     for (int iRow = 0; iRow < countRow; iRow++)
     {
         object cell = dt.Rows[iRow].ItemArray[iCol];

     }
}

How to obtain the location of cacerts of the default java installation?

If you need to access those certs programmatically it is best to not use the file at all, but access it via the trust manager. The following code is from a OpenJDK Test case (which makes sure the built cacerts collection is not empty):

TrustManagerFactory trustManagerFactory =
    TrustManagerFactory.getInstance("PKIX");
trustManagerFactory.init((KeyStore) null);
TrustManager[] trustManagers =
    trustManagerFactory.getTrustManagers();
X509TrustManager trustManager =
    (X509TrustManager) trustManagers[0];
X509Certificate[] acceptedIssuers =
    trustManager.getAcceptedIssuers();

So you don’t have to deal with file location or keystore password.

docker : invalid reference format

I ran into this issue when I didn't have an environment variable set.

docker push ${repo}${image_name}:${tag}

repo and image_name were defined but tag wasn't.

This resulted in docker push repo/image_name:.

Which threw the docker: invalid reference format.

String concatenation of two pandas columns

series.str.cat is the most flexible way to approach this problem:

For df = pd.DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3]})

df.foo.str.cat(df.bar.astype(str), sep=' is ')

>>>  0    a is 1
     1    b is 2
     2    c is 3
     Name: foo, dtype: object

OR

df.bar.astype(str).str.cat(df.foo, sep=' is ')

>>>  0    1 is a
     1    2 is b
     2    3 is c
     Name: bar, dtype: object

Unlike .join() (which is for joining list contained in a single Series), this method is for joining 2 Series together. It also allows you to ignore or replace NaN values as desired.

No module named serial

Download this file :- (https://pypi.python.org/packages/1f/3b/ee6f354bcb1e28a7cd735be98f39ecf80554948284b41e9f7965951befa6/pyserial-3.2.1.tar.gz#md5=7142a421c8b35d2dac6c47c254db023d):

cd /opt
sudo tar -xvf ~/Downloads/pyserial-3.2.1.tar.gz -C .
cd /opt/pyserial-3.2.1 
sudo python setup.py install 

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

The ":PATH" part in the accepted answer can be omitted. This syntax may be more memorable:

cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install

...as used in the answers here.

Passing arguments to "make run"

You can pass the variable to the Makefile like below:

run:
    @echo ./prog $$FOO

Usage:

$ make run FOO="the dog kicked the cat"
./prog the dog kicked the cat

or:

$ FOO="the dog kicked the cat" make run
./prog the dog kicked the cat

Alternatively use the solution provided by Beta:

run:
    @echo ./prog $(filter-out $@,$(MAKECMDGOALS))
%:
    @:

%: - rule which match any task name; @: - empty recipe = do nothing

Usage:

$ make run the dog kicked the cat
./prog the dog kicked the cat

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

 // prepare json data
        let mapDict = [ "1":"First", "2":"Second"]

        let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]
        let jsonData : NSData = NSKeyedArchiver.archivedData(withRootObject: json) as NSData

        // create post request
        let url = NSURL(string: "http://httpbin.org/post")!
        let request = NSMutableURLRequest(url: url as URL)
        request.httpMethod = "POST"

        // insert json data to the request
        request.httpBody = jsonData as Data


        let task = URLSession.shared.dataTask(with: request as URLRequest){ data,response,error in
            if error != nil{
                return
            }
            do {
                let result = try JSONSerialization.jsonObject(with: data!, options: []) as? [String:AnyObject]

                print("Result",result!)

            } catch {
                print("Error -> \(error)")
            }
        }

        task.resume()

Send Outlook Email Via Python?

using pywin32:

from win32com.client import Dispatch

session = Dispatch('MAPI.session')
session.Logon('','',0,1,0,0,'exchange.foo.com\nUserName');
msg = session.Outbox.Messages.Add('Hello', 'This is a test')
msg.Recipients.Add('Corey', 'SMTP:[email protected]')
msg.Send()
session.Logoff()

How can I check if a JSON is empty in NodeJS?

Object.keys(myObj).length === 0;

As there is need to just check if Object is empty it will be better to directly call a native method Object.keys(myObj).length which returns the array of keys by internally iterating with for..in loop.As Object.hasOwnProperty returns a boolean result based on the property present in an object which itself iterates with for..in loop and will have time complexity O(N2).

On the other hand calling a UDF which itself has above two implementations or other will work fine for small object but will block the code which will have severe impact on overall perormance if Object size is large unless nothing else is waiting in the event loop.

Display current date and time without punctuation

Interesting/funny way to do this using parameter expansion (requires bash 4.4 or newer):

${parameter@operator} - P operator

The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string.

$ show_time() { local format='\D{%Y%m%d%H%M%S}'; echo "${format@P}"; }
$ show_time
20180724003251

Change link color of the current page with CSS

You do not need jQuery just to do this! All you need is a tiny and very light vanilla Javascript and a css class (as in all the answers above) :

  • First define a CSS class in your stylesheet called current.

  • Second add the following pure JavaScript either in your existing JavaScript file or in a separate js script file (but add script tage link to it in the head of the pages) or event just add it in a script tag just before the closing body tag, it will still work in all these cases.



    function highlightCurrent() {
         const curPage = document.URL;
         const links = document.getElementsByTagName('a');
         for (let link of links) {
           if (link.href == curPage) {
             link.classList.add("current");
           }
         }
       }


       document.onreadystatechange = () => {
         if (document.readyState === 'complete') {
           highlightCurrent()
         }
       };

The 'href' attribute of current link should be the absolute path as given by document.URL (console.log it to make sure it is the same)

How to change Toolbar home icon color

   <!-- ToolBar -->
    <style name="ToolBarTheme.ToolBarStyle"    parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="android:textColorPrimary">@android:color/white</item>
        <item name="android:textColor">@color/white</item>
        <item name="android:textColorPrimaryInverse">@color/white</item>
    </style>

Too late to post, this worked for me to change the color of the back button

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

How to access parameters in a Parameterized Build?

To parameter variable add prefix "params." For example:

params.myParam

Don't forget: if you use some method of myParam, may be you should approve it in "Script approval".

How do I add FTP support to Eclipse?

have you checked RSE (Remote System Explorer) ? I think it's pretty close to what you want to achieve.

a blog post about it, with screenshots

form action with javascript

I always include the js files in the head of the html document and them in the action just call the javascript function. Something like this:

action="javascript:checkout()"

You try this?

Don't forget include the script reference in the html head.

I don't know cause of that works in firefox. Regards.

ssh: The authenticity of host 'hostname' can't be established

In my case, the host was unkown and instead of typing yes to the question are you sure you want to continue connecting(yes/no/[fingerprint])? I was just hitting enter .

How can I pass parameters to a partial view in mvc 4

For Asp.Net core you better use

<partial name="_MyPartialView" model="MyModel" />

So for example

@foreach (var item in Model)
{
   <partial name="_MyItemView" model="item" />
}

DLL Load Library - Error Code 126

Windows dll error 126 can have many root causes. The most useful methods I have found to debug this are:

  1. Use dependency walker to look for any obvious problems (which you have already done)
  2. Use the sysinternals utility Process Monitor http://technet.microsoft.com/en-us/sysinternals/bb896645 from Microsoft to trace all file access while your dll is trying to load. With this utility, you will see everything that that dll is trying to pull in and usually the problem can be determined from there.

How to include PHP files that require an absolute path?

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/path/to/file.php");

I use this line of code. It goes back to the "top" of the site tree, then goes to the file desired.

For example, let's say i have this file tree:

domain.com/aaa/index.php
domain.com/bbb/ccc/ddd/index.php
domain.com/_resources/functions.php

I can include the functions.php file from wherever i am, just by copy pasting

require(str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1))."/_resources/functions.php");

If you need to use this code many times, you may create a function that returns the str_repeat('../',(substr_count(getenv('SCRIPT_URL'),'/')-1)) part. Then just insert this function in the first file you include. I have an "initialize.php" file that i include at the very top of each php page and which contains this function. The next time i have to include files, i in fact just use the function (named path_back):

require(path_back()."/_resources/another_php_file.php");

How to use __doPostBack()

This is how I do it

    public void B_ODOC_OnClick(Object sender, EventArgs e)
    {
        string script="<script>__doPostBack(\'fileView$ctl01$OTHDOC\',\'{\"EventArgument\":\"OpenModal\",\"EncryptedData\":null}\');</script>";
        Page.ClientScript.RegisterStartupScript(this.GetType(),"JsOtherDocuments",script);               
    }

How do you configure tomcat to bind to a single ip address (localhost) instead of all addresses?

Several connectors are configured, and each connector has an optional "address" attribute where you can set the IP address.

  1. Edit tomcat/conf/server.xml.
  2. Specify a bind address for that connector:
    <Connector 
        port="8080" 
        protocol="HTTP/1.1" 
        address="127.0.0.1"
        connectionTimeout="20000" 
        redirectPort="8443" 
      />
    

Get value (String) of ArrayList<ArrayList<String>>(); in Java

listOfSomething.Clear();
listOfSomething.Add("first");
collection.Add(listOfSomething);

You are clearing the list here and adding one element ("first"), the 1st reference of listOfSomething is updated as well sonce both reference the same object, so when you access the second element myList.get(1) (which does not exist anymore) you get the null.

Notice both collection.Add(listOfSomething); save two references to the same arraylist object.

You need to create two different instances for two elements:

ArrayList<ArrayList<String>> collection = new ArrayList<ArrayList<String>>();

ArrayList<String> listOfSomething1 = new ArrayList<String>();
listOfSomething1.Add("first");
listOfSomething1.Add("second");

ArrayList<String> listOfSomething2 = new ArrayList<String>();
listOfSomething2.Add("first");

collection.Add(listOfSomething1);    
collection.Add(listOfSomething2);

Push JSON Objects to array in localStorage

There are a few steps you need to take to properly store this information in your localStorage. Before we get down to the code however, please note that localStorage (at the current time) cannot hold any data type except for strings. You will need to serialize the array for storage and then parse it back out to make modifications to it.

Step 1:

The First code snippet below should only be run if you are not already storing a serialized array in your localStorage session variable.
To ensure your localStorage is setup properly and storing an array, run the following code snippet first:

var a = [];
a.push(JSON.parse(localStorage.getItem('session')));
localStorage.setItem('session', JSON.stringify(a));

The above code should only be run once and only if you are not already storing an array in your localStorage session variable. If you are already doing this skip to step 2.

Step 2:

Modify your function like so:

function SaveDataToLocalStorage(data)
{
    var a = [];
    // Parse the serialized data back into an aray of objects
    a = JSON.parse(localStorage.getItem('session')) || [];
    // Push the new data (whether it be an object or anything else) onto the array
    a.push(data);
    // Alert the array value
    alert(a);  // Should be something like [Object array]
    // Re-serialize the array back into a string and store it in localStorage
    localStorage.setItem('session', JSON.stringify(a));
}

This should take care of the rest for you. When you parse it out, it will become an array of objects.

Hope this helps.

Wait until ActiveWorkbook.RefreshAll finishes - VBA

This worked for me:

ActiveWorkbook.refreshall
ActiveWorkbook.Save

When you save the workbook it's necessary to complete the refresh.

Create a CSV File for a user in PHP

Instead of:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

Use:

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error()); 

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    echo implode(",", $row)."\n";
}

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

if checkbox is checked, do this

Probably you can go with this code to take actions as the checkbox is checked or unchecked.

$('#chk').on('click',function(){
    if(this.checked==true){
      alert('yes');
    }else{
      alert('no');
    }
});

PostgreSQL: role is not permitted to log in

try to run

sudo su - postgres
psql
ALTER ROLE 'dbname'

Write objects into file with Node.js

If you're geting [object object] then use JSON.stringify

fs.writeFile('./data.json', JSON.stringify(obj) , 'utf-8');

It worked for me.

Installing mysql-python on Centos

You probably did not install MySQL via yum? The version of MySQLDB in the repository is tied to the version of MySQL in the repository. The versions need to match.

Your choices are:

  1. Install the RPM version of MySQL.
  2. Compile MySQLDB to your version of MySQL.

operator << must take exactly one argument

The problem is that you define it inside the class, which

a) means the second argument is implicit (this) and

b) it will not do what you want it do, namely extend std::ostream.

You have to define it as a free function:

class A { /* ... */ };
std::ostream& operator<<(std::ostream&, const A& a);

SecurityException: Permission denied (missing INTERNET permission?)

remove this in your manifest file

 xmlns:tools="http://schemas.android.com/tools"

Get to UIViewController from UIView?

Swift 4

(more concise than the other answers)

fileprivate extension UIView {

  var firstViewController: UIViewController? {
    let firstViewController = sequence(first: self, next: { $0.next }).first(where: { $0 is UIViewController })
    return firstViewController as? UIViewController
  }

}

My use case for which I need to access the view first UIViewController: I have an object that wraps around AVPlayer / AVPlayerViewController and I want to provide a simple show(in view: UIView) method that will embed AVPlayerViewController into view. For that, I need to access view's UIViewController.

Upload Image using POST form data in Python-requests

Use this snippet

import os
import requests
url = 'http://host:port/endpoint'
with open(path_img, 'rb') as img:
  name_img= os.path.basename(path_img)
  files= {'image': (name_img,img,'multipart/form-data',{'Expires': '0'}) }
  with requests.Session() as s:
    r = s.post(url,files=files)
    print(r.status_code)

PIL image to array (numpy array to array) - Python

Based on zenpoy's answer:

import Image
import numpy

def image2pixelarray(filepath):
    """
    Parameters
    ----------
    filepath : str
        Path to an image file

    Returns
    -------
    list
        A list of lists which make it simple to access the greyscale value by
        im[y][x]
    """
    im = Image.open(filepath).convert('L')
    (width, height) = im.size
    greyscale_map = list(im.getdata())
    greyscale_map = numpy.array(greyscale_map)
    greyscale_map = greyscale_map.reshape((height, width))
    return greyscale_map

PostgreSQL "DESCRIBE TABLE"

There are lots of ways to describe the table in PostgreSQL

The simple answer is

    > /d <table_name> -- OR

    > /d+ <table_name>

Usage

If you are in Postgres shell [psql] and you need to describe the tables

You can achieve this by Query also [As lots of friends has posted the correct ways]

There are lots of details regarding the Schema are available in Postgres's default table names information_schema. You can directly use it to retrieve the information of any of table using a simple SQL statement.

Easy query

    SELECT
      *
    FROM
      information_schema.columns
    WHERE
      table_schema = 'your_schema' AND
      table_name   = 'your_table';

Medium query

  SELECT
      a.attname AS Field,
      t.typname || '(' || a.atttypmod || ')' AS Type,
      CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,
      CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,
      (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\'(.*)\'')
              FROM
                      pg_catalog.pg_attrdef d
              WHERE
                      d.adrelid = a.attrelid
                      AND d.adnum = a.attnum
                      AND a.atthasdef) AS Default,
      '' as Extras
  FROM
        pg_class c 
        JOIN pg_attribute a ON a.attrelid = c.oid
        JOIN pg_type t ON a.atttypid = t.oid
        LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid 
                AND r.conname = a.attname
  WHERE
        c.relname = 'tablename'
        AND a.attnum > 0

  ORDER BY a.attnum

You just need to replace the tablename.

Hard query

  SELECT  
      f.attnum AS number,  
      f.attname AS name,  
      f.attnum,  
      f.attnotnull AS notnull,  
      pg_catalog.format_type(f.atttypid,f.atttypmod) AS type,  
      CASE  
          WHEN p.contype = 'p' THEN 't'  
          ELSE 'f'  
      END AS primarykey,  
      CASE  
          WHEN p.contype = 'u' THEN 't'  
          ELSE 'f'
      END AS uniquekey,
      CASE
          WHEN p.contype = 'f' THEN g.relname
      END AS foreignkey,
      CASE
          WHEN p.contype = 'f' THEN p.confkey
      END AS foreignkey_fieldnum,
      CASE
          WHEN p.contype = 'f' THEN g.relname
      END AS foreignkey,
      CASE
          WHEN p.contype = 'f' THEN p.conkey
      END AS foreignkey_connnum,
      CASE
          WHEN f.atthasdef = 't' THEN d.adsrc
      END AS default
  FROM pg_attribute f  
      JOIN pg_class c ON c.oid = f.attrelid  
      JOIN pg_type t ON t.oid = f.atttypid  
      LEFT JOIN pg_attrdef d ON d.adrelid = c.oid AND d.adnum = f.attnum  
      LEFT JOIN pg_namespace n ON n.oid = c.relnamespace  
      LEFT JOIN pg_constraint p ON p.conrelid = c.oid AND f.attnum = ANY (p.conkey)  
      LEFT JOIN pg_class AS g ON p.confrelid = g.oid  
  WHERE c.relkind = 'r'::char  
      AND n.nspname = 'schema'  -- Replace with Schema name  
      AND c.relname = 'tablename'  -- Replace with table name  
      AND f.attnum > 0 ORDER BY number;

You can choose any of the above ways, to describe the table.

Any of you can edit these answers to improve the ways. I'm open to merge your changes. :)

Phone: numeric keyboard for text input

Using the type="email" or type="url" will give you a keyboard on some phones at least, such as iPhone. For phone numbers, you can use type="tel".

JavaScript check if value is only undefined, null or false

Well, you can always "give up" :)

function b(val){
    return (val==null || val===false);
}

Easiest way to pass an AngularJS scope variable from directive to controller?

Wait until angular has evaluated the variable

I had a lot of fiddling around with this, and couldn't get it to work even with the variable defined with "=" in the scope. Here's three solutions depending on your situation.


Solution #1


I found that the variable was not evaluated by angular yet when it was passed to the directive. This means that you can access it and use it in the template, but not inside the link or app controller function unless we wait for it to be evaluated.

If your variable is changing, or is fetched through a request, you should use $observe or $watch:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // observe changes in attribute - could also be scope.$watch
            attrs.$observe('yourDirective', function (value) {
                if (value) {
                    console.log(value);
                    // pass value to app controller
                    scope.variable = value;
                }
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // observe changes in attribute - could also be scope.$watch
                $attrs.$observe('yourDirective', function (value) {
                    if (value) {
                        console.log(value);
                        // pass value to app controller
                        $scope.variable = value;
                    }
                });
            }
        ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Note that you should not set the variable to "=" in the scope, if you are using the $observe function. Also, I found that it passes objects as strings, so if you're passing objects use solution #2 or scope.$watch(attrs.yourDirective, fn) (, or #3 if your variable is not changing).


Solution #2


If your variable is created in e.g. another controller, but just need to wait until angular has evaluated it before sending it to the app controller, we can use $timeout to wait until the $apply has run. Also we need to use $emit to send it to the parent scope app controller (due to the isolated scope in the directive):

app.directive('yourDirective', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        // NB: isolated scope!!
        scope: {
            yourDirective: '='
        },
        link: function (scope, element, attrs) {
            // wait until after $apply
            $timeout(function(){
                console.log(scope.yourDirective);
                // use scope.$emit to pass it to controller
                scope.$emit('notification', scope.yourDirective);
            });
        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: [ '$scope', function ($scope) {
            // wait until after $apply
            $timeout(function(){
                console.log($scope.yourDirective);
                // use $scope.$emit to pass it to controller
                $scope.$emit('notification', scope.yourDirective);
            });
        }]
    };
}])
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$on('notification', function (evt, value) {
        console.log(value);
        $scope.variable = value;
    });
}]);

And here's the html (no brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="someObject.someVariable"></div>
    <!-- use ng-bind in stead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Solution #3


If your variable is not changing and you need to evaluate it in your directive, you can use the $eval function:

app.directive('yourDirective', function () {
    return {
        restrict: 'A',
        // NB: no isolated scope!!
        link: function (scope, element, attrs) {
            // executes the expression on the current scope returning the result
            // and adds it to the scope
            scope.variable = scope.$eval(attrs.yourDirective);
            console.log(scope.variable);

        },
        // the variable is available in directive controller,
        // and can be fetched as done in link function
        controller: ['$scope', '$element', '$attrs',
            function ($scope, $element, $attrs) {
                // executes the expression on the current scope returning the result
                // and adds it to the scope
                scope.variable = scope.$eval($attrs.yourDirective);
                console.log($scope.variable);
            }
         ]
    };
})
.controller('MyCtrl', ['$scope', function ($scope) {
    // variable passed to app controller
    $scope.$watch('variable', function (value) {
        if (value) {
            console.log(value);
        }
    });
}]);

And here's the html (remember the brackets!):

<div ng-controller="MyCtrl">
    <div your-directive="{{ someObject.someVariable }}"></div>
    <!-- use ng-bind instead of {{ }}, when you can to avoids FOUC -->
    <div ng-bind="variable"></div>
</div>

Also, have a look at this answer: https://stackoverflow.com/a/12372494/1008519

Reference for FOUC (flash of unstyled content) issue: http://deansofer.com/posts/view/14/AngularJs-Tips-and-Tricks-UPDATED

For the interested: here's an article on the angular life cycle

Find an element in DOM based on an attribute value

Here is an example , How to search images in a document by src attribute :

document.querySelectorAll("img[src='https://pbs.twimg.com/profile_images/........jpg']");

Determine the type of an object?

be careful using isinstance

isinstance(True, bool)
True
>>> isinstance(True, int)
True

but type

type(True) == bool
True
>>> type(True) == int
False

add image to uitableview cell

cell.imageView.image = [UIImage imageNamed:@"image.png"];

UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.

How to parse a CSV file in Bash?

If you want to read CSV file with some lines, so this the solution.

while IFS=, read -ra line
do 
    test $i -eq 1 && ((i=i+1)) && continue
    for col_val in ${line[@]}
    do
        echo -n "$col_val|"                 
    done
    echo        
done < "$csvFile"

rename the columns name after cbind the data

If you offer cbind a set of arguments all of whom are vectors, you will get not a dataframe, but rather a matrix, in this case an all character matrix. They have different features. You can get a dataframe if some of your arguments remain dataframes, Try:

merger <- cbind(Date =as.character(Date),
             weather1[ , c("High", "Low", "Avg..High", "Avg.Low")] , 
             ScnMov =sale$Scanned.Movement[a] )

How to have a transparent ImageButton: Android

Programmatically it can be done by :

image_button.setAlpha(0f) // to make it full transparent
image_button.setAlpha(0.5f) // to make it half transparent
image_button.setAlpha(0.6f) // to make it (40%) transparent
image_button.setAlpha(1f) // to make it opaque

JQuery window scrolling event?

Try this: http://jsbin.com/axaler/3/edit

$(function(){
  $(window).scroll(function(){
    var aTop = $('.ad').height();
    if($(this).scrollTop()>=aTop){
        alert('header just passed.');
        // instead of alert you can use to show your ad
        // something like $('#footAd').slideup();
    }
  });
});

Delayed function calls

I though the perfect solution would be to have a timer handle the delayed action. FxCop doesn't like when you have an interval less then one second. I need to delay my actions until AFTER my DataGrid has completed sorting by column. I figured a one-shot timer (AutoReset = false) would be the solution, and it works perfectly. AND, FxCop will not let me suppress the warning!

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

How do you get a timestamp in JavaScript?

Any browsers not supported Date.now, you can use this for get current date time:

currentTime = Date.now() || +new Date()

How to enable external request in IIS Express?

If you run Visual Studio from Admin you can add just

<binding protocol="http" bindingInformation="*:8080:*" />

or

<binding protocol="https" bindingInformation="*:8443:*" />

into

%userprofile%\My Documents\IISExpress\config\applicationhost.config

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

jQuery Validate Required Select

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>

 <form id="myform"> 
       <select class="form-control" name="user_type">
        <option value="">Select</option>
        <option value="2">1</option>
        <option value="3">2</option>
        </select>
       </form>


<script>
  $('#myform').validate({ // initialize the plugin
            rules: {
          user_type:{ required: true},
         }
      });
</script>

select value will be blank

number several equations with only one number

First of all, you probably don't want the align environment if you have only one column of equations. In fact, your example is probably best with the cases environment. But to answer your question directly, used the aligned environment within equation - this way the outside environment gives the number:

\begin{equation}
  \begin{aligned}
  w^T x_i + b &\geq 1-\xi_i &\text{ if }& y_i=1,  \\
  w^T x_i + b &\leq -1+\xi_i & \text{ if } &y_i=-1,
  \end{aligned}
\end{equation}

The documentation of the amsmath package explains this and more.

How do I jump to a closing bracket in Visual Studio Code?

The out-of-the-box way to do it is

Ctrl + Shift + |

How to re-enable right click so that I can inspect HTML elements in Chrome?

If the page you are on has a text or textarea input, click into this input (as if you want to enter text) then right-click and select 'Inspect element'.

RegExp matching string not starting with my

^(?!my)\w+$

should work.

It first ensures that it's not possible to match my at the start of the string, and then matches alphanumeric characters until the end of the string. Whitespace anywhere in the string will cause the regex to fail. Depending on your input you might want to either strip whitespace in the front and back of the string before passing it to the regex, or use add optional whitespace matchers to the regex like ^\s*(?!my)(\w+)\s*$. In this case, backreference 1 will contain the name of the variable.

And if you need to ensure that your variable name starts with a certain group of characters, say [A-Za-z_], use

^(?!my)[A-Za-z_]\w*$

Note the change from + to *.

What Regex would capture everything from ' mark to the end of a line?

The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:

'.*$

And if you wanted to capture everything after the ' char but not include it in the output, you would use:

(?<=').*$

This basically says give me all characters that follow the ' char until the end of the line.

Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:

'.* 

is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.

Unable to simultaneously satisfy constraints, will attempt to recover by breaking constraint

I had a hard time figuring out what constraints were causing this error. Here is a simpler way to do it.

I'm using Xcode 6.1.1

  1. "Command + A" to select all the UILabels, UIImages etc.
  2. Click Editor -> Pin > (Select...) to Superview
  3. again click Editor -> Resolve Auto Layout Issues -> Add Missing Constraints or Reset to Suggested Constraints. It depends on your case.

How can a file be copied?

In case you've come this far down. The answer is that you need the entire path and file name

import os

shutil.copy(os.path.join(old_dir, file), os.path.join(new_dir, file))

XSS prevention in JSP/Servlet web application

There is no easy, out of the box solution against XSS. The OWASP ESAPI API has some support for the escaping that is very usefull, and they have tag libraries.

My approach was to basically to extend the stuts 2 tags in following ways.

  1. Modify s:property tag so it can take extra attributes stating what sort of escaping is required (escapeHtmlAttribute="true" etc.). This involves creating a new Property and PropertyTag classes. The Property class uses OWASP ESAPI api for the escaping.
  2. Change freemarker templates to use the new version of s:property and set the escaping.

If you didn't want to modify the classes in step 1, another approach would be to import the ESAPI tags into the freemarker templates and escape as needed. Then if you need to use a s:property tag in your JSP, wrap it with and ESAPI tag.

I have written a more detailed explanation here.

http://www.nutshellsoftware.org/software/securing-struts-2-using-esapi-part-1-securing-outputs/

I agree escaping inputs is not ideal.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

In my case, I had replaced math library files from a previous Game Engine Graphics course with GLM. The problem was that I didn't add them to the project within Visual Studio's Solution Explorer (even though they were in the project repository).

How to use .htaccess in WAMP Server?

click: WAMP icon->Apache->Apache modules->chose rewrite_module

and do restart for all services.

Evaluate empty or null JSTL c tags

How can I validate if a String is null or empty using the c tags of JSTL?

You can use the empty keyword in a <c:if> for this:

<c:if test="${empty var1}">
    var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
    var1 is NOT empty or null.
</c:if>

Or the <c:choose>:

<c:choose>
    <c:when test="${empty var1}">
        var1 is empty or null.
    </c:when>
    <c:otherwise>
        var1 is NOT empty or null.
    </c:otherwise>
</c:choose>

Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator ${condition? valueIfTrue : valueIfFalse}:

<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />

To learn more about those ${} things (the Expression Language, which is a separate subject from JSTL), check here.

See also:

Proper use of mutexes in Python

I would like to improve answer from chris-b a little bit more.

See below for my code:

from threading import Thread, Lock
import threading
mutex = Lock()


def processData(data, thread_safe):
    if thread_safe:
        mutex.acquire()
    try:
        thread_id = threading.get_ident()
        print('\nProcessing data:', data, "ThreadId:", thread_id)
    finally:
        if thread_safe:
            mutex.release()


counter = 0
max_run = 100
thread_safe = False
while True:
    some_data = counter        
    t = Thread(target=processData, args=(some_data, thread_safe))
    t.start()
    counter = counter + 1
    if counter >= max_run:
        break

In your first run if you set thread_safe = False in while loop, mutex will not be used, and threads will step over each others in print method as below;

Not Thread safe

but, if you set thread_safe = True and run it, you will see all the output comes perfectly fine;

Thread safe

hope this helps.

Count items in a folder with PowerShell

I finally found this link:

https://blogs.perficient.com/microsoft/2011/06/powershell-count-property-returns-nothing/

Well, it turns out that this is a quirk caused precisely because there was only one file in the directory. Some searching revealed that in this case, PowerShell returns a scalar object instead of an array. This object doesn’t have a count property, so there isn’t anything to retrieve.

The solution -- force PowerShell to return an array with the @ symbol:

Write-Host @( Get-ChildItem c:\MyFolder ).Count;

OpenCV with Network Cameras

OpenCV can be compiled with FFMPEG support. From ./configure --help:

--with-ffmpeg     use ffmpeg libraries (see LICENSE) [automatic]

You can then use cvCreateFileCapture_FFMPEG to create a CvCapture with e.g. the URL of the camera's MJPG stream.

I use this to grab frames from an AXIS camera:

CvCapture *capture = 
    cvCreateFileCapture_FFMPEG("http://axis-cam/mjpg/video.mjpg?resolution=640x480&req_fps=10&.mjpg");

Eclipse plugin for generating a class diagram

Must it be an Eclipse plug-in? I use doxygen, just supply your code folder, it handles the rest.

How to revert multiple git commits?

For doing so you just have to use the revert command, specifying the range of commits you want to get reverted.

Taking into account your example, you'd have to do this (assuming you're on branch 'master'):

git revert master~3..master

or git revert B...D or git revert D C B

This will create a new commit in your local with the inverse commit of B, C and D (meaning that it will undo changes introduced by these commits):

A <- B <- C <- D <- BCD' <- HEAD

Call to undefined function mysql_query() with Login

What is your PHP version? Extension "Mysql" was deprecated in PHP 5.5.0. Use extension Mysqli (like mysqli_query).

Angular HttpClient "Http failure during parsing"

I use .NetCore for my back-end tasks,I was able to resolve this issue by using the Newtonsoft.Json library package to return a JSON string from my controller.

Apparently, not all JSON Serializers are built to the right specifications..NET 5's "return Ok("");" was definitely not sufficient.

How to change default text color using custom theme?

When you create an App, a file called styles.xml will be created in your res/values folder. If you change the styles, you can change the background, text color, etc for all your layouts. That way you don’t have to go into each individual layout and change the it manually.

styles.xml:

<resources xmlns:android="http://schemas.android.com/apk/res/android">
<style name="Theme.AppBaseTheme" parent="@android:style/Theme.Light">
    <item name="android:editTextColor">#295055</item> 
    <item name="android:textColorPrimary">#295055</item>
    <item name="android:textColorSecondary">#295055</item>
    <item name="android:textColorTertiary">#295055</item>
    <item name="android:textColorPrimaryInverse">#295055</item>
    <item name="android:textColorSecondaryInverse">#295055</item>
    <item name="android:textColorTertiaryInverse">#295055</item>

     <item name="android:windowBackground">@drawable/custom_background</item>        
</style>

<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
    <!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>

parent="@android:style/Theme.Light" is Google’s native colors. Here is a reference of what the native styles are: https://android.googlesource.com/platform/frameworks/base/+/refs/heads/master/core/res/res/values/themes.xml

The default Android style is also called “Theme”. So you calling it Theme probably confused the program.

name="Theme.AppBaseTheme" means that you are creating a style that inherits all the styles from parent="@android:style/Theme.Light". This part you can ignore unless you want to inherit from AppBaseTheme again. = <style name="AppTheme" parent="AppBaseTheme">

@drawable/custom_background is a custom image I put in the drawable’s folder. It is a 300x300 png image.

#295055 is a dark blue color.

My code changes the background and text color. For Button text, please look through Google’s native stlyes (the link I gave u above).

Then in Android Manifest, remember to include the code:

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

SQL sum with condition

Try this instead:

SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)

Explanation

Your CASE expression has incorrect syntax. It seems you are confusing the simple CASE expression syntax with the searched CASE expression syntax. See the documentation for CASE:

The CASE expression has two formats:

  • The simple CASE expression compares an expression to a set of simple expressions to determine the result.
  • The searched CASE expression evaluates a set of Boolean expressions to determine the result.

You want the searched CASE expression syntax:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

As a side note, if performance is an issue you may find that this expression runs more quickly if you rewrite using a JOIN and GROUP BY instead of using a dependent subquery.

How do you create a Marker with a custom icon for google maps API v3?

LatLng hello = new LatLng(X, Y);          // whereX & Y are coordinates

Bitmap icon = BitmapFactory.decodeResource(getApplicationContext().getResources(),
                R.drawable.university);   // where university is the icon name that is used as a marker.

mMap.addMarker(new MarkerOptions().icon(BitmapDescriptorFactory.fromBitmap(icon)).position(hello).title("Hello World!"));

mMap.moveCamera(CameraUpdateFactory.newLatLng(hello));

Epoch vs Iteration when training neural networks

1.Epoch is 1 complete cycle where Neural network has seen all he data.
2. One might have say 100,000 images to train the model, however memory space might not be sufficient to process all the images at once, hence we split training the model on smaller chunks of data called batches. e.g. batch size is 100.
3. We need to cover all the images using multiple batches. So we will need 1000 iterations to cover all the 100,000 images. (100 batch size * 1000 iterations)
4. Once Neural Network looks at entire data it is called 1 Epoch (Point 1). One might need multiple epochs to train the model. (let us say 10 epochs).

Text not wrapping inside a div element

Might benefit you to be aware of another option, word-wrap: break-word;

The difference here is that words that can completely fit on 1 line will do that, vs. being forced to break simply because there is no more real estate on the line the word starts on.

See the fiddle for an illustration http://jsfiddle.net/Jqkcp/

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

For me it was picking the default JVM v6 set in env vars.

Needed to explicitly add below in eclipse.ini to use v8 which is req by photon.

-vm
C:\Program Files\Java\jdk1.8.0_75\bin\javaw.exe
--launcher.appendVmargs
-vmargs
-Dosgi.requiredJavaVersion=1.8

NOTE : Add the entry of vm above the vm args else it will not work!

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

While a lot of the above answers give ways to embed an image using a file or with Python code, there is a way to embed an image in the jupyter notebook itself using only markdown and base64!

To view an image in the browser, you can visit the link data:image/png;base64,**image data here** for a base64-encoded PNG image, or data:image/jpg;base64,**image data here** for a base64-encoded JPG image. An example link can be found at the end of this answer.

To embed this into a markdown page, simply use a similar construct as the file answers, but with a base64 link instead: ![**description**](data:image/**type**;base64,**base64 data**). Now your image is 100% embedded into your Jupyter Notebook file!

Example link: data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==

Example markdown: ![smile](data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAABHNCSVQICAgIfAhkiAAAAD9JREFUGJW1jzEOADAIAqHx/1+mE4ltNXEpI3eJQknCIGsiHSLJB+aO/06PxOo/x2wBgKR2jCeEy0rOO6MDdzYQJRcVkl1NggAAAABJRU5ErkJggg==)

Adding headers when using httpClient.GetAsync

You can add whatever headers you need to the HttpClient.

Here is a nice tutorial about it.

This doesn't just reference to POST-requests, you can also use it for GET-requests.

Getting realtime output using subprocess

I tried this, and for some reason while the code

for line in p.stdout:
  ...

buffers aggressively, the variant

while True:
  line = p.stdout.readline()
  if not line: break
  ...

does not. Apparently this is a known bug: http://bugs.python.org/issue3907 (The issue is now "Closed" as of Aug 29, 2018)

Easy way to convert a unicode list to a list containing python strings?

There are several ways to do this. I converted like this

def clean(s):
    s = s.replace("u'","")
    return re.sub("[\[\]\'\s]", '', s)

EmployeeList = [clean(i) for i in str(EmployeeList).split(',')]

After that you can check

if '1001' in EmployeeList:
    #do something

Hope it will help you.

Mismatch Detected for 'RuntimeLibrary'

Issue can be solved by adding CRT of msvcrtd.lib in the linker library. Because cryptlib.lib used CRT version of debug.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Suppose you have data in A1:A10 and B1:B10 and you want to highlight which values in A1:A10 do not appear in B1:B10.

Try as follows:

  1. Format > Conditional Formating...
  2. Select 'Formula Is' from drop down menu
  3. Enter the following formula:

    =ISERROR(MATCH(A1,$B$1:$B$10,0))

  4. Now select the format you want to highlight the values in col A that do not appear in col B

This will highlight any value in Col A that does not appear in Col B.

Json.NET serialize object with root name

[Newtonsoft.Json.JsonObject(Title = "root")]
public class TestMain

this is the only attrib you need to add to get your code working.

Store List to session

Yes. Which platform are you writing for? ASP.NET C#?

List<string> myList = new List<string>();
Session["var"] = myList;

Then, to retrieve:

myList = (List<string>)Session["var"];

How to invoke the super constructor in Python?

Short Answer

super(DerivedClass, self).__init__()

Long Answer

What does super() do?

It takes specified class name, finds its base classes (Python allows multiple inheritance) and looks for the method (__init__ in this case) in each of them from left to right. As soon as it finds method available, it will call it and end the search.

How do I call init of all base classes?

Above works if you have only one base class. But Python does allow multiple inheritance and you might want to make sure all base classes are initialized properly. To do that, you should have each base class call init:

class Base1:
  def __init__():
    super(Base1, self).__init__()

class Base2:
  def __init__():
    super(Base2, self).__init__()

class Derived(Base1, Base2):
  def __init__():
    super(Derived, self).__init__()

What if I forget to call init for super?

The constructor (__new__) gets invoked in a chain (like in C++ and Java). Once the instance is created, only that instance's initialiser (__init__) is called, without any implicit chain to its superclass.

Handling null values in Freemarker

I think it works the other way

<#if object.attribute??>
   Do whatever you want....
</#if>

If object.attribute is NOT NULL, then the content will be printed.

How to add data to DataGridView

Let's assume you have a class like this:

public class Staff
{
    public int ID { get; set; }
    public string Name { get; set; }
}

And assume you have dragged and dropped a DataGridView to your form, and name it dataGridView1.

You need a BindingSource to hold your data to bind your DataGridView. This is how you can do it:

private void frmDGV_Load(object sender, EventArgs e)
{
    //dummy data
    List<Staff> lstStaff = new List<Staff>();
    lstStaff.Add(new Staff()
    {
        ID = 1,
        Name = "XX"
    });
    lstStaff.Add(new Staff()
    {
        ID = 2,
        Name = "YY"
    });

    //use binding source to hold dummy data
    BindingSource binding = new BindingSource();
    binding.DataSource = lstStaff;

    //bind datagridview to binding source
    dataGridView1.DataSource = binding;
}

PHP/MySQL Insert null values

I think you need quotes around your {$row['null_field']}, so '{$row['null_field']}'

If you don't have the quotes, you'll occasionally end up with an insert statement that looks like this: insert into table2 (f1, f2) values ('val1',) which is a syntax error.

If that is a numeric field, you will have to do some testing above it, and if there is no value in null_field, explicitly set it to null..

Reset textbox value in javascript

In Javascript :

document.getElementById('searchField').value = '';

In jQuery :

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

That should do it

Docker: "no matching manifest for windows/amd64 in the manifest list entries"

You need to pull with the Linux platform first, then you can run on Windows:

docker pull --platform linux php
docker run -it php

See blog post Docker for Windows Desktop 18.02 with Windows 10 Fall Creators Update.

Redirect from asp.net web api post action

You can check this

[Route("Report/MyReport")]
public IHttpActionResult GetReport()
{

   string url = "https://localhost:44305/Templates/ReportPage.html";

   System.Uri uri = new System.Uri(url);

   return Redirect(uri);
}

How do I convert a date/time to epoch time (unix time/seconds since 1970) in Perl?

Possibly one of the better examples of 'There's More Than One Way To Do It", with or without the help of CPAN.

If you have control over what you get passed as a 'date/time', I'd suggest going the DateTime route, either by using a specific Date::Time::Format subclass, or using DateTime::Format::Strptime if there isn't one supporting your wacky date format (see the datetime FAQ for more details). In general, Date::Time is the way to go if you want to do anything serious with the result: few classes on CPAN are quite as anal-retentive and obsessively accurate.

If you're expecting weird freeform stuff, throw it at Date::Parse's str2time() method, which'll get you a seconds-since-epoch value you can then have your wicked way with, without the overhead of Date::Manip.

Call Class Method From Another Class

Just call it and supply self

class A:
    def m(self, x, y):
        print(x+y)

class B:
    def call_a(self):
        A.m(self, 1, 2)

b = B()
b.call_a()

output: 3

How to Compare two strings using a if in a stored procedure in sql server 2008?

Two things:

  1. Only need one (1) equals sign to evaluate
  2. You need to specify a length on the VARCHAR - the default is a single character.

Use:

DECLARE @temp VARCHAR(10)
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

VARCHAR(10) means the VARCHAR will accommodate up to 10 characters. More examples of the behavior -

DECLARE @temp VARCHAR
    SET @temp = 'm'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "yes"

DECLARE @temp VARCHAR
    SET @temp = 'mtest'

IF @temp = 'm'
  SELECT 'yes'
ELSE
  SELECT 'no'

...will return "no".

What function is to replace a substring from a string in C?

// Here is the code for unicode strings!


int mystrstr(wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *posstr=wcsstr(txt1,txt2);
    if(posstr!=NULL)
    {
        return (posstr-txt1);
    }else
    {
        return -1;
    }
}

// assume: supplied buff is enough to hold generated text
void StringReplace(wchar_t *buff,wchar_t *txt1,wchar_t *txt2)
{
    wchar_t *tmp;
    wchar_t *nextStr;
    int pos;

    tmp=wcsdup(buff);

    pos=mystrstr(tmp,txt1);
    if(pos!=-1)
    {
        buff[0]=0;
        wcsncpy(buff,tmp,pos);
        buff[pos]=0;

        wcscat(buff,txt2);

        nextStr=tmp+pos+wcslen(txt1);

        while(wcslen(nextStr)!=0)
        {
            pos=mystrstr(nextStr,txt1);

            if(pos==-1)
            {
                wcscat(buff,nextStr);
                break;
            }

            wcsncat(buff,nextStr,pos);
            wcscat(buff,txt2);

            nextStr=nextStr+pos+wcslen(txt1);   
        }
    }

    free(tmp);
}

What is the best way to paginate results in SQL Server

From 2012 onward we can use OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY

How to trim a string to N chars in Javascript?

Why not just use substring... string.substring(0, 7); The first argument (0) is the starting point. The second argument (7) is the ending point (exclusive). More info here.

var string = "this is a string";
var length = 7;
var trimmedString = string.substring(0, length);

Failed to execute 'atob' on 'Window'

here's an updated fiddle where the user's input is saved in local storage automatically. each time the fiddle is re-run or the page is refreshed the previous state is restored. this way you do not need to prompt users to save, it just saves on it's own.

http://jsfiddle.net/tZPg4/9397/

stack overflow requires I include some code with a jsFiddle link so please ignore snippet:

localStorage.setItem(...)

PostgreSQL Error: Relation already exists

There should be no single quotes here 'A'. Single quotes are for string literals: 'some value'.
Either use double quotes to preserve the upper case spelling of "A":

CREATE TABLE "A" ...

Or don't use quotes at all:

CREATE TABLE A ...

which is identical to

CREATE TABLE a ...

because all unquoted identifiers are folded to lower case automatically in PostgreSQL.


You could avoid problems with the index name completely by using simpler syntax:

CREATE TABLE csd_relationship (
    csd_relationship_id serial PRIMARY KEY,
    type_id integer NOT NULL,
    object_id integer NOT NULL
);

Does the same as your original query, only it avoids naming conflicts automatically. It picks the next free identifier automatically. More about the serial type in the manual.

Get integer value of the current year in Java

In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD and java.time.Instant uses it, so (for UTC):

import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));

P.S. just in case (and shorted for getting String, not int), using Calendar looks better and can be made zone-aware.

Python: Open file in zip without temporarily extracting it

Vincent Povirk's answer won't work completely;

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...

You have to change it in:

import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...

For details read the ZipFile docs here.

Serializing PHP object to JSON


edit: it's currently 2016-09-24, and PHP 5.4 has been released 2012-03-01, and support has ended 2015-09-01. Still, this answer seems to gain upvotes. If you're still using PHP < 5.4, your are creating a security risk and endagering your project. If you have no compelling reasons to stay at <5.4, or even already use version >= 5.4, do not use this answer, and just use PHP>= 5.4 (or, you know, a recent one) and implement the JsonSerializable interface


You would define a function, for instance named getJsonData();, which would return either an array, stdClass object, or some other object with visible parameters rather then private/protected ones, and do a json_encode($data->getJsonData());. In essence, implement the function from 5.4, but call it by hand.

Something like this would work, as get_object_vars() is called from inside the class, having access to private/protected variables:

function getJsonData(){
    $var = get_object_vars($this);
    foreach ($var as &$value) {
        if (is_object($value) && method_exists($value,'getJsonData')) {
            $value = $value->getJsonData();
        }
    }
    return $var;
}

Python float to int conversion

int converts by truncation, as has been mentioned by others. This can result in the answer being one different than expected. One way around this is to check if the result is 'close enough' to an integer and adjust accordingly, otherwise the usual conversion. This is assuming you don't get too much roundoff and calculation error, which is a separate issue. For example:

def toint(f):
    trunc = int(f)
    diff = f - trunc

    # trunc is one too low
    if abs(f - trunc - 1) < 0.00001:
        return trunc + 1
    # trunc is one too high
    if abs(f - trunc + 1) < 0.00001:
        return trunc - 1
    # trunc is the right value
    return trunc

This function will adjust for off-by-one errors for near integers. The mpmath library does something similar for floating point numbers that are close to integers.

Oracle Not Equals Operator

The difference is :

"If you use !=, it returns sub-second. If you use <>, it takes 7 seconds to return. Both return the right answer."

Oracle not equals (!=) SQL operator

Regards

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I had a similar error but with different context when I uploaded a *.p file to Google Drive. I tried to use it later in a Google Colab session, and got this error:

    1 with open("/tmp/train.p", mode='rb') as training_data:
----> 2     train = pickle.load(training_data)
UnpicklingError: invalid load key, '<'.

I solved it by compressing the file, upload it and then unzip on the session. It looks like the pickle file is not saved correctly when you upload/download it so it gets corrupted.

How to save SELECT sql query results in an array in C# Asp.net

Use a SQL DATA READER:

In this example i use a List instead an array.

try
{
    SqlCommand comm = new SqlCommand("SELECT CategoryID, CategoryName FROM Categories;",connection);
    connection.Open();

    SqlDataReader reader = comm.ExecuteReader();
    List<string> str = new List<string>();
    int i=0;
    while (reader.Read())
    {
        str.Add( reader.GetValue(i).ToString() );
        i++;
    }
    reader.Close();
}
catch (Exception)
{
    throw;
}
finally
{
    connection.Close();
}

JavaScript unit test tools for TDD

YUI has a testing framework as well. This video from Yahoo! Theater is a nice introduction, although there are a lot of basics about TDD up front.

This framework is generic and can be run against any JavaScript or JS library.