Programs & Examples On #Windowless

ExecuteReader: Connection property has not been initialized

After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... Add

cmd.Connection = conn;

Hope this help

How to use Scanner to accept only valid int as input

I see that Character.isDigit perfectly suits the need, since the input will be just one symbol. Of course we don't have any info about this kb object but just in case it's a java.util.Scanner instance, I'd also suggest using java.io.InputStreamReader for command line input. Here's an example:

java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
try {
  reader.read();
}
catch(Exception e) {
  e.printStackTrace();
}
reader.close();

What are SP (stack) and LR in ARM?

LR is link register used to hold the return address for a function call.

SP is stack pointer. The stack is generally used to hold "automatic" variables and context/parameters across function calls. Conceptually you can think of the "stack" as a place where you "pile" your data. You keep "stacking" one piece of data over the other and the stack pointer tells you how "high" your "stack" of data is. You can remove data from the "top" of the "stack" and make it shorter.

From the ARM architecture reference:

SP, the Stack Pointer

Register R13 is used as a pointer to the active stack.

In Thumb code, most instructions cannot access SP. The only instructions that can access SP are those designed to use SP as a stack pointer. The use of SP for any purpose other than as a stack pointer is deprecated. Note Using SP for any purpose other than as a stack pointer is likely to break the requirements of operating systems, debuggers, and other software systems, causing them to malfunction.

LR, the Link Register

Register R14 is used to store the return address from a subroutine. At other times, LR can be used for other purposes.

When a BL or BLX instruction performs a subroutine call, LR is set to the subroutine return address. To perform a subroutine return, copy LR back to the program counter. This is typically done in one of two ways, after entering the subroutine with a BL or BLX instruction:

• Return with a BX LR instruction.

• On subroutine entry, store LR to the stack with an instruction of the form: PUSH {,LR} and use a matching instruction to return: POP {,PC} ...

This link gives an example of a trivial subroutine.

Here is an example of how registers are saved on the stack prior to a call and then popped back to restore their content.

Declaring array of objects

Well array.length should do the trick or not? something like, i mean you don't need to know the index range if you just read it..

var arrayContainingObjects = [];
for (var i = 0; i < arrayContainingYourItems.length; i++){
    arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
}

Maybe i didn't understand your Question correctly, but you should be able to get the length of your Array this way and transforming them into objects. Daniel kind of gave the same answer to be honest. You could just save your array-length in to his variable and it would be done.

IF and this should not happen in my opinion you can't get your Array-length. As you said w/o getting the index number you could do it like this:

var arrayContainingObjects = [];
for (;;){
    try{
        arrayContainingObjects.push {(property: arrayContainingYourItems[i])};
    }
}
catch(err){
    break;
}

It is the not-nice version of the one above but the loop would execute until you "run" out of the index range.

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

One important fact about NVIDIA drivers that is not very well known is that its built is done by DKMS. This allows automatic rebuild in case of kernel upgrade, this happens on system startup. Because of that, it's quite easy to miss error messages, especially if you're working on cloud VM, or server without an additional IPMI/management interface. However, it's possible to trigger DKMS build just executing dkms autoinstall right after packages installation. If this fails then you'll have a meaningful error message about missing dependency or what so ever. If dkms autoinstall builds modules correctly you can simply load it by modprobe - there is no need to reboot the system (which is often used as a way to trigger DKMS rebuild). You can check an example here

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

using windows 10

I was facing issue .. then I removed JAVA_HOME variable completly and just added %JAVA_HOME%\bin in PATH then it worked!!! for mee

Download a specific tag with Git

first fetch all the tags in that specific remote

git fetch <remote> 'refs/tags/*:refs/tags/*'

or just simply type

git fetch <remote>

Then check for the available tags

git tag -l

then switch to that specific tag using below command

git checkout tags/<tag_name>

Hope this will helps you!

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

MySQL CURRENT_TIMESTAMP on create and on update

You cannot have two TIMESTAMP column with the same default value of CURRENT_TIMESTAMP on your table. Please refer to this link: http://www.mysqltutorial.org/mysql-timestamp.aspx

Cannot find R.layout.activity_main

First Doing This --> Select Build > Clean Project from the Android Studio toolbar, wait a few moments, and then build your project by selecting Build > Rebuild Project.

if Problem Not solved then doing This --> File > Invalidate Caches / Restart > Invalidate and Restart from Android Studio’s toolbar.

How to commit to remote git repository

You just need to make sure you have the rights to push to the remote repository and do

git push origin master

or simply

git push

LinkButton Send Value to Code Behind OnClick

Just add to the CommandArgument parameter and read it out on the Click handler:

<asp:LinkButton ID="ENameLinkBtn" runat="server" 
    style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere" 
    OnClick="ENameLinkBtn_Click" >

Then in your click event:

protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
    LinkButton btn = (LinkButton)(sender);
    string yourValue = btn.CommandArgument;
    // do what you need here
}   

Also you can set the CommandArgument argument when binding if you are using the LinkButton in any bindable controls by doing:

CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'

Android Studio Stuck at Gradle Download on create new project

Quick Fix: Just turn off your firewall, it seems that android studio wants to download something and because our firewall prevents it from downloading the file that it wants it becomes stuck.

Note: Turning your firewall off can lower your security, if you have time you can just allow android studio in your firewall. By doing this you can turn on your firewall while allowing android studio to download anything that it wants.

css3 text-shadow in IE9

I was looking for a cross-browser text-stroke solution that works when overlaid on background images. think I have a solution for this that doesn't involve extra mark-up, js and works in IE7-9 (I haven't tested 6), and doesn't cause aliasing problems.

This is a combination of using CSS3 text-shadow, which has good support except IE (http://caniuse.com/#search=text-shadow), then using a combination of filters for IE. CSS3 text-stroke support is poor at the moment.

IE Filters

The glow filter (http://www.impressivewebs.com/css3-text-shadow-ie/) looks terrible, so I didn't use that.

David Hewitt's answer involved adding dropshadow filters in a combination of directions. ClearType is then removed unfortunately so we end up with badly aliased text.

I then combined some of the elements suggested on useragentman with the dropshadow filters.

Putting it together

This example would be black text with a white stroke. I'm using conditional html classes by the way to target IE (http://paulirish.com/2008/conditional-stylesheets-vs-css-hacks-answer-neither/).

#myelement {
    color: #000000;
    text-shadow:
    -1px -1px 0 #ffffff,  
    1px -1px 0 #ffffff,
    -1px 1px 0 #ffffff,
    1px 1px 0 #ffffff;
}

html.ie7 #myelement,
html.ie8 #myelement,
html.ie9 #myelement {
    background-color: white;
    filter: progid:DXImageTransform.Microsoft.Chroma(color='white') progid:DXImageTransform.Microsoft.Alpha(opacity=100) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=1,offY=-1) progid:DXImageTransform.Microsoft.dropshadow(color=#ffffff,offX=-1,offY=-1);
    zoom: 1;
}

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

This should do it for you.

<div id="nav-wrap">
    <ul id="nav">
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
        <li><a href="#">Link</a></li>
    </ul>
</div>

#nav-wrap {
    float: left;
    height: 87px;
    width: 900px;
}

#nav {
    display: inline;
    height: 87px;
    width: 100%;
}

.nav-item {
    float: left;
    height: 87px;
    line-height: 87px;
    text-align: center;
    text-decoration: none;
    width: 150px;

}

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

Validate a username and password against Active Directory?

We do this on our Intranet

You have to use System.DirectoryServices;

Here are the guts of the code

using (DirectoryEntry adsEntry = new DirectoryEntry(path, strAccountId, strPassword))
{
    using (DirectorySearcher adsSearcher = new DirectorySearcher(adsEntry))
    {
        //adsSearcher.Filter = "(&(objectClass=user)(objectCategory=person))";
        adsSearcher.Filter = "(sAMAccountName=" + strAccountId + ")";

        try
        {
            SearchResult adsSearchResult = adsSearcher.FindOne();
            bSucceeded = true;

            strAuthenticatedBy = "Active Directory";
            strError = "User has been authenticated by Active Directory.";
        }
        catch (Exception ex)
        {
            // Failed to authenticate. Most likely it is caused by unknown user
            // id or bad strPassword.
            strError = ex.Message;
        }
        finally
        {
            adsEntry.Close();
        }
    }
}

Get the Year/Month/Day from a datetime in php?

Check out the manual: http://www.php.net/manual/en/datetime.format.php

<?php
$date = new DateTime('2000-01-01');
echo $date->format('Y-m-d H:i:s');
?>

Will output: 2000-01-01 00:00:00

Configuring IntelliJ IDEA for unit testing with JUnit

If you already have a test class, but missing the JUnit library dependency, please refer to Configuring Libraries for Unit Testing documentation section. Pressing Alt+Enter on the red code should give you an intention action to add the missing jar.

However, IDEA offers much more. If you don't have a test class yet and want to create one for any of the source classes, see instructions below.

You can use the Create Test intention action by pressing Alt+Enter while standing on the name of your class inside the editor or by using Ctrl+Shift+T keyboard shortcut.

A dialog appears where you select what testing framework to use and press Fix button for the first time to add the required library jars to the module dependencies. You can also select methods to create the test stubs for.

Create Test Intention

Create Test Dialog

You can find more details in the Testing help section of the on-line documentation.

Django URLs TypeError: view must be a callable or a list/tuple in the case of include()

Your code is

urlpatterns = [
    url(r'^$', 'myapp.views.home'),
    url(r'^contact/$', 'myapp.views.contact'),
    url(r'^login/$', 'django.contrib.auth.views.login'),
]

change it to following as you're importing include() function :

urlpatterns = [
    url(r'^$', views.home),
    url(r'^contact/$', views.contact),
    url(r'^login/$', views.login),
]

What are alternatives to document.write?

I fail to see the problem with document.write. If you are using it before the onload event fires, as you presumably are, to build elements from structured data for instance, it is the appropriate tool to use. There is no performance advantage to using insertAdjacentHTML or explicitly adding nodes to the DOM after it has been built. I just tested it three different ways with an old script I once used to schedule incoming modem calls for a 24/7 service on a bank of 4 modems.

By the time it is finished this script creates over 3000 DOM nodes, mostly table cells. On a 7 year old PC running Firefox on Vista, this little exercise takes less than 2 seconds using document.write from a local 12kb source file and three 1px GIFs which are re-used about 2000 times. The page just pops into existence fully formed, ready to handle events.

Using insertAdjacentHTML is not a direct substitute as the browser closes tags which the script requires remain open, and takes twice as long to ultimately create a mangled page. Writing all the pieces to a string and then passing it to insertAdjacentHTML takes even longer, but at least you get the page as designed. Other options (like manually re-building the DOM one node at a time) are so ridiculous that I'm not even going there.

Sometimes document.write is the thing to use. The fact that it is one of the oldest methods in JavaScript is not a point against it, but a point in its favor - it is highly optimized code which does exactly what it was intended to do and has been doing since its inception.

It's nice to know that there are alternative post-load methods available, but it must be understood that these are intended for a different purpose entirely; namely modifying the DOM after it has been created and memory allocated to it. It is inherently more resource-intensive to use these methods if your script is intended to write the HTML from which the browser creates the DOM in the first place.

Just write it and let the browser and interpreter do the work. That's what they are there for.

PS: I just tested using an onload param in the body tag and even at this point the document is still open and document.write() functions as intended. Also, there is no perceivable performance difference between the various methods in the latest version of Firefox. Of course there is a ton of caching probably going on somewhere in the hardware/software stack, but that's the point really - let the machine do the work. It may make a difference on a cheap smartphone though. Cheers!

Databinding an enum property to a ComboBox in WPF

I've created an open source CodePlex project that does this. You can download the NuGet package from here.

<enumComboBox:EnumComboBox EnumType="{x:Type demoApplication:Status}" SelectedValue="{Binding Status}" />

anaconda - path environment variable in windows

In windows 10 you can find it here:

C:\Users\[USER]\AppData\Local\conda\conda\envs\[ENVIRONMENT]\python.exe

How to Remove the last char of String in C#?

newString = yourString.Substring(0, yourString.length -1);

Merge PDF files

Is it possible, using Python, to merge seperate PDF files?

Yes.

The following example merges all files in one folder to a single new PDF file:

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

from argparse import ArgumentParser
from glob import glob
from pyPdf import PdfFileReader, PdfFileWriter
import os

def merge(path, output_filename):
    output = PdfFileWriter()

    for pdffile in glob(path + os.sep + '*.pdf'):
        if pdffile == output_filename:
            continue
        print("Parse '%s'" % pdffile)
        document = PdfFileReader(open(pdffile, 'rb'))
        for i in range(document.getNumPages()):
            output.addPage(document.getPage(i))

    print("Start writing '%s'" % output_filename)
    with open(output_filename, "wb") as f:
        output.write(f)

if __name__ == "__main__":
    parser = ArgumentParser()

    # Add more options if you like
    parser.add_argument("-o", "--output",
                        dest="output_filename",
                        default="merged.pdf",
                        help="write merged PDF to FILE",
                        metavar="FILE")
    parser.add_argument("-p", "--path",
                        dest="path",
                        default=".",
                        help="path of source PDF files")

    args = parser.parse_args()
    merge(args.path, args.output_filename)

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

How do you use NSAttributedString?

This solution will work for any length

NSString *strFirst = @"Anylengthtext";
NSString *strSecond = @"Anylengthtext";
NSString *strThird = @"Anylengthtext";

NSString *strComplete = [NSString stringWithFormat:@"%@ %@ %@",strFirst,strSecond,strThird];

NSMutableAttributedString *attributedString =[[NSMutableAttributedString alloc] initWithString:strComplete];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor redColor]
              range:[strComplete rangeOfString:strFirst]];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor yellowColor]
              range:[strComplete rangeOfString:strSecond]];

[attributedString addAttribute:NSForegroundColorAttributeName
              value:[UIColor blueColor]
              range:[strComplete rangeOfString:strThird]];


self.lblName.attributedText = attributedString;

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

Organize your code as a maven module. Once done run the command from terminal
$mvn installl
to check if your code builds fine.
Finally import the project in netbeans or eclipse as maven project.

Shell - Write variable contents to a file

echo has the problem that if var contains something like -e, it will be interpreted as a flag. Another option is printf, but printf "$var" > "$destdir" will expand any escaped characters in the variable, so if the variable contains backslashes the file contents won't match. However, because printf only interprets backslashes as escapes in the format string, you can use the %s format specifier to store the exact variable contents to the destination file:

printf "%s" "$var" > "$destdir"

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

npm can't find package.json

Go inside the project folder and check whether the package.json file does exist.

If you are creating the project using Visual Studio Angular project, make sure you run this command inside the ClientApp Folder. there is a good chance, you could be looking for project.json file outside the ClientApp folder.

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

Run Following command to show catalina logs on the terminal---

sh start-camunda.sh; tail -f server/apache-tomcat-8.0.24/logs/catalina.out

Hide Twitter Bootstrap nav collapse on click

Here's how I did it. If there is a smoother way, please please tell me.

Inside the <a> tags where the links for the menu are I added this code:

onclick="$('.navbar-toggle').click()"

It preserves the slide animation. So in full use it would look like this:

<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation" ng-controller="topNavController as topNav">
<div class="container">
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="home.html">My Cool Site</a>
    </div>
    <div id="navbar" class="navbar-collapse collapse">
        <ul class="nav navbar-nav">
            <li class="active" onclick="$('.navbar-toggle').click()"><a href="home.html" onclick="$('.navbar-toggle').click()"><i class="fa fa-home"></i> Home</a></li>
            <li><a href="aboutus.html" onclick="$('.navbar-toggle').click()">About Us</a></li>
        </ul>
    </div><!--/.nav-collapse -->
</div>

How to display items side-by-side without using tables?

Try calling the image in a <DIV> tag, which will allow a smoother and faster loading time. Take note that because this is a background image, you can also put text over the image between the <DIV></DIV> tags. This works great for custom store/shop listings as well...to post a cool " Sold Out! " overlay, or whatever you might want.

Here is the pic/text- sided by side version, which can be used for blog post and article listing:

<div class="whatever_container">
<h2>Title/Header Here</h2>
 <div id="image-container-name"style="background-image:url('images/whatever-this-is-named.jpg');background color:#FFFFFF;height:75px;width:20%;float:left;margin:0px 25px 0px 5px;"></div>
<p>All of your text goes here next to the image.</p></div>

Check if a String is in an ArrayList of Strings

    List list1 = new ArrayList();
    list1.add("one");
    list1.add("three");
    list1.add("four");

    List list2 = new ArrayList();
    list2.add("one");
    list2.add("two");
    list2.add("three");
    list2.add("four");
    list2.add("five");


    list2.stream().filter( x -> !list1.contains(x) ).forEach(x -> System.out.println(x));

The output is:

two
five

Is there a RegExp.escape function in JavaScript?

In jQuery UI's autocomplete widget (version 1.9.1) they use a slightly different regular expression (line 6753), here's the regular expression combined with bobince's approach.

RegExp.escape = function( value ) {
     return value.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
}

@font-face not working

try to put below html in head tag.It worked for me.

 <title>ABC</title>
 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 
 <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

How do I concatenate two lists in Python?

If you need to merge two ordered lists with complicated sorting rules, you might have to roll it yourself like in the following code (using a simple sorting rule for readability :-) ).

list1 = [1,2,5]
list2 = [2,3,4]
newlist = []

while list1 and list2:
    if list1[0] == list2[0]:
        newlist.append(list1.pop(0))
        list2.pop(0)
    elif list1[0] < list2[0]:
        newlist.append(list1.pop(0))
    else:
        newlist.append(list2.pop(0))

if list1:
    newlist.extend(list1)
if list2:
    newlist.extend(list2)

assert(newlist == [1, 2, 3, 4, 5])

How to check permissions of a specific directory?

ls -lstr

This shows the normal ls view with permissions and user:group as well

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

  1. Go to your React-native Project -> Android
  2. Create a file local.properties

  3. Open the file

  4. paste your Android SDK path like below

     in Windows sdk.dir = C:\\Users\\USERNAME\\AppData\\Local\\Android\\sdk
    
     in macOS sdk.dir = /Users/USERNAME/Library/Android/sdk
    
     in linux sdk.dir = /home/USERNAME/Android/Sdk
    
  5. Replace USERNAME with your user name

  6. Now, Run the react-native run-android in your terminal

or

Sometimes project might be missing a settings.gradle file. Make sure that file exists from the project you are importing. If not add the settings.gradle file with the following :

    include ':app'

Save the file and put it at the top level folder in your project.

Vertical Alignment of text in a table cell

Try

_x000D_
_x000D_
td.description {_x000D_
  line-height: 15px_x000D_
}
_x000D_
<td class="description">Description</td>
_x000D_
_x000D_
_x000D_

Set the line-height value to the desired value.

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

Just another way to fix this up on Heroku: Make sure your Rakefile is committed and pushed.

Annotation-specified bean name conflicts with existing, non-compatible bean def

Using Eclipse, I had moved classes into new packages, and was getting this error. What worked for me was doing: Project > Clean

and also cleaning my TomCat server by right-clicking on it and selecting clean

Thanks to Rock Lee's answer for helping me figure it out :)

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

'Access denied for user 'root'@'localhost' (using password: NO)'

For some information I've get error after changing password:

Access denied for user 'root'@'localhost' (using password: NO)

Access denied for user 'root'@'localhost' (using password: YES)

In both cases there was error.

But the thing is after that I've tried it with

mysql -uroot -ppassword instead of

mysql -u root -p password -> with spaces between -uroot and -ppassword so maybe if someone get trouble can try this way.

How to make remote REST call inside Node.js? any CURL?

Look at http.request

var options = {
  host: url,
  port: 80,
  path: '/resource?id=foo&bar=baz',
  method: 'POST'
};

http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
}).end();

XSS filtering function in PHP

htmlspecialchars() is perfectly adequate for filtering user input that is displayed in html forms.

make: *** [ ] Error 1 error

I got the same thing. Running "make" and it fails with just this message.

% make
make: *** [all] Error 1

This was caused by a command in a rule terminates with non-zero exit status. E.g. imagine the following (stupid) Makefile:

all:
       @false
       echo "hello"

This would fail (without printing "hello") with the above message since false terminates with exit status 1.

In my case, I was trying to be clever and make a backup of a file before processing it (so that I could compare the newly generated file with my previous one). I did this by having a in my Make rule that looked like this:

@[ -e $@ ] && mv $@ [email protected]

...not realizing that if the target file does not exist, then the above construction will exit (without running the mv command) with exit status 1, and thus any subsequent commands in that rule failed to run. Rewriting my faulty line to:

@if [ -e $@ ]; then mv $@ [email protected]; fi

Solved my problem.

Using a BOOL property

There's no benefit to using properties with primitive types. @property is used with heap allocated NSObjects like NSString*, NSNumber*, UIButton*, and etc, because memory managed accessors are created for free. When you create a BOOL, the value is always allocated on the stack and does not require any special accessors to prevent memory leakage. isWorking is simply the popular way of expressing the state of a boolean value.

In another OO language you would make a variable private bool working; and two accessors: SetWorking for the setter and IsWorking for the accessor.

single line comment in HTML

TL;DR For conforming browsers, yes; but there are no conforming browsers, so no.

According to the HTML 4 specification, <!------> hello--> is a perfectly valid comment. However, I've not found a browser which implements this correctly (i.e. per the specification) due to developers not knowing, nor following, the standards (as digitaldreamer pointed out).

You can find the definition of a comment for HTML4 on the w3c's website: http://www.w3.org/TR/html4/intro/sgmltut.html#h-3.2.4

Another thing that many browsers get wrong is that -- > closes a comment just like -->.

updating table rows in postgres using subquery

Postgres allows:

UPDATE dummy
SET customer=subquery.customer,
    address=subquery.address,
    partn=subquery.partn
FROM (SELECT address_id, customer, address, partn
      FROM  /* big hairy SQL */ ...) AS subquery
WHERE dummy.address_id=subquery.address_id;

This syntax is not standard SQL, but it is much more convenient for this type of query than standard SQL. I believe Oracle (at least) accepts something similar.

Run a Java Application as a Service on Linux

Linux service init script are stored into /etc/init.d. You can copy and customize /etc/init.d/skeleton file, and then call

service [yourservice] start|stop|restart

see http://www.ralfebert.de/blog/java/debian_daemon/. Its for Debian (so, Ubuntu as well) but fit more distribution.

How do you read from stdin?

Read from sys.stdin, but to read binary data on Windows, you need to be extra careful, because sys.stdin there is opened in text mode and it will corrupt \r\n replacing them with \n.

The solution is to set mode to binary if Windows + Python 2 is detected, and on Python 3 use sys.stdin.buffer.

import sys

PY3K = sys.version_info >= (3, 0)

if PY3K:
    source = sys.stdin.buffer
else:
    # Python 2 on Windows opens sys.stdin in text mode, and
    # binary data that read from it becomes corrupted on \r\n
    if sys.platform == "win32":
        # set sys.stdin to binary mode
        import os, msvcrt
        msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
    source = sys.stdin

b = source.read()

SVN undo delete before commit

1) do

svn revert . --recursive

2) parse output for errors like

"Failed to revert 'dir1/dir2' -- try updating instead."

3) call svn up for each of error directories:

svn up dir1/dir2

Converting A String To Hexadecimal In Java

Convert a letter in hex code and hex code in letter.

        String letter = "a";
    String code;
    int decimal;

    code = Integer.toHexString(letter.charAt(0));
    decimal = Integer.parseInt(code, 16);

    System.out.println("Hex code to " + letter + " = " + code);
    System.out.println("Char to " + code + " = " + (char) decimal);

Is Ruby pass by reference or by value?

It should be noted that you do not have to even use the "replace" method to change the value original value. If you assign one of the hash values for a hash, you are changing the original value.

def my_foo(a_hash)
  a_hash["test"]="reference"
end;

hash = {"test"=>"value"}
my_foo(hash)
puts "Ruby is pass-by-#{hash["test"]}"

Android draw a Horizontal line between views

_x000D_
_x000D_
 <view
        android:id="@+id/blackLine"
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#000000"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>
_x000D_
_x000D_
_x000D_

app:layout_constraintStart_toStartOf="parent"/>

String format currency

For razor you can use: culture, value

@String.Format(new CultureInfo("sv-SE"), @Model.value)

How to scroll to top of long ScrollView layout?

Try

mainScrollView.fullScroll(ScrollView.FOCUS_UP);

it should work.

Select rows of a matrix that meet a condition

m <- matrix(1:20, ncol = 4) 
colnames(m) <- letters[1:4]

The following command will select the first row of the matrix above.

subset(m, m[,4] == 16)

And this will select the last three.

subset(m, m[,4] > 17)

The result will be a matrix in both cases. If you want to use column names to select columns then you would be best off converting it to a dataframe with

mf <- data.frame(m)

Then you can select with

mf[ mf$a == 16, ]

Or, you could use the subset command.

implement time delay in c

There are no sleep() functions in the pre-C11 C Standard Library, but POSIX does provide a few options.

The POSIX function sleep() (unistd.h) takes an unsigned int argument for the number of seconds desired to sleep. Although this is not a Standard Library function, it is widely available, and glibc appears to support it even when compiling with stricter settings like --std=c11.

The POSIX function nanosleep() (time.h) takes two pointers to timespec structures as arguments, and provides finer control over the sleep duration. The first argument specifies the delay duration. If the second argument is not a null pointer, it holds the time remaining if the call is interrupted by a signal handler.

Programs that use the nanosleep() function may need to include a feature test macro in order to compile. The following code sample will not compile on my linux system without a feature test macro when I use a typical compiler invocation of gcc -std=c11 -Wall -Wextra -Wpedantic.

POSIX once had a usleep() function (unistd.h) that took a useconds_t argument to specify sleep duration in microseconds. This function also required a feature test macro when used with strict compiler settings. Alas, usleep() was made obsolete with POSIX.1-2001 and should no longer be used. It is recommended that nanosleep() be used now instead of usleep().

#define _POSIX_C_SOURCE  199309L     // feature test macro for nanosleep()

#include <stdio.h>
#include <unistd.h>    // for sleep()
#include <time.h>      // for nanosleep()

int main(void)
{
    // use unsigned sleep(unsigned seconds)
    puts("Wait 5 sec...");
    sleep(5);

    // use int nanosleep(const struct timespec *req, struct timespec *rem);
    puts("Wait 2.5 sec...");
    struct timespec ts = { .tv_sec = 2,          // seconds to wait
                           .tv_nsec = 5e8 };     // additional nanoseconds
    nanosleep(&ts, NULL);
    puts("Bye");

    return 0;
}

Addendum:

C11 does have the header threads.h providing thrd_sleep(), which works identically to nanosleep(). GCC did not support threads.h until 2018, with the release of glibc 2.28. It has been difficult in general to find implementations with support for threads.h (Clang did not support it for a long time, but I'm not sure about the current state of affairs there). You will have to use this option with care.

How to get Activity's content view?

There is no "isContentViewSet" method. You may put some dummy requestWindowFeature call into try/catch block before setContentView like this:

try {
  requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
  setContentView(...)
} catch (AndroidRuntimeException e) {
  // do smth or nothing
}

If content view was already set, requestWindowFeature will throw an exception.

Android Open External Storage directory(sdcard) for storing file

taking @rijul's answer forward, it doesn't work in marshmallow and above versions:

       //for pre-marshmallow versions
       String path = System.getenv("SECONDARY_STORAGE");

       // For Marshmallow, use getExternalCacheDirs() instead of System.getenv("SECONDARY_STORAGE")
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
           File[] externalCacheDirs = mContext.getExternalCacheDirs();
           for (File file : externalCacheDirs) {
               if (Environment.isExternalStorageRemovable(file)) {
                   // Path is in format /storage.../Android....
                   // Get everything before /Android
                   path = file.getPath().split("/Android")[0];
                   break;
               }
           }
       }


        // Android avd emulator doesn't support this variable name so using other one
        if ((null == path) || (path.length() == 0))
            path = Environment.getExternalStorageDirectory().getAbsolutePath();

What is the difference between SessionState and ViewState?

Session is used mainly for storing user specific data [ session specific data ]. In the case of session you can use the value for the whole session until the session expires or the user abandons the session. Viewstate is the type of data that has scope only in the page in which it is used. You canot have viewstate values accesible to other pages unless you transfer those values to the desired page. Also in the case of viewstate all the server side control datas are transferred to the server as key value pair in __Viewstate and transferred back and rendered to the appropriate control in client when postback occurs.

How to check Elasticsearch cluster health?

The _cluster/health API can do far more than the typical output that most see with it:

 $ curl -XGET 'localhost:9200/_cluster/health?pretty'

Most APIs within Elasticsearch can take a variety of arguments to augment their output. This applies to Cluster Health API as well.

Examples

all the indices health
$ curl -XGET 'localhost:9200/_cluster/health?level=indices&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.11" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.12" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0
    },
    "filebeat-6.5.1-2019.06.13" : {
      "status" : "green",
      "number_of_shards" : 3,
all shards health
$ curl -XGET 'localhost:9200/_cluster/health?level=shards&pretty' | head -50
{
  "cluster_name" : "rdu-es-01",
  "status" : "green",
  "timed_out" : false,
  "number_of_nodes" : 9,
  "number_of_data_nodes" : 6,
  "active_primary_shards" : 1106,
  "active_shards" : 2213,
  "relocating_shards" : 0,
  "initializing_shards" : 0,
  "unassigned_shards" : 0,
  "delayed_unassigned_shards" : 0,
  "number_of_pending_tasks" : 0,
  "number_of_in_flight_fetch" : 0,
  "task_max_waiting_in_queue_millis" : 0,
  "active_shards_percent_as_number" : 100.0,
  "indices" : {
    "filebeat-6.5.1-2019.06.10" : {
      "status" : "green",
      "number_of_shards" : 3,
      "number_of_replicas" : 1,
      "active_primary_shards" : 3,
      "active_shards" : 6,
      "relocating_shards" : 0,
      "initializing_shards" : 0,
      "unassigned_shards" : 0,
      "shards" : {
        "0" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "1" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0
        },
        "2" : {
          "status" : "green",
          "primary_active" : true,
          "active_shards" : 2,
          "relocating_shards" : 0,
          "initializing_shards" : 0,
          "unassigned_shards" : 0

The API also has a variety of wait_* options where it'll wait for various state changes before returning immediately or after some specified timeout.

Java: int[] array vs int array[]

No, there is no difference. But I prefer using int[] array as it is more readable.

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

This explains better: Postman docs

Request body

While constructing requests, you would be dealing with the request body editor a lot. Postman lets you send almost any kind of HTTP request (If you can't send something, let us know!). The body editor is divided into 4 areas and has different controls depending on the body type.

form-data

multipart/form-data is the default encoding a web form uses to transfer data. This simulates filling a form on a website, and submitting it. The form-data editor lets you set key/value pairs (using the key-value editor) for your data. You can attach files to a key as well. Do note that due to restrictions of the HTML5 spec, files are not stored in history or collections. You would have to select the file again at the time of sending a request.

urlencoded

This encoding is the same as the one used in URL parameters. You just need to enter key/value pairs and Postman will encode the keys and values properly. Note that you can not upload files through this encoding mode. There might be some confusion between form-data and urlencoded so make sure to check with your API first.

raw

A raw request can contain anything. Postman doesn't touch the string entered in the raw editor except replacing environment variables. Whatever you put in the text area gets sent with the request. The raw editor lets you set the formatting type along with the correct header that you should send with the raw body. You can set the Content-Type header manually as well. Normally, you would be sending XML or JSON data here.

binary

binary data allows you to send things which you can not enter in Postman. For example, image, audio or video files. You can send text files as well. As mentioned earlier in the form-data section, you would have to reattach a file if you are loading a request through the history or the collection.

UPDATE

As pointed out by VKK, the WHATWG spec say urlencoded is the default encoding type for forms.

The invalid value default for these attributes is the application/x-www-form-urlencoded state. The missing value default for the enctype attribute is also the application/x-www-form-urlencoded state.

Convert a negative number to a positive one in JavaScript

You can use ~ operator that logically converts the number to negative and adds 1 to the negative:

_x000D_
_x000D_
var x = 3;_x000D_
x = (~x + 1);_x000D_
console.log(x)_x000D_
// result = -3
_x000D_
_x000D_
_x000D_

jQuery - How to dynamically add a validation rule

As well as making sure that you have first called $("#myForm").validate();, make sure that your dynamic control has been added to the DOM before adding the validation rules.

Changing line colors with ggplot()

color and fill are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:

d + scale_color_manual(values=c("#CC6666", "#9999CC"))

is what you want.

How can I directly view blobs in MySQL Workbench

I'm not sure if this answers the question but if if you right click on the "blob" icon in the field (when viewing the table) there is an option to "Open Value in Editor". One of the tabs lets you view the blob. This is in ver. 5.2.34

Java read file and store text in an array

I use this method:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class TEST {
    static Scanner scn;

public static void main(String[] args) {
    String text = "";

    try{
        scn = new Scanner(new File("test.txt"));
    }catch(FileNotFoundException ex){System.out.println(ex.getMessage());}
    while(scn.hasNext()){
        text += scn.next();
        }
        String[] arry = text.split(",");

    //if need converting to float do this:
    Float[] arrdy = new Float[arry.length];
    for(int i = 0; i < arry.length; i++){
            arrdy[i] = Float.parseFloat(arry[i]);
        }
    System.out.println(Arrays.toString(arrdy));
            }
}

ctypes - Beginner

Firstly: The >>> code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:

>>> 4+5
9

Here we see that the line that starts with >>> is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.

You never enter the >>> part into a .py file.

That takes care of your syntax error.

Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.

They all have benefits and drawbacks.

SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.

Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.

ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.

Opening Chrome From Command Line

if you want to open incognito window, put the command below:

start chrome /incognito

How do you reverse a string in place in JavaScript?

Detailed analysis and ten different ways to reverse a string and their performance details.

http://eddmann.com/posts/ten-ways-to-reverse-a-string-in-javascript/

Perfomance of these implementations:

Best performing implementation(s) per browser

  • Chrome 15 - Implemations 1 and 6
  • Firefox 7 - Implementation 6
  • IE 9 - Implementation 4
  • Opera 12 - Implementation 9

Here are those implementations:

Implementation 1:

function reverse(s) {
  var o = '';
  for (var i = s.length - 1; i >= 0; i--)
    o += s[i];
  return o;
}

Implementation 2:

function reverse(s) {
  var o = [];
  for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
    o[j] = s[i];
  return o.join('');
}

Implementation 3:

function reverse(s) {
  var o = [];
  for (var i = 0, len = s.length; i <= len; i++)
    o.push(s.charAt(len - i));
  return o.join('');
}

Implementation 4:

function reverse(s) {
  return s.split('').reverse().join('');
}

Implementation 5:

function reverse(s) {
  var i = s.length,
      o = '';
  while (i > 0) {
    o += s.substring(i - 1, i);
    i--;
  }
  return o;
}

Implementation 6:

function reverse(s) {
  for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
  return o;
}

Implementation 7:

function reverse(s) {
  return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}

Implementation 8:

function reverse(s) {
  function rev(s, len, o) {
    return (len === 0) ? o : rev(s, --len, (o += s[len]));
  };
  return rev(s, s.length, '');
}

Implementation 9:

function reverse(s) {
  s = s.split('');
  var len = s.length,
      halfIndex = Math.floor(len / 2) - 1,
      tmp;


     for (var i = 0; i <= halfIndex; i++) {
        tmp = s[len - i - 1];
        s[len - i - 1] = s[i];
        s[i] = tmp;
      }
      return s.join('');
    }

Implementation 10

function reverse(s) {
  if (s.length < 2)
    return s;
  var halfIndex = Math.ceil(s.length / 2);
  return reverse(s.substr(halfIndex)) +
         reverse(s.substr(0, halfIndex));
}

T-SQL substring - separating first and last name

Assuming the FirstName is all of the characters up to the first space:

SELECT
  SUBSTRING(username, 1, CHARINDEX(' ', username) - 1) AS FirstName,
  SUBSTRING(username, CHARINDEX(' ', username) + 1, LEN(username)) AS LastName
FROM
  whereever

CSS to line break before/after a particular `inline-block` item

When rewriting the html is allowed, you can nest <ul>s within the <ul> and just let the inner <li>s display as inline-block. This would also semantically make sense IMHO, as the grouping also is reflected within the html.


<ul>
    <li>
        <ul>
            <li>Item 1</li>
            <li>Item 2</li>
            <li>Item 3</li>
        </ul>
    </li>
    <li>
        <ul>
            <li>Item 4</li>
            <li>Item 5</li>
            <li>Item 6</li>
        </ul>
    </li>
</ul>

li li { display:inline-block; }

Demo

_x000D_
_x000D_
$(function() { $('img').attr('src', 'http://phrogz.net/tmp/alphaball.png'); });
_x000D_
h3 {_x000D_
  border-bottom: 1px solid #ccc;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
}_x000D_
ul {_x000D_
  margin: 0.5em auto;_x000D_
  list-style-type: none;_x000D_
}_x000D_
li li {_x000D_
  text-align: center;_x000D_
  display: inline-block;_x000D_
  padding: 0.1em 1em;_x000D_
}_x000D_
img {_x000D_
  width: 64px;_x000D_
  display: block;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<h3>Features</h3>_x000D_
<ul>_x000D_
  <li>_x000D_
    <ul>_x000D_
      <li><img />Smells Good</li>_x000D_
      <li><img />Tastes Great</li>_x000D_
      <li><img />Delicious</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
  <li>_x000D_
    <ul>_x000D_
      <li><img />Wholesome</li>_x000D_
      <li><img />Eats Children</li>_x000D_
      <li><img />Yo' Mama</li>_x000D_
    </ul>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Is it possible to change the speed of HTML's <marquee> tag?

You can change the speed of marquee tag using scrollamount attribute.

It accepts integer values 6 being the default speed, so any value lower then 6 will slow down the marquee effect.

Example :

<marquee scrollamount=4>Scrolling text</marquee>

Read more : http://code2care.org/pages/marquee-tag-scrollamount/

http://www.htmlcodetutorial.com/_MARQUEE_SCROLLAMOUNT.html

P.S : Avoid using marquee!

Browser Timeouts

You can see the default value in Chrome in this link

int64_t g_used_idle_socket_timeout_s = 300 // 5 minutes

In Chrome, as far as I know, there isn't an easy way (as Firefox do) to change the timeout value.

Postman addon's like in firefox

The feature that I'm missing a lot from postman in Firefox extensions is WebView
(preview when API returns HTML).

Now I'm settled with Fiddler (Inspectors > WebView)

Media Player called in state 0, error (-38,0)

I am new in android programming and i had same error as this one. so i simply redefined the mp.createmediaPlayer = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI). It may not the true way to do it but it worked fined for me:

try {
  mp = MediaPlayer.create(getApplicationContext(), Settings.System.DEFAULT_RINGTONE_URI);
} catch (Exception e) {
  e.printStackTrace();
}

mp.start();

ERROR: Error 1005: Can't create table (errno: 121)

You can login to mysql and type

mysql> SHOW INNODB STATUS\G

You will have all the output and you should have a better idea of what the error is.

Scroll to a div using jquery

you can try :

$("#MediaPlayer").ready(function(){
    $("html, body").delay(2000).animate({
        scrollTop: $('#MediaPlayer').offset().top 
    }, 2000);
});

Set the maximum character length of a UITextField

You can't do this directly - UITextField has no maxLength attribute, but you can set the UITextField's delegate, then use:

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

jQuery - Create hidden form element on the fly

if you want to add more attributes just do like:

$('<input>').attr('type','hidden').attr('name','foo[]').attr('value','bar').appendTo('form');

Or

$('<input>').attr({
    type: 'hidden',
    id: 'foo',
    name: 'foo[]',
    value: 'bar'
}).appendTo('form');

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

mvn command not found in OSX Mavrerick

I got same problem, I tried all above, noting solved my problem. Luckely, I solved the problem this way:

echo $SHELL

Output

/bin/zsh
OR 
/bin/bash

If it showing "bash" in output. You have to add env properties in .bashrc file (.bash_profile i did not tried, you can try) or else
It is showing 'zsh' in output. You have to add env properties in .zshrc file, if not exist already you create one no issue.

Escape string Python for MySQL

conn.escape_string()

See MySQL C API function mapping: http://mysql-python.sourceforge.net/MySQLdb.html

maximum value of int

In C++:

#include <limits>

then use

int imin = std::numeric_limits<int>::min(); // minimum value
int imax = std::numeric_limits<int>::max();

std::numeric_limits is a template type which can be instantiated with other types:

float fmin = std::numeric_limits<float>::min(); // minimum positive value
float fmax = std::numeric_limits<float>::max();

In C:

#include <limits.h>

then use

int imin = INT_MIN; // minimum value
int imax = INT_MAX;

or

#include <float.h>

float fmin = FLT_MIN;  // minimum positive value
double dmin = DBL_MIN; // minimum positive value

float fmax = FLT_MAX;
double dmax = DBL_MAX;

How many bytes in a JavaScript string?

This function will return the byte size of any UTF-8 string you pass to it.

function byteCount(s) {
    return encodeURI(s).split(/%..|./).length - 1;
}

Source

JavaScript engines are free to use UCS-2 or UTF-16 internally. Most engines that I know of use UTF-16, but whatever choice they made, it’s just an implementation detail that won’t affect the language’s characteristics.

The ECMAScript/JavaScript language itself, however, exposes characters according to UCS-2, not UTF-16.

Source

Angular bootstrap datepicker date format does not format ng-model value

The format specified through datepicker-popup is just the format for the displayed date. The underlying ngModel is a Date object. Trying to display it will show it as it's default, standard-compliant rapresentation.

You can show it as you want by using the date filter in the view, or, if you need it to be parsed in the controller, you can inject $filter in your controller and call it as $filter('date')(date, format). See also the date filter docs.

How to store Node.js deployment settings/configuration files?

You can use pconf: https://www.npmjs.com/package/pconf

Example:

var Config = require("pconf");
var testConfig = new Config("testConfig");
testConfig.onload = function(){

  testConfig.setValue("test", 1);
  testConfig.getValue("test");
  //testConfig.saveConfig(); Not needed

}

Convert Java String to sql.Timestamp

I believe you need to do this:

  1. Convert everythingButNano using SimpleDateFormat or the like to everythingDate.
  2. Convert nano using Long.valueof(nano)
  3. Convert everythingDate to a Timestamp with new Timestamp(everythingDate.getTime())
  4. Set the Timestamp nanos with Timestamp.setNano()

Option 2 Convert to the date format pointed out in Jon Skeet's answer and use that.

ALTER TABLE on dependent column

I believe that you will have to drop the foreign key constraints first. Then update all of the appropriate tables and remap them as they were.

ALTER TABLE [dbo.Details_tbl] DROP CONSTRAINT [FK_Details_tbl_User_tbl];
-- Perform more appropriate alters
ALTER TABLE [dbo.Details_tbl] ADD FOREIGN KEY (FK_Details_tbl_User_tbl) 
    REFERENCES User_tbl(appId);
-- Perform all appropriate alters to bring the key constraints back

However, unless memory is a really big issue, I would keep the identity as an INT. Unless you are 100% positive that your keys will never grow past the TINYINT restraints. Just a word of caution :)

Multiple variables in a 'with' statement?

It is possible in Python 3 since v3.1 and Python 2.7. The new with syntax supports multiple context managers:

with A() as a, B() as b, C() as c:
    doSomething(a,b,c)

Unlike the contextlib.nested, this guarantees that a and b will have their __exit__()'s called even if C() or it's __enter__() method raises an exception.

You can also use earlier variables in later definitions (h/t Ahmad below):

with A() as a, B(a) as b, C(a, b) as c:
    doSomething(a, c)

Composer install error - requires ext_curl when it's actually enabled

if use wamp go to:

wamp\bin\php\php.5.x.x\php.ini find: ;extension=php_curl.dll remove (;)

Textarea that can do syntax highlighting on the fly?

Update: Bespin is now ACE, which is mentioned by the highest rated answer here. Use ACE instead.

Gotta go with Bespin by Mozilla. It's built using HTML5 features (so it's quick and fast, but doesn't support legacy browsers though), but definitely amazing to use and beats everything I've come across - probably beacause it's Mozilla backing it, and they develop Firefox so yeah... There's also a jQuery Plugin which contains a extension for it to make it a bit easier to use with jQuery.

MySQL query to get column names?

I have tried this query in SQL Server and this worked for me :

SELECT name FROM sys.columns WHERE OBJECT_ID = OBJECT_ID('table_name')

Using both Python 2.x and Python 3.x in IPython Notebook

Under Windows 7 I had anaconda and anaconda3 installed. I went into \Users\me\anaconda\Scripts and executed

sudo .\ipython kernelspec install-self

then I went into \Users\me\anaconda3\Scripts and executed

sudo .\ipython kernel install

(I got jupyter kernelspec install-self is DEPRECATED as of 4.0. You probably want 'ipython kernel install' to install the IPython kernelspec.)

After starting jupyter notebook (in anaconda3) I got a neat dropdown menu in the upper right corner under "New" letting me choose between Python 2 odr Python 3 kernels.

AWS S3: how do I see how much disk space is using

Well, you can do it also through an S3 client if you prefer a human friendly UI.

I use CrossFTP, which is free and cross-platform, and there you can right-click on the folder directory -> select "Properties..." -> click on "Calculate" button next to Size and voila.

Get random sample from list while maintaining ordering of items?

Maybe you can just generate the sample of indices and then collect the items from your list.

randIndex = random.sample(range(len(mylist)), sample_size)
randIndex.sort()
rand = [mylist[i] for i in randIndex]

Why is null an object and what's the difference between null and undefined?

Comparison of many different null checks in JavaScript:

http://jsfiddle.net/aaronhoffman/DdRHB/5/

// Variables to test
var myNull = null;
var myObject = {};
var myStringEmpty = "";
var myStringWhiteSpace = " ";
var myStringHello = "hello";
var myIntZero = 0;
var myIntOne = 1;
var myBoolTrue = true;
var myBoolFalse = false;
var myUndefined;

...trim...

http://aaron-hoffman.blogspot.com/2013/04/javascript-null-checking-undefined-and.html

JavaScript Null Check Comparison Chart

Removing duplicate rows from table in Oracle

From DevX.com:

DELETE FROM our_table
WHERE rowid not in
(SELECT MIN(rowid)
FROM our_table
GROUP BY column1, column2, column3...) ;

Where column1, column2, etc. is the key you want to use.

Retrieve a Fragment from a ViewPager

I couldn't find a simple, clean way to do this. However, the ViewPager widget is just another ViewGroup , which hosts your fragments. The ViewPager has these fragments as immediate children. So you could just iterate over them (using .getChildCount() and .getChildAt() ), and see if the fragment instance that you're looking for is currently loaded into the ViewPager and get a reference to it. E.g. you could use some static unique ID field to tell the fragments apart.

Note that the ViewPager may not have loaded the fragment you're looking for since it's a virtualizing container like ListView.

Android emulator not able to access the internet

I had this also and I solved it by creating new android emulator virtual device and chosen Nexus 4 api 27. Before I was creating Pixel device api 28, and it was not working even after recreating device. So I tried totally different configuration and Android Emulator has internet connection as is expected. Other solutions did not work for me but I did no try it all.

Importing class/java files in Eclipse

create a new java project in Eclipse and copy .java files to its src directory, if you don't know where those source files should be placed, right click on the root of the project and choose new->class to create a test class and see where its .java file is placed, then put other files with it, in the same directory, you may have to adjust the package in those source files according to the new project directory structure.

if you use external libraries in your code, you have two options: either copy / download jar files or use maven if you use maven you'll have to create the project at maven project in the first place, creating java projects as maven projects are the way to go anyway but that's for another post...

Method to Add new or update existing item in Dictionary

There's no problem. I would even remove the CreateNewOrUpdateExisting from the source and use map[key] = value directly in your code, because this this is much more readable, because developers would usually know what map[key] = value means.

Creating multiline strings in JavaScript

to sum up, I have tried 2 approaches listed here in user javascript programming (Opera 11.01):

So I recommend the working approach for Opera user JS users. Unlike what the author was saying:

It doesn't work on firefox or opera; only on IE, chrome and safari.

It DOES work in Opera 11. At least in user JS scripts. Too bad I can't comment on individual answers or upvote the answer, I'd do it immediately. If possible, someone with higher privileges please do it for me.

How to manually send HTTP POST requests from Firefox or Chrome browser?

You could also use Watir or Watin to automate browsers. Watir is written for ruby and Watin is for .Net languages. Not sure if it's what you are looking for though.

Nested classes' scope?

All explanations can be found in Python Documentation The Python Tutorial

For your first error <type 'exceptions.NameError'>: name 'outer_var' is not defined. The explanation is:

There is no shorthand for referencing data attributes (or other methods!) from within methods. I find that this actually increases the readability of methods: there is no chance of confusing local variables and instance variables when glancing through a method.

quoted from The Python Tutorial 9.4

For your second error <type 'exceptions.NameError'>: name 'OuterClass' is not defined

When a class definition is left normally (via the end), a class object is created.

quoted from The Python Tutorial 9.3.1

So when you try inner_var = Outerclass.outer_var, the Quterclass hasn't been created yet, that's why name 'OuterClass' is not defined

A more detailed but tedious explanation for your first error:

Although classes have access to enclosing functions’ scopes, though, they do not act as enclosing scopes to code nested within the class: Python searches enclosing functions for referenced names, but never any enclosing classes. That is, a class is a local scope and has access to enclosing local scopes, but it does not serve as an enclosing local scope to further nested code.

quoted from Learning.Python(5th).Mark.Lutz

Find specific string in a text file with VBS script

Wow, after few attempts I finally figured out how to deal with my text edits in vbs. The code works perfectly, it gives me the result I was expecting. Maybe it's not the best way to do this, but it does its job. Here's the code:

Option Explicit

Dim StdIn:  Set StdIn = WScript.StdIn
Dim StdOut: Set StdOut = WScript


Main()

Sub Main()

Dim objFSO, filepath, objInputFile, tmpStr, ForWriting, ForReading, count, text, objOutputFile, index, TSGlobalPath, foundFirstMatch
Set objFSO = CreateObject("Scripting.FileSystemObject")
TSGlobalPath = "C:\VBS\TestSuiteGlobal\Test suite Dispatch Decimal - Global.txt"
ForReading = 1
ForWriting = 2
Set objInputFile = objFSO.OpenTextFile(TSGlobalPath, ForReading, False)
count = 7
text=""
foundFirstMatch = false

Do until objInputFile.AtEndOfStream
    tmpStr = objInputFile.ReadLine
    If foundStrMatch(tmpStr)=true Then
        If foundFirstMatch = false Then
            index = getIndex(tmpStr)
            foundFirstMatch = true
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
        If index = getIndex(tmpStr) Then
            text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
        ElseIf index < getIndex(tmpStr) Then
            index = getIndex(tmpStr)
            text = text & vbCrLf & textSubstitution(tmpStr,index,"true")
        End If
    Else
        text = text & vbCrLf & textSubstitution(tmpStr,index,"false")
    End If
Loop
Set objOutputFile = objFSO.CreateTextFile("C:\VBS\NuovaProva.txt", ForWriting, true)
objOutputFile.Write(text)
End Sub


Function textSubstitution(tmpStr,index,foundMatch)
Dim strToAdd
strToAdd = "<tr><td><a href=" & chr(34) & "../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC" & CStr(index) & ".html" & chr(34) & ">Beginning_of_CF5.0_Features_TC" & CStr(index) & "</a></td></tr>"
If foundMatch = "false" Then
    textSubstitution = tmpStr
ElseIf foundMatch = "true" Then
    textSubstitution = strToAdd & vbCrLf & tmpStr
End If
End Function


Function getIndex(tmpStr)
Dim substrToFind, charAtPos, char1, char2
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
charAtPos = len(substrToFind) + 1
char1 = Mid(tmpStr, charAtPos, 1)
char2 = Mid(tmpStr, charAtPos+1, 1)
If IsNumeric(char2) Then
    getIndex = CInt(char1 & char2)
Else
    getIndex = CInt(char1)
End If
End Function

Function foundStrMatch(tmpStr)
Dim substrToFind
substrToFind = "<tr><td><a href=" & chr(34) & "../Test case "
If InStr(tmpStr, substrToFind) > 0 Then
    foundStrMatch = true
Else
    foundStrMatch = false
End If
End Function

This is the original txt file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

And this is the result I'm expecting

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <meta content="text/html; charset=UTF-8" http-equiv="content-type" />
  <title>Test Suite</title>
</head>
<body>
<table id="suiteTable" cellpadding="1" cellspacing="1" border="1" class="selenium"><tbody>
<tr><td><b>Test Suite</b></td></tr>
<tr><td><a href="../../Component/TC_Environment_setting">TC_Environment_setting</a></td></tr>
<tr><td><a href="../../Component/TC_Set_variables">TC_Set_variables</a></td></tr>
<tr><td><a href="../../Component/TC_Set_ID">TC_Set_ID</a></td></tr>
<tr><td><a href="../../Login/Log_in_Admin">Log_in_Admin</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC5.html">Beginning_of_CF5.0_Features_TC5</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 5 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../Test case 5 DD/FormEND">FormEND</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC6.html">Beginning_of_CF5.0_Features_TC6</a></td></tr>
<tr><td><a href="../Test case 6 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../Test case 6 DD/contrD1">contrD1</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1B1">Log_ in_U1B1</a></td></tr>
<tr><td><a href="../../Component/Search&OpenApp">Search&OpenApp</a></td></tr>
<tr><td><a href="../../Component/Controllo END">Controllo END</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Login/Log_ in_U1A1">Log_ in_U1A1</a></td></tr>
<tr><td><a href="../../Logs/CF5.0_Features/Beginning_of_CF5.0_Features_TC7.html">Beginning_of_CF5.0_Features_TC7</a></td></tr>
<tr><td><a href="../Test case 7 DD/Form1">Form1</a></td></tr>
<tr><td><a href="../../Component/Controllo DeadLetter">Controllo DeadLetter</a></td></tr>
<tr><td><a href="../../Login/Logout">Logout</a></td></tr>
<tr><td><a href="../../Component/Set_Roles_Dispatch_Decimal">Set_Roles_Dispatch_Decimal</a></td></tr>
<tr><td><a href="../../Login/Logout_BAC">Logout_BAC</a></td></tr>
</tbody></table>
</body>
</html>

Reload an iframe with jQuery

If the iframe was not on a different domain, you could do something like this:

document.getElementById(FrameID).contentDocument.location.reload(true);

But since the iframe is on a different domain, you will be denied access to the iframe's contentDocument property by the same-origin policy.

But you can hackishly force the cross-domain iframe to reload if your code is running on the iframe's parent page, by setting it's src attribute to itself. Like this:

// hackishly force iframe to reload
var iframe = document.getElementById(FrameId);
iframe.src = iframe.src;

If you are trying to reload the iframe from another iframe, you are out of luck, that is not possible.

Hide particular div onload and then show div after click

This is an easier way to do it. Hope this helps...

<script type="text/javascript">
$(document).ready(function () {
    $("#preview").toggle(function() {
        $("#div1").hide();
        $("#div2").show();
    }, function() {
        $("#div1").show();
        $("#div2").hide();
    });
});

<div id="div1">
This is preview Div1. This is preview Div1.
</div>

<div id="div2" style="display:none;">
This is preview Div2 to show after div 1 hides.
</div>

<div id="preview" style="color:#999999; font-size:14px">
PREVIEW
</div>
  • If you want the div to be hidden on load, make the style display:none
  • Use toggle rather than click function.


Links:

JQuery Tutorials

JQuery References

Is it possible to use Visual Studio on macOS?

While Parallels is technically a VM it is capable of running games in high resolution at a high frame rate. If you run Parallels in Coherence mode it completely integrates Windows 7 into OS X and .Net framework is fully supported. So yes you can install Visual Studio on your Mac however the Apps you created would only run of windows computers unless they were web based.

Transposing a 2D-array in JavaScript

Just another variation using Array.map. Using indexes allows to transpose matrices where M != N:

// Get just the first row to iterate columns first
var t = matrix[0].map(function (col, c) {
    // For each column, iterate all rows
    return matrix.map(function (row, r) { 
        return matrix[r][c]; 
    }); 
});

All there is to transposing is mapping the elements column-first, and then by row.

How to parse a string in JavaScript?

Use split on string:

var array = coolVar.split(/-/);

How can I clone a private GitLab repository?

If you are using Windows,

  1. make a folder and open git bash from there

  2. in the git bash,

    git clone [email protected]:Example/projectName.git

What is InputStream & Output Stream? Why and when do we use them?

InputStream is used for reading, OutputStream for writing. They are connected as decorators to one another such that you can read/write all different types of data from all different types of sources.

For example, you can write primitive data to a file:

File file = new File("C:/text.bin");
file.createNewFile();
DataOutputStream stream = new DataOutputStream(new FileOutputStream(file));
stream.writeBoolean(true);
stream.writeInt(1234);
stream.close();

To read the written contents:

File file = new File("C:/text.bin");
DataInputStream stream = new DataInputStream(new FileInputStream(file));
boolean isTrue = stream.readBoolean();
int value = stream.readInt();
stream.close();
System.out.printlin(isTrue + " " + value);

You can use other types of streams to enhance the reading/writing. For example, you can introduce a buffer for efficiency:

DataInputStream stream = new DataInputStream(
    new BufferedInputStream(new FileInputStream(file)));

You can write other data such as objects:

MyClass myObject = new MyClass(); // MyClass have to implement Serializable
ObjectOutputStream stream = new ObjectOutputStream(
    new FileOutputStream("C:/text.obj"));
stream.writeObject(myObject);
stream.close();

You can read from other different input sources:

byte[] test = new byte[] {0, 0, 1, 0, 0, 0, 1, 1, 8, 9};
DataInputStream stream = new DataInputStream(new ByteArrayInputStream(test));
int value0 = stream.readInt();
int value1 = stream.readInt();
byte value2 = stream.readByte();
byte value3 = stream.readByte();
stream.close();
System.out.println(value0 + " " + value1 + " " + value2 + " " + value3);

For most input streams there is an output stream, also. You can define your own streams to reading/writing special things and there are complex streams for reading complex things (for example there are Streams for reading/writing ZIP format).

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

How do I remove the first characters of a specific column in a table?

The Complete thing

DECLARE @v varchar(10)

SET @v='#temp'

select STUFF(@v, 1, 1, '')
WHERE LEFT(@v,1)='#'

How to install pip for Python 3.6 on Ubuntu 16.10?

In at least in ubuntu 16.10, the default python3 is python3.5. As such, all of the python3-X packages will be installed for python3.5 and not for python3.6.

You can verify this by checking the shebang of pip3:

$ head -n1 $(which pip3)
#!/usr/bin/python3

Fortunately, the pip installed by the python3-pip package is installed into the "shared" /usr/lib/python3/dist-packages such that python3.6 can also take advantage of it.

You can install packages for python3.6 by doing:

python3.6 -m pip install ...

For example:

$ python3.6 -m pip install requests
$ python3.6 -c 'import requests; print(requests.__file__)'
/usr/local/lib/python3.6/dist-packages/requests/__init__.py

MySQL timestamp select date range

If you have a mysql timestamp, something like 2013-09-29 22:27:10 you can do this

 select * from table WHERE MONTH(FROM_UNIXTIME(UNIX_TIMESTAMP(time)))=9;

Convert to unix, then use the unix time functions to extract the month, in this case 9 for september.

How to check whether a variable is a class or not?

class Foo: is called old style class and class X(object): is called new style class.

Check this What is the difference between old style and new style classes in Python? . New style is recommended. Read about "unifying types and classes"

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

CABForum Baseline Requirements

I see no one has mentioned the section in the Baseline Requirements yet. I feel they are important.

Q: SSL - How do Common Names (CN) and Subject Alternative Names (SAN) work together?
A: Not at all. If there are SANs, then CN can be ignored. -- At least if the software that does the checking adheres very strictly to the CABForum's Baseline Requirements.

(So this means I can't answer the "Edit" to your question. Only the original question.)

CABForum Baseline Requirements, v. 1.2.5 (as of 2 April 2015), page 9-10:

9.2.2 Subject Distinguished Name Fields
a. Subject Common Name Field
Certificate Field: subject:commonName (OID 2.5.4.3)
Required/Optional: Deprecated (Discouraged, but not prohibited)
Contents: If present, this field MUST contain a single IP address or Fully-Qualified Domain Name that is one of the values contained in the Certificate’s subjectAltName extension (see Section 9.2.1).

EDIT: Links from @Bruno's comment

RFC 2818: HTTP Over TLS, 2000, Section 3.1: Server Identity:

If a subjectAltName extension of type dNSName is present, that MUST be used as the identity. Otherwise, the (most specific) Common Name field in the Subject field of the certificate MUST be used. Although the use of the Common Name is existing practice, it is deprecated and Certification Authorities are encouraged to use the dNSName instead.

RFC 6125: Representation and Verification of Domain-Based Application Service Identity within Internet Public Key Infrastructure Using X.509 (PKIX) Certificates in the Context of Transport Layer Security (TLS), 2011, Section 6.4.4: Checking of Common Names:

[...] if and only if the presented identifiers do not include a DNS-ID, SRV-ID, URI-ID, or any application-specific identifier types supported by the client, then the client MAY as a last resort check for a string whose form matches that of a fully qualified DNS domain name in a Common Name field of the subject field (i.e., a CN-ID).

Want to show/hide div based on dropdown box selection

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    $('#purpose').on('change', function() {
      if ( this.value == '1')
      //.....................^.......
      {
           $("#business_new").hide();
        $("#business").show();
      }
      else  if ( this.value == '2')
      {
          $("#business").hide();
        $("#business_new").show();
      }
       else  
      {
        $("#business").hide();
      }
    });
});
</script>
<body>
<select id='purpose'>
<option value="0">Personal use</option>
<option value="1">Business use</option>
<option value="2">Passing on to a client</option>
</select>
<div style='display:none;' id='business'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
<div style='display:none;' id='business_new'>Business Name<br/>&nbsp;
<br/>&nbsp;
    <input type='text' class='text' name='business' value="1254" size='20' />
    <input type='text' class='text' name='business' value size='20' />
    <br/>
</div>
</body>

What are the "spec.ts" files generated by Angular CLI for?

.spec.ts file is used for unit testing of your application.

If you don't to get it generated just use --spec=false while creating new Component. Like this

ng generate component --spec=false mycomponentName

How do you simulate Mouse Click in C#?

I have tried the code that Marcos posted and it didn't worked for me. Whatever i was given to the Y coordinate the cursor didn't moved on Y axis. The code below will work if you want the position of the cursor relative to the left-up corner of your desktop, not relative to your application.

    [DllImport("user32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall)]
    public static extern void mouse_event(long dwFlags, long dx, long dy, long cButtons, long dwExtraInfo);
    private const int MOUSEEVENTF_LEFTDOWN = 0x02;
    private const int MOUSEEVENTF_LEFTUP = 0x04;
    private const int MOUSEEVENTF_MOVE = 0x0001;

    public void DoMouseClick()
    {
        X = Cursor.Position.X;
        Y = Cursor.Position.Y;

        //move to coordinates
        pt = (Point)pc.ConvertFromString(X + "," + Y);
        Cursor.Position = pt;       

        //perform click            
        mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);
        mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
    }

I only use mouse_event function to actually perform the click. You can give X and Y what coordinates you want, i used values from textbox:

            X = Convert.ToInt32(tbX.Text);
            Y = Convert.ToInt32(tbY.Text);

Oracle date to string conversion

Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL

AWK: Access captured group from line pattern

You can simulate capturing in vanilla awk too, without extensions. Its not intuitive though:

step 1. use gensub to surround matches with some character that doesnt appear in your string. step 2. Use split against the character. step 3. Every other element in the splitted array is your capture group.

$ echo 'ab cb ad' | awk '{ split(gensub(/a./,SUBSEP"&"SUBSEP,"g",$0),cap,SUBSEP); print cap[2]"|" cap[4] ; }'
ab|ad

Why is __dirname not defined in node REPL?

If you got node __dirname not defined with node --experimental-modules, you can do :

const __dirname = path.dirname(import.meta.url)
                      .replace(/^file:\/\/\//, '') // can be usefull

Because othe example, work only with current/pwd directory not other directory.

how to find 2d array size in c++

Use an std::vector.

std::vector< std::vector<int> > my_array; /* 2D Array */

my_array.size(); /* size of y */
my_array[0].size(); /* size of x */

Or, if you can only use a good ol' array, you can use sizeof.

sizeof( my_array ); /* y size */
sizeof( my_array[0] ); /* x size */

How do I make a composite key with SQL Server Management Studio?

create table my_table (
    id_part1 int not null,
    id_part2 int not null,
    primary key (id_part1, id_part2)
)

Looping through all the properties of object php

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

How to set image width to be 100% and height to be auto in react native?

Solution April 2020:

So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.

To have a truly responsive (i.e. width: 100%, height: auto) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.

Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.

So all we need to do is create a View with width: "100%", then use onLayout to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.

 

Just show me the code...

The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.

JavaScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";

const ResponsiveImage = props => {
  const [containerWidth, setContainerWidth] = useState(0);
  const _onViewLayoutChange = event => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

 

TypeScript:

// ResponsiveImage.ts

import React, { useMemo, useState } from "react";
import {
  Image,
  ImageSourcePropType,
  LayoutChangeEvent,
  StyleSheet,
  View
} from "react-native";

interface ResponsiveImageProps {
  src: ImageSourcePropType;
  srcWidth: number;
  srcHeight: number;
}

const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
  const [containerWidth, setContainerWidth] = useState<number>(0);
  const _onViewLayoutChange = (event: LayoutChangeEvent) => {
    const { width } = event.nativeEvent.layout;
    setContainerWidth(width);
  }

  const imageStyles = useMemo(() => {
    const ratio = containerWidth / props.srcWidth;
    return {
      width: containerWidth,
      height: props.srcHeight * ratio
    };
  }, [containerWidth]);

  return (
    <View style={styles.container} onLayout={_onViewLayoutChange}>
      <Image source={props.src} style={imageStyles} />
    </View>
  );
};

const styles = StyleSheet.create({
  container: { width: "100%" }
});

export default ResponsiveImage;


// Example usage...

import ResponsiveImage from "../components/ResponsiveImage";

...

<ResponsiveImage
  src={require("./images/your-image.jpg")}
  srcWidth={910} // replace with your image width
  srcHeight={628} // replace with your image height
/>

filter out multiple criteria using excel vba

This works for me: This is a criteria over two fields/columns (9 and 10), this filters rows with values >0 on column 9 and rows with values 4, 7, and 8 on column 10. lastrow is the number of rows on the data section.

ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=9, Criteria1:=">0", Operator:=xlAnd
ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=10, Criteria1:=Arr("4","7","8"), Operator:=xlFilterValues

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

Get input type="file" value when it has multiple files selected

The files selected are stored in an array: [input].files

For example, you can access the items

// assuming there is a file input with the ID `my-input`...
var files = document.getElementById("my-input").files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

For jQuery-comfortable people, it's similarly easy

// assuming there is a file input with the ID `my-input`...
var files = $("#my-input")[0].files;

for (var i = 0; i < files.length; i++)
{
 alert(files[i].name);
}

How to reset settings in Visual Studio Code?

The best easiest way I found to reset settings:

Open Settings page (Ctrl+Shift+P):

enter image description here

Go onto your desire setting section to reset, click on icon and then Reset Setting :

enter image description here

Date minus 1 year?

Using the DateTime object...

$time = new DateTime('2099-01-01');
$newtime = $time->modify('-1 year')->format('Y-m-d');

Or using now for today

$time = new DateTime('now');
$newtime = $time->modify('-1 year')->format('Y-m-d');

How do I write data to csv file in columns and rows from a list in python?

Have a go with these code:

>>> import pyexcel as pe
>>> sheet = pe.Sheet(data)
>>> data=[[1, 2], [2, 3], [4, 5]]
>>> sheet
Sheet Name: pyexcel
+---+---+
| 1 | 2 |
+---+---+
| 2 | 3 |
+---+---+
| 4 | 5 |
+---+---+
>>> sheet.save_as("one.csv")
>>> b = [[126, 125, 123, 122, 123, 125, 128, 127, 128, 129, 130, 130, 128, 126, 124, 126, 126, 128, 129, 130, 130, 130, 130, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 132, 134, 134, 134, 134, 134, 134, 134, 134, 133, 134, 135, 134, 133, 133, 134, 135, 136], [135, 135, 136, 137, 137, 136, 134, 135, 135, 135, 134, 134, 133, 133, 133, 134, 134, 134, 133, 133, 132, 132, 132, 135, 135, 133, 133, 133, 133, 135, 135, 131, 135, 136, 134, 133, 136, 137, 136, 133, 134, 135, 136, 136, 135, 134, 133, 133, 134, 135, 136, 136, 136, 135, 134, 135, 138, 138, 135, 135, 138, 138, 135, 139], [137, 135, 136, 138, 139, 137, 135, 142, 139, 137, 139, 138, 136, 137, 141, 138, 138, 139, 139, 139, 139, 138, 138, 138, 138, 137, 137, 137, 137, 138, 138, 136, 137, 137, 137, 137, 137, 137, 138, 148, 144, 140, 138, 137, 138, 138, 138, 137, 137, 137, 137, 137, 138, 139, 140, 141, 141, 141, 141, 141, 141, 141, 141, 141], [141, 141, 141, 141, 141, 141, 141, 139, 139, 139, 140, 140, 141, 141, 141, 140, 140, 140, 140, 140, 141, 142, 143, 138, 138, 138, 139, 139, 140, 140, 140, 141, 140, 139, 139, 141, 141, 140, 139, 145, 137, 137, 145, 145, 137, 137, 144, 141, 139, 146, 134, 145, 140, 149, 144, 145, 142, 140, 141, 144, 145, 142, 139, 140]]
>>> s2 = pe.Sheet(b)
>>> s2
Sheet Name: pyexcel
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 126 | 125 | 123 | 122 | 123 | 125 | 128 | 127 | 128 | 129 | 130 | 130 | 128 | 126 | 124 | 126 | 126 | 128 | 129 | 130 | 130 | 130 | 130 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 132 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 134 | 133 | 134 | 135 | 134 | 133 | 133 | 134 | 135 | 136 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 135 | 135 | 136 | 137 | 137 | 136 | 134 | 135 | 135 | 135 | 134 | 134 | 133 | 133 | 133 | 134 | 134 | 134 | 133 | 133 | 132 | 132 | 132 | 135 | 135 | 133 | 133 | 133 | 133 | 135 | 135 | 131 | 135 | 136 | 134 | 133 | 136 | 137 | 136 | 133 | 134 | 135 | 136 | 136 | 135 | 134 | 133 | 133 | 134 | 135 | 136 | 136 | 136 | 135 | 134 | 135 | 138 | 138 | 135 | 135 | 138 | 138 | 135 | 139 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 137 | 135 | 136 | 138 | 139 | 137 | 135 | 142 | 139 | 137 | 139 | 138 | 136 | 137 | 141 | 138 | 138 | 139 | 139 | 139 | 139 | 138 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 138 | 138 | 136 | 137 | 137 | 137 | 137 | 137 | 137 | 138 | 148 | 144 | 140 | 138 | 137 | 138 | 138 | 138 | 137 | 137 | 137 | 137 | 137 | 138 | 139 | 140 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 | 141 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
| 141 | 141 | 141 | 141 | 141 | 141 | 141 | 139 | 139 | 139 | 140 | 140 | 141 | 141 | 141 | 140 | 140 | 140 | 140 | 140 | 141 | 142 | 143 | 138 | 138 | 138 | 139 | 139 | 140 | 140 | 140 | 141 | 140 | 139 | 139 | 141 | 141 | 140 | 139 | 145 | 137 | 137 | 145 | 145 | 137 | 137 | 144 | 141 | 139 | 146 | 134 | 145 | 140 | 149 | 144 | 145 | 142 | 140 | 141 | 144 | 145 | 142 | 139 | 140 |
+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+-----+
>>> s2[0,0]
126
>>> s2.save_as("two.csv")

Python: How to get values of an array at certain index positions?

You can use index arrays, simply pass your ind_pos as an index argument as below:

a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])

print(a[ind_pos])
# [88,85,16]

Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).

How to convert .pem into .key?

If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.

See this SO question/answer for more details on the SSL options in that file.

Why is SSLCertificateKeyFile needed for Apache?

Convert string to int if string is a number

Just use Val():

currentLoad = Int(Val([f4]))

Now currentLoad has a integer value, zero if [f4] is not numeric.

What is the email subject length limit?

What's important is which mechanism you are using the send the email. Most modern libraries (i.e. System.Net.Mail) will hide the folding from you. You just put a very long email subject line in without (CR,LF,HTAB). If you start trying to do your own folding all bets are off. It will start reporting errors. So if you are having this issue just filter out the CR,LF,HTAB and let the library do the work for you. You can usually also set the encoding text type as a separate field. No need for iso encoding in the subject line.

Path to MSBuild

If you want to use MSBuild for .Net 4 then you can use the following PowerShell command to get the executable's path. If you want version 2.0 or 3.5 then just change the $dotNetVersion variable.

To run the executable you'll need to prepend the $msbuild variable with &. That will execute the variable.

# valid versions are [2.0, 3.5, 4.0]
$dotNetVersion = "4.0"
$regKey = "HKLM:\software\Microsoft\MSBuild\ToolsVersions\$dotNetVersion"
$regProperty = "MSBuildToolsPath"

$msbuildExe = join-path -path (Get-ItemProperty $regKey).$regProperty -childpath "msbuild.exe"

&$msbuildExe

Random float number generation

#include <cstdint>
#include <cstdlib>
#include <ctime>

using namespace std;

/* single precision float offers 24bit worth of linear distance from 1.0f to 0.0f */
float getval() {
    /* rand() has min 16bit, but we need a 24bit random number. */
    uint_least32_t r = (rand() & 0xffff) + ((rand() & 0x00ff) << 16);
    /* 5.9604645E-8 is (1f - 0.99999994f), 0.99999994f is the first value less than 1f. */
    return (double)r * 5.9604645E-8;
}

int main()
{
    srand(time(NULL));
...

I couldn't post two answers, so here is the second solution. log2 random numbers, massive bias towards 0.0f but it's truly a random float 1.0f to 0.0f.

#include <cstdint>
#include <cstdlib>
#include <ctime>

using namespace std;

float getval () {
    union UNION {
        uint32_t i;
        float f;
    } r;
    /* 3 because it's 0011, the first bit is the float's sign.
     * Clearing the second bit eliminates values > 1.0f.
     */
    r.i = (rand () & 0xffff) + ((rand () & 0x3fff) << 16);
    return r.f;
}

int main ()
{
    srand (time (NULL));
...

Auto-click button element on page load using jQuery

You would simply use jQuery like so...

<script>
jQuery(function(){
   jQuery('#modal').click();
});
</script>

Use the click function to auto-click the #modal button

PHP JSON String, escape Double Quotes for JS output

I succefully just did this :

$json = str_replace("\u0022","\\\\\"",json_encode( $phpArray,JSON_HEX_QUOT)); 

json_encode() by default will escape " to \" . But it's still wrong JSON for json.PARSE(). So by adding option JSON_HEX_QUOT, json_encode() will replace " with \u0022. json.PARSE() still will not like \u0022. So then we need to replace \u0022 with \\". The \\\\\" is escaped \\".

NOTE : you can add option JSON_HEX_APOS to replace single quote with unicode HEX value if you have javascript single quote issue.

ex: json_encode( $phpArray, JSON_HEX_APOS|JSON_HEX_QUOT ));

How to download a Nuget package without nuget.exe or Visual Studio extension?

I haven't tried it yet, but it looks like NuGet Package Explorer should be able to do it:

https://github.com/NuGetPackageExplorer/NuGetPackageExplorer

NuGet Package Explorer

(or like Colonel Panic says, 7-zip should probably do it)

How do I configure Apache 2 to run Perl CGI scripts?

As of Ubuntu 12.04 (Precise Pangolin) (and perhaps a release or two before) simply installing apache2 and mod-perl via Synaptic and placing your CGI scripts in /usr/lib/cgi-bin is really all you need to do.

How do I update an entity using spring-data-jpa?

This is how I solved the problem:

User inbound = ...
User existing = userRepository.findByFirstname(inbound.getFirstname());
if(existing != null) inbound.setId(existing.getId());
userRepository.save(inbound);

How can I make the computer beep in C#?

You can also use the relatively unused:

    System.Media.SystemSounds.Beep.Play();
    System.Media.SystemSounds.Asterisk.Play();
    System.Media.SystemSounds.Exclamation.Play();
    System.Media.SystemSounds.Question.Play();
    System.Media.SystemSounds.Hand.Play();

Documentation for this sounds is available in http://msdn.microsoft.com/en-us/library/system.media.systemsounds(v=vs.110).aspx

What are valid values for the id attribute in HTML?

Strictly it should match

[A-Za-z][-A-Za-z0-9_:.]*

But jquery seems to have problems with colons so it might be better to avoid them.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

How to sort findAll Doctrine's method?

It's useful to look at source code sometimes.

For example findAll implementation is very simple (vendor/doctrine/orm/lib/Doctrine/ORM/EntityRepository.php):

public function findAll()
{
    return $this->findBy(array());
}

So we look at findBy and find what we need (orderBy)

public function findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)

jquery live hover

This code works:

    $(".ui-button-text").live(
        'hover',
        function (ev) {
            if (ev.type == 'mouseover') {
                $(this).addClass("ui-state-hover");
            }

            if (ev.type == 'mouseout') {
                $(this).removeClass("ui-state-hover");
            }
        });

JVM heap parameters

Apart from standard Heap parameters -Xms and -Xmx it's also good to know -XX:PermSize and -XX:MaxPermSize, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

Just add AsEnumerable() andToList() , so it looks like this

db.Favorites
    .Where(x => x.userId == userId)
    .Join(db.Person, x => x.personId, y => y.personId, (x, y).ToList().AsEnumerable()

ToList().AsEnumerable()

Insert text into textarea with jQuery

I used that and it work fine :)

$("#textarea").html("Put here your content");

Remi

How do I migrate an SVN repository with history to a new Git repository?

I highly recommend this short series of screencasts I just discovered. The author walks you through the basic operations, and showcases some more advanced usages.

Shuffle DataFrame rows

You can simply use sklearn for this

from sklearn.utils import shuffle
df = shuffle(df)

Does Eclipse have line-wrap

Update 2016

As mentioned by ralfstx's answer, Eclipse 4.6 M4 Neon (or more) has a word-wrap feature!
(Nov 2015, for release mid 2016). In any editor view, type:

Alt+Shift+Y

https://www.eclipse.org/eclipse/news/4.6/M4/images/word-wrap.png

(Sadik confirms in the comments it works with Eclipse 2019-09)

By default, text editors are opened with word wrap disabled.
This can be changed with the Enable word wrap when opening an editor option on the General > Editors > Text Editors preference page.

Manually toggle word wrap by clicking in the editor window and pressing (Shift+Alt+Y).
On Mac OS X, press (Cmd-Opt-Y). [Updated May 2017]

The famous bug 35779 is finally closed by r/#/c/61972/ last November.

There are however a few new bugs:

As long as we are unable to provide acceptable editor performance for big files after toggling editor word wrap state on, we should make sure users can't set WW preference 1 always on by default and wonder why the editors are slow during resizing/zooming.

(2020) MarcGuay adds in the comments:

If you want the wrapping to be persistent/automatic, the cdhq plugin seems to still work with the 2019-03 version of Eclipse.
After installing you can turn it on via Window->Preferences->Word Wrap.


Update 2014

The de.cdhq.eclipse.wordwrap Word-Wrap Eclipse plug-in just got updated, and does provide good wrapping, as illustrated in the project page:

http://dev.cdhq.de/eclipse/word-wrap/img/01_wrappingOff.gifhttp://dev.cdhq.de/eclipse/word-wrap/img/02_wrappingOn_full.gif


Original answer May 2010

Try the Eclipse Word-Wrap Plug-In here.

Just for the record, while Eclipse Colorer might bring wrapping for xml files, Eclipse has not in general a soft wrapping feature for Text editor.

Soft and hard. Soft will just warp the text at the right window border without adding new line numbers (so there are gaps in the list of numbers when you enable them).

This is one of the most upvoted bugs in Eclipse history: bug 35779 (9 years and counting, 200+ votes)

Update February 2013:

That bug references an old Word wrap plugin, but Oak mentions in his answer (upvoted) a new plugin for recent (Juno+) versions of Eclipse (so 3.8.x, 4.x, may have been seen working with 3.7)
That plugin is from Florian Weßling, who just updated it (March 2013)

Right click in an opened file and select "Toggle Word Wrap" (shortcut ctrl+alt+e)

before
words wrapped

MySQL - Replace Character in Columns

If you have "something" and need 'something', use replace(col, "\"", "\'") and viceversa.

Display string as html in asp.net mvc view

I had a similar problem recently, and google landed me here, so I put this answer here in case others land here as well, for completeness.

I noticed that when I had badly formatted html, I was actually having all my html tags stripped out, with just the non-tag content remaining. I particularly had a table with a missing opening table tag, and then all my html tags from the entire string where ripped out completely.

So, if the above doesn't work, and you're still scratching your head, then also check you html for being valid.

I notice even after I got it working, MVC was adding tbody tags where I had none. This tells me there is clean up happening (MVC 5), and that when it can't happen, it strips out all/some tags.

Using FolderBrowserDialog in WPF application

If I'm not mistaken you're looking for the FolderBrowserDialog (hence the naming):

var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();

Also see this SO thread: Open directory dialog

Can I obtain method parameter name using Java reflection?

Yes.
Code must be compiled with Java 8 compliant compiler with option to store formal parameter names turned on (-parameters option).
Then this code snippet should work:

Class<String> clz = String.class;
for (Method m : clz.getDeclaredMethods()) {
   System.err.println(m.getName());
   for (Parameter p : m.getParameters()) {
    System.err.println("  " + p.getName());
   }
}

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

java.lang.NoSuchMethodError: javax.servlet.ServletContext.getContextPath()Ljava/lang/String;

That method was added in Servlet 2.5.

So this problem can have at least 3 causes:

  1. The servlet container does not support Servlet 2.5.
  2. The web.xml is not declared conform Servlet 2.5 or newer.
  3. The webapp's runtime classpath is littered with servlet container specific JAR files of a different servlet container make/version which does not support Servlet 2.5.

To solve it,

  1. Make sure that your servlet container supports at least Servlet 2.5. That are at least Tomcat 6, Glassfish 2, JBoss AS 4.1, etcetera. Tomcat 5.5 for example supports at highest Servlet 2.4. If you can't upgrade Tomcat, then you'd need to downgrade Spring to a Servlet 2.4 compatible version.
  2. Make sure that the root declaration of web.xml complies Servlet 2.5 (or newer, at least the highest whatever your target runtime supports). For an example, see also somewhere halfway our servlets wiki page.
  3. Make sure that you don't have any servlet container specific libraries like servlet-api.jar or j2ee.jar in /WEB-INF/lib or even worse, the JRE/lib or JRE/lib/ext. They do not belong there. This is a pretty common beginner's mistake in an attempt to circumvent compilation errors in an IDE, see also How do I import the javax.servlet API in my Eclipse project?.

How to make blinking/flashing text with CSS 3

enter image description here

.neon {
  font-size: 20px;
  color: #fff;
  text-shadow: 0 0 8px yellow;
  animation: blinker 6s;
  animation-iteration-count: 1;
}
@keyframes blinker {
  0% {
    opacity: 0.2;
  }
  19% {
    opacity: 0.2;
  }
  20% {
    opacity: 1;
  }
  21% {
    opacity: 1;
  }
  22% {
    opacity: 0.2;
  }
  23% {
    opacity: 0.2;
  }
  36% {
    opacity: 0.2;
  }
  40% {
    opacity: 1;
  }
  41% {
    opacity: 0;
  }
  42% {
    opacity: 1;
  }
  43% {
    opacity: 0.5;
  }
  50% {
    opacity: 1;
  }
  100% {
    opacity: 1;
  }
}

I used font-family: "Quicksand", sans-serif;

This is the import of the font (goes in the top of the style.css)

@import url("https://fonts.googleapis.com/css2?family=Quicksand:wght@300&display=swap");

Microsoft Visual C++ Compiler for Python 3.4

Unfortunately to be able to use the extension modules provided by others you'll be forced to use the official compiler to compile Python. These are:

Alternatively, you can use MinGw to compile extensions in a way that won't depend on others.

See: https://docs.python.org/2/install/#gnu-c-cygwin-MinGW or https://docs.python.org/3.4/install/#gnu-c-cygwin-mingw

This allows you to have one compiler to build your extensions for both versions of Python, Python 2.x and Python 3.x.

CSS :not(:last-child):after selector

Remove the : before last-child and the :after and used

 ul li:not(last-child){
 content:' |';
}

Hopefully,it should work

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

What is a good game engine that uses Lua?

There's our IDE / engine called Codea.

The runtime is iOS only, but it's open source. The development environment is iPad only at the moment.

How to set a default value for an existing column

Try following command;

ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

If the text is retrieved from a mysql database you may try adding this after BD connection.

mysqli_set_charset($con, "utf8");

https://www.php.net/manual/en/mysqli.set-charset.php

Can anyone explain what JSONP is, in layman terms?

JSONP is a way of getting around the browser's same-origin policy. How? Like this:

enter image description here

The goal here is to make a request to otherdomain.com and alert the name in the response. Normally we'd make an AJAX request:

$.get('otherdomain.com', function (response) {
  var name = response.name;
  alert(name);
});

However, since the request is going out to a different domain, it won't work.

We can make the request using a <script> tag though. Both <script src="otherdomain.com"></script> and $.get('otherdomain.com') will result in the same request being made:

GET otherdomain.com

Q: But if we use the <script> tag, how could we access the response? We need to access it if we want to alert it.

A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.

Q: But what if the server won't do this for us, and is only willing to return JSON to us?

A: Then we won't be able to use it. JSONP requires the server to cooperate.

Q: Having to use a <script> tag is ugly.

A: Libraries like jQuery make it nicer. Ex:

$.ajax({
    url: "http://otherdomain.com",
    jsonp: "callback",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response );
    }
});

It works by dynamically creating the <script> tag DOM element.

Q: <script> tags only make GET requests - what if we want to make a POST request?

A: Then JSONP won't work for us.

Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!

A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.

Combine two (or more) PDF's

This is something that I figured out, and wanted to share with you, using PdfSharp.

Here you can join multiple Pdfs in one, without the need of an output directory (following the input list order)

    public static byte[] MergePdf(List<byte[]> pdfs)
    {
        List<PdfSharp.Pdf.PdfDocument> lstDocuments = new List<PdfSharp.Pdf.PdfDocument>();
        foreach (var pdf in pdfs)
        {
            lstDocuments.Add(PdfReader.Open(new MemoryStream(pdf), PdfDocumentOpenMode.Import));
        }

        using (PdfSharp.Pdf.PdfDocument outPdf = new PdfSharp.Pdf.PdfDocument())
        { 
            for(int i = 1; i<= lstDocuments.Count; i++)
            {
                foreach(PdfSharp.Pdf.PdfPage page in lstDocuments[i-1].Pages)
                {
                    outPdf.AddPage(page);
                }
            }

            MemoryStream stream = new MemoryStream();
            outPdf.Save(stream, false);
            byte[] bytes = stream.ToArray();

            return bytes;
        }           
    }

What is the difference between private and protected members of C++ classes?

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.

Scheduled run of stored procedure on SQL server

Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.

How to turn off page breaks in Google Docs?

If You want to REMOVE page break from document

use Edit / Find-Replace \f with regex

If You want to TURN OFF (as You asked)

uncheck "Print Layout" from the "View" menu, but dotted lines will remain indicating page breaks

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

How to write LDAP query to test if user is member of a group?

You should be able to create a query with this filter here:

(&(objectClass=user)(sAMAccountName=yourUserName)
  (memberof=CN=YourGroup,OU=Users,DC=YourDomain,DC=com))

and when you run that against your LDAP server, if you get a result, your user "yourUserName" is indeed a member of the group "CN=YourGroup,OU=Users,DC=YourDomain,DC=com

Try and see if this works!

If you use C# / VB.Net and System.DirectoryServices, this snippet should do the trick:

DirectoryEntry rootEntry = new DirectoryEntry("LDAP://dc=yourcompany,dc=com");

DirectorySearcher srch = new DirectorySearcher(rootEntry);
srch.SearchScope = SearchScope.Subtree;

srch.Filter = "(&(objectClass=user)(sAMAccountName=yourusername)(memberOf=CN=yourgroup,OU=yourOU,DC=yourcompany,DC=com))";

SearchResultCollection res = srch.FindAll();

if(res == null || res.Count <= 0) {
    Console.WriteLine("This user is *NOT* member of that group");
} else {
    Console.WriteLine("This user is INDEED a member of that group");
}

Word of caution: this will only test for immediate group memberships, and it will not test for membership in what is called the "primary group" (usually "cn=Users") in your domain. It does not handle nested memberships, e.g. User A is member of Group A which is member of Group B - that fact that User A is really a member of Group B as well doesn't get reflected here.

Marc

Python - round up to the nearest ten

This will round down correctly as well:

>>> n = 46
>>> rem = n % 10
>>> if rem < 5:
...     n = int(n / 10) * 10
... else:
...     n = int((n + 10) / 10) * 10
...
>>> 50

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

I solved this error

A connection attempt failed with "ECONNREFUSED - Connection refused by server"

by changing my port to 22 that was successful

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

After update to macOS 10.13.3

After updating do macOS 10.13, I had to install "Command Line Tools (macOS 10.13) for Xcode 9.3" downloaded from https://developer.apple.com/download/more/

HQL "is null" And "!= null" on an Oracle column

If you do want to use null values with '=' or '<>' operators you may find the

answer from @egallardo hier

very useful.

Short example for '=': The expression

WHERE t.field = :param

you refactor like this

WHERE ((:param is null and t.field is null) or t.field = :param)

Now you can set the parameter param either to some non-null value or to null:

query.setParameter("param", "Hello World"); // Works
query.setParameter("param", null);          // Works also

SQL How to correctly set a date variable value and use it?

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

How do I enable logging for Spring Security?

By default Spring Security redirects user to the URL that he originally requested (/Load.do in your case) after login.

You can set always-use-default-target to true to disable this behavior:

 <security:http auto-config="true">

    <security:intercept-url pattern="/Admin**" access="hasRole('PROGRAMMER') or hasRole('ADMIN')"/>
    <security:form-login login-page="/Load.do"
        default-target-url="/Admin.do?m=loadAdminMain"
        authentication-failure-url="/Load.do?error=true"
        always-use-default-target = "true"
        username-parameter="j_username"
        password-parameter="j_password"
        login-processing-url="/j_spring_security_check"/>
    <security:csrf/><!-- enable Cross Site Request Forgery protection -->
</security:http>

How to combine two byte arrays

You're just trying to concatenate the two byte arrays?

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

for (int i = 0; i < combined.length; ++i)
{
    combined[i] = i < one.length ? one[i] : two[i - one.length];
}

Or you could use System.arraycopy:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();
byte[] combined = new byte[one.length + two.length];

System.arraycopy(one,0,combined,0         ,one.length);
System.arraycopy(two,0,combined,one.length,two.length);

Or you could just use a List to do the work:

byte[] one = getBytesForOne();
byte[] two = getBytesForTwo();

List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one));
list.addAll(Arrays.<Byte>asList(two));

byte[] combined = list.toArray(new byte[list.size()]);

Or you could simply use ByteBuffer with the advantage of adding many arrays.

byte[] allByteArray = new byte[one.length + two.length + three.length];

ByteBuffer buff = ByteBuffer.wrap(allByteArray);
buff.put(one);
buff.put(two);
buff.put(three);

byte[] combined = buff.array();

How to draw border on just one side of a linear layout?

I was able to achieve the effect with the following code

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:left="0dp" android:right="-5dp" android:top="-5dp" android:bottom="-5dp">
        <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#123456" />
        </shape>
    </item>
</layer-list>

You can adjust to your needs for border position by changing the direction of displacement

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

Page vs Window in WPF?

Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

How to create a dynamic array of integers

int main()
{
  int size;

  std::cin >> size;

  int *array = new int[size];

  delete [] array;

  return 0;
}

Don't forget to delete every array you allocate with new.

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>