Programs & Examples On #White labelling

0

SVN (Subversion) Problem "File is scheduled for addition, but is missing" - Using Versions

This solved my similar problem. I used it to revert the changes, then I added everything and commited changes in the terminal with

svn add folder_path/*
svn commit -m "message"

Node.js version on the command line? (not the REPL)

You can simply do

node --version

or short form would also do

node -v

If above commands does not work, you have done something wrong in installation, reinstall the node.js and try.

LaTeX: remove blank page after a \part or \chapter

I know it's a bit late, but I just came across this post and wanted to mention that I don't really see way everybody wants to do it in a difficult way... The problem here is just that the book class takes twoside as default, so, as gromgull said, just pass oneside as argument and it's solved.

jQuery autohide element after 5 seconds

This is how you can set the timeout after you click.

$(".selectorOnWhichEventCapture").on('click', function() {
    setTimeout(function(){
        $(".selector").doWhateverYouWantToDo();
    }, 5000);
});

//5000 = 5sec = 5000 milisec

Does Java have something like C#'s ref and out keywords?

Direct answer: No

But you can simulate reference with wrappers.

And do the following:

void changeString( _<String> str ) {
    str.s("def");
}

void testRef() {
     _<String> abc = new _<String>("abc");
     changeString( abc );
     out.println( abc ); // prints def
}

Out

void setString( _<String> ref ) {
    str.s( "def" );
}
void testOut(){
    _<String> abc = _<String>();
    setString( abc );
    out.println(abc); // prints def
}

And basically any other type such as:

_<Integer> one = new <Integer>(1);
addOneTo( one );

out.println( one ); // May print 2

Asp Net Web API 2.1 get client IP address

I think this is the most clear solution, using an extension method:

public static class HttpRequestMessageExtensions
{
    private const string HttpContext = "MS_HttpContext";
    private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

    public static string GetClientIpAddress(this HttpRequestMessage request)
    {
        if (request.Properties.ContainsKey(HttpContext))
        {
            dynamic ctx = request.Properties[HttpContext];
            if (ctx != null)
            {
                return ctx.Request.UserHostAddress;
            }
        }

        if (request.Properties.ContainsKey(RemoteEndpointMessage))
        {
            dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
            if (remoteEndpoint != null)
            {
                return remoteEndpoint.Address;
            }
        }

        return null;
    }
}

So just use it like:

var ipAddress = request.GetClientIpAddress();

We use this in our projects.

Source/Reference: Retrieving the client’s IP address in ASP.NET Web API

Moving up one directory in Python

>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\

HTML: how to force links to open in a new tab, not new window

Simply using "target=_blank" will respect the user/browser preference of whether to use a tab or a new window, which in most cases is "doing the right thing".

If you specify the dimensions of the new window, some browsers will use this as an indicator that a certain size is needed, in which case a new window will always be used. Stack overflow code example Stack Overflow

ImportError: No module named 'bottle' - PyCharm

I am using Ubuntu 16.04. For me it was the incorrect interpretor, which was by default using the virtual interpretor from project.

So, make sure you select the correct one, as the pip install will install the package to system python interpretor.

enter image description here

ngOnInit not being called when Injectable class is Instantiated

I had to call a function once my dataService was initialized, instead, I called it inside the constructor, that worked for me.

Element-wise addition of 2 lists?

Perhaps this is pythonic and slightly useful if you have an unknown number of lists, and without importing anything.

As long as the lists are of the same length, you can use the below function.

Here the *args accepts a variable number of list arguments (but only sums the same number of elements in each).

The * is used again in the returned list to unpack the elements in each of the lists.

def sum_lists(*args):
    return list(map(sum, zip(*args)))

a = [1,2,3]
b = [1,2,3]  

sum_lists(a,b)

Output:

[2, 4, 6]

Or with 3 lists

sum_lists([5,5,5,5,5], [10,10,10,10,10], [4,4,4,4,4])

Output:

[19, 19, 19, 19, 19]

Putty: Getting Server refused our key Error

In my case, I had to disable SELinux on Centos6.6 to get it working :)

Edit /etc/selinux/config and set the following and then reboot the host.

selinux=disabled

BTW...forgot to mention that I had to set the LogLevel=DEBUG3 to identify the issue.

What is the significance of load factor in HashMap?

From the documentation:

The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased

It really depends on your particular requirements, there's no "rule of thumb" for specifying an initial load factor.

How to shuffle an ArrayList

Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.

Change Name of Import in Java, or import two classes with the same name

There is no import aliasing mechanism in Java. You cannot import two classes with the same name and use both of them unqualified.

Import one class and use the fully qualified name for the other one, i.e.

import com.text.Formatter;

private Formatter textFormatter;
private com.json.Formatter jsonFormatter;

Making a Sass mixin with optional arguments

Old question, I know, but I think this is still relevant. Arguably, a clearer way of doing this is to use the unquote() function (which SASS has had since version 3.0.0):

@mixin box-shadow($top, $left, $blur, $color, $inset:"") {
  -webkit-box-shadow: $top $left $blur $color unquote($inset);
  -moz-box-shadow: $top $left $blur $color unquote($inset);
  box-shadow: $top $left $blur $color unquote($inset);
}

This is roughly equivalent to Josh's answer, but I think the explicitly named function is less obfuscated than the string interpolation syntax.

What are the differences between if, else, and else if?

if (condition)
{
  thingsToDo()..
} 
else if (condition2)
{
  thingsToDoInTheSecondCase()..
}
else
{
  thingsToDoInOtherCase()..
}

Capture keyboardinterrupt in Python without try-except

You can prevent printing a stack trace for KeyboardInterrupt, without try: ... except KeyboardInterrupt: pass (the most obvious and propably "best" solution, but you already know it and asked for something else) by replacing sys.excepthook. Something like

def custom_excepthook(type, value, traceback):
    if type is KeyboardInterrupt:
        return # do nothing
    else:
        sys.__excepthook__(type, value, traceback)

How can I display a JavaScript object?

A simple way to show the contents of the object is using console.log as shown below

console.log("Object contents are ", obj);

Please note that I am not using '+' to concatenate the object. If I use '+' than I will only get the string representation if object, something like [Object object].

to_string not declared in scope

There could be different reasons why it doesn't work for you: perhaps you need to qualify the name with std::, or perhaps you do not have C++11 support.

This works, provided you have C++11 support:

#include <string>

int main()
{
  std::string s = std::to_string(42);
}

To enable C++11 support with g++ or clang, you need to pass the option -std=c++0x. You can also use -std=c++11 on the newer versions of those compilers.

How can I give eclipse more memory than 512M?

I've had a lot of problems trying to get Eclipse to accept as much memory as I'd like it to be able to use (between 2 and 4 gigs for example).

Open eclipse.ini in the Eclipse installation directory. You should be able to change the memory sizes after -vmargs up to 1024 without a problem up to some maximum value that's dependent on your system. Here's that section on my Linux box:

-vmargs
-Dosgi.requiredJavaVersion=1.5
-XX:MaxPermSize=512m
-Xms512m
-Xmx1024m

And here's that section on my Windows box:

-vmargs
-Xms256m
-Xmx1024m

But, I've failed at setting it higher than 1024 megs. If anybody knows how to make that work, I'd love to know.

EDIT: 32bit version of juno seems to not accept more than Xmx1024m where the 64 bit version accept 2048.

EDIT: Nick's post contains some great links that explain two different things:

  • The problem is largely dependent on your system and the amount of contiguous free memory available, and
  • By using javaw.exe (on Windows), you may be able to get a larger allocated block of memory.

I have 8 gigs of Ram and can't set -Xmx to more than 1024 megs of ram, even when a minimal amount of programs are loaded and both windows/linux report between 4 and 5 gigs of free ram.

How to use android emulator for testing bluetooth application?

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

You can only use real devices.

Emulator Limitations

The functional limitations of the emulator include:

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

Refer to the documentation

How do I put my website's logo to be the icon image in browser tabs?

This is the favicon and is explained in the link.

e.g. from W3C

  <link rel="icon" 
     type="image/png" 
     href="http://example.com/myicon.png">

Plus, of course the image file in the appropriate place.

Rendering HTML elements to <canvas>

You won't get real HTML rendering to <canvas> per se currently, because canvas context does not have functions to render HTML elements.

There are some emulations:

html2canvas project http://html2canvas.hertzen.com/index.html (basically a HTML renderer attempt built on Javascript + canvas)

HTML to SVG to <canvas> might be possible depending on your use case:

https://github.com/miohtama/Krusovice/blob/master/src/tools/html2svg2canvas.js

Also if you are using Firefox you can hack some extended permissions and then render a DOM window to <canvas>

https://developer.mozilla.org/en-US/docs/HTML/Canvas/Drawing_Graphics_with_Canvas?redirectlocale=en-US&redirectslug=Drawing_Graphics_with_Canvas#Rendering_Web_Content_Into_A_Canvas

Efficient way to determine number of digits in an integer

Yet another code snippet, doing basically the same as Vitali's but employs binary search. Powers array is lazy initialized once per unsigned type instance. Signed type overload takes care of minus sign.

#include <limits>
#include <type_traits>
#include <array>

template <class T> 
size_t NumberOfDecPositions ( T v, typename std::enable_if<std::is_unsigned<T>::value>::type* = 0 )
{
    typedef std::array<T,std::numeric_limits<T>::digits10+1> array_type;
    static array_type powers_of_10;
    if ( powers_of_10.front() == 0 )
    {
        T n = 1;
        for ( T& i: powers_of_10 )
        {
            i = n;
            n *= 10;
        }
    }

    size_t l = 0, r = powers_of_10.size(), p;
    while ( l+1 < r )
    {
        p = (l+r)/2;
        if ( powers_of_10[p] <= v )
            l = p;
        else
            r = p;
    }
    return l + 1;
};

template <class T> 
size_t NumberOfDecPositions ( T v, typename std::enable_if<std::is_signed<T>::value>::type* = 0 )
{
    typedef typename std::make_unsigned<T>::type unsigned_type;
    if ( v < 0 )
        return NumberOfDecPositions ( static_cast<unsigned_type>(-v) ) + 1;
    else
        return NumberOfDecPositions ( static_cast<unsigned_type>(v) );
}

If anybody cares of further optimization, please note that the first element of powers array is never used, and the l appears with +1 2 times.

Jenkins CI: How to trigger builds on SVN commit

There are two ways to go about this:

I recommend the first option initially, due to its ease of implementation. Once you mature in your build processes, switch over to the second.

  1. Poll the repository to see if changes occurred. This might "skip" a commit if two commits come in within the same polling interval. Description of how to do so here, note the fourth screenshot where you configure on the job a "build trigger" based on polling the repository (with a crontab-like configuration).

  2. Configure your repository to have a post-commit hook which notifies Jenkins that a build needs to start. Description of how to do so here, in the section "post-commit hooks"

The SVN Tag feature is not part of the polling, it is part of promoting the current "head" of the source code to a tag, to snapshot a build. This allows you to refer to Jenkins buid #32 as SVN tag /tags/build-32 (or something similar).

m2e lifecycle-mapping not found

m2e 1.7 introduces a new syntax for lifecycle mapping metadata that doesn't cause this warning anymore:

<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
    <execution>

        <!-- This executes the goal in Eclipse on project import.
             Other options like are available, eg ignore.  -->
        <?m2e execute?>

        <phase>generate-sources</phase>
        <goals><goal>add-source</goal></goals>
        <configuration>
            <sources>
                <source>src/bootstrap/java</source>
            </sources>
        </configuration>
    </execution>
</executions>
</plugin>

How does the "final" keyword in Java work? (I can still modify an object.)

Above all are correct. Further if you do not want others to create sub classes from your class, then declare your class as final. Then it becomes the leaf level of your class tree hierarchy that no one can extend it further. It is a good practice to avoid huge hierarchy of classes.

android.widget.Switch - on/off event listener?

Use the following snippet to add a Switch to your layout via XML:

<Switch
     android:id="@+id/on_off_switch"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:textOff="OFF"
     android:textOn="ON"/>

Then in your Activity's onCreate method, get a reference to your Switch and set its OnCheckedChangeListener:

Switch onOffSwitch = (Switch)  findViewById(R.id.on_off_switch); 
onOffSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Log.v("Switch State=", ""+isChecked);
}       

});

C++ floating point to integer type conversions

One thing I want to add. Sometimes, there can be precision loss. You may want to add some epsilon value first before converting. Not sure why that works... but it work.

int someint = (somedouble+epsilon);

How to move from one fragment to another fragment on click of an ImageView in Android?

purple.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        Fragment fragment = new tasks();
        FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.content_frame, fragment);
        fragmentTransaction.addToBackStack(null);
        fragmentTransaction.commit();
    }
});

you write the above code...there we are replacing R.id.content_frame with our fragment. hope this helps you

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

For me it was tls12:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

How to apply an XSLT Stylesheet in C#

I found a possible answer here: http://web.archive.org/web/20130329123237/http://www.csharpfriends.com/Articles/getArticle.aspx?articleID=63

From the article:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslTransform myXslTrans = new XslTransform() ;
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null) ;
myXslTrans.Transform(myXPathDoc,null,myWriter) ;

Edit:

But my trusty compiler says, XslTransform is obsolete: Use XslCompiledTransform instead:

XPathDocument myXPathDoc = new XPathDocument(myXmlFile) ;
XslCompiledTransform myXslTrans = new XslCompiledTransform();
myXslTrans.Load(myStyleSheet);
XmlTextWriter myWriter = new XmlTextWriter("result.html",null);
myXslTrans.Transform(myXPathDoc,null,myWriter);

How to pass Multiple Parameters from ajax call to MVC Controller

function final_submit1() {
    var city = $("#city").val();
    var airport = $("#airport").val();

    var vehicle = $("#vehicle").val();

    if(city && airport){
    $.ajax({
        type:"POST",
        cache:false,
        data:{"city": city,"airport": airport},
        url:'http://airportLimo/ajax-car-list', 
        success: function (html) {
             console.log(html);
          //$('#add').val('data sent');
          //$('#msg').html(html);
           $('#pprice').html("Price: $"+html);
        }
      });

    }  
}

Html: Difference between cell spacing and cell padding

cellspacing and cell padding


Cell padding

is used for formatting purpose which is used to specify the space needed between the edges of the cells and also in the cell contents. The general format of specifying cell padding is as follows:

< table width="100" border="2" cellpadding="5">

The above adds 5 pixels of padding inside each cell .

Cell Spacing:

Cell spacing is one also used f formatting but there is a major difference between cell padding and cell spacing. It is as follows: Cell padding is used to set extra space which is used to separate cell walls from their contents. But in contrast cell spacing is used to set space between cells.

How to send Request payload to REST API in java?

The following code works for me.

//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);

method implementation:

public static String sendPostRequest(String requestUrl, String payload) {
    try {
        URL url = new URL(requestUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
        writer.write(payload);
        writer.close();
        BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        StringBuffer jsonString = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
                jsonString.append(line);
        }
        br.close();
        connection.disconnect();
        return jsonString.toString();
    } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
    }

}

setTimeout in for-loop does not print consecutive values

I had the same problem once this is how I solved it.

Suppose I want 12 delays with an interval of 2 secs

    function animate(i){
         myVar=setTimeout(function(){
            alert(i);
            if(i==12){
              clearTimeout(myVar);
              return;
            }
           animate(i+1)
         },2000)
    }

    var i=1; //i is the start point 1 to 12 that is
    animate(i); //1,2,3,4..12 will be alerted with 2 sec delay

How to replace substrings in windows batch file

Expanding from Andriy M, and yes you can do this from a file, even one with multiple lines

@echo off
setlocal EnableExtensions EnableDelayedExpansion
set "INTEXTFILE=test.txt"
set "OUTTEXTFILE=test_out.txt"
set "SEARCHTEXT=bath"
set "REPLACETEXT=hello"

for /f "delims=" %%A in ('type "%INTEXTFILE%"') do (
    set "string=%%A"
    set "modified=!string:%SEARCHTEXT%=%REPLACETEXT%!"
    echo !modified!>>"%OUTTEXTFILE%"
)

del "%INTEXTFILE%"
rename "%OUTTEXTFILE%" "%INTEXTFILE%"
endlocal

EDIT

Thanks David Nelson, I have updated the script so it doesn't have the hard coded values anymore.

Check if DataRow exists by column name in c#?

You should try

if (row.Table.Columns.Contains("US_OTHERFRIEND"))

I don't believe that row has a columns property itself.

C99 stdint.h header and MS Visual Studio

Boost contains cstdint.hpp header file with the types you are looking for: http://www.boost.org/doc/libs/1_36_0/boost/cstdint.hpp

How can I loop through enum values for display in radio buttons?

Two options:

for (let item in MotifIntervention) {
    if (isNaN(Number(item))) {
        console.log(item);
    }
}

Or

Object.keys(MotifIntervention).filter(key => !isNaN(Number(MotifIntervention[key])));

(code in playground)


Edit

String enums look different than regular ones, for example:

enum MyEnum {
    A = "a",
    B = "b",
    C = "c"
}

Compiles into:

var MyEnum;
(function (MyEnum) {
    MyEnum["A"] = "a";
    MyEnum["B"] = "b";
    MyEnum["C"] = "c";
})(MyEnum || (MyEnum = {}));

Which just gives you this object:

{
    A: "a",
    B: "b",
    C: "c"
}

You can get all the keys (["A", "B", "C"]) like this:

Object.keys(MyEnum);

And the values (["a", "b", "c"]):

Object.keys(MyEnum).map(key => MyEnum[key])

Or using Object.values():

Object.values(MyEnum)

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

Stack, Static, and Heap in C++

It's been said elaborately, just as "the short answer":

  • static variable (class)
    lifetime = program runtime (1)
    visibility = determined by access modifiers (private/protected/public)

  • static variable (global scope)
    lifetime = program runtime (1)
    visibility = the compilation unit it is instantiated in (2)

  • heap variable
    lifetime = defined by you (new to delete)
    visibility = defined by you (whatever you assign the pointer to)

  • stack variable
    visibility = from declaration until scope is exited
    lifetime = from declaration until declaring scope is exited


(1) more exactly: from initialization until deinitialization of the compilation unit (i.e. C / C++ file). Order of initialization of compilation units is not defined by the standard.

(2) Beware: if you instantiate a static variable in a header, each compilation unit gets its own copy.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Had this same error, even though I was only updating one table with one entry, but after restarting mysql, it was resolved.

How to make a select with array contains value clause in psql

Try

SELECT * FROM table WHERE arr @> ARRAY['s']::varchar[]

How to create JSON object using jQuery

Just put your data into an Object like this:

var myObject = new Object();
myObject.name = "John";
myObject.age = 12;
myObject.pets = ["cat", "dog"];

Afterwards stringify it via:

var myString = JSON.stringify(myObject);

You don't need jQuery for this. It's pure JS.

Centering a Twitter Bootstrap button

Since you want to center the button, and not the text, what I've done in the past is add a class, then use that class to center the button:

<button class="btn btn-large btn-primary newclass" type="button">Submit</button>

and the CSS would be:

.btn.newclass {width:25%; display:block; margin: 0 auto;}

The "width" value is up to you, and you can play with that to get the right look.

Steve

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Create two-dimensional arrays and access sub-arrays in Ruby

x.transpose[6][3..8] or x[3..8].map {|r| r [6]} would give what you want.

Example:

a = [ [1,  2,  3,  4,  5],
      [6,  7,  8,  9,  10],
      [11, 12, 13, 14, 15],
      [21, 22, 23, 24, 25]
    ]

#a[1..2][2]  -> [8,13]
puts a.transpose[2][1..2].inspect   # [8,13]
puts a[1..2].map {|r| r[2]}.inspect  # [8,13]

How to delete/truncate tables from Hadoop-Hive?

To Truncate:

hive -e "TRUNCATE TABLE IF EXISTS $tablename"

To Drop:

hive -e "Drop TABLE IF EXISTS $tablename"

using href links inside <option> tag

    <select name="career" id="career" onchange="location = this.value;">
        <option value="resume" selected> All Applications </option>
        <option value="resume&j=14">Seo Expert</option>
        <option value="resume&j=21">Project Manager</option>
        <option value="resume&j=33">Php Developer</option>
    </select>

jQuery.each - Getting li elements inside an ul

First I think you need to fix your lists, as the first node of a <ul> must be a <li> (stackoverflow ref). Once that is setup you can do this:

// note this array has outer scope
var phrases = [];

$('.phrase').each(function(){
        // this is inner scope, in reference to the .phrase element
        var phrase = '';
        $(this).find('li').each(function(){
            // cache jquery var
            var current = $(this);
            // check if our current li has children (sub elements)
            // if it does, skip it
            // ps, you can work with this by seeing if the first child
            // is a UL with blank inside and odd your custom BLANK text
            if(current.children().size() > 0) {return true;}
            // add current text to our current phrase
            phrase += current.text();
        });
        // now that our current phrase is completely build we add it to our outer array
        phrases.push(phrase);
    });
    // note the comma in the alert shows separate phrases
    alert(phrases);

Working jsfiddle.

One thing is if you get the .text() of an upper level li you will get all sub level text with it.

Keeping an array will allow for many multiple phrases to be extracted.


EDIT:

This should work better with an empty UL with no LI:

// outer scope
var phrases = [];

$('.phrase').each(function(){
    // inner scope
    var phrase = '';
    $(this).find('li').each(function(){
        // cache jquery object
        var current = $(this);
        // check for sub levels
        if(current.children().size() > 0) {
            // check is sublevel is just empty UL
            var emptyULtest = current.children().eq(0); 
            if(emptyULtest.is('ul') && $.trim(emptyULtest.text())==""){
                phrase += ' -BLANK- '; //custom blank text
                return true;   
            } else {
             // else it is an actual sublevel with li's
             return true;   
            }
        }
        // if it gets to here it is actual li
        phrase += current.text();
    });
    phrases.push(phrase);
});
// note the comma to separate multiple phrases
alert(phrases);

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I think that's another case of git error messages being misleading. Usually when I've seen that error it's due to ssh problems. Did you add your public ssh key to your github account?

Edit: Also, the xinet.d forum post is referring to running the git-daemon as a service so that people could pull from your system. It's not necessary to run git-daemon to push to github.

Unsigned values in C

In the hexadecimal it can't get a negative value. So it shows it like ffffffff.

The advantage to using the unsigned version (when you know the values contained will be non-negative) is that sometimes the computer will spot errors for you (the program will "crash" when a negative value is assigned to the variable).

JQuery confirm dialog

Have you tried using the official JQueryUI implementation (not jQuery only) : ?

Unzip All Files In A Directory

Just put in some quotes to escape the wildcard:

unzip "*.zip"

Can we define min-margin and max-margin, max-padding and min-padding in css?

Yes, you can!

Or if not those terms exactly, then at least the next best thing. In 2020 this is now very straightforward using the CSS math functions: min(), max(), and clamp().

A min calculation picks the smallest from a comma separated list of values (of any length). This can be used to define a max-padding or max-margin rule:

padding-right: min(50px, 5%);

A max calculation similarly picks the largest from a comma separated list of values (of any length). This can be used to define a min-padding or min-margin rule:

padding-right: max(15px, 5%);

A clamp takes three values; the minimum, preferred, and maximum values, in that order.

padding-right: clamp(15px, 5%, 50px);

MDN specifies that clamp is actually just shorthand for:

max(MINIMUM, min(PREFERRED, MAXIMUM))

Here is a clamp being used to contain a 25vw margin between the values 100px and 200px:

_x000D_
_x000D_
* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
  width: 100vw;
  border: 2px dashed red;
}

.margin {
  width: auto;
  min-width: min-content;
  background-color: lightblue;
  padding: 10px;
  margin-right: clamp(100px, 25vw, 200px);
}
_x000D_
<div class="container">
  <div class="margin">
    The margin-right on this div uses 25vw as its preferred value,
    100px as its minimum, and 200px as its maximum.
  </div>
</div>
_x000D_
_x000D_
_x000D_

The math functions can be used in all sorts of different scenarios, even potentially obscure ones like scaling font-size - they are not just for controlling margin and padding. Check out the full list of use cases at the MDN links at the top of this post.

Here is the caniuse list of browser support. Coverage is generally very good, including almost all modern browsers - with the exception, it appears, of some secondary mobile browsers although have not tested this myself.

EC2 instance has no public DNS

  1. Go to VPC
  2. Select your VPC
  3. Click actions and choose Edit DNS hostnames
  4. Tick Enable for DNS Hostnames
  5. Click save changes

PHP - Get array value with a numeric index

Yes, for scalar values, a combination of implode and array_slice will do:

$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));

Or mix it up with array_values and list (thanks @nikic) so that it works with all types of values:

list($bar) = array_values(array_slice($array, 0, 1));

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

jQuery UI Datepicker - Multiple Date Selections

use this on:

$('body').on('focus',".datumwaehlen", function(){
    $(this).datepicker({
        minDate: -20
    });
});

How to create a DataFrame from a text file in Spark

You will not able to convert it into data frame until you use implicit conversion.

val sqlContext = new SqlContext(new SparkContext())

import sqlContext.implicits._

After this only you can convert this to data frame

case class Test(id:String,filed2:String)

val myFile = sc.textFile("file.txt")

val df= myFile.map( x => x.split(";") ).map( x=> Test(x(0),x(1)) ).toDF()

Does Java have a complete enum for HTTP response codes?

Here's an enum with status codes and their descriptions that (at time of writing) corresponds to the HTTP status code registry.

Note that the registry might get updated, and that sometimes unofficial status codes are used.

public enum HttpStatusCode {

    //1xx: Informational
    CONTINUE(100, "Continue"),
    SWITCHING_PROTOCOLS(101, "Switching Protocols"),
    PROCESSING(102, "Processing"),
    EARLY_HINTS(103, "Early Hints"),

    //2xx: Success
    OK(200, "OK"),
    CREATED(201, "Created"),
    ACCEPTED(202, "Accepted"),
    NON_AUTHORITATIVE_INFORMATION(203, "Non-Authoritative Information"),
    NO_CONTENT(204, "No Content"),
    RESET_CONTENT(205, "Reset Content"),
    PARTIAL_CONTENT(206, "Partial Content"),
    MULTI_STATUS(207, "Multi-Status"),
    ALREADY_REPORTED(208, "Already Reported"),
    IM_USED(226, "IM Used"),

    //3xx: Redirection
    MULTIPLE_CHOICES(300, "Multiple Choice"),
    MOVED_PERMANENTLY(301, "Moved Permanently"),
    FOUND(302, "Found"),
    SEE_OTHER(303, "See Other"),
    NOT_MODIFIED(304, "Not Modified"),
    USE_PROXY(305, "Use Proxy"),
    TEMPORARY_REDIRECT(307, "Temporary Redirect"),
    PERMANENT_REDIRECT(308, "Permanent Redirect"),

    //4xx: Client Error
    BAD_REQUEST(400, "Bad Request"),
    UNAUTHORIZED(401, "Unauthorized"),
    PAYMENT_REQUIRED(402, "Payment Required"),
    FORBIDDEN(403, "Forbidden"),
    NOT_FOUND(404, "Not Found"),
    METHOD_NOT_ALLOWED(405, "Method Not Allowed"),
    NOT_ACCEPTABLE(406, "Not Acceptable"),
    PROXY_AUTHENTICATION_REQUIRED(407, "Proxy Authentication Required"),
    REQUEST_TIMEOUT(408, "Request Timeout"),
    CONFLICT(409, "Conflict"),
    GONE(410, "Gone"),
    LENGTH_REQUIRED(411, "Length Required"),
    PRECONDITION_FAILED(412, "Precondition Failed"),
    REQUEST_TOO_LONG(413, "Payload Too Large"),
    REQUEST_URI_TOO_LONG(414, "URI Too Long"),
    UNSUPPORTED_MEDIA_TYPE(415, "Unsupported Media Type"),
    REQUESTED_RANGE_NOT_SATISFIABLE(416, "Range Not Satisfiable"),
    EXPECTATION_FAILED(417, "Expectation Failed"),
    MISDIRECTED_REQUEST(421, "Misdirected Request"),
    UNPROCESSABLE_ENTITY(422, "Unprocessable Entity"),
    LOCKED(423, "Locked"),
    FAILED_DEPENDENCY(424, "Failed Dependency"),
    TOO_EARLY(425, "Too Early"),
    UPGRADE_REQUIRED(426, "Upgrade Required"),
    PRECONDITION_REQUIRED(428, "Precondition Required"),
    TOO_MANY_REQUESTS(429, "Too Many Requests"),
    REQUEST_HEADER_FIELDS_TOO_LARGE(431, "Request Header Fields Too Large"),
    UNAVAILABLE_FOR_LEGAL_REASONS(451, "Unavailable For Legal Reasons"),

    //5xx: Server Error
    INTERNAL_SERVER_ERROR(500, "Internal Server Error"),
    NOT_IMPLEMENTED(501, "Not Implemented"),
    BAD_GATEWAY(502, "Bad Gateway"),
    SERVICE_UNAVAILABLE(503, "Service Unavailable"),
    GATEWAY_TIMEOUT(504, "Gateway Timeout"),
    HTTP_VERSION_NOT_SUPPORTED(505, "HTTP Version Not Supported"),
    VARIANT_ALSO_NEGOTIATES(506, "Variant Also Negotiates"),
    INSUFFICIENT_STORAGE(507, "Insufficient Storage"),
    LOOP_DETECTED(508, "Loop Detected"),
    NOT_EXTENDED(510, "Not Extended"),
    NETWORK_AUTHENTICATION_REQUIRED(511, "Network Authentication Required");

    private final int value;
    private final String description;

    HttpStatusCode(int value, String description) {
        this.value = value;
        this.description = description;
    }

    public int getValue() {
        return value;
    }

    public String getDescription() {
        return description;
    }

    @Override
    public String toString() {
        return value + " " + description;
    }

    public static HttpStatusCode getByValue(int value) {
        for(HttpStatusCode status : values()) {
            if(status.value == value) return status;
        }
        throw new IllegalArgumentException("Invalid status code: " + value);
    }
}

How do I include a JavaScript script file in Angular and call a function from that script?

Add external js file in index.html.

<script src="./assets/vendors/myjs.js"></script>

Here's myjs.js file :

var myExtObject = (function() {

    return {
      func1: function() {
        alert('function 1 called');
      },
      func2: function() {
        alert('function 2 called');
      }
    }

})(myExtObject||{})


var webGlObject = (function() { 
    return { 
      init: function() { 
        alert('webGlObject initialized');
      } 
    } 
})(webGlObject||{})

Then declare it is in component like below

demo.component.ts

declare var myExtObject: any;
declare var webGlObject: any;

constructor(){
    webGlObject.init();
}

callFunction1() {
    myExtObject.func1();
}

callFunction2() {
    myExtObject.func2();
}

demo.component.html

<div>
    <p>click below buttons for function call</p>
    <button (click)="callFunction1()">Call Function 1</button>
    <button (click)="callFunction2()">Call Function 2</button>
</div>

It's working for me...

"register" keyword in C?

You are messing with the compiler's sophisticated graph-coloring algorithm. This is used for register allocation. Well, mostly. It acts as a hint to the compiler -- that's true. But not ignored in its entirety since you are not allowed to take the address of a register variable (remember the compiler, now on your mercy, will try to act differently). Which in a way is telling you not to use it.

The keyword was used long, long back. When there were only so few registers that could count them all using your index finger.

But, as I said, deprecated doesn't mean you cannot use it.

How to concatenate two strings in SQL Server 2005

I got a easy solution which will select from database table and let you do easily.

SELECT b.FirstName + b.LastName FROM tbl_Users b WHERE b.Id='11'

You can easily add a space there if you try

SELECT b.FirstName +' '+ b.LastName FROM Users b WHERE b.Id='23'

Here you can combine as much as your table have.

MySQL compare DATE string with string from DATETIME field

Use the following:

SELECT * FROM `calendar` WHERE DATE(startTime) = '2010-04-29'

Just for reference I have a 2 million record table, I ran a similar query. Salils answer took 4.48 seconds, the above took 2.25 seconds.

So if the table is BIG I would suggest this rather.

How to make an embedded Youtube video automatically start playing?

Add &autoplay=1 to your syntax, like this

<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/zGPuazETKkI&amp;autoplay=1" frameborder="0" allowfullscreen></iframe>

How do you get centered content using Twitter Bootstrap?

Bootstrap 2.3 has a text-center class.

<p class="text-left">Left aligned text.</p>
<p class="text-center">Center aligned text.</p>
<p class="text-right">Right aligned text.</p>

How to serve an image using nodejs

_x000D_
_x000D_
//This method involves directly integrating HTML Code in the res.write
//first time posting to stack ...pls be kind

const express = require('express');
const app = express();
const https = require('https');

app.get("/",function(res,res){
    res.write("<img src="+image url / src +">");
    res.send();
});

app.listen(3000, function(req, res) {
  console.log("the server is onnnn");
});
_x000D_
_x000D_
_x000D_

how to convert Lower case letters to upper case letters & and upper case letters to lower case letters

public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String satr=scanner.nextLine();
    String newString = "";
    for (int i = 0; i < satr.length(); i++) {
        if (Character.isUpperCase(satr.charAt(i))) {
            newString+=Character.toLowerCase(satr.charAt(i));
        }else newString += Character.toUpperCase(satr.charAt(i));
    }
    System.out.println(newString);
}

What is Unicode, UTF-8, UTF-16?

Unicode is a standard which maps the characters in all languages to a particular numeric value called Code Points. The reason it does this is that it allows different encodings to be possible using the same set of code points.

UTF-8 and UTF-16 are two such encodings. They take code points as input and encodes them using some well-defined formula to produce the encoded string.

Choosing a particular encoding depends upon your requirements. Different encodings have different memory requirements and depending upon the characters that you will be dealing with, you should choose the encoding which uses the least sequences of bytes to encode those characters.

For more in-depth details about Unicode, UTF-8 and UTF-16, you can check out this article,

What every programmer should know about Unicode

Setting the default active profile in Spring-boot

The neat way to do this without changing your source code each time is to use the OS environment variable SPRING_PROFILES_ACTIVE:

export SPRING_PROFILES_ACTIVE=production

how-to-set-active-spring-profiles

How to create a new component in Angular 4 using CLI

Did you update the angular-cli to latest version? or did you try updating node or npm or typescript? this issue comes because of versions like angular/typescript/node. If you are updating the cli, use this link here. https://github.com/angular/angular-cli/wiki/stories-1.0-update

How do I create ColorStateList programmatically?

The first dimension is an array of state sets, the second ist the state set itself. The colors array lists the colors for each matching state set, therefore the length of the colors array has to match the first dimension of the states array (or it will crash when the state is "used"). Here and example:

ColorStateList myColorStateList = new ColorStateList(
                        new int[][]{
                                new int[]{android.R.attr.state_pressed}, //1
                                new int[]{android.R.attr.state_focused}, //2
                                new int[]{android.R.attr.state_focused, android.R.attr.state_pressed} //3
                        },
                        new int[] {
                            Color.RED, //1
                            Color.GREEN, //2
                            Color.BLUE //3
                        }
                    );

hope this helps.

EDIT example: a xml color state list like:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:color="@color/white"/>
    <item android:color="@color/black"/>
</selector>

would look like this

ColorStateList myColorStateList = new ColorStateList(
        new int[][]{
                new int[]{android.R.attr.state_pressed},
                new int[]{}
        },
        new int[] {
                context.getResources().getColor(R.color.white),
                context.getResources().getColor(R.color.black)
        }
);

python NameError: global name '__file__' is not defined

If all you are looking for is to get your current working directory os.getcwd() will give you the same thing as os.path.dirname(__file__) as long as you have not changed the working directory elsewhere in your code. os.getcwd() also works in interactive mode.

So os.path.join(os.path.dirname(__file__)) becomes os.path.join(os.getcwd())

How to set index.html as root file in Nginx?

According to the documentation Checks the existence of files in the specified order and uses the first found file for request processing; the processing is performed in the current context. The path to a file is constructed from the file parameter according to the root and alias directives. It is possible to check directory’s existence by specifying a slash at the end of a name, e.g. “$uri/”. If none of the files were found, an internal redirect to the uri specified in the last parameter is made. Important

an internal redirect to the uri specified in the last parameter is made.

So in last parameter you should add your page or code if first two parameters returns false.

location / {
  try_files $uri $uri/index.html index.html;
}

Why is the Java main method static?

because, a static members are not part of any specific class and that main method, not requires to create its Object, but can still refer to all other classes.

How to get the difference between two arrays in JavaScript?

The selected answer is only half right. You must compare the arrays both ways to get a complete answer.

const ids_exist = [
   '1234',
   '5678',
   'abcd',
]

const ids_new = [
  '1234',
  '5678',
  'efjk',
  '9999',
]

function __uniq_Filter (__array_1, __array_2) {
  const one_not_in_two = __array_1.filter(function (obj) {
    return __array_2.indexOf(obj) == -1
  })
  const two_not_in_one = __array_2.filter(function (obj) {
    return __array_1.indexOf(obj) == -1
  })
  return one_not_in_two.concat(two_not_in_one)
}

let uniq_filter = __uniq_Filter(ids_exist, ids_new)

console.log('uniq_filter', uniq_filter) // => [ 'abcd', 'efjk', '9999' ]

"Use the new keyword if hiding was intended" warning

The parent function needs the virtual keyword, and the child function needs the override keyword in front of the function definition.

How to perform mouseover function in Selenium WebDriver using Java?

This code works perfectly well:

 Actions builder = new Actions(driver);
 WebElement element = driver.findElement(By.linkText("Put your text here"));
 builder.moveToElement(element).build().perform();

After the mouse over, you can then go on to perform the next action you want on the revealed information

What is the standard exception to throw in Java for not supported/implemented operations?

Differentiate between the two cases you named:

Can't get value of input type="file"?

You can read it, but you can't set it. value="123" will be ignored, so it won't have a value until you click on it and pick a file.

Even then, the value will likely be mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

How to add a downloaded .box file to Vagrant?

You can point to the folder where vagrant and copy the box file to same location. Then after you may run as follows

vagrant box add my-box name-of-the-box.box
vagrant init my-box
vagrant up

Just to check status

vagrant status

How do I programmatically determine operating system in Java?

You can use:

System.getProperty("os.name")

P.S. You may find this code useful:

class ShowProperties {
    public static void main(String[] args) {
        System.getProperties().list(System.out);
    }
}

All it does is print out all the properties provided by your Java implementations. It'll give you an idea of what you can find out about your Java environment via properties. :-)

Asynchronously wait for Task<T> to complete with timeout

Here's a extension method version that incorporates cancellation of the timeout when the original task completes as suggested by Andrew Arnott in a comment to his answer.

public static async Task<TResult> TimeoutAfter<TResult>(this Task<TResult> task, TimeSpan timeout) {

    using (var timeoutCancellationTokenSource = new CancellationTokenSource()) {

        var completedTask = await Task.WhenAny(task, Task.Delay(timeout, timeoutCancellationTokenSource.Token));
        if (completedTask == task) {
            timeoutCancellationTokenSource.Cancel();
            return await task;  // Very important in order to propagate exceptions
        } else {
            throw new TimeoutException("The operation has timed out.");
        }
    }
}

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

How to send email via Django?

For Django version 1.7, if above solutions dont work then try the following

in settings.py add

#For email
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'

EMAIL_USE_TLS = True

EMAIL_HOST = 'smtp.gmail.com'

EMAIL_HOST_USER = '[email protected]'

#Must generate specific password for your app in [gmail settings][1]
EMAIL_HOST_PASSWORD = 'app_specific_password'

EMAIL_PORT = 587

#This did the trick
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER

The last line did the trick for django 1.7

Usages of doThrow() doAnswer() doNothing() and doReturn() in mockito

If you are testing a logic class and it is calling some internal void methods the doNothing is perfect.

The developers of this app have not set up this app properly for Facebook Login?

after a lot of tries, I've read in other topics which someone said "delete all your apps and create it again". I did that but, as you can imagine, a new App will create a new Application ID on Facebook's page.

So, even after all the "set public things" it didn't work because the application ID was wrong in my code due to the creation of a new App on Facebook developer page.

So, as AndrewSmiley said above, you should remeber to update that in your app @strings

Batch Extract path and filename from a variable

You can only extract path and filename from (1) a parameter of the BAT itself %1, or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a.


in HELP CALL or HELP FOR you may find more detailed information:

%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file


And then try the following:

Either pass the string to be parsed as a parameter to a CALL

call :setfile ..\Desktop\fs.cfg
echo %file% = %filepath% + %filename%
goto :eof

:setfile
set file=%~f1
set filepath=%~dp1
set filename=%~nx1
goto :eof

or the equivalent, pass the filename as a local FOR variable

for %%a in (..\Desktop\fs.cfg) do (
    set file=%%~fa
    set filepath=%%~dpa
    set filename=%%~nxa
)    
echo %file% = %filepath% + %filename%

How can I enable CORS on Django REST Framework

Below are the working steps without the need for any external modules:

Step 1: Create a module in your app.

E.g, lets assume we have an app called user_registration_app. Explore user_registration_app and create a new file.

Lets call this as custom_cors_middleware.py

Paste the below Class definition:

class CustomCorsMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        # One-time configuration and initialization.

    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.

        response = self.get_response(request)
        response["Access-Control-Allow-Origin"] = "*"
        response["Access-Control-Allow-Headers"] = "*"

        # Code to be executed for each request/response after
        # the view is called.

        return response

Step 2: Register a middleware

In your projects settings.py file, add this line

'user_registration_app.custom_cors_middleware.CustomCorsMiddleware'

E.g:

  MIDDLEWARE = [
        'user_registration_app.custom_cors_middleware.CustomCorsMiddleware', # ADD THIS LINE BEFORE CommonMiddleware
         ...
        'django.middleware.common.CommonMiddleware',

    ]

Remember to replace user_registration_app with the name of your app where you have created your custom_cors_middleware.py module.

You can now verify it will add the required response headers to all the views in the project!

How to copy a huge table data into another table in SQL Server

If your focus is Archiving (DW) and are dealing with VLDB with 100+ partitioned tables and you want to isolate most of these resource intensive work on a non production server (OLTP) here is a suggestion (OLTP -> DW) 1) Use backup / Restore to get the data onto the archive server (so now, on Archive or DW you will have Stage and Target database) 2) Stage database: Use partition switch to move data to corresponding stage table
3) Use SSIS to transfer data from staged database to target database for each staged table on both sides 4) Target database: Use partition switch on target database to move data from stage to base table Hope this helps.

How to get selenium to wait for ajax response?

I had a similar situation, i wanted to wait for ajax requests so that the loading panel would have disappeared, I have inspected the html before and after the requests, found that there is a div for the ajax loading panel, the dix is displayed during the ajax request, and hidden after the request ends. I have created a function to wait for the panel to be displayed, then wait for it to be hidden

public void WaitForModalPanel() { string element_xpath = ".//*[@id='ajaxLoadingModalPanelContainer' and not(contains(@style,'display: none'))]"; WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 2, 0)); wait.Until(ExpectedConditions.ElementIsVisible(By.XPath(element_xpath))); element_xpath = ".//*[@id='ajaxLoadingModalPanelContainer' and contains(@style,'DISPLAY: none')]"; wait.Until(ExpectedConditions.ElementExists(By.XPath(element_xpath))); }

Check this for more details

How to fix java.net.SocketException: Broken pipe?

The issue could be that your deployed files are not updated with the correct RMI methods. Check to see that your RMI interface has updated parameters, or updated data structures that your client does not have. Or that your RMI client has no parameters that differ from what your server version has.

This is just an educated guess. After re-deploying my server application's class files and re-testing, the problem of "Broken pipe" went away.

How to set DateTime to null

It looks like you just want:

eventCustom.DateTimeEnd = string.IsNullOrWhiteSpace(dateTimeEnd)
    ? (DateTime?) null
    : DateTime.Parse(dateTimeEnd);

Note that this will throw an exception if dateTimeEnd isn't a valid date.

An alternative would be:

DateTime validValue;
eventCustom.DateTimeEnd = DateTime.TryParse(dateTimeEnd, out validValue)
    ? validValue
    : (DateTime?) null;

That will now set the result to null if dateTimeEnd isn't valid. Note that TryParse handles null as an input with no problems.

When should I use a table variable vs temporary table in sql server?

writing data in tables declared declare @tb and after joining with other tables, I realized that the response time compared to temporary tables tempdb .. # tb is much higher.

When I join them with @tb the time is much longer to return the result, unlike #tm, the return is almost instantaneous.

I did tests with a 10,000 rows join and join with 5 other tables

How to check for DLL dependency?

NDepend was already mentioned by Jesse (if you analyze .NET code) but let's explain exactly how it can help.

Is there a program/script that can scan an executable for DLL dependencies or execute the program in a "clean" DLL-free environment for testing to prevent these oops situations?

In the NDepend Project Properties panel, you can define what application assemblies to analyze (in green) and NDepend will infer Third-Party assemblies used by application ones (in blue). A list of directories where to search application and third-party assemblies is provided.

NDepend Project Properties Application and Third-Party assemblies

If a third-party assembly is not found in these directories, it will be in error mode. For example, if I remove the .NET Fx directory C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319, I can see that .NET Fx third-party assemblies are not resolved:

NDepend Project Properties Application and Third-Party assemblies not resolved

Disclaimer: I work for NDepend

How to compare timestamp dates with date-only parameter in MySQL?

In case you are using SQL parameters to run the query then this would be helpful

SELECT * FROM table WHERE timestamp between concat(date(?), ' ', '00:00:00') and concat(date(?), ' ', '23:59:59')

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

Using Spring 3 autowire in a standalone Java application

A nice solution would be to do following,

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

/**
 * Returns the Spring managed bean instance of the given class type if it exists.
 * Returns null otherwise.
 * @param beanClass
 * @return
 */
public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {

    // store ApplicationContext reference to access required beans later on
    SpringContext.context = context;
}
}

Then you can use it like:

YourClass yourClass = SpringContext.getBean(YourClass.class);

I found this very nice solution in the following website: https://confluence.jaytaala.com/pages/viewpage.action?pageId=18579463

psycopg2: insert multiple rows with one query

I built a program that inserts multiple lines to a server that was located in another city.

I found out that using this method was about 10 times faster than executemany. In my case tup is a tuple containing about 2000 rows. It took about 10 seconds when using this method:

args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str) 

and 2 minutes when using this method:

cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)

install / uninstall APKs programmatically (PackageManager vs Intents)

If you're using Kotlin, API 14+, and just wish to show uninstall dialog for your app:

startActivity(Intent(Intent.ACTION_UNINSTALL_PACKAGE).apply {
    data = Uri.parse("package:$packageName")
})

You can change packageName to any other package name if you want to prompt the user to uninstall another app on the device

How can I enable auto complete support in Notepad++?

The link provided by Mark no longer works, but you can go to:

Notpad++ 6.6.9

  • Settings -> Preferences -> Auto-Completion -> Enable auto-completion on each input.

I find it very annoying though, since a big autocomplete block is always coming up and I would just like to see autocomplete when I press tab or a key combination. I am fairly new to Notepad++ though. If you know of such a key combination, please feel free to reply. I found this question via Google, so we can always help others.enter image description here

How to use XPath in Python?

libxml2 has a number of advantages:

  1. Compliance to the spec
  2. Active development and a community participation
  3. Speed. This is really a python wrapper around a C implementation.
  4. Ubiquity. The libxml2 library is pervasive and thus well tested.

Downsides include:

  1. Compliance to the spec. It's strict. Things like default namespace handling are easier in other libraries.
  2. Use of native code. This can be a pain depending on your how your application is distributed / deployed. RPMs are available that ease some of this pain.
  3. Manual resource handling. Note in the sample below the calls to freeDoc() and xpathFreeContext(). This is not very Pythonic.

If you are doing simple path selection, stick with ElementTree ( which is included in Python 2.5 ). If you need full spec compliance or raw speed and can cope with the distribution of native code, go with libxml2.

Sample of libxml2 XPath Use


import libxml2

doc = libxml2.parseFile("tst.xml")
ctxt = doc.xpathNewContext()
res = ctxt.xpathEval("//*")
if len(res) != 2:
    print "xpath query: wrong node set size"
    sys.exit(1)
if res[0].name != "doc" or res[1].name != "foo":
    print "xpath query: wrong node set value"
    sys.exit(1)
doc.freeDoc()
ctxt.xpathFreeContext()

Sample of ElementTree XPath Use


from elementtree.ElementTree import ElementTree
mydoc = ElementTree(file='tst.xml')
for e in mydoc.findall('/foo/bar'):
    print e.get('title').text

Adjust UILabel height to text

Swift 4.0

Instead of calculating the text/label height, I just resize the label after inserting the (dynamic) text.

Assuming that myLabel is the UILabel in question:

let myLabel = UILabel(frame: CGRect(x: 0, y: 0, width: *somewidth*, height: *placeholder, e.g. 20*))
myLabel.numberOfLines = 0
myLabel.lineBreakMode = .byWordWrapping
...

And now comes the fun part:

var myLabelText: String = "" {
   didSet {
      myLabel.text = myLabelText
      myLabel.sizeToFit()
   }
}

How do I count occurrence of duplicate items in array

I actually wrote a function recently that would check for a substring within an array that will come in handy in this situation.

function strInArray($haystack, $needle) {
    $i = 0;
    foreach ($haystack as $value) {
        $result = stripos($value,$needle);
        if ($result !== FALSE) return TRUE;
        $i++;
    }
    return FALSE;
}

$array = array(12,43,66,21,56,43,43,78,78,100,43,43,43,21);

for ($i = 0; $i < count($array); $i++) {
    if (strInArray($array,$array[$i])) {
        unset($array[$i]);
    }
}
var_dump($array);

How to set time delay in javascript

I'll give my input because it helps me understand what im doing.

To make an auto scrolling slide show that has a 3 second wait I did the following:

var isPlaying = true;

function autoPlay(playing){
   var delayTime = 3000;
   var timeIncrement = 3000;

   if(playing){
        for(var i=0; i<6; i++){//I have 6 images
            setTimeout(nextImage, delayTime);
            delayTime += timeIncrement;
        }
        isPlaying = false;

   }else{
       alert("auto play off");
   }
}

autoPlay(isPlaying);

Remember that when executing setTimeout() like this; it will execute all time out functions as if they where executed at the same time assuming that in setTimeout(nextImage, delayTime);delay time is a static 3000 milliseconds.

What I did to account for this was add an extra 3000 milli/s after each for loop incrementation via delayTime += timeIncrement;.

For those who care here is what my nextImage() looks like:

function nextImage(){
    if(currentImg === 1){//change to img 2
        for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[1].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[1];
        imgDescription.innerHTML = imgDescText[1];

        currentImg = 2;
    }
    else if(currentImg === 2){//change to img 3
        for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[2].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[2];
        imgDescription.innerHTML = imgDescText[2];

        currentImg = 3;
    }
    else if(currentImg === 3){//change to img 4
        for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[3].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[3];
        imgDescription.innerHTML = imgDescText[3];

        currentImg = 4;
    }
    else if(currentImg === 4){//change to img 5
        for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[4].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[4];
        imgDescription.innerHTML = imgDescText[4];

        currentImg = 5;
    }
    else if(currentImg === 5){//change to img 6
    for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[5].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[5];
        imgDescription.innerHTML = imgDescText[5];

        currentImg = 6;
    }
    else if(currentImg === 6){//change to img 1
        for(var i=0; i<6; i++){
            images[i].style.zIndex = "0";
        }
        images[0].style.zIndex = "1";
        imgNumber.innerHTML = imageNumber_Text[0];
        imgDescription.innerHTML = imgDescText[0];

        currentImg = 1;
    }
}

What is the difference between HTML tags <div> and <span>?

In HTML there are tags that add structure or semantics to content. For example the <p> tag is used to identify a paragraph. Another example is the <ol> tag for an ordered list.

When there is no suitable tag available in HTML as shown above, the <div> and <span> tags are usually resorted to.

The <div> tag is used to identify a blocklevel section/division of a document that has a line break both before and after it.

Examples of where div tags can be used are headers, footers, navigations etc. However in HTML 5 these tags have already been provided.

The <span> tag is used to identify an inline section/division of a document.

For example a span tag can be used to add inline pictographs to an element.

What is the purpose of Android's <merge> tag in XML layouts?

The include tag

The <include> tag lets you to divide your layout into multiple files: it helps dealing with complex or overlong user interface.

Let's suppose you split your complex layout using two include files as follows:

top_level_activity.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <include layout="@layout/include1.xml" />

    <!-- Second include file -->
    <include layout="@layout/include2.xml" />

</LinearLayout>

Then you need to write include1.xml and include2.xml.

Keep in mind that the xml from the include files is simply dumped in your top_level_activity layout at rendering time (pretty much like the #INCLUDE macro for C).

The include files are plain jane layout xml.

include1.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView1"
    android:text="First include"
    android:textAppearance="?android:attr/textAppearanceMedium"/>

... and include2.xml:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/button1"
    android:text="Button" />

See? Nothing fancy. Note that you still have to declare the android namespace with xmlns:android="http://schemas.android.com/apk/res/android.

So the rendered version of top_level_activity.xml is:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <TextView
        android:id="@+id/textView1"
        android:text="First include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />


</LinearLayout>

In your java code, all this is transparent: findViewById(R.id.textView1) in your activity class returns the correct widget ( even if that widget was declared in a xml file different from the activity layout).

And the cherry on top: the visual editor handles the thing swimmingly. The top level layout is rendered with the xml included.

The plot thickens

As an include file is a classic layout xml file, it means that it must have one top element. So in case your file needs to include more than one widget, you would have to use a layout.

Let's say that include1.xml has now two TextView: a layout has to be declared. Let's choose a LinearLayout.

include1.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout2" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</LinearLayout>

The top_level_activity.xml will be rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file -->
    <LinearLayout 
        android:id="@+id/layout2" 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

       <TextView
            android:id="@+id/textView1"
            android:text="Second include"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

       <TextView
            android:id="@+id/textView2"
            android:text="More text"
            android:textAppearance="?android:attr/textAppearanceMedium"/>

   </LinearLayout>

     <!-- Second include file -->
   <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

But wait the two levels of LinearLayout are redundant!

Indeed, the two nested LinearLayout serve no purpose as the two TextView could be included under layout1for exactly the same rendering.

So what can we do?

Enter the merge tag

The <merge> tag is just a dummy tag that provides a top level element to deal with this kind of redundancy issues.

Now include1.xml becomes:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

</merge>

and now top_level_activity.xml is rendered as:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout1" 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <!-- First include file --> 
    <TextView
        android:id="@+id/textView1"
        android:text="Second include"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <TextView
        android:id="@+id/textView2"
        android:text="More text"
        android:textAppearance="?android:attr/textAppearanceMedium"/>

    <!-- Second include file -->
    <Button
        android:id="@+id/button1"
        android:text="Button" />

</LinearLayout>

You saved one hierarchy level, avoid one useless view: Romain Guy sleeps better already.

Aren't you happier now?

Responsive web design is working on desktop but not on mobile device

I have also faced this problem. Finally I got a solution. Use this bellow code. Hope: problem will be solve.

<meta name="viewport" content="initial-scale=1, maximum-scale=1">

How do I set the value property in AngularJS' ng-options?

The correct answer to this question has been provided by user frm.adiputra, as currently this seems to be the only way to explicitly control the value attribute of the option elements.

However, I just wanted to emphasize that "select" is not a keyword in this context, but it is just a placeholder for an expression. Please refer to the following list, for the definition of the "select" expression as well as other expressions that can be used in ng-options directive.

The use of select as it is depicted in the question:

ng-options='select p.text for p  in resultOptions'

is essentially wrong.

Based on the list of expressions, it seems that trackexpr may be used to specify the value, when options are given in an array of objects, but it has been used with grouping only.


From AngularJS' documentation for ng-options:

  • array / object: an expression which evaluates to an array / object to iterate over.
  • value: local variable which will refer to each item in the array or each property value of object during iteration.
  • key: local variable which will refer to a property name in object during iteration.
  • label: The result of this expression will be the label for element. The expression will most likely refer to the value variable (e.g. value.propertyName).
  • select: The result of this expression will be bound to the model of the parent element. If not specified, select expression will default to value.
  • group: The result of this expression will be used to group options using the DOM element.
  • trackexpr: Used when working with an array of objects. The result of this expression will be used to identify the objects in the array. The trackexpr will most likely refer to the value variable (e.g. value.propertyName).

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

It is because you use a relative path.

The easy way to fix this is by using the __DIR__ magic constant, like:

require_once(__DIR__."/initcontrols/config.php");

From the PHP doc:

The directory of the file. If used inside an include, the directory of the included file is returned

Send auto email programmatically

Sending email programmatically with Kotlin.

  • simple email sending, not all the other features (like attachments).
  • TLS is always on
  • Only 1 gradle email dependency needed also.

I also found this list of email POP services really helpful:

https://support.office.com/en-gb/article/pop-and-imap-email-settings-for-outlook-8361e398-8af4-4e97-b147-6c6c4ac95353

How to use:

    val auth = EmailService.UserPassAuthenticator("yourUser", "yourPass")
    val to = listOf(InternetAddress("[email protected]"))
    val from = InternetAddress("[email protected]")
    val email = EmailService.Email(auth, to, from, "Test Subject", "Hello Body World")
    val emailService = EmailService("yourSmtpServer", 587)

    GlobalScope.launch { // or however you do background threads
        emailService.send(email)
    }

The code:

import java.util.*
import javax.mail.*
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart

class EmailService(private var server: String, private var port: Int) {

    data class Email(
        val auth: Authenticator,
        val toList: List<InternetAddress>,
        val from: Address,
        val subject: String,
        val body: String
    )

    class UserPassAuthenticator(private val username: String, private val password: String) : Authenticator() {
        override fun getPasswordAuthentication(): PasswordAuthentication {
            return PasswordAuthentication(username, password)
        }
    }

    fun send(email: Email) {
        val props = Properties()
        props["mail.smtp.auth"] = "true"
        props["mail.user"] = email.from
        props["mail.smtp.host"] = server
        props["mail.smtp.port"] = port
        props["mail.smtp.starttls.enable"] = "true"
        props["mail.smtp.ssl.trust"] = server
        props["mail.mime.charset"] = "UTF-8"
        val msg: Message = MimeMessage(Session.getDefaultInstance(props, email.auth))
        msg.setFrom(email.from)
        msg.sentDate = Calendar.getInstance().time
        msg.setRecipients(Message.RecipientType.TO, email.toList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.CC, email.ccList.toTypedArray())
//      msg.setRecipients(Message.RecipientType.BCC, email.bccList.toTypedArray())
        msg.replyTo = arrayOf(email.from)

        msg.addHeader("X-Mailer", CLIENT_NAME)
        msg.addHeader("Precedence", "bulk")
        msg.subject = email.subject

        msg.setContent(MimeMultipart().apply {
            addBodyPart(MimeBodyPart().apply {
                setText(email.body, "iso-8859-1")
                //setContent(email.htmlBody, "text/html; charset=UTF-8")
            })
        })
        Transport.send(msg)
    }

    companion object {
        const val CLIENT_NAME = "Android StackOverflow programmatic email"
    }
}

Gradle:

dependencies {
    implementation 'com.sun.mail:android-mail:1.6.4'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.3"
}

AndroidManifest:

<uses-permission name="android.permission.INTERNET" />

how to check if the input is a number or not in C?

Using fairly simple code:

int i;
int value;
int n;
char ch;

/* Skip i==0 because that will be the program name */
for (i=1; i<argc; i++) {
    n = sscanf(argv[i], "%d%c", &value, &ch);

    if (n != 1) {
        /* sscanf didn't find a number to convert, so it wasn't a number */
    }
    else {
        /* It was */
    }
}

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

How do I read the first line of a file using cat?

Use the below command to get the first row from a CSV file or any file formats.

head -1 FileName.csv

How to scroll HTML page to given anchor?

In 2018, you don't need jQuery for something simple like this. The built in scrollIntoView() method supports a "behavior" property to smoothly scroll to any element on the page. You can even update the browser URL with a hash to make it bookmarkable.

From this tutorial on scrolling HTML Bookmarks, here is a native way to add smooth scrolling to all anchor links on your page automatically:

let anchorlinks = document.querySelectorAll('a[href^="#"]')
 
for (let item of anchorlinks) { // relitere 
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

(The following is a very artificial example cooked up to illustrate.) One major use of packed structs is where you have a stream of data (say 256 bytes) to which you wish to supply meaning. If I take a smaller example, suppose I have a program running on my Arduino which sends via serial a packet of 16 bytes which have the following meaning:

0: message type (1 byte)
1: target address, MSB
2: target address, LSB
3: data (chars)
...
F: checksum (1 byte)

Then I can declare something like

typedef struct {
  uint8_t msgType;
  uint16_t targetAddr; // may have to bswap
  uint8_t data[12];
  uint8_t checksum;
} __attribute__((packed)) myStruct;

and then I can refer to the targetAddr bytes via aStruct.targetAddr rather than fiddling with pointer arithmetic.

Now with alignment stuff happening, taking a void* pointer in memory to the received data and casting it to a myStruct* will not work unless the compiler treats the struct as packed (that is, it stores data in the order specified and uses exactly 16 bytes for this example). There are performance penalties for unaligned reads, so using packed structs for data your program is actively working with is not necessarily a good idea. But when your program is supplied with a list of bytes, packed structs make it easier to write programs which access the contents.

Otherwise you end up using C++ and writing a class with accessor methods and stuff that does pointer arithmetic behind the scenes. In short, packed structs are for dealing efficiently with packed data, and packed data may be what your program is given to work with. For the most part, you code should read values out of the structure, work with them, and write them back when done. All else should be done outside the packed structure. Part of the problem is the low level stuff that C tries to hide from the programmer, and the hoop jumping that is needed if such things really do matter to the programmer. (You almost need a different 'data layout' construct in the language so that you can say 'this thing is 48 bytes long, foo refers to the data 13 bytes in, and should be interpreted thus'; and a separate structured data construct, where you say 'I want a structure containing two ints, called alice and bob, and a float called carol, and I don't care how you implement it' -- in C both these use cases are shoehorned into the struct construct.)

Insert line break in wrapped cell via code

You could also use vbCrLf which corresponds to Chr(13) & Chr(10).

When does a cookie with expiration time 'At end of session' expire?

When you use setcookie, you can either set the expiration time to 0 or simply omit the parametre - the cookie will then expire at the end of session (ie, when you close the browser).

Execute Shell Script after post build in Jenkins

You should be able to do that with the Batch Task plugin.

  1. Create a batch task in the project.
  2. Add a "Invoke batch tasks" post-build option selecting the same project.

An alternative can also be Post build task plugin.

Android TabLayout Android Design

So easy way :

XML:

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"/>
<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Java code:

private ViewPager viewPager;

private String[] PAGE_TITLES = new String[]{
        "text1",
        "text1",
        "text3"
};
private final Fragment[] PAGES = new Fragment[]{
        new fragment1(), 
        new fragment2(),
        new fragment3()

};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_a_requests);

    /**TODO ***************tebLayout*************************/
    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    TabLayout tabLayout = findViewById(R.id.tab_layout);
    tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
    tabLayout.setSelectedTabIndicatorHeight((int) (4 * 
    getResources().getDisplayMetrics().density));
    tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"), 
    Color.parseColor("#0d0e10"));
    tabLayout.setupWithViewPager(viewPager);
    /***************************************************************************/
    }

jQuery - Increase the value of a counter when a button is clicked

You are trying to set "++" on a jQuery element!

YOu could declare a js variable

var counter = 0;

and in jQuery code do:

$("#counter").html(counter++);

ImportError: No module named enum

Or run a pip install --upgrade pip enum34

How do I get current URL in Selenium Webdriver 2 Python?

Use current_url element for Python 2:

print browser.current_url

For Python 3 and later versions of selenium:

print(driver.current_url)

Escape a string for a sed replace pattern

An easier way to do this is simply building the string before hand and using it as a parameter for sed

rpstring="s/KEYWORD/$REPLACE/g"
sed -i $rpstring  test.txt

How to copy directory recursively in python and overwrite all?

Have a look at the shutil package, especially rmtree and copytree. You can check if a file / path exists with os.paths.exists(<path>).

import shutil
import os

def copy_and_overwrite(from_path, to_path):
    if os.path.exists(to_path):
        shutil.rmtree(to_path)
    shutil.copytree(from_path, to_path)

Vincent was right about copytree not working, if dirs already exist. So distutils is the nicer version. Below is a fixed version of shutil.copytree. It's basically copied 1-1, except the first os.makedirs() put behind an if-else-construct:

import os
from shutil import *
def copytree(src, dst, symlinks=False, ignore=None):
    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.isdir(dst): # This one line does the trick
        os.makedirs(dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                copytree(srcname, dstname, symlinks, ignore)
            else:
                # Will raise a SpecialFileError for unsupported file types
                copy2(srcname, dstname)
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except Error, err:
            errors.extend(err.args[0])
        except EnvironmentError, why:
            errors.append((srcname, dstname, str(why)))
    try:
        copystat(src, dst)
    except OSError, why:
        if WindowsError is not None and isinstance(why, WindowsError):
            # Copying file access times may fail on Windows
            pass
        else:
            errors.extend((src, dst, str(why)))
    if errors:
        raise Error, errors

How does numpy.newaxis work and when to use it?

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

Here is a visual illustration which depicts promotion of 1D array to 2D arrays.

newaxis canva visualization


Scenario-1: np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.

Example:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)

Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.

Example:

Let's say you want to add the following two arrays:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError :

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that NumPy can broadcast.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])

Now, add:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])

Alternatively, you can also add new axis to the array x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])

Now, add:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).


Scenario-3: This is similar to scenario-1. But, you can use np.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

Example:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)

More background on np.newaxis vs np.reshape

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

Example

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)

In the above example, we inserted a temporary axis between the first and second axes of B (to use broadcasting). A missing axis is filled-in here using np.newaxis to make the broadcasting operation work.


General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

Unit testing click event in Angular

My objective is to check if the 'onEditButtonClick' is getting invoked when the user clicks the edit button and not checking just the console.log being printed.

You will need to first set up the test using the Angular TestBed. This way you can actually grab the button and click it. What you will do is configure a module, just like you would an @NgModule, just for the testing environment

import { TestBed, async, ComponentFixture } from '@angular/core/testing';

describe('', () => {
  let fixture: ComponentFixture<TestComponent>;
  let component: TestComponent;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [ ],
      declarations: [ TestComponent ],
      providers: [  ]
    }).compileComponents().then(() => {
      fixture = TestBed.createComponent(TestComponent);
      component = fixture.componentInstance;
    });
  }));
});

Then you need to spy on the onEditButtonClick method, click the button, and check that the method was called

it('should', async(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();

  fixture.whenStable().then(() => {
    expect(component.onEditButtonClick).toHaveBeenCalled();
  });
}));

Here we need to run an async test as the button click contains asynchronous event handling, and need to wait for the event to process by calling fixture.whenStable()

Update

It is now preferred to use fakeAsync/tick combo as opposed to the async/whenStable combo. The latter should be used if there is an XHR call made, as fakeAsync does not support it. So instead of the above code, refactored, it would look like

it('should', fakeAsync(() => {
  spyOn(component, 'onEditButtonClick');

  let button = fixture.debugElement.nativeElement.querySelector('button');
  button.click();
  tick();
  expect(component.onEditButtonClick).toHaveBeenCalled();

}));

Don't forget to import fakeAsync and tick.

See also:

Bootstrap dropdown not working

I had a similar issue only to observe that i had added the bootstrap script twice and the second bootstrap script was after above the jquery script.

Solution:

  • Ensure that bootstrap.min.js and jquery.min.js are only included once in your file.
  • The bootstrap.min.js script should be included after jquery.min.js

How can I slice an ArrayList out of an ArrayList in Java?

If there is no existing method then I guess you can iterate from 0 to input.size()/2, taking each consecutive element and appending it to a new ArrayList.

EDIT: Actually, I think you can take that List and use it to instantiate a new ArrayList using one of the ArrayList constructors.

Keep the order of the JSON keys during JSON conversion to CSV

Apache Wink has OrderedJSONObject. It keeps the order while parsing the String.

How to create id with AUTO_INCREMENT on Oracle?

Maybe just try this simple script:

http://www.hlavaj.sk/ai.php

Result is:

CREATE SEQUENCE TABLE_PK_SEQ; 
CREATE OR REPLACE TRIGGER TR_SEQ_TABLE BEFORE INSERT ON TABLE FOR EACH ROW 

BEGIN
SELECT TABLE_PK_SEQ.NEXTVAL
INTO :new.PK
FROM dual;
END;

How does data binding work in AngularJS?

AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

$watch() :-

This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

$digest() -

This function iterates through all the watches in the $scope object, and its child $scope objects
(if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

$apply() -

Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

How can I parse JSON with C#?

 using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(user)))
 {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UserListing))
    DataContractJsonSerializer(typeof(UserListing));
    UserListing response = (UserListing)deserializer.ReadObject(ms);

 }

 public class UserListing
 {
    public List<UserList> users { get; set; }      
 }

 public class UserList
 {
    public string FirstName { get; set; }       
    public string LastName { get; set; } 
 }

adding onclick event to dynamically added button?

but.onclick = function() { yourjavascriptfunction();};

or

but.onclick = function() { functionwithparam(param);};

Responsive Images with CSS

Use max-width:100%;, height: auto; and display:block; as follow:

image {
    max-width:100%;
    height: auto;
    display:block;
}

How to select specific columns in laravel eloquent

You first need to create a Model, that represent that Table and then use the below Eloquent way to fetch the data of only 2 fields.

Model::where('id', 1)
         ->pluck('name', 'surname')
         ->all();

How to run a Runnable thread in Android at defined intervals?

Kotlin

private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
    val handler = Handler()
    runnable = Runnable {
        // do your work
        handler.postDelayed(runnable, 2000)
    }
    handler.postDelayed(runnable, 2000)
}

Java

Runnable runnable;
Handler handler;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            // do your work
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(runnable, 1000);
}

Which .NET Dependency Injection frameworks are worth looking into?

It depends on what you are looking for, as they each have their pros and cons.

  1. Spring.NET is the most mature as it comes out of Spring from the Java world. Spring has a very rich set of framework libraries that extend it to support Web, Windows, etc.
  2. Castle Windsor is one of the most widely used in the .NET platform and has the largest ecosystem, is highly configurable / extensible, has custom lifetime management, AOP support, has inherent NHibernate support and is an all around awesome container. Windsor is part of an entire stack which includes Monorail, Active Record, etc. NHibernate itself builds on top of Windsor.
  3. Structure Map has very rich and fine grained configuration through an internal DSL.
  4. Autofac is an IoC container of the new age with all of it's inherent functional programming support. It also takes a different approach on managing lifetime than the others. Autofac is still very new, but it pushes the bar on what is possible with IoC.
  5. Ninject I have heard is more bare bones with a less is more approach (heard not experienced).
  6. The biggest discriminator of Unity is: it's from and supported by Microsoft (p&p). Unity has very good performance, and great documentation. It is also highly configurable. It doesn't have all the bells and whistles of say Castle / Structure Map.

So in summary, it really depends on what is important to you. I would agree with others on going and evaluating and seeing which one fits. The nice thing is you have a nice selection of donuts rather than just having to have a jelly one.

Which comment style should I use in batch files?

tl;dr: REM is the documented and supported way to embed comments in batch files.


:: is essentially a blank label that can never be jumped to, whereas REM is an actual command that just does nothing. In neither case (at least on Windows 7) does the presence of redirection operators cause a problem.

However, :: is known to misbehave in blocks under certain circumstances, being parsed not as a label but as some sort of drive letter. I'm a little fuzzy on where exactly but that alone is enough to make me use REM exclusively. It's the documented and supported way to embed comments in batch files whereas :: is merely an artifact of a particular implementation.


Here is an example where :: produces a problem in a FOR loop.

This example will not work in a file called test.bat on your desktop:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    ::echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

While this example will work as a comment correctly:

@echo off
for /F "delims=" %%A in ('type C:\Users\%username%\Desktop\test.bat') do (
    REM echo hello>C:\Users\%username%\Desktop\text.txt
)
pause

The problem appears to be when trying to redirect output into a file. My best guess is that it is interpreting :: as an escaped label called :echo.

How can I remove all text after a character in bash?

Let's say you have a path with a file in this format:

/dirA/dirB/dirC/filename.file

Now you only want the path which includes four "/". Type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-4 -d"/"

and your output will be

/dirA/dirB/dirC

The advantage of using cut is that you can also cut out the uppest directory as well as the file (in this example), so if you type

$ echo "/dirA/dirB/dirC/filename.file" | cut -f1-3 -d"/"

your output would be

/dirA/dirB

Though you can do the same from the other side of the string, it would not make that much sense in this case as typing

$ echo "/dirA/dirB/dirC/filename.file" | cut -f2-4 -d"/"

results in

dirA/dirB/dirC

In some other cases the last case might also be helpful. Mind that there is no "/" at the beginning of the last output.

Seeing the underlying SQL in the Spring JdbcTemplate?

Try adding in log4j.xml

<!--  enable query logging -->
<category name="org.springframework.jdbc.core.JdbcTemplate">
    <priority value="DEBUG" />
</category>

<!-- enable query logging for SQL statement parameter value -->
<category name="org.springframework.jdbc.core.StatementCreatorUtils">
    <priority value="TRACE" />
</category>

your logs looks like:

DEBUG JdbcTemplate:682 - Executing prepared SQL query
DEBUG JdbcTemplate:616 - Executing prepared SQL statement [your sql query]
TRACE StatementCreatorUtils:228 - Setting SQL statement parameter value: column index 1, parameter value [param], value class [java.lang.String], SQL type unknown

How do I install Keras and Theano in Anaconda Python on Windows?

Anaconda with Windows

  • Run anaconda prompt with administrator privilages
  • conda update conda
  • conda update --all
  • conda install mingw libpython
  • conda install theano

After conda commands it's required to accept process - Proceed ([y]/n)?

java.io.InvalidClassException: local class incompatible:

If a class does not explicitly define a private static final long serialVersionUID in the code it will be autogenerated, and there is no guarantee that different machines will generate the same id; it looks like that is exactly what happened. Also if the classes are different in any way (using different versions of the class) the autogenerated serialVersionUIDs will also be different.

From the Serializable interface's docs:

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members. Array classes cannot declare an explicit serialVersionUID, so they always have the default computed value, but the requirement for matching serialVersionUID values is waived for array classes.

You should define a serialVersionUID in the class definition, e.g.:

class MyClass implements Serializable {
    private static final long serialVersionUID = 6529685098267757690L;
    ...

What is the correct way to read a serial port using .NET framework?

Could you try something like this for example I think what you are wanting to utilize is the port.ReadExisting() Method

 using System;
 using System.IO.Ports;

 class SerialPortProgram 
 { 
  // Create the serial port with basic settings 
    private SerialPort port = new   SerialPort("COM1",
      9600, Parity.None, 8, StopBits.One); 
    [STAThread] 
    static void Main(string[] args) 
    { 
      // Instatiate this 
      SerialPortProgram(); 
    } 

    private static void SerialPortProgram() 
    { 
        Console.WriteLine("Incoming Data:");
         // Attach a method to be called when there
         // is data waiting in the port's buffer 
        port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); 
        // Begin communications 
        port.Open(); 
        // Enter an application loop to keep this thread alive 
        Console.ReadLine();
     } 

    private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) 
    { 
       // Show all the incoming data in the port's buffer
       Console.WriteLine(port.ReadExisting()); 
    } 
}

Or is you want to do it based on what you were trying to do , you can try this

public class MySerialReader : IDisposable
{
  private SerialPort serialPort;
  private Queue<byte> recievedData = new Queue<byte>();

  public MySerialReader()
  {
    serialPort = new SerialPort();
    serialPort.Open();
    serialPort.DataReceived += serialPort_DataReceived;
  }

  void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
  {
    byte[] data = new byte[serialPort.BytesToRead];
    serialPort.Read(data, 0, data.Length);
    data.ToList().ForEach(b => recievedData.Enqueue(b));
    processData();
  }

  void processData()
  {
    // Determine if we have a "packet" in the queue
    if (recievedData.Count > 50)
    {
        var packet = Enumerable.Range(0, 50).Select(i => recievedData.Dequeue());
    }
  }

  public void Dispose()
  {
        if (serialPort != null)
        {
            serialPort.Dispose();
        }
  }

Import functions from another js file. Javascript

From a quick glance on MDN I think you may need to include the .js at the end of your file name so the import would read import './course.js' instead of import './course'

Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'. when updating to Support Library 26.0.0

For this you have to do below things 1.right click the project click.

2.open module settings->in properties tab->change the compile sdk and build tool version into 26,26.0.0.

3.click ok.

Its working for me after an hour tried.

How to include a Font Awesome icon in React's render()

Alexander's answer from above really helped me out!

I was trying to get social accounts icons in the footer of my app I created with ReactJS so that I could easily add a hover state to them while also having them link my social accounts. This is what I ended up having to do:

$ npm i --save @fortawesome/fontawesome-free-brands

Then at the top of my footer component I included this:

import React from 'react';
import './styles/Footer.css';
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import {faTwitter, faLinkedin, faGithub} from '@fortawesome/fontawesome-free-brands';

My component then looked like this:

<a href='https://github.com/yourusernamehere'>
  <FontAwesomeIcon className ='font-awesome' icon={faGithub} />
</a>

Worked like a charm.

What is thread safe or non-thread safe in PHP?

For me, I always choose non-thread safe version because I always use nginx, or run PHP from the command line.

The non-thread safe version should be used if you install PHP as a CGI binary, command line interface or other environment where only a single thread is used.

A thread-safe version should be used if you install PHP as an Apache module in a worker MPM (multi-processing model) or other environment where multiple PHP threads run concurrently.

How to handle login pop up window using Selenium WebDriver?

I used IE, then create code like that and works after modification several code:

       public class TestIEBrowser {
                          public static void main(String[] args) throws Exception {
               //Set path of IEDriverServer.exe.
              // Note : IEDriverServer.exe should be In D: drive.
              System.setProperty("webdriver.ie.driver", "path /IEDriverServer.exe");

              // Initialize InternetExplorerDriver Instance.
              WebDriver driver = new InternetExplorerDriver();

              // Load sample calc test URL.
              driver.get("http://...  /");

              //Code to handle Basic Browser Authentication in Selenium.
              Alert aa = driver.switchTo().alert();

              Robot a = new Robot();
              aa.sendKeys("host"+"\\"+"user");  

              a.keyPress(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_TAB);
              a.keyRelease(KeyEvent.VK_ADD);                

              setClipboardData("password");

              a.keyPress(KeyEvent.VK_CONTROL);
              a.keyPress(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_V);
              a.keyRelease(KeyEvent.VK_CONTROL);
              //Thread.sleep(5000);
              aa.accept();        




    }

             private static void setClipboardData(String string) {
            // TODO Auto-generated method stub
                        StringSelection stringSelection = new StringSelection(string);                            Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
        }
}

How do I pass a list as a parameter in a stored procedure?

I solved this problem through the following:

  1. In C # I built a String variable.

string userId="";

  1. I put my list's item in this variable. I separated the ','.

for example: in C#

userId= "5,44,72,81,126";

and Send to SQL-Server

 SqlParameter param = cmd.Parameters.AddWithValue("@user_id_list",userId);
  1. I Create Separated Function in SQL-server For Convert my Received List (that it's type is NVARCHAR(Max)) to Table.
CREATE FUNCTION dbo.SplitInts  
(  
   @List      VARCHAR(MAX),  
   @Delimiter VARCHAR(255)  
)  
RETURNS TABLE  
AS  
  RETURN ( SELECT Item = CONVERT(INT, Item) FROM  
      ( SELECT Item = x.i.value('(./text())[1]', 'varchar(max)')  
        FROM ( SELECT [XML] = CONVERT(XML, '<i>'  
        + REPLACE(@List, @Delimiter, '</i><i>') + '</i>').query('.')  
          ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y  
      WHERE Item IS NOT NULL  
  );
  1. In the main Store Procedure, using the command below, I use the entry list.

SELECT user_id = Item FROM dbo.SplitInts(@user_id_list, ',');

Regular expression for decimal number

^[0-9]([.,][0-9]{1,3})?$

It allows:

0
1
1.2
1.02
1.003
1.030
1,2
1,23
1,234

BUT NOT:

.1
,1
12.1
12,1
1.
1,
1.2345
1,2345

How does one remove a Docker image?

Removing Containers

  1. To remove a specific container

    docker rm CONTAINER_ID CONTAINER_ID
    
    • For single image

      docker rm  70c0e19168cf
      
    • For multiple images

      docker rm  70c0e19168cf c2ce80b62174
      
  2. Remove exited containers

    docker ps -a -f status=exited
    
  3. Remove all the containers

    docker ps -q -a | xargs docker rm
    


Removing Images

docker rmi IMAGE_ID
  1. Remove specific images

    • for single image

      docker rmi ubuntu
      
    • for multiple images

      docker rmi ubuntu alpine
      
  2. Remove dangling images
    Dangling images are layers that have no relationship to any tagged images as the Docker images are constituted of multiple images.

    docker rmi -f $(docker images -f dangling=true -q)
    
  3. Remove all Docker images

    docker rmi -f $(docker images -a -q)
    

Removing Volumes

To list volumes, run docker volume ls

  1. Remove a specific volume

    docker volume rm VOLUME_NAME
    
  2. Remove dangling volumes

    docker volume rm $(docker volume ls -f dangling=true -q)
    
  3. Remove a container and its volumes

    docker rm -v CONTAINER_NAME
    

Increasing the Command Timeout for SQL command

Setting command timeout to 2 minutes.

 scGetruntotals.CommandTimeout = 120;

but you can optimize your stored Procedures to decrease that time! like

  • removing courser or while and etc
  • using paging
  • using #tempTable and @variableTable
  • optimizing joined tables

Is there a Java equivalent or methodology for the typedef keyword in C++?

There is no typedef in java as of 1.6, what you can do is make a wrapper class for what you want since you can't subclass final classes (Integer, Double, etc)

Do you recommend using semicolons after every statement in JavaScript?

I use semicolon, since it is my habit. Now I understand why I can't have string split into two lines... it puts semicolon at the end of each line.

Remove table row after clicking table row delete button

Following solution is working fine.

HTML:

<table>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
  <tr>
    <td>
      <input type="button" value="Delete Row" onclick="SomeDeleteRowFunction(this);">
    </td>
  </tr>
</table>

JQuery:

function SomeDeleteRowFunction(btndel) {
    if (typeof(btndel) == "object") {
        $(btndel).closest("tr").remove();
    } else {
        return false;
    }
}

I have done bins on http://codebins.com/bin/4ldqpa9

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

Best C# API to create PDF

Update:

I'm not sure when or if the license changed for the iText# library, but it is licensed under AGPL which means it must be licensed if included with a closed-source product. The question does not (currently) require free or open-source libraries. One should always investigate the license type of any library used in a project.


I have used iText# with success in .NET C# 3.5; it is a port of the open source Java library for PDF generation and it's free.

There is a NuGet package available for iTextSharp version 5 and the official developer documentation, as well as C# examples, can be found at itextpdf.com

Random state (Pseudo-random number) in Scikit learn

sklearn.model_selection.train_test_split(*arrays, **options)[source]

Split arrays or matrices into random train and test subsets

Parameters: ... 
    random_state : int, RandomState instance or None, optional (default=None)

If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. source: http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html

'''Regarding the random state, it is used in many randomized algorithms in sklearn to determine the random seed passed to the pseudo-random number generator. Therefore, it does not govern any aspect of the algorithm's behavior. As a consequence, random state values which performed well in the validation set do not correspond to those which would perform well in a new, unseen test set. Indeed, depending on the algorithm, you might see completely different results by just changing the ordering of training samples.''' source: https://stats.stackexchange.com/questions/263999/is-random-state-a-parameter-to-tune

How to read the last row with SQL Server

If you don't have any ordered column, you can use the physical id of each lines:

SELECT top 1 sys.fn_PhysLocFormatter(%%physloc%%) AS [File:Page:Slot], 
              T.*
FROM MyTable As T
order by sys.fn_PhysLocFormatter(%%physloc%%) DESC

How to create an Observable from static data similar to http one in Angular?

This is how you can create a simple observable for static data.

let observable = Observable.create(observer => {
  setTimeout(() => {
    let users = [
      {username:"balwant.padwal",city:"pune"},
      {username:"test",city:"mumbai"}]

    observer.next(users); // This method same as resolve() method from Angular 1
    console.log("am done");
    observer.complete();//to show we are done with our processing
    // observer.error(new Error("error message"));
  }, 2000);

})

to subscribe to it is very easy

observable.subscribe((data)=>{
  console.log(data); // users array display
});

I hope this answer is helpful. We can use HTTP call instead static data.

Write-back vs Write-Through caching?

Let's look at this with the help of an example. Suppose we have a direct mapped cache and the write back policy is used. So we have a valid bit, a dirty bit, a tag and a data field in a cache line. Suppose we have an operation : write A ( where A is mapped to the first line of the cache).

What happens is that the data(A) from the processor gets written to the first line of the cache. The valid bit and tag bits are set. The dirty bit is set to 1.

Dirty bit simply indicates was the cache line ever written since it was last brought into the cache!

Now suppose another operation is performed : read E(where E is also mapped to the first cache line)

Since we have direct mapped cache, the first line can simply be replaced by the E block which will be brought from memory. But since the block last written into the line (block A) is not yet written into the memory(indicated by the dirty bit), so the cache controller will first issue a write back to the memory to transfer the block A to memory, then it will replace the line with block E by issuing a read operation to the memory. dirty bit is now set to 0.

So write back policy doesnot guarantee that the block will be the same in memory and its associated cache line. However whenever the line is about to be replaced, a write back is performed at first.

A write through policy is just the opposite. According to this, the memory will always have a up-to-date data. That is, if the cache block is written, the memory will also be written accordingly. (no use of dirty bits)

jQuery toggle CSS?

You might want to use jQuery's .addClass and .removeClass commands, and create two different classes for the states. This, to me, would be the best practice way of doing it.

How do you get the selected value of a Spinner?

To get just the string value within the spinner use the following:

spinner.getSelectedItem().toString();

How do you clear Apache Maven's cache?

I've had this same problem, and I wrote a one-liner in shell to do it.

rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
                       -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
                       -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*

I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:

#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
  -Dexpression=settings.localRepository \
  -Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
  -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
  --batch-mode \
  | grep -vF '[INFO]')

rm -rf $REPOSITORY/*

Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.

It's a bit wieldy, but it's a decent way of doing business, IMO.

Non greedy (reluctant) regex matching in sed?

I realize this is an old entry, but someone may find it useful. As the full domain name may not exceed a total length of 253 characters replace .* with .\{1, 255\}

set option "selected" attribute from dynamic created option

This should work.

$("#country [value='ID']").attr("selected","selected");

If you have function calls bound to the element just follow it with something like

$("#country").change();

Python Pandas - Find difference between two data frames

Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.

newDf = df1.set_index('Name1')
           .drop(df2['Name2'], errors='ignore')
           .reset_index(drop=False)

Single quotes vs. double quotes in C or C++

Single quotes are characters (char), double quotes are null-terminated strings (char *).

char c = 'x';
char *s = "Hello World";

Get property value from string using reflection

Here's what I got based on other answers. A little overkill on getting so specific with the error handling.

public static T GetPropertyValue<T>(object sourceInstance, string targetPropertyName, bool throwExceptionIfNotExists = false)
{
    string errorMsg = null;

    try
    {
        if (sourceInstance == null || string.IsNullOrWhiteSpace(targetPropertyName))
        {
            errorMsg = $"Source object is null or property name is null or whitespace. '{targetPropertyName}'";
            Log.Warn(errorMsg);

            if (throwExceptionIfNotExists)
                throw new ArgumentException(errorMsg);
            else
                return default(T);
        }

        Type returnType = typeof(T);
        Type sourceType = sourceInstance.GetType();

        PropertyInfo propertyInfo = sourceType.GetProperty(targetPropertyName, returnType);
        if (propertyInfo == null)
        {
            errorMsg = $"Property name '{targetPropertyName}' of type '{returnType}' not found for source object of type '{sourceType}'";
            Log.Warn(errorMsg);

            if (throwExceptionIfNotExists)
                throw new ArgumentException(errorMsg);
            else
                return default(T);
        }

        return (T)propertyInfo.GetValue(sourceInstance, null);
    }
    catch(Exception ex)
    {
        errorMsg = $"Problem getting property name '{targetPropertyName}' from source instance.";
        Log.Error(errorMsg, ex);

        if (throwExceptionIfNotExists)
            throw;
    }

    return default(T);
}

Can I change the checkbox size using CSS?

My understanding is that this isn't easy at all to do cross-browser. Instead of trying to manipulate the checkbox control, you could always build your own implementation using images, javascript, and hidden input fields. I'm assuming this is similar to what niceforms is (from Staicu lonut's answer above), but wouldn't be particularly difficult to implement. I believe jQuery has a plugin to allow for this custom behavior as well (will look for the link and post here if I can find it).

Adding multiple columns AFTER a specific column in MySQL

If you want to add a single column after a specific field, then the following MySQL query should work:

ALTER TABLE users
    ADD COLUMN count SMALLINT(6) NOT NULL
    AFTER lastname

If you want to add multiple columns, then you need to use 'ADD' command each time for a column. Here is the MySQL query for this:

ALTER TABLE users
    ADD COLUMN count SMALLINT(6) NOT NULL,
    ADD COLUMN log VARCHAR(12) NOT NULL,
    ADD COLUMN status INT(10) UNSIGNED NOT NULL
    AFTER lastname

Point to note

In the second method, the last ADD COLUMN column should actually be the first column you want to append to the table.

E.g: if you want to add count, log, status in the exact order after lastname, then the syntax would actually be:

ALTER TABLE users
    ADD COLUMN log VARCHAR(12) NOT NULL AFTER lastname,
    ADD COLUMN status INT(10) UNSIGNED NOT NULL AFTER lastname,
    ADD COLUMN count SMALLINT(6) NOT NULL AFTER lastname
    

HTML5 Canvas 100% Width Height of Viewport?

http://jsfiddle.net/mqFdk/10/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

with CSS

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

How to hide the Google Invisible reCAPTCHA badge

I have tested all approaches and:

WARNING: display: none DISABLES the spam checking!

visibility: hidden and opacity: 0 do NOT disable the spam checking.

Code to use:

.grecaptcha-badge { 
    visibility: hidden;
}

When you hide the badge icon, Google wants you to reference their service on your form by adding this:

<small>This site is protected by reCAPTCHA and the Google 
    <a href="https://policies.google.com/privacy">Privacy Policy</a> and
    <a href="https://policies.google.com/terms">Terms of Service</a> apply.
</small>

Example result

What is the ultimate postal code and zip regex?

Given that there are so many edge cases for each country (eg. London addresses may use a slightly different format to the rest of the UK) I don't think that there is an ultimate regex other than maybe:

[0-9a-zA-Z]+

Best of going with a fairly broad pattern (well not quite as broad as the above), or treat each country/region with a specific pattern of its own!

UPDATE: However, it may be possible to dynamically construct a regex based upon lots of smaller, region specific rules - not sure about performance though!

Lots of country specific patterns can be found on the RegExLib site.

Lazy Loading vs Eager Loading

Eager Loading: Eager Loading helps you to load all your needed entities at once. i.e. related objects (child objects) are loaded automatically with its parent object.

When to use:

  1. Use Eager Loading when the relations are not too much. Thus, Eager Loading is a good practice to reduce further queries on the Server.
  2. Use Eager Loading when you are sure that you will be using related entities with the main entity everywhere.

Lazy Loading: In case of lazy loading, related objects (child objects) are not loaded automatically with its parent object until they are requested. By default LINQ supports lazy loading.

When to use:

  1. Use Lazy Loading when you are using one-to-many collections.
  2. Use Lazy Loading when you are sure that you are not using related entities instantly.

NOTE: Entity Framework supports three ways to load related data - eager loading, lazy loading and explicit loading.

How to split a data frame?

Splitting the data frame seems counter-productive. Instead, use the split-apply-combine paradigm, e.g., generate some data

df = data.frame(grp=sample(letters, 100, TRUE), x=rnorm(100))

then split only the relevant columns and apply the scale() function to x in each group, and combine the results (using split<- or ave)

df$z = 0
split(df$z, df$grp) = lapply(split(df$x, df$grp), scale)
## alternative: df$z = ave(df$x, df$grp, FUN=scale)

This will be very fast compared to splitting data.frames, and the result remains usable in downstream analysis without iteration. I think the dplyr syntax is

library(dplyr)
df %>% group_by(grp) %>% mutate(z=scale(x))

In general this dplyr solution is faster than splitting data frames but not as fast as split-apply-combine.

How can I exclude a directory from Visual Studio Code "Explore" tab?

In newer versions of VS Code, you navigate to settings (Ctrl+,), and make sure to select Workspace Settings at the top right.

enter image description here

Then add a files.exclude option to specify patterns to exclude.

You can also add search.exclude if you only want to exclude a file from search results, and not from the folder explorer.

ASP MVC href to a controller/view

If using ASP.NET Core, you can adjust the accepted answer to:

<a href="@Url.Action("Index", null, new { area = string.Empty, controller = "User" }, @Context.Request.Scheme)">
     <span>Clients</span>
</a>

replacing @Request.Url.Scheme with @Context.Request.Scheme

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

The short answer is yes. The most important difference is that an AutoResetEvent will only allow one single waiting thread to continue. A ManualResetEvent on the other hand will keep allowing threads, several at the same time even, to continue until you tell it to stop (Reset it).

Passing arguments to angularjs filters

Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:

<div ng:app>
 <div ng-controller="HelloCntl">
 <ul>
    <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
        <span>{{friend.name}}</span>
        <span>{{friend.phone}}</span>
    </li>
 </ul>
 </div>
</div>

http://jsfiddle.net/ZfGx4/59/

Oracle SQL, concatenate multiple columns + add text

You have two options for concatenating strings in Oracle:

CONCAT example:

CONCAT(
  CONCAT(
    CONCAT(
      CONCAT(
        CONCAT('I like ', t.type_desc_column), 
        ' cake with '), 
      t.icing_desc_column),
    ' and a '),
  t.fruit_desc_column)

Using || example:

'I like ' || t.type_desc_column || ' cake with ' || t.icing_desc_column || ' and a ' || t.fruit_desc_column

Mapping a JDBC ResultSet to an object

If you don't want to use any JPA provider such as OpenJPA or Hibernate, you can just give Apache DbUtils a try.

http://commons.apache.org/proper/commons-dbutils/examples.html

Then your code will look like this:

QueryRunner run = new QueryRunner(dataSource);

// Use the BeanListHandler implementation to convert all
// ResultSet rows into a List of Person JavaBeans.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class);

// Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
List<Person> persons = run.query("SELECT * FROM Person", h);

Swap DIV position with CSS only

Using CSS only:

#blockContainer {
display: -webkit-box;
display: -moz-box;
display: box;

-webkit-box-orient: vertical;
-moz-box-orient: vertical;
box-orient: vertical;
}
#blockA {
-webkit-box-ordinal-group: 2;
-moz-box-ordinal-group: 2;
box-ordinal-group: 2;
}
#blockB {
-webkit-box-ordinal-group: 3;
-moz-box-ordinal-group: 3;
box-ordinal-group: 3;

}

<div id="blockContainer">
 <div id="blockA">Block A</div>
 <div id="blockB">Block B</div>
 <div id="blockC">Block C</div>
</div>

http://jsfiddle.net/thirtydot/hLUHL/

Permission is only granted to system app

Path In Android Studio in mac:

Android Studio -> Preferences -> Editor -> Inspections

Expand Android -> Expand Lint -> Expand Correctness

Uncheck the checkbox for Using system app permission

Click on "APPLY" -> "OK"

Prevent WebView from displaying "web page not available"

I suppose that if you insist on doing this, you could just check if the resource is there before calling the loadURL function. Just simply override the functions and do the check before calling the super()

REMARK (maybe off-topic): In http, there is a method called HEAD which is described as follow:

The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response

This method might be handy. Anyway how ever you implement it ... check this code:

import java.util.Map;

import android.content.Context;
import android.webkit.WebView;

public class WebViewPreLoad extends WebView{

public WebViewPreLoad(Context context) {
super(context);
}
public void loadUrl(String str){
if(//Check if exists)
super.loadUrl(str);
else
//handle error
}
public void loadUrl(String url, Map<String,String> extraHeaders){
if(//Check if exists)
super.loadUrl(url, extraHeaders);
else
//handle error
}
}

You could try this check using

if(url.openConnection().getContentLength() > 0)

How to add results of two select commands in same query

If you want to make multiple operation use

select (sel1.s1+sel2+s2)

(select sum(hours) s1 from resource) sel1
join 
(select sum(hours) s2 from projects-time)sel2
on sel1.s1=sel2.s2

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

Simply Use in Laravel Eloquent:

$a='foo', $b='bar', $c='john', $d='doe';

Coder::where(function ($query) use ($a, $b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})->where(function ($query) use ($c, $d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
})->get();

Will produce a query like:

SELECT * FROM <table> WHERE (a='foo' or b='bar') AND (c='john' or d='doe');

PyCharm shows unresolved references error for valid code

In my case the inspection error shows up due to a very specific case of python code. A min function that contains two numpy functions and two list accesses makes my code inspection give this kind of errors.

Removing the 'd=0' line in the following example gives an unresolved reference error as expected, but readding doesn't make the error go away for the code inspector. I can still execute the code without problems afterwards.

import numpy as np
def strange(S, T, U, V):
    d = 0
    print min(np.abs(S[d]), np.abs(T[d]), U[d], V[d])

Clearing caches and reloading list of paths doesn't work. Only altering the code with one of the following example patches does work:

  • Another ordering of the 'min' parameters: schematically S U T V but not S T U V or T S U V
  • Using a method instead of the function: S[d].abs() instead of np.abs(S[d])
  • Using the built-in abs() function
  • Adding a number to a parameter of choice: U[d] + 0.