Programs & Examples On #Libavcodec

libavcodec is a free software/open source LGPL-licensed library of codecs for encoding and decoding video and audio data.

What are the differences and similarities between ffmpeg, libav, and avconv?

Confusing messages

These messages are rather misleading and understandably a source of confusion. Older Ubuntu versions used Libav which is a fork of the FFmpeg project. FFmpeg returned in Ubuntu 15.04 "Vivid Vervet".

The fork was basically a non-amicable result of conflicting personalities and development styles within the FFmpeg community. It is worth noting that the maintainer for Debian/Ubuntu switched from FFmpeg to Libav on his own accord due to being involved with the Libav fork.

The real ffmpeg vs the fake one

For a while both Libav and FFmpeg separately developed their own version of ffmpeg.

Libav then renamed their bizarro ffmpeg to avconv to distance themselves from the FFmpeg project. During the transition period the "not developed anymore" message was displayed to tell users to start using avconv instead of their counterfeit version of ffmpeg. This confused users into thinking that FFmpeg (the project) is dead, which is not true. A bad choice of words, but I can't imagine Libav not expecting such a response by general users.

This message was removed upstream when the fake "ffmpeg" was finally removed from the Libav source, but, depending on your version, it can still show up in Ubuntu because the Libav source Ubuntu uses is from the ffmpeg-to-avconv transition period.

In June 2012, the message was re-worded for the package libav - 4:0.8.3-0ubuntu0.12.04.1. Unfortunately the new "deprecated" message has caused additional user confusion.

Starting with Ubuntu 15.04 "Vivid Vervet", FFmpeg's ffmpeg is back in the repositories again.

libav vs Libav

To further complicate matters, Libav chose a name that was historically used by FFmpeg to refer to its libraries (libavcodec, libavformat, etc). For example the libav-user mailing list, for questions and discussions about using the FFmpeg libraries, is unrelated to the Libav project.

How to tell the difference

If you are using avconv then you are using Libav. If you are using ffmpeg you could be using FFmpeg or Libav. Refer to the first line in the console output to tell the difference: the copyright notice will either mention FFmpeg or Libav.

Secondly, the version numbering schemes differ. Each of the FFmpeg or Libav libraries contains a version.h header which shows a version number. FFmpeg will end in three digits, such as 57.67.100, and Libav will end in one digit such as 57.67.0. You can also view the library version numbers by running ffmpeg or avconv and viewing the console output.

If you want to use the real ffmpeg

Ubuntu 15.04 "Vivid Vervet" or newer

The real ffmpeg is in the repository, so you can install it with:

apt-get install ffmpeg

For older Ubuntu versions

Your options are:

These methods are non-intrusive, reversible, and will not interfere with the system or any repository packages.

Another possible option is to upgrade to Ubuntu 15.04 "Vivid Vervet" or newer and just use ffmpeg from the repository.

Also see

For an interesting blog article on the situation, as well as a discussion about the main technical differences between the projects, see The FFmpeg/Libav situation.

ASP.NET custom error page - Server.GetLastError() is null

Try using something like Server.Transfer("~/ErrorPage.aspx"); from within the Application_Error() method of global.asax.cs

Then from within Page_Load() of ErrorPage.aspx.cs you should be okay to do something like: Exception exception = Server.GetLastError().GetBaseException();

Server.Transfer() seems to keep the exception hanging around.

set initial viewcontroller in appdelegate - swift

Swift 5 & Xcode 11

So in xCode 11 the window solution is no longer valid inside of appDelegate. They moved this to the SceneDelgate. You can find this in the SceneDelgate.swift file.

You will notice it now has a var window: UIWindow? present.

In my situation I was using a TabBarController from a storyboard and wanted to set it as the rootViewController.

This is my code:

sceneDelegate.swift

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        self.window = self.window ?? UIWindow()//@JA- If this scene's self.window is nil then set a new UIWindow object to it.

        //@Grab the storyboard and ensure that the tab bar controller is reinstantiated with the details below.
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let tabBarController = storyboard.instantiateViewController(withIdentifier: "tabBarController") as! UITabBarController

        for child in tabBarController.viewControllers ?? [] {
            if let top = child as? StateControllerProtocol {
                print("State Controller Passed To:")
                print(child.title!)
                top.setState(state: stateController)
            }
        }

        self.window!.rootViewController = tabBarController //Set the rootViewController to our modified version with the StateController instances
        self.window!.makeKeyAndVisible()

        print("Finished scene setting code")
        guard let _ = (scene as? UIWindowScene) else { return }
    }

Make sure to add this to the correct scene method as I did here. Note that you will need to set the identifier name for the tabBarController or viewController you are using in the storyboard.

how to set the storyboard ID

In my case I was doing this to set a stateController to keep track of shared variables amongst the tab views. If you wish to do this same thing add the following code...

StateController.swift

import Foundation

struct tdfvars{
    var rbe:Double = 1.4
    var t1half:Double = 1.5
    var alphaBetaLate:Double = 3.0
    var alphaBetaAcute:Double = 10.0
    var totalDose:Double = 6000.00
    var dosePerFraction:Double = 200.0
    var numOfFractions:Double = 30
    var totalTime:Double = 168
    var ldrDose:Double = 8500.0
}

//@JA - Protocol that view controllers should have that defines that it should have a function to setState
protocol StateControllerProtocol {
  func setState(state: StateController)
}

class StateController {
    var tdfvariables:tdfvars = tdfvars()
}

Note: Just use your own variables or whatever you are trying to keep track of instead, I just listed mine as an example in tdfvariables struct.

In each view of the TabController add the following member variable.

    class SettingsViewController: UIViewController {
    var stateController: StateController?
.... }

Then in those same files add the following:

extension SettingsViewController: StateControllerProtocol {
  func setState(state: StateController) {
    self.stateController = state
  }
}

What this does is allows you to avoid the singleton approach to passing variables between the views. This allows easily for the dependency injection model which is much better long run then the singleton approach.

angularjs directive call function specified in attribute and pass an argument to it

My solution:

  1. on polymer raise an event (eg. complete)
  2. define a directive linking the event to control function

Directive

/*global define */
define(['angular', './my-module'], function(angular, directives) {
    'use strict';
    directives.directive('polimerBinding', ['$compile', function($compile) {

            return {
                 restrict: 'A',
                scope: { 
                    method:'&polimerBinding'
                },
                link : function(scope, element, attrs) {
                    var el = element[0];
                    var expressionHandler = scope.method();
                    var siemEvent = attrs['polimerEvent'];
                    if (!siemEvent) {
                        siemEvent = 'complete';
                    }
                    el.addEventListener(siemEvent, function (e, options) {
                        expressionHandler(e.detail);
                    })
                }
            };
        }]);
});

Polymer component

<dom-module id="search">

<template>
<h3>Search</h3>
<div class="input-group">

    <textarea placeholder="search by expression (eg. temperature>100)"
        rows="10" cols="100" value="{{text::input}}"></textarea>
    <p>
        <button id="button" class="btn input-group__addon">Search</button>
    </p>
</div>
</template>

 <script>
  Polymer({
    is: 'search',
            properties: {
      text: {
        type: String,
        notify: true
      },

    },
    regularSearch: function(e) {
      console.log(this.range);
      this.fire('complete', {'text': this.text});
    },
    listeners: {
        'button.click': 'regularSearch',
    }
  });
</script>

</dom-module>

Page

 <search id="search" polimer-binding="searchData"
 siem-event="complete" range="{{range}}"></siem-search>

searchData is the control function

$scope.searchData = function(searchObject) {
                    alert('searchData '+ searchObject.text + ' ' + searchObject.range);

}

Argument of type 'X' is not assignable to parameter of type 'X'

For what it worth, if anyone has this problem only in VSCode, just restart VSCode and it should fix it. Sometimes, Intellisense seems to mess up with imports or types.

Related to Typescript: Argument of type 'RegExpMatchArray' is not assignable to parameter of type 'string'

CSS-Only Scrollable Table with fixed headers

I had the same problem and after spending 2 days researching I found this solution from Ksesocss that fits for me and maybe is good for you too. It allows fixed header and dynamic width and only uses CSS. The only problem is that the source is in spanish but you can find the html and css code there.

This is the link:

http://ksesocss.blogspot.com/2014/10/responsive-table-encabezado-fijo-scroll.html

I hope this helps

How to document Python code using Doxygen

In the end, you only have two options:

You generate your content using Doxygen, or you generate your content using Sphinx*.

  1. Doxygen: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using doxypypy.

  2. Sphinx: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like).

    1. For manual API documentation you have Sphinx autodoc. This is great to write a user guide with embedded API generated elements.
    2. For semi-automatic you have Sphinx autosummary. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the autosummary_generate config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.
    3. Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until AutoAPI came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).

There are other options to note:

  • Breathe: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.
  • pydoctor*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Combine or merge JSON on node.js without jQuery

It can easy be done using Object.assign() method -

 var object1 = {name: "John"};
 var object2 = {location: "San Jose"};
 var object3 = Object.assign(object1,object2);
 console.log(object3);

now object3 is { name: 'John', location: 'San Jose' }

Unknown SSL protocol error in connection

execute

nc -v -z <git-repository> <port>

your out put should look like

"Connection to <git-repository> <port> port [tcp/*] succeeded!"

if you get

connect to <git-repository> <port> (tcp) failed: Connection timed out

You need to edit your ~/.ssh/config file. Add something like the following:

Host example.com
Port 1234

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

Calling async method synchronously

I prefer a non blocking approach:

            Dim aw1=GenerateCodeAsync().GetAwaiter()
            While Not aw1.IsCompleted
                Application.DoEvents()
            End While

Take a full page screenshot with Firefox on the command-line

Firefox Screenshots is a new tool that ships with Firefox. It is not a developer tool, it is aimed at end-users of the browser.

To take a screenshot, click on the page actions menu in the address bar, and click "take a screenshot". If you then click "Save full page", it will save the full page, scrolling for you.


(source: mozilla.net)

ViewDidAppear is not called when opening app from background

Swift 3.0 ++ version

In your viewDidLoad, register at notification center to listen to this opened from background action

NotificationCenter.default.addObserver(self, selector:#selector(doSomething), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
        

Then add this function and perform needed action

func doSomething(){
    //...
}

Finally add this function to clean up the notification observer when your view controller is destroyed.

deinit {
    NotificationCenter.default.removeObserver(self)
}

PHP code is not being executed, instead code shows on the page

in my case (Apache/2.4.34),

after uncommenting the specific module

"LoadModule php7_module libexec/apache2/libphp7.so"

from

"/etc/apache2/httpd.conf"

my problem was gone.

Sync data between Android App and webserver

If you write this yourself these are some of the points to keep in mind

Proper authentication between the device and the Sync Server

A sync protocol between the device and the server. It will usually go in 3 phases, authentication, data exchange, status exchange (which operations worked and which failed)

Pick your payload format. I suggest SyncML based XML mixed with JSON based format to represent the actual data. So SyncML for the protocol, and JSON for the actual data being exchanged. Using JSON Array while manipulating the data is always preferred as it is easy to access data using JSON Array.

Keeping track of data changes on both client and server. You can maintain a changelog of ids that change and pick them up during a sync session. Also, clear the changelog as the objects are successfully synchronized. You can also use a boolean variable to confirm the synchronization status, i.e. last time of sync. It will be helpful for end users to identify the time when last sync is done.

Need to have a way to communicate from the server to the device to start a sync session as data changes on the server. You can use C2DM or write your own persistent tcp based communication. The tcp approach is a lot seamless

A way to replicate data changes across multiple devices

And last but not the least, a way to detect and handle conflicts

Hope this helps as a good starting point.

Storing and displaying unicode string (??????) using PHP and MySQL

For Those who are facing difficulty just got to php admin and change collation to utf8_general_ci Select Table go to Operations>> table options>> collations should be there

What is the difference between old style and new style classes in Python?

New style classes may use super(Foo, self) where Foo is a class and self is the instance.

super(type[, object-or-type])

Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class. The search order is same as that used by getattr() except that the type itself is skipped.

And in Python 3.x you can simply use super() inside a class without any parameters.

ffmpeg usage to encode a video to H264 codec format

I believe that by now the above answers are outdated (or at least unclear) so here's my little go at it. I tried compiling ffmpeg with the option --enable-encoders=libx264 and it will give no error but it won't enable anything (I can't seem to find where I found that suggestion).

Anyways step-by-step, first you must compile libx264 yourself because repository version is outdated:

  wget ftp://ftp.videolan.org/pub/x264/snapshots/last_x264.tar.bz2
  tar --bzip2 -xvf last_x264.tar.bz2
  cd x264-snapshot-XXXXXXXX-XXXX/
  ./configure
  make
  sudo make install

And then get and compile ffmpeg with libx264 enabled. I'm using the latest release which is "Happiness":

wget http://ffmpeg.org/releases/ffmpeg-0.11.2.tar.bz2
tar --bzip2 -xvf ffmpeg-0.11.2.tar.bz2
cd ffmpeg-0.11.2/
./configure --enable-libx264 --enable-gpl
make
sudo install

Now finally you have the libx264 codec to encode, to check it you may run

ffmpeg -codecs | grep h264

and you'll see the options you have were the first D means decoding and the first E means encoding

Merge DLL into EXE?

I Found The Solution Below are the Stpes:-

  1. Download ILMerge.msi and Install it on your Machine.
  2. Open Command Prompt
  3. type cd C:\Program Files (x86)\Microsoft\ILMerge Preess Enter
  4. C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName.dll

For Multiple Dll :-

C:\Program Files (x86)\Microsoft\ILMerge>ILMerge.exe /target:winexe /targetplatform:"v4,C:\Windows\Microsoft.NET\Framework\v4.0.30319" /out:NewExeName.exe SourceExeName.exe DllName1.dll DllName2.dll DllName3.dll

Create instance of generic type whose constructor requires a parameter?

As Jon pointed out this is life for constraining a non-parameterless constructor. However a different solution is to use a factory pattern. This is easily constrainable

interface IFruitFactory<T> where T : BaseFruit {
  T Create(int weight);
}

public void AddFruit<T>( IFruitFactory<T> factory ) where T: BaseFruit {    
  BaseFruit fruit = factory.Create(weight); /*new Apple(150);*/    
  fruit.Enlist(fruitManager);
}

Yet another option is to use a functional approach. Pass in a factory method.

public void AddFruit<T>(Func<int,T> factoryDel) where T : BaseFruit { 
  BaseFruit fruit = factoryDel(weight); /* new Apple(150); */
  fruit.Enlist(fruitManager);
}

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

Automatically accept all SDK licences

There are 2 approach that I can found to this problem.

  1. Update sdk tools with command window by accepting licence agreement as follows, just change the version according to your need.

    android update sdk --no-ui --filter build-tools-25.0.2,android-25,extra-android-m2repository

  2. Second approach is copying licence folders to Android root directory. Goto your development machine open Android Studio. Find your sdk location from Project Structure menu. (C:\Users\UserName\AppData\Local\Android\sdk). Under that directory there must be a licence folder. Copy that folder with the content. Paste that folder in your Jenkins server machine (or where you face with this problem) under android sdk root folder. (C:\Users\UserName.jenkins\tools\android-sdk)

Static variables in C++

Excuse me when I answer your questions out-of-order, it makes it easier to understand this way.

When static variable is declared in a header file is its scope limited to .h file or across all units.

There is no such thing as a "header file scope". The header file gets included into source files. The translation unit is the source file including the text from the header files. Whatever you write in a header file gets copied into each including source file.

As such, a static variable declared in a header file is like a static variable in each individual source file.

Since declaring a variable static this way means internal linkage, every translation unit #includeing your header file gets its own, individual variable (which is not visible outside your translation unit). This is usually not what you want.

I would like to know what is the difference between static variables in a header file vs declared in a class.

In a class declaration, static means that all instances of the class share this member variable; i.e., you might have hundreds of objects of this type, but whenever one of these objects refers to the static (or "class") variable, it's the same value for all objects. You could think of it as a "class global".

Also generally static variable is initialized in .cpp file when declared in a class right ?

Yes, one (and only one) translation unit must initialize the class variable.

So that does mean static variable scope is limited to 2 compilation units ?

As I said:

  • A header is not a compilation unit,
  • static means completely different things depending on context.

Global static limits scope to the translation unit. Class static means global to all instances.

I hope this helps.

PS: Check the last paragraph of Chubsdad's answer, about how you shouldn't use static in C++ for indicating internal linkage, but anonymous namespaces. (Because he's right. ;-) )

Optimal way to Read an Excel file (.xls/.xlsx)

Read from excel, modify and write back

 /// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
    var _xl = new Excel.Application();
    var wb = _xl.Workbooks.Open(filename);
    var sheets = wb.Sheets;
    DataSet dataSet = null;
    if (sheets != null && sheets.Count != 0)
    {
        dataSet = new DataSet();
        foreach (var item in sheets)
        {
            var sheet = (Excel.Worksheet)item;
            DataTable dt = null;
            if (sheet != null)
            {
                dt = new DataTable();
                var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
                var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;

                for (int j = 0; j < ColumnCount; j++)
                {
                    var cell = (Excel.Range)sheet.Cells[1, j + 1];
                    var column = new DataColumn(headers ? cell.Value : string.Empty);
                    dt.Columns.Add(column);
                }

                for (int i = 0; i < rowCount; i++)
                {
                    var r = dt.NewRow();
                    for (int j = 0; j < ColumnCount; j++)
                    {
                        var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
                        r[j] = cell.Value;
                    }
                    dt.Rows.Add(r);
                }

            }
            dataSet.Tables.Add(dt);
        }
    }
    _xl.Quit();
    return dataSet;
}



 public string Export(DataTable dt, bool headers = false)
    {
        var wb = _xl.Workbooks.Add();
        var sheet = (Excel.Worksheet)wb.ActiveSheet;
        //process columns
        for (int i = 0; i < dt.Columns.Count; i++)
        {
            var col = dt.Columns[i];
            //added columns to the top of sheet
            var currentCell = (Excel.Range)sheet.Cells[1, i + 1];
            currentCell.Value = col.ToString();
            currentCell.Font.Bold = true;
            //process rows
            for (int j = 0; j < dt.Rows.Count; j++)
            {
                var row = dt.Rows[j];
                //added rows to sheet
                var cell = (Excel.Range)sheet.Cells[j + 1 + 1, i + 1];
                cell.Value = row[i];
            }
            currentCell.EntireColumn.AutoFit();
        }
        var fileName="{somepath/somefile.xlsx}";
        wb.SaveCopyAs(fileName);
        _xl.Quit();
        return fileName;
    }

how to delete files from amazon s3 bucket?

The following worked for me (based on example for a Django model, but you can pretty much use the code of the delete method on its own).

import boto3
from boto3.session import Session
from django.conf import settings

class Video(models.Model):
    title=models.CharField(max_length=500)
    description=models.TextField(default="")
    creation_date=models.DateTimeField(default=timezone.now)
    videofile=models.FileField(upload_to='videos/', null=True, verbose_name="")
    tags = TaggableManager()

    actions = ['delete']

    def __str__(self):
        return self.title + ": " + str(self.videofile)

    def delete(self, *args, **kwargs):
        session = Session (settings.AWS_ACCESS_KEY_ID, settings.AWS_SECRET_ACCESS_KEY)
        s3_resource = session.resource('s3')
        s3_bucket = s3_resource.Bucket(settings.AWS_STORAGE_BUCKET_NAME)

        file_path = "media/" + str(self.videofile)
        response = s3_bucket.delete_objects(
            Delete={
                'Objects': [
                    {
                        'Key': file_path
                    }
                ]
            })
        super(Video, self).delete(*args, **kwargs)

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<APost> aPosts;

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Python integer incrementing with ++

You can do:

number += 1

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

Why doesn't CSS ellipsis work in table cell?

If you don't want to set max-width to td (like in this answer), you can set max-width to div:

function so_hack(){}

function so_hack(){} http://jsfiddle.net/fd3Zx/754/ function so_hack(){}

function so_hack(){}

Note: 100% doesn't work, but 99% does the trick in FF. Other modern browsers doesn't need silly div hacks.

td {
  border: 1px solid black;
    padding-left:5px;
    padding-right:5px;
}
td>div{
    max-width: 99%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

How to set a binding in Code?

In addition to the answer of Dyppl, I think it would be nice to place this inside the OnDataContextChanged event:

private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    // Unforunately we cannot bind from the viewmodel to the code behind so easily, the dependency property is not available in XAML. (for some reason).
    // To work around this, we create the binding once we get the viewmodel through the datacontext.
    var newViewModel = e.NewValue as MyViewModel;

    var executablePathBinding = new Binding
    {
        Source = newViewModel,
        Path = new PropertyPath(nameof(newViewModel.ExecutablePath))
    };

    BindingOperations.SetBinding(LayoutRoot, ExecutablePathProperty, executablePathBinding);
}

We have also had cases were we just saved the DataContext to a local property and used that to access viewmodel properties. The choice is of course yours, I like this approach because it is more consistent with the rest. You can also add some validation, like null checks. If you actually change your DataContext around, I think it would be nice to also call:

BindingOperations.ClearBinding(myText, TextBlock.TextProperty);

to clear the binding of the old viewmodel (e.oldValue in the event handler).

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.


Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":

GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed

T-SQL string replace in Update

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

How can I see an the output of my C programs using Dev-C++?

When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

Change SVN repository URL

Given that the Apache Subversion server will be moved to this new DNS alias: sub.someaddress.com.tr:

  • With Subversion 1.7 or higher, use svn relocate. Relocate is used when the SVN server's location changes. switch is only used if you want to change your local working copy to another branch or another path. If using TortoiseSVN, you may follow instructions from the TortoiseSVN Manual. If using the SVN command line interface, refer to this section of SVN's documentation. The command should look like this:

    svn relocate svn://sub.someaddress.com.tr/project

  • Keep using /project given that the actual contents of your repository probably won't change.

Note: svn relocate is not available before version 1.7 (thanks to ColinM for the info). In older versions you would use:

    svn switch --relocate OLD NEW

Kubernetes service external ip pending

If you are using minikube then run commands below from terminal,

$ minikube ip
$ 172.17.0.2 // then 
$ curl http://172.17.0.2:31245
or simply
$ curl http://$(minikube ip):31245

The endpoint reference (EPR) for the Operation not found is

By removing cache wsdl-* files in /tmp folder, my problem was solved

see https://www.drupal.org/node/1132926#comment-6283348

be careful about permission to delete

I'm in ubuntu os

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

TypeError: only length-1 arrays can be converted to Python scalars while plot showing

Take note of what is printed for x. You are trying to convert an array (basically just a list) into an int. length-1 would be an array of a single number, which I assume numpy just treats as a float. You could do this, but it's not a purely-numpy solution.

EDIT: I was involved in a post a couple of weeks back where numpy was slower an operation than I had expected and I realised I had fallen into a default mindset that numpy was always the way to go for speed. Since my answer was not as clean as ayhan's, I thought I'd use this space to show that this is another such instance to illustrate that vectorize is around 10% slower than building a list in Python. I don't know enough about numpy to explain why this is the case but perhaps someone else does?

import numpy as np
import matplotlib.pyplot as plt
import datetime

time_start = datetime.datetime.now()

# My original answer
def f(x):
    rebuilt_to_plot = []
    for num in x:
        rebuilt_to_plot.append(np.int(num))
    return rebuilt_to_plot

for t in range(10000):
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f(x))

time_end = datetime.datetime.now()

# Answer by ayhan
def f_1(x):
    return np.int(x)

for t in range(10000):
    f2 = np.vectorize(f_1)
    x = np.arange(1, 15.1, 0.1)
    plt.plot(x, f2(x))

time_end_2 = datetime.datetime.now()

print time_end - time_start
print time_end_2 - time_end

configure Git to accept a particular self-signed server certificate for a particular https remote

Briefly:

  1. Get the self signed certificate
  2. Put it into some (e.g. ~/git-certs/cert.pem) file
  3. Set git to trust this certificate using http.sslCAInfo parameter

In more details:

Get self signed certificate of remote server

Assuming, the server URL is repos.sample.com and you want to access it over port 443.

There are multiple options, how to get it.

Get certificate using openssl

$ openssl s_client -connect repos.sample.com:443

Catch the output into a file cert.pem and delete all but part between (and including) -BEGIN CERTIFICATE- and -END CERTIFICATE-

Content of resulting file ~/git-certs/cert.pem may look like this:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
EwYDVQQIEwxMb3dlciBTYXhvbnkxEjAQBgNVBAcTCVdvbGZzYnVyZzEYMBYGA1UE
ChMPU2FhUy1TZWN1cmUuY29tMRowGAYDVQQDFBEqLnNhYXMtc2VjdXJlLmNvbTEj
MCEGCSqGSIb3DQEJARYUaW5mb0BzYWFzLXNlY3VyZS5jb20wHhcNMTIwNzAyMTMw
OTA0WhcNMTMwNzAyMTMwOTA0WjCBkzELMAkGA1UEBhMCREUxFTATBgNVBAgTDExv
d2VyIFNheG9ueTESMBAGA1UEBxMJV29sZnNidXJnMRgwFgYDVQQKEw9TYWFTLVNl
Y3VyZS5jb20xGjAYBgNVBAMUESouc2Fhcy1zZWN1cmUuY29tMSMwIQYJKoZIhvcN
AQkBFhRpbmZvQHNhYXMtc2VjdXJlLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEP
ADCCAQoCggEBAMUZ472W3EVFYGSHTgFV0LR2YVE1U//sZimhCKGFBhH3ZfGwqtu7
mzOhlCQef9nqGxgH+U5DG43B6MxDzhoP7R8e1GLbNH3xVqMHqEdcek8jtiJvfj2a
pRSkFTCVJ9i0GYFOQfQYV6RJ4vAunQioiw07OmsxL6C5l3K/r+qJTlStpPK5dv4z
Sy+jmAcQMaIcWv8wgBAxdzo8UVwIL63gLlBz7WfSB2Ti5XBbse/83wyNa5bPJPf1
U+7uLSofz+dehHtgtKfHD8XpPoQBt0Y9ExbLN1ysdR9XfsNfBI5K6Uokq/tVDxNi
SHM4/7uKNo/4b7OP24hvCeXW8oRyRzpyDxMCAwEAATANBgkqhkiG9w0BAQUFAAOC
AQEAp7S/E1ZGCey5Oyn3qwP4q+geQqOhRtaPqdH6ABnqUYHcGYB77GcStQxnqnOZ
MJwIaIZqlz+59taB6U2lG30u3cZ1FITuz+fWXdfELKPWPjDoHkwumkz3zcCVrrtI
ktRzk7AeazHcLEwkUjB5Rm75N9+dOo6Ay89JCcPKb+tNqOszY10y6U3kX3uiSzrJ
ejSq/tRyvMFT1FlJ8tKoZBWbkThevMhx7jk5qsoCpLPmPoYCEoLEtpMYiQnDZgUc
TNoL1GjoDrjgmSen4QN5QZEGTOe/dsv1sGxWC+Tv/VwUl2GqVtKPZdKtGFqI8TLn
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

Get certificate using your web browser

I use Redmine with Git repositories and I access the same URL for web UI and for git command line access. This way, I had to add exception for that domain into my web browser.

Using Firefox, I went to Options -> Advanced -> Certificates -> View Certificates -> Servers, found there the selfsigned host, selected it and using Export button I got exactly the same file, as created using openssl.

Note: I was a bit surprised, there is no name of the authority visibly mentioned. This is fine.

Having the trusted certificate in dedicated file

Previous steps shall result in having the certificate in some file. It does not matter, what file it is as long as it is visible to your git when accessing that domain. I used ~/git-certs/cert.pem

Note: If you need more trusted selfsigned certificates, put them into the same file:

-----BEGIN CERTIFICATE-----
MIIDnzCCAocCBE/xnXAwDQYJKoZIhvcNAQEFBQAwgZMxCzAJBgNVBAYTAkRFMRUw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
AnOtHeRtRuStEdCeRtIfIcAtEgOeShErExxxxxxxxxxxxxxxxxxxxxxxxxxxxxxw
...........
/27/jIdVQIKvHok2P/u9tvTUQA==
-----END CERTIFICATE-----

This shall work (but I tested it only with single certificate).

Configure git to trust this certificate

$ git config --global http.sslCAInfo /home/javl/git-certs/cert.pem

You may also try to do that system wide, using --system instead of --global.

And test it: You shall now be able communicating with your server without resorting to:

$ git config --global http.sslVerify false #NO NEED TO USE THIS

If you already set your git to ignorance of ssl certificates, unset it:

$ git config --global --unset http.sslVerify

and you may also check, that you did it all correctly, without spelling errors:

$ git config --global --list

what should list all variables, you have set globally. (I mispelled http to htt).

Selecting Multiple Values from a Dropdown List in Google Spreadsheet

You would use data validation for this. Click in the cell you want to have a multiple drop down > DATA > Validation > Criteria (List from a Range) - here you select form a list of items you want in the drop down. And .. you are good. I have included an example to reference.

Creating a triangle with for loops

Try this

class piramid 
{
    public static void main(String[] args) 
    {
        //System.out.println("Hello World!");

    int max = 7; 
    int k=max/2;
    int j ; 
    printf("\n");
    printf("\n");
    printf("\n");
    printf("\n");
    for(i=k;i>0;i--){

          for(j=0;j<k+1;j++){

                if(i==j){

                       printf("*");

                }else if(j>i){
                      printf(" ");
                      printf("*");
                }else {
                      printf(" ");

                }

           }
            printf("\n");

    }

   }

}

hope it will help you

Failed to open/create the internal network Vagrant on Windows10

I had the same problem after upgrading from Windows 7 to Windows 10. Tried all the popular answers which did not work. Finally, I understood that Windows had changed the name of the adapter. Virtual Box was configured to use Realtek PCIe GBE Family Controller while device manager had this as Realtek PCIe GBE Family Controller #2. Selecting proper controller fixed the problem.

enter image description here enter image description here

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

How to get first/top row of the table in Sqlite via Sql Query

Use the following query:

SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1

Note: Sqlite's row id references are detailed here.

Get Current Session Value in JavaScript?

try like this

var username= "<%= Session["UserName"]%>";

Python Matplotlib figure title overlaps axes label when using twiny

You can use pad for this case:

ax.set_title("whatever", pad=20)

How to check if a particular service is running on Ubuntu

If you run the following command you will get a list of services:

sudo service --status-all

To get a list of upstart jobs run this command:

sudo initctl list

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Try using anaconda. I had the same error. One lone option was to build tensorflow from source which took long time. I tried using conda and it worked.

  1. Create a new environment in anaconda.
  2. conda -c conda-forge tensorflow

Then, it worked.

How to add shortcut keys for java code in eclipse

I've been Eclipse-free for over a year now, but I believe Eclipse calls these "Templates". Look in your settings for them. You invoke a template by typing its abbreviation and pressing the normal code completion hotkey (ctrl+space by default) or using the Tab key. The standard eclipse shortcut for System.out.println() is "sysout", so "sysout" would do what you want.

Here's another stackoverflow question that has some more details about it: How to use the "sysout" snippet in Eclipse with selected text?

Bash script to run php script

You just need to set :

/usr/bin/php path_to_your_php_file

in your crontab.

Git keeps asking me for my ssh key passphrase

It sounds like you may be having trouble with SSH-Agent itself. I would try troubleshooting that.

1) Did you do ssh-add to add your key to SSH?

2) Are you closing the terminal window between uses, because if you close the window you will have to enter the password again when you reopen it.

If Browser is Internet Explorer: run an alternative script instead

Note that you can also determine in pure js in what browser you script is beeing executed through : window.navigator.userAgent

However, that's not a recommended way as it's configurable in the browser settings. More info available there: https://developer.mozilla.org/fr/docs/DOM/window.navigator.userAgent

Window vs Page vs UserControl for WPF navigation?

We usually use One Main Window for the application and other windows can be used in situations like when you need popups because instead of using popup controls in XAML which are not visible we can use a Window that is visible at design time so that'll be easy to work with

on the other hand we use many pages to navigate from one screen to another like User management screen to Order Screen etc In the main Window we can use Frame control for navigation like below XAML

    <Frame Name="mainWinFrame" NavigationUIVisibility="Hidden"  ButtonBase.Click="mainWinFrame_Click">
    </Frame>

C#

     private void mainWinFrame_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            if (e.OriginalSource is Button)
            {
                Button btn = (Button)e.OriginalSource;

                if ((btn.CommandParameter != null) && (btn.CommandParameter.Equals("Order")))
                {

                    mainWinFrame.Navigate(OrderPage);
                }
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message, "Error");
        }
    }

That's one way of doing it We can also use a Tab Control instead of Fram and Add pages to it using a Dictionary while adding new page check if the control already exists then only navigate otherwise add and navigate. I hope that'll help someone

Open button in new window?

<input type="button" onclick="window.open(); return false;" value="click me" />

http://www.javascript-coder.com/window-popup/javascript-window-open.phtml

Why javascript getTime() is not a function?

That's because your dat1 and dat2 variables are just strings.

You should parse them to get a Date object, for that format I always use the following function:

// parse a date in yyyy-mm-dd format
function parseDate(input) {
  var parts = input.match(/(\d+)/g);
  // new Date(year, month [, date [, hours[, minutes[, seconds[, ms]]]]])
  return new Date(parts[0], parts[1]-1, parts[2]); // months are 0-based
}

I use this function because the Date.parse(string) (or new Date(string)) method is implementation dependent, and the yyyy-MM-dd format will work on modern browser but not on IE, so I prefer doing it manually.

How to set default value for HTML select?

You first need to add values to your select options and for easy targetting give the select itself an id.

Let's make option b the default:

<select id="mySelect">
    <option>a</option>
    <option selected="selected">b</option>
    <option>c</option>
</select>

Now you can change the default selected value with JavaScript like this:

<script>
var temp = "a";
var mySelect = document.getElementById('mySelect');

for(var i, j = 0; i = mySelect.options[j]; j++) {
    if(i.value == temp) {
        mySelect.selectedIndex = j;
        break;
    }
}
</script>

See it in action on codepen.

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

You can just do:

@some_var.class == Hash

or also something like:

@some_var.is_a?(Hash)

It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:

@some_var.is_a?(Object)  # => true

the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.

Adding an onclicklistener to listview (android)

The prestListView.getItemAtPosition(position); returns the UI widget: Text, Icon, ...

Try this instead:

Object o = prestationAdapterEco.getItemAtPosition(position);

or

Object o = arg0.getItemAtPosition(position);

Get the object from the adapter. Not from the list-view.

2. Object o is a prestationEco object. Not a String.

How to add an extra column to a NumPy array

np.concatenate also works

>>> a = np.array([[1,2,3],[2,3,4]])
>>> a
array([[1, 2, 3],
       [2, 3, 4]])
>>> z = np.zeros((2,1))
>>> z
array([[ 0.],
       [ 0.]])
>>> np.concatenate((a, z), axis=1)
array([[ 1.,  2.,  3.,  0.],
       [ 2.,  3.,  4.,  0.]])

Add all files to a commit except a single file?

For a File

git add -u
git reset -- main/dontcheckmein.txt

For a folder

git add -u
git reset -- main/*

jQuery Get Selected Option From Dropdown

Try this for value...

$("select#id_of_select_element option").filter(":selected").val();

or this for text...

$("select#id_of_select_element option").filter(":selected").text();

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

The real reason you want to use NVARCHAR is when you have different languages in the same column, you need to address the columns in T-SQL without decoding, you want to be able to see the data "natively" in SSMS, or you want to standardize on Unicode.

If you treat the database as dumb storage, it is perfectly possible to store wide strings and different (even variable-length) encodings in VARCHAR (for instance UTF-8). The problem comes when you are attempting to encode and decode, especially if the code page is different for different rows. It also means that the SQL Server will not be able to deal with the data easily for purposes of querying within T-SQL on (potentially variably) encoded columns.

Using NVARCHAR avoids all this.

I would recommend NVARCHAR for any column which will have user-entered data in it which is relatively unconstrained.

I would recommend VARCHAR for any column which is a natural key (like a vehicle license plate, SSN, serial number, service tag, order number, airport callsign, etc) which is typically defined and constrained by a standard or legislation or convention. Also VARCHAR for user-entered, and very constrained (like a phone number) or a code (ACTIVE/CLOSED, Y/N, M/F, M/S/D/W, etc). There is absolutely no reason to use NVARCHAR for those.

So for a simple rule:

VARCHAR when guaranteed to be constrained NVARCHAR otherwise

Can a CSV file have a comment?

No, CSV doesn't specify any way of tagging comments - they will just be loaded by programs like Excel as additional cells containing text.

The closest you can manage (with CSV being imported into a specific application such as Excel) is to define a special way of tagging comments that Excel will ignore. For Excel, you can "hide" the comment (to a limited degree) by embedding it into a formula. For example, try importing the following csv file into Excel:

=N("This is a comment and will appear as a simple zero value in excel")
John, Doe, 24

You still end up with a cell in the spreadsheet that displays the number 0, but the comment is hidden.

Alternatively, you can hide the text by simply padding it out with spaces so that it isn't displayed in the visible part of cell:

                              This is a sort-of hidden comment!,
John, Doe, 24

Note that you need to follow the comment text with a comma so that Excel fills the following cell and thus hides any part of the text that doesn't fit in the cell.

Nasty hacks, which will only work with Excel, but they may suffice to make your output look a little bit tidier after importing.

Get dates from a week number in T-SQL

To answer your question:

--CHANGE A WEEK NUMBER BACK INTO A DATE FOR THE FIRST DATE OF THE WEEK
DECLARE @TaskWeek INT = 17
DECLARE @TaskYear INT = 2013

SELECT DATEADD(WEEK, @TaskWeek - 1,DATEADD(dd, 1 - DATEPART(dw, '1/1/' + CONVERT(VARCHAR(4),@TaskYear)), '1/1/' + CONVERT(VARCHAR(4),@TaskYear)))

Error in plot.new() : figure margins too large in R

I have just use the Clear all plots then again give the plot command and it was helpfull

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Init method in Spring Controller (annotation version)

There are several ways to intercept the initialization process in Spring. If you have to initialize all beans and autowire/inject them there are at least two ways that I know of that will ensure this. I have only testet the second one but I belive both work the same.

If you are using @Bean you can reference by initMethod, like this.

@Configuration
public class BeanConfiguration {

  @Bean(initMethod="init")
  public BeanA beanA() {
    return new BeanA();
  }
}

public class BeanA {

  // method to be initialized after context is ready
  public void init() {
  }

} 

If you are using @Component you can annotate with @EventListener like this.

@Component
public class BeanB {

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
  }
}

In my case I have a legacy system where I am now taking use of IoC/DI where Spring Boot is the choosen framework. The old system brings many circular dependencies to the table and I therefore must use setter-dependency a lot. That gave me some headaches since I could not trust @PostConstruct since autowiring/injection by setter was not yet done. The order is constructor, @PostConstruct then autowired setters. I solved it with @EventListener annotation which wil run last and at the "same" time for all beans. The example shows implementation of InitializingBean aswell.

I have two classes (@Component) with dependency to each other. The classes looks the same for the purpose of this example displaying only one of them.

@Component
public class BeanA implements InitializingBean {
  private BeanB beanB;

  public BeanA() {
    log.debug("Created...");
  }

  @PostConstruct
  private void postConstruct() {
    log.debug("@PostConstruct");
  }

  @Autowired
  public void setBeanB(BeanB beanB) {
    log.debug("@Autowired beanB");
    this.beanB = beanB;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    log.debug("afterPropertiesSet()");
  }

  @EventListener
  public void onApplicationEvent(ContextRefreshedEvent event) {
    log.debug("@EventListener");
  } 
}

This is the log output showing the order of the calls when the container starts.

2018-11-30 18:29:30.504 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : Created...
2018-11-30 18:29:30.509 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : Created...
2018-11-30 18:29:30.517 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @Autowired beanA
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : afterPropertiesSet()
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @Autowired beanB
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @PostConstruct
2018-11-30 18:29:30.518 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : afterPropertiesSet()
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanA                   : @EventListener
2018-11-30 18:29:30.607 DEBUG 3624 --- [           main] com.example.demo.BeanB                   : @EventListener

As you can see @EventListener is run last after everything is ready and configured.

PHP checkbox set to check based on database value

Extract the information from the database for the checkbox fields. Next change the above example line to: (this code assumes that you've retrieved the information for the user into an associative array called dbvalue and the DB field names match those on the HTML form)

<input type="checkbox" name="tag_1" id="tag_1" value="yes" <?php echo ($dbvalue['tag_1']==1 ? 'checked' : '');?>>

If you're looking for the code to do everything for you, you've come to the wrong place.

How to refresh an access form

You can repaint and / or requery:

On the close event of form B:

Forms!FormA.Requery

Is this what you mean?

How can I get the executing assembly version?

In MSDN, Assembly.GetExecutingAssembly Method, is remark about method "getexecutingassembly", that for performance reasons, you should call this method only when you do not know at design time what assembly is currently executing.

The recommended way to retrieve an Assembly object that represents the current assembly is to use the Type.Assembly property of a type found in the assembly.

The following example illustrates:

using System;
using System.Reflection;

public class Example
{
    public static void Main()
    {
        Console.WriteLine("The version of the currently executing assembly is: {0}",
                          typeof(Example).Assembly.GetName().Version);
    }
}

/* This example produces output similar to the following:
   The version of the currently executing assembly is: 1.1.0.0

Of course this is very similar to the answer with helper class "public static class CoreAssembly", but, if you know at least one type of executing assembly, it isn't mandatory to create a helper class, and it saves your time.

Check if string contains only whitespace

Check the length of the list given by of split() method.

if len(your_string.split()==0:
     print("yes")

Or Compare output of strip() method with null.

if your_string.strip() == '':
     print("yes")

Select value if condition in SQL Server

Try Case

SELECT   stock.name,
      CASE 
         WHEN stock.quantity <20 THEN 'Buy urgent'
         ELSE 'There is enough'
      END
FROM stock

How to change FontSize By JavaScript?

try this:

var span = document.getElementById("span");
span.style.fontSize = "25px";
span.innerHTML = "String";

How to connect Android app to MySQL database?

Yes you can connect your android app to your PHP to grab results from your database. Use a webservice to connect to your backend script via ASYNC task and http post requests. Check this link for more information Connecting to MySQL

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

Just as an FYI - "best" questions aren't the norm at SO, but I will give you a list of options, just as a service.

OK then. These two are the ones I used:

Komodo Edit

Aptana Studio 3

and then there is always Eclipse.

*UPDATE 20 March 2013 *

Well, Sublime Text 2 is the one to heavily consider. Heavily.

Add key value pair to all objects in array

_.forEach(arrOfObj,(arrVal,arrIn) => {
             arrVal.isAcitve = true;
            }

Objective-C and Swift URL encoding

This is how I am doing this in swift.

extension String {
    func encodeURIComponent() -> String {
        return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
    }

    func decodeURIComponent() -> String {
        return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
    }
}

Java array assignment (multiple values)

for example i tried all above for characters it fails but that worked for me >> reserved a pointer then assign values

char A[];
A = new char[]{'a', 'b', 'a', 'c', 'd', 'd', 'e', 'f', 'q', 'r'};

Redirecting to URL in Flask

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('foo'))

@app.route('/foo')
def foo():
    return 'Hello Foo!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Take a look at the example in the documentation.

Node.js EACCES error when listening on most ports

Remember if you use sudo to bind to port 80 and are using the env variables PORT & NODE_ENV you must reexport those vars as you are now under root profile and not your user profile. So, to get this to work on my Mac i did the following:

sudo su
export NODE_ENV=production
export PORT=80
docpad run

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

How to find a value in an excel column by vba code Cells.Find

I'd prefer to use the .Find method directly on a range object containing the range of cells to be searched. For original poster's code it might look like:

Set cell = ActiveSheet.Columns("B:B").Find( _
    What:=celda, _
    After:=ActiveCell _
    LookIn:=xlFormulas, _
    LookAt:=xlWhole, _
    SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, _
    MatchCase:=False, _
    SearchFormat:=False _
)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I'd prefer to use more variables (and be sure to declare them) and let a lot of optional arguments use their default values:

Dim rng as Range
Dim cell as Range
Dim search as String

Set rng = ActiveSheet.Columns("B:B")
search = "String to Find"
Set cell = rng.Find(What:=search, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=False)

If cell Is Nothing Then
    'do something
Else
    'do something else
End If

I kept LookIn:=, LookAt::=, and MatchCase:= to be explicit about what is being matched. The other optional parameters control the order matches are returned in - I'd only specify those if the order is important to my application.

OSX -bash: composer: command not found

Tested on Mac OSX after installing via instructions on composer website:

sudo mv composer.phar /usr/local/bin/composer

Which HTML elements can receive focus?

The ally.js accessibility library provides an unofficial, test-based list here:

https://allyjs.io/data-tables/focusable.html

(NB: Their page doesn't say how often tests were performed.)

YouTube Video Embedded via iframe Ignoring z-index?

I have the same problem on YouTube iframe embeds only in internet explorer though.

Z-index was being ignored totally, or the flash video was just appearing at highest index possible.

This was what I used, slight adapting the above jquery script.

My embed code, straight from YouTube...

<iframe width="560" height="315" src="http://www.youtube.com/embed/QldZiR9eQ_0?rel=0" frameborder="0" allowfullscreen></iframe>


The jQuery slighty adapted from the above answer...

$('iframe').each( function() {
    var url = $(this).attr("src")
    $(this).attr({
        "src" : url.replace('?rel=0', '')+"?wmode=transparent",
        "wmode" : "Opaque"
    })
});


Basically if you don't select Show suggested videos when the video finishes in your embed settings, you have a ?rel=0 at the end of your "src" url. So I've added the replace bit in case ?rel=0 exists. Otherwise ?wmode=transparent won't work.


Sorting multiple keys with Unix sort

Use the -k option (or --key=POS1[,POS2]). It can appear multiple times and each key can have global options (such as n for numeric sort)

How to add one day to a date?

I prefer joda for date and time arithmetics because it is much better readable:

Date tomorrow = now().plusDays(1).toDate();

Or

endOfDay(now().plus(days(1))).toDate()
startOfDay(now().plus(days(1))).toDate()

How to install OpenSSL for Python

SSL development libraries have to be installed

CentOS:

$ yum install openssl-devel libffi-devel

Ubuntu:

$ apt-get install libssl-dev libffi-dev

OS X (with Homebrew installed):

$ brew install openssl

How do I order my SQLITE database in descending order, for an android app?

Cursor c = myDB.rawQuery("SELECT distinct p_name,p_price FROM products order by Id desc",new String[]{});

this works for me!!!

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

Add day(s) to a Date object

Note : Use it if calculating / adding days from current date.

Be aware: this answer has issues (see comments)

var myDate = new Date();
myDate.setDate(myDate.getDate() + AddDaysHere);

It should be like

var newDate = new Date(date.setTime( date.getTime() + days * 86400000 ));

How can I catch a ctrl-c event?

You have to catch the SIGINT signal (we are talking POSIX right?)

See @Gab Royer´s answer for sigaction.

Example:

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

void my_handler(sig_t s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{
   signal (SIGINT,my_handler);

   while(1);
   return 0;

}

Place a button right aligned

_x000D_
_x000D_
<div style = "display: flex; justify-content:flex-end">
    <button>Click me!</button>
</div>
_x000D_
_x000D_
_x000D_

<div style = "display: flex; justify-content: flex-end">
    <button>Click me!</button>
</div>

How to use ArgumentCaptor for stubbing?

Hypothetically, if search landed you on this question then you probably want this:

doReturn(someReturn).when(someObject).doSomething(argThat(argument -> argument.getName().equals("Bob")));

Why? Because like me you value time and you are not going to implement .equals just for the sake of the single test scenario.

And 99 % of tests fall apart with null returned from Mock and in a reasonable design you would avoid return null at all costs, use Optional or move to Kotlin. This implies that verify does not need to be used that often and ArgumentCaptors are just too tedious to write.

Using global variables in a function

With parallel execution, global variables can cause unexpected results if you don't understand what is happening. Here is an example of using a global variable within multiprocessing. We can clearly see that each process works with its own copy of the variable:

import multiprocessing
import os
import random
import sys
import time

def worker(new_value):
    old_value = get_value()
    set_value(random.randint(1, 99))
    print('pid=[{pid}] '
          'old_value=[{old_value:2}] '
          'new_value=[{new_value:2}] '
          'get_value=[{get_value:2}]'.format(
          pid=str(os.getpid()),
          old_value=old_value,
          new_value=new_value,
          get_value=get_value()))

def get_value():
    global global_variable
    return global_variable

def set_value(new_value):
    global global_variable
    global_variable = new_value

global_variable = -1

print('before set_value(), get_value() = [%s]' % get_value())
set_value(new_value=-2)
print('after  set_value(), get_value() = [%s]' % get_value())

processPool = multiprocessing.Pool(processes=5)
processPool.map(func=worker, iterable=range(15))

Output:

before set_value(), get_value() = [-1]
after  set_value(), get_value() = [-2]
pid=[53970] old_value=[-2] new_value=[ 0] get_value=[23]
pid=[53971] old_value=[-2] new_value=[ 1] get_value=[42]
pid=[53970] old_value=[23] new_value=[ 4] get_value=[50]
pid=[53970] old_value=[50] new_value=[ 6] get_value=[14]
pid=[53971] old_value=[42] new_value=[ 5] get_value=[31]
pid=[53972] old_value=[-2] new_value=[ 2] get_value=[44]
pid=[53973] old_value=[-2] new_value=[ 3] get_value=[94]
pid=[53970] old_value=[14] new_value=[ 7] get_value=[21]
pid=[53971] old_value=[31] new_value=[ 8] get_value=[34]
pid=[53972] old_value=[44] new_value=[ 9] get_value=[59]
pid=[53973] old_value=[94] new_value=[10] get_value=[87]
pid=[53970] old_value=[21] new_value=[11] get_value=[21]
pid=[53971] old_value=[34] new_value=[12] get_value=[82]
pid=[53972] old_value=[59] new_value=[13] get_value=[ 4]
pid=[53973] old_value=[87] new_value=[14] get_value=[70]

AcquireConnection method call to the connection manager <Excel Connection Manager> failed with error code 0xC0202009

Setting RetainSameConnection property to True for Excel manager Worked for me .

Get current user id in ASP.NET Identity 2.0

Just in case you are like me and the Id Field of the User Entity is an Int or something else other than a string,

using Microsoft.AspNet.Identity;

int userId = User.Identity.GetUserId<int>();

will do the trick

What is "stdafx.h" used for in Visual Studio?

All C++ compilers have one serious performance problem to deal with. Compiling C++ code is a long, slow process.

Compiling headers included on top of C++ files is a very long, slow process. Compiling the huge header structures that form part of Windows API and other large API libraries is a very, very long, slow process. To have to do it over, and over, and over for every single Cpp source file is a death knell.

This is not unique to Windows but an old problem faced by all compilers that have to compile against a large API like Windows.

The Microsoft compiler can ameliorate this problem with a simple trick called precompiled headers. The trick is pretty slick: although every CPP file can potentially and legally give a sligthly different meaning to the chain of header files included on top of each Cpp file (by things like having different macros #define'd in advance of the includes, or by including the headers in different order), that is most often not the case. Most of the time, we have dozens or hundreds of included files, but they all are intended to have the same meaning for all the Cpp files being compiled in your application.

The compiler can make huge time savings if it doesn't have to start to compile every Cpp file plus its dozens of includes literally from scratch every time.

The trick consists of designating a special header file as the starting point of all compilation chains, the so called 'precompiled header' file, which is commonly a file named stdafx.h simply for historical reasons.

Simply list all your big huge headers for your APIs in your stdafx.h file, in the appropriate order, and then start each of your CPP files at the very top with an #include "stdafx.h", before any meaningful content (just about the only thing allowed before is comments).

Under those conditions, instead of starting from scratch, the compiler starts compiling from the already saved results of compiling everything in stdafx.h.

I don't believe that this trick is unique to Microsoft compilers, nor do I think it was an original development.

For Microsoft compilers, the setting that controls the use of precompiled headers is controlled by a command line argument to the compiler: /Yu "stdafx.h". As you can imagine, the use of the stdafx.h file name is simply a convention; you can change the name if you so wish.

In Visual Studio 2010, this setting is controlled from the GUI via Right-clicking on a CPP Project, selecting 'Properties' and navigating to "Configuration Properties\C/C++\Precompiled Headers". For other versions of Visual Studio, the location in the GUI will be different.

Note that if you disable precompiled headers (or run your project through a tool that doesn't support them), it doesn't make your program illegal; it simply means that your tool will compile everything from scratch every time.

If you are creating a library with no Windows dependencies, you can easily comment out or remove #includes from the stdafx.h file. There is no need to remove the file per se, but clearly you may do so as well, by disabling the precompile header setting above.

VSCode regex find & replace submatch math?

In my case $1 was not working, but $0 works fine for my purpose.

In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!

Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}

Regex Replace String for Laravel Translation

Error : ORA-01704: string literal too long

To solve this issue on my side, I had to use a combo of what was already proposed there

DECLARE
  chunk1 CLOB; chunk2 CLOB; chunk3 CLOB;
BEGIN
  chunk1 := 'very long literal part 1';
  chunk2 := 'very long literal part 2';
  chunk3 := 'very long literal part 3';

  INSERT INTO table (MY_CLOB)
  SELECT ( chunk1 || chunk2 || chunk3 ) FROM dual;
END;

Hope this helps.

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How to create Gmail filter searching for text only at start of subject line?

The only option I have found to do this is find some exact wording and put that under the "Has the words" option. Its not the best option, but it works.

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Rollback to last git commit

You can revert a commit using git revert HEAD^ for reverting to the next-to-last commit. You can also specify the commit to revert using the id instead of HEAD^

bodyParser is deprecated express 4

It means that using the bodyParser() constructor has been deprecated, as of 2014-06-19.

app.use(bodyParser()); //Now deprecated

You now need to call the methods separately

app.use(bodyParser.urlencoded());

app.use(bodyParser.json());

And so on.

If you're still getting a warning with urlencoded you need to use

app.use(bodyParser.urlencoded({
  extended: true
}));

The extended config object key now needs to be explicitly passed, since it now has no default value.

If you are using Express >= 4.16.0, body parser has been re-added under the methods express.json() and express.urlencoded().

CSS - how to make image container width fixed and height auto stretched

Try width:inherit to make the image take the width of it's container <div>. It will stretch/shrink it's height to maintain proportion. Don't set the height in the <div>, it will size to fit the image height.

img {
    width:inherit;
}

.item {
    border:1px solid pink;
    width: 120px;
    float: left;
    margin: 3px;
    padding: 3px;
}

JSFiddle example

Comparing floating point number to zero

notice, that code is:

std::abs((x - y)/x) <= epsilon

you are requiring that the "relative error" on the var is <= epsilon, not that the absolute difference is

How to use a variable of one method in another method?

You can't. Variables defined inside a method are local to that method.

If you want to share variables between methods, then you'll need to specify them as member variables of the class. Alternatively, you can pass them from one method to another as arguments (this isn't always applicable).


Looks like you're using instance methods instead of static ones.

If you don't want to create an object, you should declare all your methods static, so something like

private static void methodName(Argument args...)

If you want a variable to be accessible by all these methods, you should initialise it outside the methods and to limit its scope, declare it private.

private static int[][] array = new int[3][5];

Global variables are usually looked down upon (especially for situations like your one) because in a large-scale program they can wreak havoc, so making it private will prevent some problems at the least.

Also, I'll say the usual: You should try to keep your code a bit tidy. Use descriptive class, method and variable names and keep your code neat (with proper indentation, linebreaks etc.) and consistent.

Here's a final (shortened) example of what your code should be like:

public class Test3 {
    //Use this array in your methods
    private static int[][] scores = new int[3][5];

    /* Rather than just "Scores" name it so people know what
     * to expect
     */
    private static void createScores() {
        //Code...
    }
    //Other methods...

    /* Since you're now using static methods, you don't 
     * have to initialise an object and call its methods.
     */
    public static void main(String[] args){
        createScores();
        MD();   //Don't know what these do
        sumD(); //so I'll leave them.
    }
}

Ideally, since you're using an array, you would create the array in the main method and pass it as an argument across each method, but explaining how that works is probably a whole new question on its own so I'll leave it at that.

How to get element value in jQuery

<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.



 $('#unOrderedList li').click(function(){
      var value = $(this).attr('value');
     alert(value); 
  });

Your looking for the attribute "value" inside the "li" tag

Use Device Login on Smart TV / Console

They change it again. At this moment documentation does not fit actual situation.

Commonly all works as expected with one small difference. Login from Devices config now moves to Products -> Facebook Login.

So you need to:

  • get your App id from headline,
  • get Client Token from app Settings -> Advanced. There is also Native or desktop app? question/config. I turn it on.
  • Add product (just click on Add product and then Get started on Facebook login. Move back to your app config, click to newly added Facebook login and you'll see your Login from Devices config.

PHP regular expression - filter number only

Using is_numeric or intval is likely the best way to validate a number here, but to answer your question you could try using preg_replace instead. This example removes all non-numeric characters:

$output = preg_replace( '/[^0-9]/', '', $string );

Sorting a Python list by two fields

In ascending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]))

or in descending order you can use:

sorted_data= sorted(non_sorted_data, key=lambda k: (k[1],k[0]),reverse=True)

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

Sorry guys.. actually because of a csrf token was needed I was getting that issue. I have implemented spring security and csrf is enable. And through ajax call I need to pass the csrf token.

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

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

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

SYSTEM ?= generic
ENVIRONMENT ?= generic

in the makefile which gives them default values.

Your output looks to be missing the all important output:

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

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

Not equal <> != operator on NULL

We use

SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';

to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.

Error message "Linter pylint is not installed"

I had this issue this weekend. It seems to have happened because I opened my project in my venv, but I also opened a second instance outside of the venv. I never closed either instance - I just shut my PC down and let Windows do the work. When I went back and called up Visual Studio Code from within my venv, both the project, and the other non-venv window opened. That's when I started seeing this error.

To fix it, I had to remove the \.vscode folder from the workspace directory.

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

Selecting option by text content with jQuery

I know this question is too old, but still, I think this approach would be cleaner:

cat = $.URLDecode(cat);
$('#cbCategory option:contains("' + cat + '")').prop('selected', true);

In this case you wont need to go over the entire options with each(). Although by that time prop() didn't exist so for older versions of jQuery use attr().


UPDATE

You have to be certain when using contains because you can find multiple options, in case of the string inside cat matches a substring of a different option than the one you intend to match.

Then you should use:

cat = $.URLDecode(cat);
$('#cbCategory option')
    .filter(function(index) { return $(this).text() === cat; })
    .prop('selected', true);

How can I make setInterval also work when a tab is inactive in Chrome?

I think that a best understanding about this problem is in this example: http://jsfiddle.net/TAHDb/

I am doing a simple thing here:

Have a interval of 1 sec and each time hide the first span and move it to last, and show the 2nd span.

If you stay on page it works as it is supposed. But if you hide the tab for some seconds, when you get back you will see a weired thing.

Its like all events that didn't ucur during the time you were inactive now will ocur all in 1 time. so for some few seconds you will get like X events. they are so quick that its possible to see all 6 spans at once.

So it seams chrome only delays the events, so when you get back all events will occur but all at once...

A pratical application were this ocur iss for a simple slideshow. Imagine the numbers being Images, and if user stay with tab hidden when he came back he will see all imgs floating, Totally mesed.

To fix this use the stop(true,true) like pimvdb told. THis will clear the event queue.

Create line after text with css

This is the most easy way I found to achieve the result: Just use hr tag before the text, and set the margin top for text. Very short and easy to understand! jsfiddle

_x000D_
_x000D_
h2 {_x000D_
  background-color: #ffffff;_x000D_
  margin-top: -22px;_x000D_
  width: 25%;_x000D_
}_x000D_
_x000D_
hr {_x000D_
  border: 1px solid #e9a216;_x000D_
}
_x000D_
<br>_x000D_
_x000D_
<hr>_x000D_
<h2>ABOUT US</h2>
_x000D_
_x000D_
_x000D_

How to save an image locally using Python whose URL address I already know?

import urllib
resource = urllib.urlopen("http://www.digimouth.com/news/media/2011/09/google-logo.jpg")
output = open("file01.jpg","wb")
output.write(resource.read())
output.close()

file01.jpg will contain your image.

How to get first character of a string in SQL?

LEFT(colName, 1) will also do this, also. It's equivalent to SUBSTRING(colName, 1, 1).

I like LEFT, since I find it a bit cleaner, but really, there's no difference either way.

When and why to 'return false' in JavaScript?

Er ... how about in a boolean function to indicate 'not true'?

How to increase request timeout in IIS?

To Increase request time out add this to web.config

<system.web>
    <httpRuntime executionTimeout="180" />
</system.web>

and for a specific page add this

<location path="somefile.aspx">
    <system.web>
        <httpRuntime executionTimeout="180"/>
    </system.web>
</location>

The default is 90 seconds for .NET 1.x.

The default 110 seconds for .NET 2.0 and later.

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

Select multiple records based on list of Id's with linq

That should be simple. Try this:

var idList = new int[1, 2, 3, 4, 5];
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e));

Java correct way convert/cast object to Double

You can't cast an object to a Double if the object is not a Double.

Check out the API.

particularly note

valueOf(double d);

and

valueOf(String s);

Those methods give you a way of getting a Double instance from a String or double primitive. (Also not the constructors; read the documentation to see how they work) The object you are trying to convert naturally has to give you something that can be transformed into a double.

Finally, keep in mind that Double instances are immutable -- once created you can't change them.

Convert char array to a int number in C

Why not just use atoi? For example:

char myarray[4] = {'-','1','2','3'};

int i = atoi(myarray);

printf("%d\n", i);

Gives me, as expected:

-123

Update: why not - the character array is not null terminated. Doh!

Export and import table dump (.sql) using pgAdmin

An another way, you can do it easily with CMD on Windows

Put your installed version (mine is 11).

cd C:\Program Files\PostgreSQL\11\bin\

and run simple query

psql -U <postgre_username> -d <db_name> < <C:\path\data_dump.sql>

enter password then wait the final console message.

Android getResources().getDrawable() deprecated API 22

You can use

ContextCompat.getDrawable(getApplicationContext(),R.drawable.example);

that's work for me

How to verify static void method has been called with power mockito

Thou the above answer is widely accepted and well documented, I found some of the reason to post my answer here :-

    doNothing().when(InternalUtils.class); //This is the preferred way
                                           //to mock static void methods.
    InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

Here, I dont understand why we are calling InternalUtils.sendEmail ourself. I will explain in my code why we don't need to do that.

mockStatic(Internalutils.class);

So, we have mocked the class which is fine. Now, lets have a look how we need to verify the sendEmail(/..../) method.

@PrepareForTest({InternalService.InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest {

    @Mock
    private InternalService.Order order;

    private InternalService internalService;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
        internalService = new InternalService();
    }

    @Test
    public void processOrder() throws Exception {

        Mockito.when(order.isSuccessful()).thenReturn(true);
        PowerMockito.mockStatic(InternalService.InternalUtils.class);

        internalService.processOrder(order);

        PowerMockito.verifyStatic(times(1));
        InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());
    }

}

These two lines is where the magic is, First line tells the PowerMockito framework that it needs to verify the class it statically mocked. But which method it need to verify ?? Second line tells which method it needs to verify.

PowerMockito.verifyStatic(times(1));
InternalService.InternalUtils.sendEmail(anyString(), any(String[].class), anyString(), anyString());

This is code of my class, sendEmail api twice.

public class InternalService {

    public void processOrder(Order order) {
        if (order.isSuccessful()) {
            InternalUtils.sendEmail("", new String[1], "", "");
            InternalUtils.sendEmail("", new String[1], "", "");
        }
    }

    public static class InternalUtils{

        public static void sendEmail(String from, String[]  to, String msg, String body){

        }

    }

    public class Order{

        public boolean isSuccessful(){
            return true;
        }

    }

}

As it is calling twice you just need to change the verify(times(2))... that's all.

Making an svg image object clickable with onclick, avoiding absolute positioning

In case you're fine with wrapping the svg in another element (a for example) and putting onclick on the wrapper, svg {pointer-events: none;} CSS will do the trick.

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

Is it possible to declare a variable in Gradle usable in Java?

You can create build config field overridable via system environment variables during build:

Fallback is used while developing, but you can override the variable when you run the build on Jenkins or another tool.

In your app build.gradle:

buildTypes {
        def serverUrl =  '\"' + (System.getenv("SERVER_URL")?: "http://default.fallback.url.com")+'\"'
        debug{
            buildConfigField "String", "SERVER_URL", serverUrl
        }
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            buildConfigField "String", "SERVER_URL", serverUrl
        }
    } 

The variable will be available as BuildConfig.SERVER_URL.

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

What is your most productive shortcut with Vim?

Automatic indentation:

gg (go to start of document)
= (indent time!)
shift-g (go to end of document)

You'll need 'filetype plugin indent on' in your .vimrc file, and probably appropriate 'shiftwidth' and 'expandtab' settings.

Difference between \w and \b regular expression meta characters

\b <= this is a word boundary.

Matches at a position that is followed by a word character but not preceded by a word character, or that is preceded by a word character but not followed by a word character.

\w <= stands for "word character". 

It always matches the ASCII characters [A-Za-z0-9_]

Is there anything specific you are trying to match?

Some useful regex websites for beginners or just to wet your appetite.

I found this to be a very useful book:

Java compiler level does not match the version of the installed Java project facet

In Eclipse, right click on your project, go to Maven> Update projetc. Wait and the error will disappear. This is already configured correctly the version of Java for this project.

enter image description here

ASP.NET GridView RowIndex As CommandArgument

I think this will work.

<gridview>
<Columns>

            <asp:ButtonField  ButtonType="Button" CommandName="Edit" Text="Edit" Visible="True" CommandArgument="<%# Container.DataItemIndex %>" />
        </Columns>
</gridview>

What is the difference between Task.Run() and Task.Factory.StartNew()

The Task.Run got introduced in newer .NET framework version and it is recommended.

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task.

The Task.Factory.StartNew has more options, the Task.Run is a shorthand:

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

And by shorthand I mean a technical shortcut:

public static Task Run(Action action)
{
    return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
        TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}

UITableView with fixed section headers

Swift 3.0

Create a ViewController with the UITableViewDelegate and UITableViewDataSource protocols. Then create a tableView inside it, declaring its style to be UITableViewStyle.grouped. This will fix the headers.

lazy var tableView: UITableView = {
    let view = UITableView(frame: UIScreen.main.bounds, style: UITableViewStyle.grouped)
    view.delegate = self
    view.dataSource = self
    view.separatorStyle = .none
    return view
}()

Checking for a null object in C++

You should use NULL only with pointers. Your function accepts a reference and they can't be NULL.

Write your function just like you would write it in C.

Visual Studio: How to show Overloads in IntelliSense?

Tested only on Visual Studio 2010.

Place your cursor within the (), press Ctrl+K, then P.

Now navigate by pressing the  ?  / ?   arrow keys.

Converting Python dict to kwargs?

Use the double-star (aka double-splat?) operator:

func(**{'type':'Event'})

is equivalent to

func(type='Event')

Twitter bootstrap remote modal shows same content every time

Adding an $(this).html(''); to clear visible data as well, and it works pretty fine

subquery in codeigniter active record

I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

$subquery = 'SELECT id_cer FROM revokace';

$this->db->select('*');
$this->db->where_not_in(id, $subquery);
$this->db->from('certs');
$query = $this->db->get();

Open File in Another Directory (Python)

import os
import os.path
import shutil

You find your current directory:

d = os.getcwd() #Gets the current working directory

Then you change one directory up:

os.chdir("..") #Go up one directory from working directory

Then you can get a tupple/list of all the directories, for one directory up:

o = [os.path.join(d,o) for o in os.listdir(d) if os.path.isdir(os.path.join(d,o))] # Gets all directories in the folder as a tuple

Then you can search the tuple for the directory you want and open the file in that directory:

for item in o:
    if os.path.exists(item + '\\testfile.txt'):
    file = item + '\\testfile.txt'

Then you can do stuf with the full file path 'file'

Links in <select> dropdown options

This is an old question, I know but for 2019 peeps:

Like above if you just want to change the URL you can do this:

<select onChange="window.location.href=this.value">
    <option value="www.google.com">A</option>
    <option value="www.aol.com">B</option>
</select>

But if you want it to act like an a tag and so you can do "./page", "#bottom" or "?a=567" use window.location.replace()

<select onChange="window.location.redirect(this.value)">
    <option value="..">back</option>
    <option value="./list">list</option>
    <option value="#bottom">bottom</option>
</select>

Find PHP version on windows command line

Nothing to worry it's easy

If you are using any local server like Wamp, Xampp then Go to this Steps

  1. Go to your drive
  2. Check xampp or wamp server that you installed
  3. Inside that check php, if you got then go for next step
  4. You will find php.exe, Once you get php.exe then you are done. Just type the path like below, here i am using XAMPP and type v for checking version and you are done.

    C:>"C:\xampp\php\php.exe" -v

Thanks.

REST API using POST instead of GET

It is nice that REST brings meaning to HTTP verbs (as they defined) but I prefer to agree with Scott Peal.

Here is also item from WIKI's extended explanation on POST request:

There are times when HTTP GET is less suitable even for data retrieval. An example of this is when a great deal of data would need to be specified in the URL. Browsers and web servers can have limits on the length of the URL that they will handle without truncation or error. Percent-encoding of reserved characters in URLs and query strings can significantly increase their length, and while Apache HTTP Server can handle up to 4,000 characters in a URL,[5] Microsoft Internet Explorer is limited to 2,048 characters in any URL.[6] Equally, HTTP GET should not be used where sensitive information, such as user names and passwords, have to be submitted along with other data for the request to complete. Even if HTTPS is used, preventing the data from being intercepted in transit, the browser history and the web server's logs will likely contain the full URL in plaintext, which may be exposed if either system is hacked. In these cases, HTTP POST should be used.[7]

I could only suggest to REST team to consider more secure use of HTTP protocol to avoid making consumers struggle with non-secure "good practice".

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Linux supports capabilities to support more fine-grained permissions than just "this application is run as root". One of those capabilities is CAP_NET_BIND_SERVICE which is about binding to a privileged port (<1024).

Unfortunately I don't know how to exploit that to run an application as non-root while still giving it CAP_NET_BIND_SERVICE (probably using setcap, but there's bound to be an existing solution for this).

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

Just a few minutes ago i was facing the same problem. I got the problem that is after just placing your jQuery start the other jQuery scripting. After all it will work fine.

Typing the Enter/Return key using Python and Selenium

For Selenium Remote Control with Java:

selenium.keyPress("elementID", "\13");

For Selenium WebDriver (a.k.a. Selenium 2) with Java:

driver.findElement(By.id("elementID")).sendKeys(Keys.ENTER);

Or,

driver.findElement(By.id("elementID")).sendKeys(Keys.RETURN);

Another way to press Enter in WebDriver is by using the Actions class:

Actions action = new Actions(driver);
action.sendKeys(driver.findElement(By.id("elementID")), Keys.ENTER).build().perform();

How to getText on an input in protractor

You can try something like this

var access_token = driver.findElement(webdriver.By.name("AccToken"))

        var access_token_getTextFunction = function() {
            access_token.getText().then(function(value) {
                console.log(value);
                return value;
            });
        }

Than you can call this function where you want to get the value..

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

ping response "Request timed out." vs "Destination Host unreachable"

Destination Host Unreachable

This message indicates one of two problems: either the local system has no route to the desired destination, or a remote router reports that it has no route to the destination.

If the message is simply "Destination Host Unreachable," then there is no route from the local system, and the packets to be sent were never put on the wire.

If the message is "Reply From < IP address >: Destination Host Unreachable," then the routing problem occurred at a remote router, whose address is indicated by the "< IP address >" field.

Request Timed Out

This message indicates that no Echo Reply messages were received within the default time of 1 second. This can be due to many different causes; the most common include network congestion, failure of the ARP request, packet filtering, routing error, or a silent discard.

For more info Refer: http://technet.microsoft.com/en-us/library/cc940095.aspx

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Change the class from factor to numeric of many columns in a data frame

I think that ucfagls found why your loop is not working.

In case you still don't want use a loop here is solution with lapply:

factorToNumeric <- function(f) as.numeric(levels(f))[as.integer(f)] 
cols <- c(1, 3:ncol(stats))
stats[cols] <- lapply(stats[cols], factorToNumeric)

Edit. I found simpler solution. It seems that as.matrix convert to character. So

stats[cols] <- as.numeric(as.matrix(stats[cols]))

should do what you want.

Android BroadcastReceiver within Activity

You need to define the receiver as a class in the manifest and it will receive the intent:

<application
  ....
  <receiver android:name=".ToastReceiver">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

And you don't need to create the class manually inside ToastDisplay.

In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.

AngularJS: Service vs provider vs factory

1.Services are singleton objects that are created when necessary and are never cleaned up until the end of the application life-cycle (when the browser is closed). Controllers are destroyed and cleaned up when they are no longer needed.

2.The easiest way to create a service is by using the factory() method. The factory() method allows us to define a service by returning an object that contains service functions and service data. The service definition function is where we place our injectable services, such as $http and $q. Ex:

angular.module('myApp.services')
.factory('User', function($http) { // injectables go here
var backendUrl = "http://localhost:3000"; var service = {
    // our factory definition
user: {},
setName: function(newName) {
      service.user['name'] = newName;
    },
setEmail: function(newEmail) { service.user['email'] = newEmail;
},
save: function() {
return $http.post(backendUrl + '/users', { user: service.user
}); }
};
return service; });

Using the factory() in our app

It’s easy to use the factory in our application as we can simply inject it where we need it at run-time.

angular.module('myApp')
.controller('MainController', function($scope, User) {
  $scope.saveUser = User.save;
});
  1. The service() method, on the other hand allows us to create a service by defining a constructor function. We can use a prototypical object to define our service, instead of a raw javascript object. Similar to the factory() method, we’ll also set the injectables in the function definition.
  2. The lowest level way to create a service is by using the provide() method. This is the only way to create a service that we can configure using the .config() function. Unlike the previous to methods, we’ll set the injectables in a defined this.$get() function definition.

How do I format my oracle queries so the columns don't wrap?

I use a generic query I call "dump" (why? I don't know) that looks like this:

SET NEWPAGE NONE
SET PAGESIZE 0
SET SPACE 0
SET LINESIZE 16000
SET ECHO OFF
SET FEEDBACK OFF
SET VERIFY OFF
SET HEADING OFF
SET TERMOUT OFF
SET TRIMOUT ON
SET TRIMSPOOL ON
SET COLSEP |

spool &1..txt

@@&1

spool off
exit

I then call SQL*Plus passing the actual SQL script I want to run as an argument:

sqlplus -S user/password@database @dump.sql my_real_query.sql

The result is written to a file

my_real_query.sql.txt

.

How to check if that data already exist in the database during update (Mongoose And Express)

check with one query if email or phoneNumber already exists in DB

let userDB = await UserS.findOne({ $or: [
  { email: payload.email },
  { phoneNumber: payload.phoneNumber }
] })

if (userDB) {
  if (payload.email == userDB.email) {
    throw new BadRequest({ message: 'E-mail already exists' })
  } else if (payload.phoneNumber == userDB.phoneNumber) {
    throw new BadRequest({ message: 'phoneNumber already exists' })
  }
}

What is a callback function?

Call After would be a better name than the stupid name, callback. When or if condition gets met within a function, call another function, the Call After function, the one received as argument.

Rather than hard-code an inner function within a function, one writes a function to accept an already-written Call After function as argument. The Call After might get called based on state changes detected by code in the function receiving the argument.

How do I set session timeout of greater than 30 minutes

If you want to never expire a session use 0 or negative value -1.

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

or mention 1440 it indicates 1440 minutes [24hours * 60 minutes]

<session-config>
  <session-timeout>1440</session-timeout><!-- 24hours -->
</session-config>

Session will be expire after 24hours.

How can I convert a dictionary into a list of tuples?

These are the breaking changes from Python 3.x and Python 2.x

For Python3.x use

dictlist = []
for key, value in dict.items():
    temp = [key,value]
    dictlist.append(temp)

For Python 2.7 use

dictlist = []
for key, value in dict.iteritems():
    temp = [key,value]
    dictlist.append(temp)

How can I find which tables reference a given table in Oracle SQL Developer?

To add this to SQL Developer as an extension do the following:

  1. Save the below code into an xml file (e.g. fk_ref.xml):
<items>
    <item type="editor" node="TableNode" vertical="true">
    <title><![CDATA[FK References]]></title>
    <query>
        <sql>
            <![CDATA[select a.owner,
                            a.table_name,
                            a.constraint_name,
                            a.status
                     from   all_constraints a
                     where  a.constraint_type = 'R'
                            and exists(
                               select 1
                               from   all_constraints
                               where  constraint_name=a.r_constraint_name
                                      and constraint_type in ('P', 'U')
                                      and table_name = :OBJECT_NAME
                                      and owner = :OBJECT_OWNER)
                               order by table_name, constraint_name]]>
        </sql>
    </query>
    </item>
</items>
  1. Add the extension to SQL Developer:

    • Tools > Preferences
    • Database > User Defined Extensions
    • Click "Add Row" button
    • In Type choose "EDITOR", Location is where you saved the xml file above
    • Click "Ok" then restart SQL Developer
  2. Navigate to any table and you should now see an additional tab next to SQL one, labelled FK References, which displays the new FK information.

  3. Reference

WAMP 403 Forbidden message on Windows 7

My solution was to disable encoding for encoded files (these files are green in windows). Ive got these files from MAC computer and it was encrypted by default.

Ive select these files > right click > properities > general tab > andvanced > uncheck encrypt files...

And voila it works.

How to use cURL in Java?

Using standard java libs, I suggest looking at the HttpUrlConnection class http://java.sun.com/javase/6/docs/api/java/net/HttpURLConnection.html

It can handle most of what curl can do with setting up the connection. What you do with the stream is up to you.

Android ImageView setImageResource in code

You can use this code:

// Create an array that matches any country to its id (as String):
String[][] countriesId = new String[NUMBER_OF_COUNTRIES_SUPPORTED][];

// Initialize the array, where the first column will be the country's name (in uppercase) and the second column will be its id (as String):
countriesId[0] = new String[] {"US", String.valueOf(R.drawable.us)};
countriesId[1] = new String[] {"FR", String.valueOf(R.drawable.fr)};
// and so on...

// And after you get the variable "countryCode":
int i;
for(i = 0; i<countriesId.length; i++) {
   if(countriesId[i][0].equals(countryCode))
      break;
}
// Now "i" is the index of the country

img.setImageResource(Integer.parseInt(countriesId[i][1]));

How to use OrderBy with findAll in Spring Data

I try in this example to show you a complete example to personalize your OrderBy sorts

 import java.util.List;
 import org.springframework.data.domain.Page;
 import org.springframework.data.domain.Sort;
 import org.springframework.data.jpa.repository.*;
 import org.springframework.data.repository.query.Param;
 import org.springframework.stereotype.Repository;
 import org.springframework.data.domain.Sort;
 /**
 * Spring Data  repository for the User entity.
 */
 @SuppressWarnings("unused")
 @Repository
 public interface UserRepository extends JpaRepository<User, Long> {
 List <User> findAllWithCustomOrderBy(Sort sort);
 }

you will use this example : A method for build dynamically a object that instance of Sort :

import org.springframework.data.domain.Sort;
public class SampleOrderBySpring{
 Sort dynamicOrderBySort = createSort();
     public static void main( String[] args )
     {
       System.out.println("default sort \"firstName\",\"name\",\"age\",\"size\" ");
       Sort defaultSort = createStaticSort();
       System.out.println(userRepository.findAllWithCustomOrderBy(defaultSort ));


       String[] orderBySortedArray = {"name", "firstName"};
       System.out.println("default sort ,\"name\",\"firstName\" ");
       Sort dynamicSort = createDynamicSort(orderBySortedArray );
       System.out.println(userRepository.findAllWithCustomOrderBy(dynamicSort ));
      }
      public Sort createDynamicSort(String[] arrayOrdre) {
        return  Sort.by(arrayOrdre);
        }

   public Sort createStaticSort() {
        String[] arrayOrdre  ={"firstName","name","age","size");
        return  Sort.by(arrayOrdre);
        }
}

How to get the selected value from RadioButtonList?

Technically speaking the answer is correct, but there is a potential problem remaining. string test = rb.SelectedValue is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.

string test = rb.SelectedValue;  //May work fine
SomeMethod(rb.SelectedValue);

where SomeMethod is expecting a string may not.

Sadly the rb.SelectedValue.ToString(); can save a few unexpected issues.

How to name variables on the fly?

It seems to me that you might be better off with a list rather than using orca1, orca2, etc, ... then it would be orca[1], orca[2], ...

Usually you're making a list of variables differentiated by nothing but a number because that number would be a convenient way to access them later.

orca <- list()
orca[1] <- "Hi"
orca[2] <- 59

Otherwise, assign is just what you want.

what is this value means 1.845E-07 in excel?

1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.

1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.

C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.

You can specify a format string if you don't want to use the e-notation.

Detect if page has finished loading

jQuery(window).load(function () {
    alert('page is loaded');

    setTimeout(function () {
        alert('page is loaded and 1 minute has passed');   
    }, 60000);

});

Or http://jsfiddle.net/tangibleJ/fLLrs/1/

See also http://api.jquery.com/load-event/ for an explanation on the jQuery(window).load.

Update

A detailed explanation on how javascript loading works and the two events DOMContentLoaded and OnLoad can be found on this page.

DOMContentLoaded: When the DOM is ready to be manipulated. jQuery's way of capturing this event is with jQuery(document).ready(function () {});.

OnLoad: When the DOM is ready and all assets - this includes images, iframe, fonts, etc - have been loaded and the spinning wheel / hour class disappear. jQuery's way of capturing this event is the above mentioned jQuery(window).load.

PHP - Check if the page run on Mobile or Desktop browser

I used Robert Lee`s answer and it works great! Just writing down the complete function i'm using:

function isMobileDevice(){
    $aMobileUA = array(
        '/iphone/i' => 'iPhone', 
        '/ipod/i' => 'iPod', 
        '/ipad/i' => 'iPad', 
        '/android/i' => 'Android', 
        '/blackberry/i' => 'BlackBerry', 
        '/webos/i' => 'Mobile'
    );

    //Return true if Mobile User Agent is detected
    foreach($aMobileUA as $sMobileKey => $sMobileOS){
        if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            return true;
        }
    }
    //Otherwise return false..  
    return false;
}

Description for event id from source cannot be found

I got this error after creating an event source under the Application Log from the command line using "EventCreate". This command creates a new key under: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Eventlog\Application

If you look at the Key that's been created (e.g. SourceTest) there will be a string value calledEventMessageFile, which for me was set to %SystemRoot%\System32\EventCreate.exe.

Change this to c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\EventLogMessages.dll

Delete theCustomSource and TypesSupported values.

This should stop the "The description for Event ID...." message.

Get file name from URL

I've come up with this:

String url = "http://www.example.com/some/path/to/a/file.xml";
String file = url.substring(url.lastIndexOf('/')+1, url.lastIndexOf('.'));

Import Python Script Into Another?

I highly recommend the reading of a lecture in SciPy-lectures organization:

https://scipy-lectures.org/intro/language/reusing_code.html

It explains all the commented doubts.

But, new paths can be easily added and avoiding duplication with the following code:

import sys
new_path = 'insert here the new path'

if new_path not in sys.path:
    sys.path.append(new_path)
import funcoes_python #Useful python functions saved in a different script

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

Here is a small hint that I hope might be useful to other poor saps that experienced the same issue as I did.

My Setup: Host: Windows 7 Enterprise - build 7601 SP 1 VM: VMware® Workstation 12 Player 12.1.1 build-3770994 (free) Guest: Fedora release 23

I naively failed to install open-vm-tools-desktop. I say naively because I had no idea such a thing existed, nor do I understand why instructions to install open-vm-tools do not (or at least where I read them, do not) include mentions of this package.

Installing open-vm-tools on its own appears to be nearly useless - the desktop package makes the copy and paste function - probably the single most important function of VMTools - work.

So, there you go. Install open-vm-tools-desktop, and copy-paste should work

tar: add all files and directories in current directory INCLUDING .svn and so on

Actually the problem is with the compression options. The trick is the pipe the tar result to a compressor instead of using the built-in options. Incidentally that can also give you better compression, since you can set extra compresion options.

Minimal tar:

tar --exclude=*.tar* -cf workspace.tar .

Pipe to a compressor of your choice. This example is verbose and uses xz with maximum compression:

tar --exclude=*.tar* -cv . | xz -9v >workspace.tar.xz

Solution was tested on Ubuntu 14.04 and Cygwin on Windows 7. It's a community wiki answer, so feel free to edit if you spot a mistake.

Convert ascii char[] to hexadecimal char[] in C

Use the %02X format parameter:

printf("%02X",word[i]);

More info can be found here: http://www.cplusplus.com/reference/cstdio/printf/

How to merge two PDF files into one in Java?

A quick Google search returned this bug: "Bad file descriptor while saving a document w. imported PDFs".

It looks like you need to keep the PDFs to be merged open, until after you have saved and closed the combined PDF.

Apply .gitignore on an existing repository already tracking large number of files

As specified here You can update the index:

git update-index --assume-unchanged /path/to/file

By doing this, the files will not show up in git status or git diff.

To begin tracking the files again you can run:

git update-index --no-assume-unchanged /path/to/file

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

How to increment a variable on a for loop in jinja template?

You could use loop.index:

{% for i in p %}
  {{ loop.index }}
{% endfor %}

Check the template designer documentation.

In more recent versions, due to scoping rules, the following would not work:

{% set count = 1 %}
{% for i in p %}
  {{ count }}
  {% set count = count + 1 %}
{% endfor %}

Setting "checked" for a checkbox with jQuery

In jQuery,

if($("#checkboxId").is(':checked')){
    alert("Checked");
}

or

if($("#checkboxId").attr('checked')==true){
    alert("Checked");
}

In JavaScript,

if (document.getElementById("checkboxID").checked){
    alert("Checked");
}

Convert hex to binary

Use Built-in format() function and int() function It's simple and easy to understand. It's little bit simplified version of Aaron answer

int()

int(string, base)

format()

format(integer, # of bits)

Example

# w/o 0b prefix
>> format(int("ABC123EFFF", 16), "040b")
1010101111000001001000111110111111111111

# with 0b prefix
>> format(int("ABC123EFFF", 16), "#042b")
0b1010101111000001001000111110111111111111

# w/o 0b prefix + 64bit
>> format(int("ABC123EFFF", 16), "064b")
0000000000000000000000001010101111000001001000111110111111111111

See also this answer

Java check if boolean is null

In Java, null only applies to object references; since boolean is a primitive type, it cannot be assigned null.

It's hard to get context from your example, but I'm guessing that if hideInNav is not in the object returned by getProperties(), the (default value?) you've indicated will be false. I suspect this is the bug that you're seeing, as false is not equal to null, so hideNavigation is getting the empty string?

You might get some better answers with a bit more context to your code sample.

Pointer arithmetic for void pointer in C

You have to cast it to another type of pointer before doing pointer arithmetic.

MySQL delete multiple rows in one query conditions unique to each row

You were very close, you can use this:

DELETE FROM table WHERE (col1,col2) IN ((1,2),(3,4),(5,6))

Please see this fiddle.

How to make bootstrap 3 fluid layout without horizontal scrollbar

If it still actual for someone, my solution was as follows:

.container{
    overflow: hidden;
    overflow-y: auto;
}

Android: checkbox listener

You get the error because you imported wrong package.You should import android.widget.CompoundButton.OnCheckedChangeListener;

So the callback should be :

        box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub

        }
    });

How to find whether a ResultSet is empty or not in Java?

if (rs == null || !rs.first()) {
    //empty
} else {
    //not empty
}

Note that after this method call, if the resultset is not empty, it is at the beginning.