Programs & Examples On #Bpel

BPEL stands for Business Process Execution Language, an XML language for orchestrating Web services. It helps developing executable business processes on top of Web services based SOA. It is a defacto standard, published by OASIS.

How do I decode a base64 encoded string?

Simple:

byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);

How to remove decimal values from a value of type 'double' in Java

The solution is by using DecimalFormat class. This class provides a lot of functionality to format a number.
To get a double value as string with no decimals use the code below.

DecimalFormat decimalFormat = new DecimalFormat(".");
decimalFormat.setGroupingUsed(false);
decimalFormat.setDecimalSeparatorAlwaysShown(false);

String year = decimalFormat.format(32024.2345D);

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

Python Timezone conversion

I have found that the best approach is to convert the "moment" of interest to a utc-timezone-aware datetime object (in python, the timezone component is not required for datetime objects).

Then you can use astimezone to convert to the timezone of interest (reference).

from datetime import datetime
import pytz

utcmoment_naive = datetime.utcnow()
utcmoment = utcmoment_naive.replace(tzinfo=pytz.utc)

# print "utcmoment_naive: {0}".format(utcmoment_naive) # python 2
print("utcmoment_naive: {0}".format(utcmoment_naive))
print("utcmoment:       {0}".format(utcmoment))

localFormat = "%Y-%m-%d %H:%M:%S"

timezones = ['America/Los_Angeles', 'Europe/Madrid', 'America/Puerto_Rico']

for tz in timezones:
    localDatetime = utcmoment.astimezone(pytz.timezone(tz))
    print(localDatetime.strftime(localFormat))

# utcmoment_naive: 2017-05-11 17:43:30.802644
# utcmoment:       2017-05-11 17:43:30.802644+00:00
# 2017-05-11 10:43:30
# 2017-05-11 19:43:30
# 2017-05-11 13:43:30

So, with the moment of interest in the local timezone (a time that exists), you convert it to utc like this (reference).

localmoment_naive = datetime.strptime('2013-09-06 14:05:10', localFormat)

localtimezone = pytz.timezone('Australia/Adelaide')

try:
    localmoment = localtimezone.localize(localmoment_naive, is_dst=None)
    print("Time exists")

    utcmoment = localmoment.astimezone(pytz.utc)

except pytz.exceptions.NonExistentTimeError as e:
    print("NonExistentTimeError")

docker: executable file not found in $PATH

In the error message shown:

Error response from daemon: Cannot start container foo_1: \
    exec: "grunt serve": executable file not found in $PATH

It is complaining that it cannot find the executable grunt serve, not that it could not find the executable grunt with the argument serve. The most likely explanation for that specific error is running the command with the json syntax:

[ "grunt serve" ]

in something like your compose file. That's invalid since the json syntax requires you to split up each parameter that would normally be split by the shell on each space for you. E.g.:

[ "grunt", "serve" ]

The other possible way you can get both of those into a single parameter is if you were to quote them into a single arg in your docker run command, e.g.

docker run your_image_name "grunt serve"

and in that case, you need to remove the quotes so it gets passed as separate args to the run command:

docker run your_image_name grunt serve

For others seeing this, the executable file not found means that Linux does not see the binary you are trying to run inside your container with the default $PATH value. That could mean lots of possible causes, here are a few:

  • Did you remember to include the binary inside your image? If you run a multi-stage image, make sure that binary install is run in the final stage. Run your image with an interactive shell and verify it exists:

    docker run -it --rm your_image_name /bin/sh
    
  • Your path when shelling into the container may be modified for the interactive shell, particularly if you use bash, so you may need to specify the full path to the binary inside the container, or you may need to update the path in your Dockerfile with:

    ENV PATH=$PATH:/custom/dir/bin
    
  • The binary may not have execute bits set on it, so you may need to make it executable. Do that with chmod:

    RUN chmod 755 /custom/dir/bin/executable
    
  • If you run the image with a volume, that volume can overlay the directory where the executable exists in your image. Volumes do not merge with the image, they get mounted in the filesystem tree same as any other Linux filesystem mount. That means files from the parent filesystem at the mount point are no longer visible. (Note that named volumes are initialized by docker from the image content, but this only happens when the named volume is empty.) So the fix is to not mount volumes on top of paths where you have executables you want to run from the image.

Best way to copy from one array to another

I think your assignment is backwards:

a[i] = b[i];

should be:

b[i] = a[i];

Django CharField vs TextField

CharField has max_length of 255 characters while TextField can hold more than 255 characters. Use TextField when you have a large string as input. It is good to know that when the max_length parameter is passed into a TextField it passes the length validation to the TextArea widget.

How to get the PID of a process by giving the process name in Mac OS X ?

Try this one:

echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"

The ps command produces output like this, with the PID in the first column and the executable name (only) in the second column:

bookworm% ps -ceo pid=,comm=
    1 launchd
   10 kextd
   11 UserEventAgent
   12 mDNSResponder
   13 opendirectoryd
   14 notifyd
   15 configd

...which awk processes, printing the first column (pid) and exiting after the first match.

Create controller for partial view in ASP.NET MVC

It does not need its own controller. You can use

@Html.Partial("../ControllerName/_Testimonials.cshtml")

This allows you to render the partial from any page. Just make sure the relative path is correct.

Killing a process using Java

With Java 9, we can use ProcessHandle which makes it easier to identify and control native processes:

ProcessHandle
  .allProcesses()
  .filter(p -> p.info().commandLine().map(c -> c.contains("firefox")).orElse(false))
  .findFirst()
  .ifPresent(ProcessHandle::destroy)

where "firefox" is the process to kill.

This:

  • First lists all processes running on the system as a Stream<ProcessHandle>

  • Lazily filters this stream to only keep processes whose launched command line contains "firefox". Both commandLine or command can be used depending on how we want to retrieve the process.

  • Finds the first filtered process meeting the filtering condition.

  • And if at least one process' command line contained "firefox", then kills it using destroy.

No import necessary as ProcessHandle is part of java.lang.

How to pass a value from one jsp to another jsp page?

Use sessions

On your search.jsp

Put your scard in sessions using session.setAttribute("scard","scard")

//the 1st variable is the string name that you will retrieve in ur next page,and the 2nd variable is the its value,i.e the scard value.

And in your next page you retrieve it using session.getAttribute("scard")

UPDATE

<input type="text" value="<%=session.getAttribute("scard")%>"/>

How to get HTTP Response Code using Selenium WebDriver

For those people using Python, you might consider Selenium Wire, a library for inspecting requests made by the browser during a test.

You get access to requests via the driver.requests attribute:

from seleniumwire import webdriver  # Import from seleniumwire

# Create a new instance of the Firefox driver
driver = webdriver.Firefox()

# Go to the Google home page
driver.get('https://www.google.com')

# Access requests via the `requests` attribute
for request in driver.requests:
    if request.response:
        print(
            request.url,
            request.response.status_code,
            request.response.headers['Content-Type']
        )

Prints:

https://www.google.com/ 200 text/html; charset=UTF-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png 200 image/png
https://consent.google.com/status?continue=https://www.google.com&pc=s&timestamp=1531511954&gl=GB 204 text/html; charset=utf-8
https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png 200 image/png
https://ssl.gstatic.com/gb/images/i2_2ec824b0.png 200 image/png
https://www.google.com/gen_204?s=webaft&t=aft&atyp=csi&ei=kgRJW7DBONKTlwTK77wQ&rt=wsrt.366,aft.58,prt.58 204 text/html; charset=UTF-8
...

The library gives you the ability to access headers, status code, body content, as well as the ability to modify headers and rewrite URLs.

show dbs gives "Not Authorized to execute command" error

Create a user like this:

db.createUser(
      {
        user: "myUserAdmin",
        pwd: "abc123",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      }
    )

Then connect it following this:

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

Check the manual :

https://docs.mongodb.org/manual/tutorial/enable-authentication/

Exit a while loop in VBS/VBA

I know this is old as dirt but it ranked pretty high in google.

The problem with the solution maddy implemented (in response to rahul) to maintain the use of a While...Wend loop has some drawbacks

In the example given

num = 0
While num < 10
  If status = "Fail" Then
    num = 10
  End If
  num = num + 1
Wend

After status = "Fail" num will actually equal 11. The loop didn't end on the fail condition, it ends on the next test. All of the code after the check still processed and your counter is not what you might have expected it to be.

Now depending on what you are all doing in your loop it may not matter, but then again if your code looked something more like:

num = 0
While num < 10
  If folder = "System32" Then
    num = 10
  End If
  RecursiveDeleteFunction folder
  num = num + 1
Wend

Using Do While or Do Until allows you to stop execution of the loop using Exit Do instead of using trickery with your loop condition to maintain the While ... Wend syntax. I would recommend using that instead.

Export to CSV via PHP

Just for the record, concatenation is waaaaaay faster (I mean it) than fputcsv or even implode; And the file size is smaller:

// The data from Eternal Oblivion is an object, always
$values = (array) fetchDataFromEternalOblivion($userId, $limit = 1000);

// ----- fputcsv (slow)
// The code of @Alain Tiemblo is the best implementation
ob_start();
$csv = fopen("php://output", 'w');
fputcsv($csv, array_keys(reset($values)));
foreach ($values as $row) {
    fputcsv($csv, $row);
}
fclose($csv);
return ob_get_clean();

// ----- implode (slow, but file size is smaller)
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
foreach ($values as $row) {
    $csv .= '"' . implode('","', $row) . '"' . PHP_EOL;
}
return $csv;
// ----- concatenation (fast, file size is smaller)
// We can use one implode for the headers =D
$csv = implode(",", array_keys(reset($values))) . PHP_EOL;
$i = 1;
// This is less flexible, but we have more control over the formatting
foreach ($values as $row) {
    $csv .= '"' . $row['id'] . '",';
    $csv .= '"' . $row['name'] . '",';
    $csv .= '"' . date('d-m-Y', strtotime($row['date'])) . '",';
    $csv .= '"' . ($row['pet_name'] ?: '-' ) . '",';
    $csv .= PHP_EOL;
}
return $csv;

This is the conclusion of the optimization of several reports, from ten to thousands rows. The three examples worked fine under 1000 rows, but fails when the data was bigger.

minimize app to system tray

This is the method I use in my applications, it's fairly simple and self explanatory but I'm happy to give more details in answer to your comments.

    public Form1()
    {
        InitializeComponent();

        // When window state changed, trigger state update.
        this.Resize += SetMinimizeState;

        // When tray icon clicked, trigger window state change.       
        systemTrayIcon.Click += ToggleMinimizeState;
    }      

    // Toggle state between Normal and Minimized.
    private void ToggleMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;
        this.WindowState = (isMinimized) ? FormWindowState.Normal : FormWindowState.Minimized;
    }

    // Show/Hide window and tray icon to match window state.
    private void SetMinimizeState(object sender, EventArgs e)
    {    
        bool isMinimized = this.WindowState == FormWindowState.Minimized;

        this.ShowInTaskbar = !isMinimized;           
        systemTrayIcon.Visible = isMinimized;
        if (isMinimized) systemTrayIcon.ShowBalloonTip(500, "Application", "Application minimized to tray.", ToolTipIcon.Info);
    }

Explode PHP string by new line

this php function explode string by newline

Attention : new line in Windows is \r\n and in Linux and Unix is \n
this function change all new lines to linux mode then split it.
pay attention that empty lines will be ignored

function splitNewLine($text) {
    $code=preg_replace('/\n$/','',preg_replace('/^\n/','',preg_replace('/[\r\n]+/',"\n",$text)));
    return explode("\n",$code);
}

example

$a="\r\n\r\n\n\n\r\rsalam\r\nman khobam\rto chi\n\rche khabar\n\r\n\n\r\r\n\nbashe baba raftam\r\n\r\n\r\n\r\n";
print_r( splitNewLine($a) );

output

Array
(
    [0] => salam
    [1] => man khobam
    [2] => to chi
    [3] => che khabar
    [4] => bashe baba raftam
)

How can I build for release/distribution on the Xcode 4?

They've bundled all the target/build configuration/debugging options stuff into "schemes". The transition guide has a good explanation.

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

Replace all particular values in a data frame

Like this:

> df[df==""]<-NA
> df
     A    B
1 <NA>   12
2  xyz <NA>
3  jkl  100

Logging POST data from $request_body

Ok. So finally I was able to log the post data and return a 200. It's kind of a hacky solution that I'm not too proud of which basically overrides the natural behavior for error_page, but my inexperience of nginx plus timelines lead me to this solution:

location /bk {
  if ($request_method != POST) {
    return 405;
  }
  proxy_set_header  X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;
  proxy_redirect off;
  proxy_pass $scheme://127.0.0.1:$server_port/success;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking;
}
location /success {
  return 200;
}
error_page   500 502 503 504  /50x.html;
location = /50x.html {
  root   /var/www/nginx-default;
  log_format my_tracking $request_body;
  access_log  /mnt/logs/nginx/my_tracking.access.log my_tracking_2;
}

Now according to that config, it would seem that the proxy pass would return a 200 all the time. Occasionally I would get 500 but when I threw in an error_log to see what was going on, all of my request_body data was in there and I couldn't see a problem. So I caught that and wrote to the same log. Since nginx doesn't like the same name for the tracking variable, I just used my_tracking_2 and wrote to the same log as when it returns a 200. Definitely not the most elegant solution and I welcome any better solution. I've seen the post module, but in my scenario, I couldn't recompile from source.

Node.js - Find home directory in platform agnostic way

getUserRootFolder() {
  return process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE;
}

How to sort dates from Oldest to Newest in Excel?

Sort of an old thread, but I had this same issue today so adding the solution for my problem which nobody has mentioned above.

My date data was downloaded from a csv file but the date came with a Timezone at the end (e.g. 9/7/2018 9:43:42 AM PDT). Excel allows it to be formatted as a date column but apparently does not like the timezone (i.e. PDT) at the end for sorting.

I removed the timezone at the end & then the sorting works.

I did: (1) Format as time (mm/dd/yy xx:xx PM) (2) Search for "M PDT" & replace all with "M" (3) Then sort gives you "Oldest to Newest" sort instead of "A to Z".

Note that all my datetimes were PDT so only one search & replace, but obviously if you have other timezones, you would have to a separate search & replace for each.

Gem Command not found

Try the following:

sudo apt-get install rubygems

Using XPATH to search text containing &nbsp;

Bear in mind that a standards-compliant XML processor will have replaced any entity references other than XML's five standard ones (&amp;, &gt;, &lt;, &apos;, &quot;) with the corresponding character in the target encoding by the time XPath expressions are evaluated. Given that behavior, PhiLho's and jsulak's suggestions are the way to go if you want to work with XML tools. When you enter &#160; in the XPath expression, it should be converted to the corresponding byte sequence before the XPath expression is applied.

Change icons of checked and unchecked for Checkbox for Android

This may be achieved by using AppCompatCheckBox. You can use app:buttonCompat="@drawable/selector_drawable" to change the selector.

It's working with PNGs, but I didn't find a way for it to work with Vector Drawables.

How to check if an Object is a Collection Type in Java?

Have you thinked about using instanceof ? Like, say

if(myObject instanceof Collection) {
     Collection myCollection = (Collection) myObject;

Although not that pure OOP style, it is however largely used for so-called "type escalation".

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

I use both windows and linux, but the solution core.autocrlf true didn't help me. I even got nothing changed after git checkout <filename>.

So I use workaround to substitute git status - gitstatus.sh

#!/bin/bash

git status | grep modified | cut -d' ' -f 4 | while read x; do
 x1="$(git show HEAD:$x | md5sum | cut -d' ' -f 1 )"
 x2="$(cat $x | md5sum | cut -d' ' -f 1 )"

 if [ "$x1" != "$x2" ]; then
    echo "$x NOT IDENTICAL"
 fi
done

I just compare md5sum of a file and its brother at repository.

Example output:

$ ./gitstatus.sh
application/script.php NOT IDENTICAL
application/storage/logs/laravel.log NOT IDENTICAL

How to fix Python Numpy/Pandas installation?

I work with the guys that created Anaconda Python. You can install multiple versions of python and numpy without corrupting your system python. It's free and open source (OSX, linux, Windows). The paid packages are enhancements on top of the free version. Pandas is included.

conda create --name np17py27 anaconda=1.4 numpy=1.7 python=2.7
export PATH=~/anaconda/envs/np17py27/bin:$PATH

If you want numpy 1.6:

conda create --name np16py27 anaconda=1.4 numpy=1.6 python=2.7

Setting your PATH sets up where to find python and ipython. The environments (np17py27) can be named whatever you would like.

C# : "A first chance exception of type 'System.InvalidOperationException'"

The problem here is that your timer starts a thread and when it runs the callback function, the callback function ( updatelistview) is accessing controls on UI thread so this can not be done becuase of this

iframe to Only Show a Certain Part of the Page

I needed an iframe that would embed a portion of an external page with a vertical scroll bar, cropping out the navigation menus on the top and left of the page. I was able to do it with some simple HTML and CSS.

HTML

<div id="container">
    <iframe id="embed" src="http://www.example.com"></iframe>
</div>

CSS

div#container
{
    width:840px;
    height:317px;
    overflow:scroll;     /* if you don't want a scrollbar, set to hidden */
    overflow-x:hidden;   /* hides horizontal scrollbar on newer browsers */

    /* resize and min-height are optional, allows user to resize viewable area */
    -webkit-resize:vertical; 
    -moz-resize:vertical;
    resize:vertical;
    min-height:317px;
}

iframe#embed
{
    width:1000px;       /* set this to approximate width of entire page you're embedding */
    height:2000px;      /* determines where the bottom of the page cuts off */
    margin-left:-183px; /* clipping left side of page */
    margin-top:-244px;  /* clipping top of page */
    overflow:hidden;

    /* resize seems to inherit in at least Firefox */
    -webkit-resize:none;
    -moz-resize:none;
    resize:none;
}

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

How to restart remote MySQL server running on Ubuntu linux?

What worked for me on an Amazon EC2 server was:

sudo service mysqld restart

How to extract filename.tar.gz file

If file filename.tar.gz gives this message: POSIX tar archive, the archive is a tar, not a GZip archive.

Unpack a tar without the z, it is for gzipped (compressed), only:

mv filename.tar.gz filename.tar # optional
tar xvf filename.tar

Or try a generic Unpacker like unp (https://packages.qa.debian.org/u/unp.html), a script for unpacking a wide variety of archive formats.

determine the file type:

$ file ~/Downloads/filename.tbz2
/User/Name/Downloads/filename.tbz2: bzip2 compressed data, block size = 400k

make a header full screen (width) css

Set the max-width:1250px; that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)

Format Float to n decimal places

You may also pass the float value, and use:

String.format("%.2f", floatValue);

Documentation

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Can regular expressions be used to match nested patterns?

Using regular expressions to check for nested patterns is very easy.

'/(\((?>[^()]+|(?1))*\))/'

TypeError: Router.use() requires middleware function but got a Object

Simple solution if your are using express and doing

const router = express.Router();

make sure to

module.exports = router ;

at the end of your page

Make <body> fill entire screen?

On our site we have pages where the content is static, and pages where it is loaded in with AJAX. On one page (a search page), there were cases when the AJAX results would more than fill the page, and cases where it would return no results. In order for the background image to fill the page in all cases we had to apply the following CSS:

html {
   margin: 0px;
   height: 100%;
   width: 100%;
}

body {
   margin: 0px;
   min-height: 100%;
   width: 100%;
}

height for the html and min-height for the body.

in querySelector: how to get the first and get the last elements? what traversal order is used in the dom?

:last is not part of the css spec, this is jQuery specific.

you should be looking for last-child

var first = div.querySelector('[move_id]:first-child');
var last  = div.querySelector('[move_id]:last-child');

Disabling Chrome cache for website development

I use (in windows), ctrl + shift + delete and when the chrome dialog comes up, press enter key. This can be configured with what needs to be cleared each time you execute this sequence. No need to have dev. tools open in this case.

Getting files by creation date in .NET

You can use Linq

var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);

Create Git branch with current changes

Like stated in this question: Git: Create a branch from unstagged/uncommited changes on master: stash is not necessary.

Just use:

git checkout -b topic/newbranch

Any uncommitted work will be taken along to the new branch.

If you try to push you will get the following message

fatal: The current branch feature/NEWBRANCH has no upstream branch. To push the current branch and set the remote as upstream, use

git push --set-upstream origin feature/feature/NEWBRANCH

Just do as suggested to create the branch remotely:

git push --set-upstream origin feature/feature/NEWBRANCH

Multiple commands on a single line in a Windows batch file

Can be achieved also with scriptrunner

ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30 

Which also have some features as rollback , timeout and waiting.

Passing by reference in C

That is not pass-by-reference, that is pass-by-value as others stated.

The C language is pass-by-value without exception. Passing a pointer as a parameter does not mean pass-by-reference.

The rule is the following:

A function is not able to change the actual parameters value.


Let's try to see the differences between scalar and pointer parameters of a function.

Scalar variables

This short program shows pass-by-value using a scalar variable. param is called the formal parameter and variable at function invocation is called actual parameter. Note incrementing param in the function does not change variable.

#include <stdio.h>

void function(int param) {
    printf("I've received value %d\n", param);
    param++;
}

int main(void) {
    int variable = 111;

    function(variable);
    printf("variable %d\m", variable);
    return 0;
}

The result is

I've received value 111
variable=111

Illusion of pass-by-reference

We change the piece of code slightly. param is a pointer now.

#include <stdio.h>

void function2(int *param) {
    printf("I've received value %d\n", *param);
    (*param)++;
}

int main(void) {
    int variable = 111;

    function2(&variable);
    printf("variable %d\n", variable);
    return 0;
}

The result is

I've received value 111
variable=112

That makes you believe that the parameter was passed by reference. It was not. It was passed by value, the param value being an address. The int type value was incremented, and that is the side effect that make us think that it was a pass-by-reference function call.

Pointers - passed-by-value

How can we show/prove that fact? Well, maybe we can try the first example of Scalar variables, but instead of scalar we use addresses (pointers). Let's see if that can help.

#include <stdio.h>

void function2(int *param) {
    printf("param's address %d\n", param);
    param = NULL;
}

int main(void) {
    int variable = 111;
    int *ptr = &variable;

    function2(ptr);
    printf("ptr's address %d\n", ptr);
    return 0;
}

The result will be that the two addresses are equal (don't worry about the exact value).

Example result:

param's address -1846583468
ptr's address -1846583468

In my opinion this proves clearly that pointers are passed-by-value. Otherwise ptr would be NULL after function invocation.

Simple jQuery, PHP and JSONP example?

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here

If you look at the source code you can see that I am calling the Twitter API using .getJSON.

So your example would be: THIS IS TESTED AND WORKS (You can go to http://smallcoders.com/javascriptdevenvironment.html to see it in action)

//JAVASCRIPT

$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){
    alert('Your name is '+res.fullname);
});

//SERVER SIDE
  <?php
 $fname = $_GET['firstname'];
      if($fname=='Jeff')
      {
          //header("Content-Type: application/json");
         echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

      }
?>

Note the ?callback=? and +res.fullname

Run as java application option disabled in eclipse

You can try and add a new run configuration: Run -> Run Configurations ... -> Select "Java Appliction" and click "New".

Alternatively use the shortcut: place the cursor in the class, then press Alt + Shift + X to open up a context menu, then press J.

How to define custom exception class in Java, the easiest way?

If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception and check "Constructors from superclass" and it will generate the following:

package com.example.exception;

public class MyException extends Exception {

    public MyException() {
        // TODO Auto-generated constructor stub
    }

    public MyException(String message) {
        super(message);
        // TODO Auto-generated constructor stub
    }

    public MyException(Throwable cause) {
        super(cause);
        // TODO Auto-generated constructor stub
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
        // TODO Auto-generated constructor stub
    }

}

In response to the question below about not calling super() in the defualt constructor, Oracle has this to say:

Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.

Single quotes vs. double quotes in Python

Your team's taste or your project's coding guidelines.

If you are in a multilanguage environment, you might wish to encourage the use of the same type of quotes for strings that the other language uses, for instance. Else, I personally like best the look of '

How to Set OnClick attribute with value containing function in ie8?

You also can use:

element.addEventListener("click", function(){
    // call execute function here...
}, false);

How to make a PHP SOAP call using the SoapClient class

You need declare class Contract

class Contract {
  public $id;
  public $name;
}

$contract = new Contract();
$contract->id = 100;
$contract->name = "John";

$params = array(
  "Contact" => $contract,
  "description" => "Barrel of Oil",
  "amount" => 500,
);

or

$params = array(
  $contract,
  "description" => "Barrel of Oil",
  "amount" => 500,
);

Then

$response = $client->__soapCall("Function1", array("FirstFunction" => $params));

or

$response = $client->__soapCall("Function1", $params);

How to put a tooltip on a user-defined function

I tried @ScottK's approach, first as a side feature of my functional UDF, then as a standalone _Help suffix version when I ran into trouble (see below). In hindsight, the latter approach is better anyway--more obvious to a user attentive enough to see a tool tip, and it doesn't clutter up the functional code.

I figured if an inattentive user just typed the function name and closed the parentheses while he thought it over, help would appear and he would be on his way. But dumping a bunch of text into a single cell that I cannot format didn't seem like a good idea. Instead, When the function is entered in a cell with no arguments i.e.

   = interpolateLinear() 
or
   = interpolateLinear_Help()

a msgBox opens with the help text. A msgBox is limited to ~1000 characters, maybe it's 1024. But that's enough (barely 8^/) for my overly tricked out interpolation function. If it's not, you can always open a user form and go to town.

The first time the message box opened, it looked like success. But there are a couple of problems. First of course, the user has to know to enter the function with no arguments (+1 for the _Help suffix UDF).

The big problem is, the msgBox reopens several times in succession, spontaneously while working in unrelated parts of the workbook. Needless to say, it's very annoying. Sometimes it goes on until I get a circular reference warning. Go figure. If a UDF could change the cell formula, I would have done that to shut it up.

I don't know why Excel feels the need recalculate the formula over and over; neither the _Help standalone, nor the full up version (in help mode) has precedents or dependents. There's not an application.volatile statement anywhere. Of course the function returns a value to the calling cell. Maybe that triggers the recalc? But that's what UDFs do. I don't think you can not return a value.

Since you can't modify a worksheet formula from a UDF, I tried to return a specific string --a value --to the calling cell (the only one you can change the value of from a UDF), figuring I would inspect the cell value using application.caller on the next cycle, spot my string, and know not to re-display the help message. Seemed like a good idea at the time--didn't work. Maybe I did something stupid in my sleep-deprived state. I still like the idea. I'll update this when (if) I fix the problem. My quick fix was to add a line on the help box: "Seek help only in an emergency. Delete the offending formula to end the misery.

In the meantime, I tried the Application.MacroOptions approach. Pretty easy, and it looks professional. Just one problem to work out. I'll post a separate answer on that approach later.

Javascript window.open pass values using POST

The code helped me to fulfill my requirement.

I have made some modifications and using a form I completed this. Here is my code-

Need a 'target' attribute for 'form' -- that's it!

Form

<form id="view_form" name="view_form" method="post" action="view_report.php"  target="Map" >
  <input type="text" value="<?php echo $sale->myvalue1; ?>" name="my_value1"/>
  <input type="text" value="<?php echo $sale->myvalue2; ?>" name="my_value2"/>
  <input type="button" id="download" name="download" value="View report" onclick="view_my_report();"   /> 
</form>

JavaScript

function view_my_report() {     
   var mapForm = document.getElementById("view_form");
   map=window.open("","Map","status=0,title=0,height=600,width=800,scrollbars=1");

   if (map) {
      mapForm.submit();
   } else {
      alert('You must allow popups for this map to work.');
   }
}

Full code is explained showing normal form and form elements.

How to compare types

You can use for it the is operator. You can then check if object is specific type by writing:

if (myObject is string)
{
  DoSomething()
}

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

As an exteme turnaround, when you cannot do an alter to your date column or to update the values, or while these modifications take place, you can do a select using a case/when.

SELECT CASE ModificationDate WHEN '0000-00-00 00:00:00' THEN '1970-01-01 01:00:00' ELSE ModificationDate END AS ModificationDate FROM Project WHERE projectId=1;

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

How can I include css files using node, express, and ejs?

Use this in your server.js file

_x000D_
_x000D_
app.use(express.static('public'));
_x000D_
_x000D_
_x000D_

without the directory ( __dirname ) and then within your project folder create a new file and name it public then put all your static files inside it

How do I make curl ignore the proxy?

First, I listed the current proxy setting with

env | sort | less

(should be something like http_proxy=http://wpad.local.machine.location:port number)

Then I tried setting

export http_proxy=";" 

which gave this error message:

curl: (5) Couldn't resolve proxy ';'

Tried

export http_proxy="" && curl http://servername:portnumber/destinationpath/ -d 55

and it worked!

PS! Remember to set http-proxy back to its original settings with

export http_proxy=http://wpad.local.machine.location:port number

How to redirect output of an already running process

See Redirecting Output from a Running Process.

Firstly I run the command cat > foo1 in one session and test that data from stdin is copied to the file. Then in another session I redirect the output.

Firstly find the PID of the process:

$ ps aux | grep cat
rjc 6760 0.0 0.0 1580 376 pts/5 S+ 15:31 0:00 cat

Now check the file handles it has open:

$ ls -l /proc/6760/fd
total 3
lrwx—— 1 rjc rjc 64 Feb 27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 Feb 27 15:32 1 -> /tmp/foo1
lrwx—— 1 rjc rjc 64 Feb 27 15:32 2 -> /dev/pts/5

Now run GDB:

$ gdb -p 6760 /bin/cat
GNU gdb 6.4.90-debian

[license stuff snipped]

Attaching to program: /bin/cat, process 6760

[snip other stuff that's not interesting now]

(gdb) p close(1)
$1 = 0
(gdb) p creat("/tmp/foo3", 0600)
$2 = 1
(gdb) q
The program is running. Quit anyway (and detach it)? (y or n) y
Detaching from program: /bin/cat, process 6760

The p command in GDB will print the value of an expression, an expression can be a function to call, it can be a system call… So I execute a close() system call and pass file handle 1, then I execute a creat() system call to open a new file. The result of the creat() was 1 which means that it replaced the previous file handle. If I wanted to use the same file for stdout and stderr or if I wanted to replace a file handle with some other number then I would need to call the dup2() system call to achieve that result.

For this example I chose to use creat() instead of open() because there are fewer parameter. The C macros for the flags are not usable from GDB (it doesn’t use C headers) so I would have to read header files to discover this – it’s not that hard to do so but would take more time. Note that 0600 is the octal permission for the owner having read/write access and the group and others having no access. It would also work to use 0 for that parameter and run chmod on the file later on.

After that I verify the result:

ls -l /proc/6760/fd/
total 3
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 0 -> /dev/pts/5
l-wx—— 1 rjc rjc 64 2008-02-27 15:32 1 -> /tmp/foo3 <====
lrwx—— 1 rjc rjc 64 2008-02-27 15:32 2 -> /dev/pts/5

Typing more data in to cat results in the file /tmp/foo3 being appended to.

If you want to close the original session you need to close all file handles for it, open a new device that can be the controlling tty, and then call setsid().

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

Your wildcard *.example.com does not cover the root domain example.com but will cover any variant on a sub-domain such as www.example.com or test.example.com

The preferred method is to establish Subject Alternative Names like in Fabian's Answer but keep in mind that Chrome currently requires the Common Name to be listed additionally as one of the Subject Alternative Names (as it is correctly demonstrated in his answer). I recently discovered this problem because I had the Common Name example.com with SANs www.example.com and test.example.com, but got the NET::ERR_CERT_COMMON_NAME_INVALID warning from Chrome. I had to generate a new Certificate Signing Request with example.com as both the Common Name and one of the SANs. Then Chrome fully trusted the certificate. And don't forget to import the root certificate into Chrome as a trusted authority for identifying websites.

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly

I faced a similar issue when running SSH or Git Clone in Windows. Following findings helps to solve my problem:

  • When you run “rhc setup” or other ssh methods to generate ssh key, it will create the private key file id_rsa in .ssh folder in your home folder, default is C:\User\UserID
  • Git for windows has its own .ssh folder in its installation directory. When you run git/ssh, it will look for private key file id_rsa in this folder
  • Solved the problem by copying id_rsa from the home folder .ssh folder to the .ssh folder in the git installation directory

Also, I think there a way to “tell” git to use the default .ssh folder in home folder but still need to figure out how.

Configuration System Failed to Initialize

It is worth noting that if you add things like connection strings into the app.config, that if you add items outside of the defined config sections, that it will not immediately complain, but when you try and access it, that you may then get the above errors.

Collapse all major sections and make sure there are no items outside the defined ones. Obvious, when you have actually spotted it.

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

I think the above answer posted by Jeremy Thompson is the correct one, but I don't have enough street cred to comment. Once I updated nuget and powershellget, Install-Module was available for me.

Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force 
Install-PackageProvider -Name Powershellget -Force

What is interesting is that the version numbers returned by get-packageprovider didn't change after the update.

Alphanumeric, dash and underscore but no spaces regular expression check JavaScript

try this one, it is working fine for me.

"^([a-zA-Z])[a-zA-Z0-9-_]*$"

Jquery open popup on button click for bootstrap

Give an ID to uniquely identify the button, lets say myBtn

// when DOM is ready
$(document).ready(function () {

     // Attach Button click event listener 
    $("#myBtn").click(function(){

         // show Modal
         $('#myModal').modal('show');
    });
});

JSFIDDLE

Curly braces in string in PHP

This is the complex (curly) syntax for string interpolation. From the manual:

Complex (curly) syntax

This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.

Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in { and }. Since { can not be escaped, this syntax will only be recognised when the $ immediately follows the {. Use {\$ to get a literal {$. Some examples to make it clear:

<?php
// Show all errors
error_reporting(E_ALL);

$great = 'fantastic';

// Won't work, outputs: This is { fantastic}
echo "This is { $great}";

// Works, outputs: This is fantastic
echo "This is {$great}";
echo "This is ${great}";

// Works
echo "This square is {$square->width}00 centimeters broad."; 


// Works, quoted keys only work using the curly brace syntax
echo "This works: {$arr['key']}";


// Works
echo "This works: {$arr[4][3]}";

// This is wrong for the same reason as $foo[bar] is wrong  outside a string.
// In other words, it will still work, but only because PHP first looks for a
// constant named foo; an error of level E_NOTICE (undefined constant) will be
// thrown.
echo "This is wrong: {$arr[foo][3]}"; 

// Works. When using multi-dimensional arrays, always use braces around arrays
// when inside of strings
echo "This works: {$arr['foo'][3]}";

// Works.
echo "This works: " . $arr['foo'][3];

echo "This works too: {$obj->values[3]->name}";

echo "This is the value of the var named $name: {${$name}}";

echo "This is the value of the var named by the return value of getName(): {${getName()}}";

echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}";

// Won't work, outputs: This is the return value of getName(): {getName()}
echo "This is the return value of getName(): {getName()}";
?>

Often, this syntax is unnecessary. For example, this:

$a = 'abcd';
$out = "$a $a"; // "abcd abcd";

behaves exactly the same as this:

$out = "{$a} {$a}"; // same

So the curly braces are unnecessary. But this:

$out = "$aefgh";

will, depending on your error level, either not work or produce an error because there's no variable named $aefgh, so you need to do:

$out = "${a}efgh"; // or
$out = "{$a}efgh";

Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ]

It seems like it exists a bug in jQuery reported here : http://bugs.jquery.com/ticket/13183 that breaks the Fancybox script.

Also check https://github.com/fancyapps/fancyBox/issues/485 for further reference.

As a workaround, rollback to jQuery v1.8.3 while either the jQuery bug is fixed or Fancybox is patched.


UPDATE (Jan 16, 2013): Fancybox v2.1.4 has been released and now it works fine with jQuery v1.9.0.

For fancybox v1.3.4- you still need to rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.


UPDATE (Jan 17, 2013): Workaround for users of Fancybox v1.3.4 :

Patch the fancybox js file to make it work with jQuery v1.9.0 as follow :

  1. Open the jquery.fancybox-1.3.4.js file (full version, not pack version) with a text/html editor.
  2. Find around the line 29 where it says :

    isIE6 = $.browser.msie && $.browser.version < 7 && !window.XMLHttpRequest,
    

    and replace it by (EDITED March 19, 2013: more accurate filter):

    isIE6 = navigator.userAgent.match(/msie [6]/i) && !window.XMLHttpRequest,
    

    UPDATE (March 19, 2013): Also replace $.browser.msie by navigator.userAgent.match(/msie [6]/i) around line 615 (and/or replace all $.browser.msie instances, if any), thanks joofow ... that's it!

Or download the already patched version from HERE (UPDATED March 19, 2013 ... thanks fairylee for pointing out the extra closing bracket)

NOTE: this is an unofficial patch and is unsupported by Fancybox's author, however it works as is. You may use it at your own risk ;)

Optionally, you may rather rollback to jQuery v1.8.3 or apply the migration script as pointed out by @Manu's answer.

Uncaught ReferenceError: $ is not defined error in jQuery

Include the jQuery file first:

 <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
 <script type="text/javascript" src="./javascript.js"></script>
    <script
        src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
    </script>

How do I enable FFMPEG logging and where can I find the FFMPEG log file?

You can find more debugging info just simply adding the option -loglevel debug, full command will be

ffmpeg -i INPUT OUTPUT -loglevel debug -v verbose

How can I obfuscate (protect) JavaScript?

Try JScrambler. I gave it a spin recently and was impressed by it. It provides a set of templates for obfuscation with predefined settings for those who don't care much about the details and just want to get it done quickly. You can also create custom obfuscation by choosing whatever transformations/techniques you want.

How to copy data from one HDFS to another HDFS?

Try dtIngest, it's developed on top of Apache Apex platform. This tool copies data from different sources like HDFS, shared drive, NFS, FTP, Kafka to different destinations. Copying data from remote HDFS cluster to local HDFS cluster is supported by dtIngest. dtIngest runs yarn jobs to copy data in parallel fashion, so it's very fast. It takes care of failure handling, recovery etc. and supports polling directories periodically to do continious copy.

Usage: dtingest [OPTION]... SOURCEURL... DESTINATIONURL example: dtingest hdfs://nn1:8020/source hdfs://nn2:8020/dest

Referencing system.management.automation.dll in Visual Studio

I used the VS Project Reference menu and browsed to: C:\windows\assembly\GAC_MSIL\System.Management.Automation and added a reference for the dll and the Runspaces dll.

I did not need to hack the .csprj file and add the reference line mentioned above. I do not have the Windows SDK installed.

I did do the Powershell copy mentioned above: Copy ([PSObject].Assembly.Location) C:\

My test with a Get-Process Powershell command then worked. I used examples from Powershell for developers Chapter 5.

curl posting with header application/x-www-form-urlencoded

Try something like:

$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));   
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
$result = curl_exec($ch);

echo $result;

How to prevent scientific notation in R?

To set the use of scientific notation in your entire R session, you can use the scipen option. From the documentation (?options):

‘scipen’: integer.  A penalty to be applied when deciding to print
          numeric values in fixed or exponential notation.  Positive
          values bias towards fixed and negative towards scientific
          notation: fixed notation will be preferred unless it is more
          than ‘scipen’ digits wider.

So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999:

options(scipen=999)

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

Examples for string find in Python

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

stale element reference: element is not attached to the page document

According to @Abhishek Singh's you need to understand the problem:

What is the line which gives exception ?? The reason for this is because the element to which you have referred is removed from the DOM structure

and you can not refer to it anymore (imagine what element's ID has changed).

Follow the code:

class TogglingPage {
  @FindBy(...)
  private WebElement btnTurnOff;

  @FindBy(...)
  private WebElement btnTurnOn;

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();          // when clicked, button should swap into btnTurnOn
    this.btnTurnOn.isDisplayed();
    this.btnTurnOn.click();           // when clicked, button should swap into btnTurnOff
    this.btnTurnOff.isDisplayed();    // throws an exception
    return new TogglingPage();
  }
}

Now, let us wonder why?

  1. btnTurnOff was found by a driver - ok
  2. btnTurnOff was replaced by btnTurnOn - ok
  3. btnTurnOn was found by a driver. - ok
  4. btnTurnOn was replaced by btnTurnOff - ok
  5. we call this.btnTurnOff.isDisplayed(); on the element which does not exist anymore in Selenium sense - you can see it, it works perfectly, but it is a different instance of the same button.

Possible fix:

  TogglingPage turnOff() {
    this.btnTurnOff.isDisplayed();  
    this.btnTurnOff.click();

    TogglingPage newPage = new TogglingPage();
    newPage.btnTurnOn.isDisplayed();
    newPage.btnTurnOn.click();

    TogglingPage newerPage = new TogglingPage();
    newerPage.btnTurnOff.isDisplayed();    // ok
    return newerPage;
  }

How to get main window handle from process id?

Here, I would like to add that if you are reading window handle that is HWND of a process then that process should not be running in a debugging otherwise it will not find the window handle by using FindWindowEx.

Fast ceiling of an integer division in C / C++

You could use the div function in cstdlib to get the quotient & remainder in a single call and then handle the ceiling separately, like in the below

#include <cstdlib>
#include <iostream>

int div_ceil(int numerator, int denominator)
{
        std::div_t res = std::div(numerator, denominator);
        return res.rem ? (res.quot + 1) : res.quot;
}

int main(int, const char**)
{
        std::cout << "10 / 5 = " << div_ceil(10, 5) << std::endl;
        std::cout << "11 / 5 = " << div_ceil(11, 5) << std::endl;

        return 0;
}

List the queries running on SQL Server

Try with this:

It will provide you all user queries. Till spid 50,it's all are sql server internal process sessions. But, if you want you can remove where clause:

select
r.session_id,
r.start_time,
s.login_name,
c.client_net_address,
s.host_name,
s.program_name,
st.text
from sys.dm_exec_requests r
inner join sys.dm_exec_sessions s
on r.session_id = s.session_id
left join sys.dm_exec_connections c
on r.session_id = c.session_id
outer apply sys.dm_exec_sql_text(r.sql_handle) st where r.session_id  > 50

Deprecation warning in Moment.js - Not in a recognized ISO format

Doing this works for me:

moment(new Date("27/04/2016")).format

What is the equivalent of Java static methods in Kotlin?

Kotlin has no any static keyword. You used that for java

 class AppHelper {
        public static int getAge() {
            return 30;
        }
    }

and For Kotlin

class AppHelper {
        companion object {
            fun getAge() : Int = 30
        }
    }

Call for Java

AppHelper.getAge();

Call for Kotlin

AppHelper.Companion.getAge();

I think its working perfectly.

Getting the last element of a split string array

You can also consider to reverse your array and take the first element. That way you don't have to know about the length, but it brings no real benefits and the disadvantage that the reverse operation might take longer with big arrays:

array1.split(",").reverse()[0]

It's easy though, but also modifies the original array in question. That might or might not be a problem.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse

Probably you might want to use this though:

array1.split(",").pop()

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

How to send UTF-8 email?

If not HTML, then UTF-8 is not recommended. koi8-r and windows-1251 only without problems. So use html mail.

$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';


$mail_object=& Mail::factory('smtp',
    array ('host' => $host,
        'auth' => true,
        'username' => $username,
        'password' => $password));
$mail_object->send($recipents, $headers, $body);
}

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

Sounds like you're calling sp_executesql with a VARCHAR statement, when it needs to be NVARCHAR.

e.g. This will give the error because @SQL needs to be NVARCHAR

DECLARE @SQL VARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

So:

DECLARE @SQL NVARCHAR(100)
SET @SQL = 'SELECT TOP 1 * FROM sys.tables'
EXECUTE sp_executesql @SQL

jQuery append() vs appendChild()

appendChild is a pure javascript method where as append is a jQuery method.

Using Service to run background and create notification

The question is relatively old, but I hope this post still might be relevant for others.

TL;DR: use AlarmManager to schedule a task, use IntentService, see the sample code here;

What this test-application(and instruction) is about:

Simple helloworld app, which sends you notification every 2 hours. Clicking on notification - opens secondary Activity in the app; deleting notification tracks.

When should you use it:

Once you need to run some task on a scheduled basis. My own case: once a day, I want to fetch new content from server, compose a notification based on the content I got and show it to user.

What to do:

  1. First, let's create 2 activities: MainActivity, which starts notification-service and NotificationActivity, which will be started by clicking notification:

    activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:padding="16dp">
        <Button
            android:id="@+id/sendNotifications"
            android:onClick="onSendNotificationsButtonClick"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Start Sending Notifications Every 2 Hours!" />
    </RelativeLayout>
    

    MainActivity.java

    public class MainActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
        }
    
        public void onSendNotificationsButtonClick(View view) {
            NotificationEventReceiver.setupAlarm(getApplicationContext());
        }   
    }
    

    and NotificationActivity is any random activity you can come up with. NB! Don't forget to add both activities into AndroidManifest.

  2. Then let's create WakefulBroadcastReceiver broadcast receiver, I called NotificationEventReceiver in code above.

    Here, we'll set up AlarmManager to fire PendingIntent every 2 hours (or with any other frequency), and specify the handled actions for this intent in onReceive() method. In our case - wakefully start IntentService, which we'll specify in the later steps. This IntentService would generate notifications for us.

    Also, this receiver would contain some helper-methods like creating PendintIntents, which we'll use later

    NB1! As I'm using WakefulBroadcastReceiver, I need to add extra-permission into my manifest: <uses-permission android:name="android.permission.WAKE_LOCK" />

    NB2! I use it wakeful version of broadcast receiver, as I want to ensure, that the device does not go back to sleep during my IntentService's operation. In the hello-world it's not that important (we have no long-running operation in our service, but imagine, if you have to fetch some relatively huge files from server during this operation). Read more about Device Awake here.

    NotificationEventReceiver.java

    public class NotificationEventReceiver extends WakefulBroadcastReceiver {
    
        private static final String ACTION_START_NOTIFICATION_SERVICE = "ACTION_START_NOTIFICATION_SERVICE";
        private static final String ACTION_DELETE_NOTIFICATION = "ACTION_DELETE_NOTIFICATION";
        private static final int NOTIFICATIONS_INTERVAL_IN_HOURS = 2;
    
        public static void setupAlarm(Context context) {
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            PendingIntent alarmIntent = getStartPendingIntent(context);
            alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
                    getTriggerAt(new Date()),
                    NOTIFICATIONS_INTERVAL_IN_HOURS * AlarmManager.INTERVAL_HOUR,
                    alarmIntent);
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            Intent serviceIntent = null;
            if (ACTION_START_NOTIFICATION_SERVICE.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive from alarm, starting notification service");
                serviceIntent = NotificationIntentService.createIntentStartNotificationService(context);
            } else if (ACTION_DELETE_NOTIFICATION.equals(action)) {
                Log.i(getClass().getSimpleName(), "onReceive delete notification action, starting notification service to handle delete");
                serviceIntent = NotificationIntentService.createIntentDeleteNotification(context);
            }
    
            if (serviceIntent != null) {
                startWakefulService(context, serviceIntent);
            }
        }
    
        private static long getTriggerAt(Date now) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(now);
            //calendar.add(Calendar.HOUR, NOTIFICATIONS_INTERVAL_IN_HOURS);
            return calendar.getTimeInMillis();
        }
    
        private static PendingIntent getStartPendingIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_START_NOTIFICATION_SERVICE);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    
        public static PendingIntent getDeleteIntent(Context context) {
            Intent intent = new Intent(context, NotificationEventReceiver.class);
            intent.setAction(ACTION_DELETE_NOTIFICATION);
            return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        }
    }
    
  3. Now let's create an IntentService to actually create notifications.

    There, we specify onHandleIntent() which is responses on NotificationEventReceiver's intent we passed in startWakefulService method.

    If it's Delete action - we can log it to our analytics, for example. If it's Start notification intent - then by using NotificationCompat.Builder we're composing new notification and showing it by NotificationManager.notify. While composing notification, we are also setting pending intents for click and remove actions. Fairly Easy.

    NotificationIntentService.java

    public class NotificationIntentService extends IntentService {
    
        private static final int NOTIFICATION_ID = 1;
        private static final String ACTION_START = "ACTION_START";
        private static final String ACTION_DELETE = "ACTION_DELETE";
    
        public NotificationIntentService() {
            super(NotificationIntentService.class.getSimpleName());
        }
    
        public static Intent createIntentStartNotificationService(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_START);
            return intent;
        }
    
        public static Intent createIntentDeleteNotification(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_DELETE);
            return intent;
        }
    
        @Override
        protected void onHandleIntent(Intent intent) {
            Log.d(getClass().getSimpleName(), "onHandleIntent, started handling a notification event");
            try {
                String action = intent.getAction();
                if (ACTION_START.equals(action)) {
                    processStartNotification();
                }
                if (ACTION_DELETE.equals(action)) {
                    processDeleteNotification(intent);
                }
            } finally {
                WakefulBroadcastReceiver.completeWakefulIntent(intent);
            }
        }
    
        private void processDeleteNotification(Intent intent) {
            // Log something?
        }
    
        private void processStartNotification() {
            // Do something. For example, fetch fresh data from backend to create a rich notification?
    
            final NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Scheduled Notification")
                    .setAutoCancel(true)
                    .setColor(getResources().getColor(R.color.colorAccent))
                    .setContentText("This notification has been triggered by Notification Service")
                    .setSmallIcon(R.drawable.notification_icon);
    
            PendingIntent pendingIntent = PendingIntent.getActivity(this,
                    NOTIFICATION_ID,
                    new Intent(this, NotificationActivity.class),
                    PendingIntent.FLAG_UPDATE_CURRENT);
            builder.setContentIntent(pendingIntent);
            builder.setDeleteIntent(NotificationEventReceiver.getDeleteIntent(this));
    
            final NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
            manager.notify(NOTIFICATION_ID, builder.build());
        }
    }
    
  4. Almost done. Now I also add broadcast receiver for BOOT_COMPLETED, TIMEZONE_CHANGED, and TIME_SET events to re-setup my AlarmManager, once device has been rebooted or timezone has changed (For example, user flown from USA to Europe and you don't want notification to pop up in the middle of the night, but was sticky to the local time :-) ).

    NotificationServiceStarterReceiver.java

    public final class NotificationServiceStarterReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationEventReceiver.setupAlarm(context);
        }
    }
    
  5. We need to also register all our services, broadcast receivers in AndroidManifest:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="klogi.com.notificationbyschedule">
    
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
        <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
        <uses-permission android:name="android.permission.WAKE_LOCK" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <service
                android:name=".notifications.NotificationIntentService"
                android:enabled="true"
                android:exported="false" />
    
            <receiver android:name=".broadcast_receivers.NotificationEventReceiver" />
            <receiver android:name=".broadcast_receivers.NotificationServiceStarterReceiver">
                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                    <action android:name="android.intent.action.TIMEZONE_CHANGED" />
                    <action android:name="android.intent.action.TIME_SET" />
                </intent-filter>
            </receiver>
    
            <activity
                android:name=".NotificationActivity"
                android:label="@string/title_activity_notification"
                android:theme="@style/AppTheme.NoActionBar"/>
        </application>
    
    </manifest>
    

That's it!

The source code for this project you can find here. I hope, you will find this post helpful.

Listing available com ports with Python

Works only on Windows:

import winreg
import itertools

def serial_ports() -> list:
    path = 'HARDWARE\\DEVICEMAP\\SERIALCOMM'
    key = winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, path)

    ports = []
    for i in itertools.count():
        try:
            ports.append(winreg.EnumValue(key, i)[1])
        except EnvironmentError:
            break

    return ports

if __name__ == "__main__":
    ports = serial_ports()

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Java Comparator class to sort arrays

[...] How should Java Comparator class be declared to sort the arrays by their first elements in decreasing order [...]

Here's a complete example using Java 8:

import java.util.*;

public class Test {

    public static void main(String args[]) {

        int[][] twoDim = { {1, 2}, {3, 7}, {8, 9}, {4, 2}, {5, 3} };

        Arrays.sort(twoDim, Comparator.comparingInt(a -> a[0])
                                      .reversed());

        System.out.println(Arrays.deepToString(twoDim));
    }
}

Output:

[[8, 9], [5, 3], [4, 2], [3, 7], [1, 2]]

For Java 7 you can do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return Integer.compare(o2[0], o1[0]);
    }
});

If you unfortunate enough to work on Java 6 or older, you'd do:

Arrays.sort(twoDim, new Comparator<int[]>() {
    @Override
    public int compare(int[] o1, int[] o2) {
        return ((Integer) o2[0]).compareTo(o1[0]);
    }
});

Can one do a for each loop in java in reverse order?

Not without writing some custom code which will give you an enumerator which will reverse the elements for you.

You should be able to do it in Java by creating a custom implementation of Iterable which will return the elements in reverse order.

Then, you would instantiate the wrapper (or call the method, what-have-you) which would return the Iterable implementation which reverses the element in the for each loop.

How to connect to a docker container from outside the host (same network) [Windows]

After trying several things, this worked for me:

  • use the --publish=0.0.0.0:8080:8080 docker flag
  • set the virtualbox network mode to NAT, and don't use any port forwarding

With addresses other than 0.0.0.0 I had no success.

How to upload image in CodeIgniter?

//this is the code you have to use in you controller 

        $config['upload_path'] = './uploads/';  

// directory (http://localhost/codeigniter/index.php/your directory)

        $config['allowed_types'] = 'gif|jpg|png|jpeg';  
//Image type  

        $config['max_size'] = 0;    

 // I have chosen max size no limit 
        $new_name = time() . '-' . $_FILES["txt_file"]['name']; 

//Added time function in image name for no duplicate image 

        $config['file_name'] = $new_name;

//Stored the new name into $config['file_name']

        $this->load->library('upload', $config);

        if (!$this->upload->do_upload() && !empty($_FILES['txt_file']['name'])) {
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('production/create_images', $error);
        } else {
            $upload_data = $this->upload->data();   
        }

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

One line ftp server in python

Check out pyftpdlib from Giampaolo Rodola. It is one of the very best ftp servers out there for python. It's used in google's chromium (their browser) and bazaar (a version control system). It is the most complete implementation on Python for RFC-959 (aka: FTP server implementation spec).

To install:

pip3 install pyftpdlib

From the commandline:

python3 -m pyftpdlib

Alternatively 'my_server.py':

#!/usr/bin/env python3

from pyftpdlib import servers
from pyftpdlib.handlers import FTPHandler
address = ("0.0.0.0", 21)  # listen on every IP on my machine on port 21
server = servers.FTPServer(address, FTPHandler)
server.serve_forever()

There's more examples on the website if you want something more complicated.

To get a list of command line options:

python3 -m pyftpdlib --help

Note, if you want to override or use a standard ftp port, you'll need admin privileges (e.g. sudo).

How to suppress scientific notation when printing float values?

Most of the answers above require you to specify precision. But what if you want to display floats like this, with no unnecessary zeros:

1
0.1
0.01
0.001
0.0001
0.00001
0.000001
0.000000000001

numpy has an answer: np.format_float_positional

import numpy as np

def format_float(num):
    return np.format_float_positional(num, trim='-')

Correct way to handle conditional styling in React

You can use somthing like this.

render () {
    var btnClass = 'btn';
    if (this.state.isPressed) btnClass += ' btn-pressed';
    else if (this.state.isHovered) btnClass += ' btn-over';
    return <button className={btnClass}>{this.props.label}</button>;
  }

Or else, you can use classnames NPM package to make dynamic and conditional className props simpler to work with (especially more so than conditional string manipulation).

classNames('foo', 'bar'); // => 'foo bar'
classNames('foo', { bar: true }); // => 'foo bar'
classNames({ 'foo-bar': true }); // => 'foo-bar'
classNames({ 'foo-bar': false }); // => ''
classNames({ foo: true }, { bar: true }); // => 'foo bar'
classNames({ foo: true, bar: true }); // => 'foo bar'

SQL query for a carriage return in a string and ultimately removing carriage return

The main question was to remove the CR/LF. Using the replace and char functions works for me:

Select replace(replace(Name,char(10),''),char(13),'')

For Postgres or Oracle SQL, use the CHR function instead:

       replace(replace(Name,CHR(10),''),CHR(13),'')

How to bind a List to a ComboBox?

As you are referring to a combobox, I'm assuming you don't want to use 2-way databinding (if so, look at using a BindingList)

public class Country
{
    public string Name { get; set; }
    public IList<City> Cities { get; set; }
    public Country(string _name)
    {
        Cities = new List<City>();
        Name = _name;
    }
}



List<Country> countries = new List<Country> { new Country("UK"), 
                                     new Country("Australia"), 
                                     new Country("France") };

var bindingSource1 = new BindingSource();
bindingSource1.DataSource = countries;

comboBox1.DataSource = bindingSource1.DataSource;

comboBox1.DisplayMember = "Name";
comboBox1.ValueMember = "Name";

To find the country selected in the bound combobox, you would do something like: Country country = (Country)comboBox1.SelectedItem;.

If you want the ComboBox to dynamically update you'll need to make sure that the data structure that you have set as the DataSource implements IBindingList; one such structure is BindingList<T>.


Tip: make sure that you are binding the DisplayMember to a Property on the class and not a public field. If you class uses public string Name { get; set; } it will work but if it uses public string Name; it will not be able to access the value and instead will display the object type for each line in the combo box.

System not declared in scope?

Chances are that you've not included the header file that declares system().

In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include preprocessor directive. As the code does not #include the header file in which system() is declared, the compilation fails.

To fix this issue, find out which header file provides you with the declaration of system() and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>

Java POI : How to read Excel cell value and not the formula computing it?

Previously posted solutions did not work for me. cell.getRawValue() returned the same formula as stated in the cell. The following function worked for me:

public void readFormula() throws IOException {
    FileInputStream fis = new FileInputStream("Path of your file");
    Workbook wb = new XSSFWorkbook(fis);
    Sheet sheet = wb.getSheetAt(0);
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

    CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
    Row row = sheet.getRow(cellReference.getRow());
    Cell cell = row.getCell(cellReference.getCol());

    CellValue cellValue = evaluator.evaluate(cell);

    switch (cellValue.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cellValue.getBooleanValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println(cellValue.getNumberValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println(cellValue.getStringValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_ERROR:
            break;

        // CELL_TYPE_FORMULA will never happen
        case Cell.CELL_TYPE_FORMULA:
            break;
    }

}

Mocking static methods with Mockito

Use PowerMockito on top of Mockito.

Example code:

@RunWith(PowerMockRunner.class)
@PrepareForTest(DriverManager.class)
public class Mocker {

    @Test
    public void shouldVerifyParameters() throws Exception {

        //given
        PowerMockito.mockStatic(DriverManager.class);
        BDDMockito.given(DriverManager.getConnection(...)).willReturn(...);

        //when
        sut.execute(); // System Under Test (sut)

        //then
        PowerMockito.verifyStatic();
        DriverManager.getConnection(...);

    }

More information:

Python concatenate text files

I don't know about elegance, but this works:

    import glob
    import os
    for f in glob.glob("file*.txt"):
         os.system("cat "+f+" >> OutFile.txt")

Android ListView with onClick items

lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Intent i = new Intent(getActivity(), DiscussAddValu.class);
        startActivity(i);
    }
});

Display array values in PHP

a simple code snippet that i prepared, hope it will be usefull for you;

$ages = array("Kerem"=>"35","Ahmet"=>"65","Talip"=>"62","Kamil"=>"60");

reset($ages);

for ($i=0; $i < count($ages); $i++){
echo "Key : " . key($ages) . " Value : " . current($ages) . "<br>";
next($ages);
}
reset($ages);

Jquery Validate custom error message location

You can simply create extra conditions which match the fields you require in the same function. For example, using your code above...

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            //Custom position: first name
            if (element.attr("name") == "first" ) {
                $("#errNm1").text(error);
            }
            //Custom position: second name
            else if (element.attr("name") == "second" ) {
                $("#errNm2").text(error);
            }
            // Default position: if no match is met (other fields)
            else {
                 error.append($('.errorTxt span'));
            }
        },
        rules
});

Hope that helps!

How to make Bootstrap Panel body with fixed height

You can use max-height in an inline style attribute, as below:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

To use scrolling with content that overflows a given max-height, you can alternatively try the following:

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>

To restrict the height to a fixed value you can use something like this.

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>

Specify the same value for both max-height and min-height (either in pixels or in points – as long as it’s consistent).

You can also put the same styles in css class in a stylesheet (or a style tag as shown below) and then include the same in your tag. See below:

Style Code:

.fixed-panel {
  min-height: 10;
  max-height: 10;
  overflow-y: scroll;
}

Apply Style :

<div class="panel panel-primary">
  <div class="panel-heading">jhdsahfjhdfhs</div>
  <div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>

Hope this helps with your need.

Deploy a project using Git push

Sounds like you should have two copies on your server. A bare copy, that you can push/pull from, which your would push your changes when you're done, and then you would clone this into you web directory and set up a cronjob to update git pull from your web directory every day or so.

Junit - run set up method once

JUnit 5 @BeforeAll can be non static provided the lifecycle of the test class is per class, i.e., annotate the test class with a @TestInstance(Lifecycle.PER_CLASS) and you are good to go

Why is "throws Exception" necessary when calling a function?

Exception is a checked exception class. Therefore, any code that calls a method that declares that it throws Exception must handle or declare it.

Populating spinner directly in the layout xml

Define this in your String.xml file and name the array what you want, such as "Weight"

<string-array name="Weight">
<item>Kg</item>
<item>Gram</item>
<item>Tons</item>
</string-array>

and this code in your layout.xml

<Spinner 
        android:id="@+id/fromspin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:entries="@array/Weight"
 />

In your java file, getActivity is used in fragment; if you write that code in activity, then remove getActivity.

a = (Spinner) findViewById(R.id.fromspin);

 ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this.getActivity(),
                R.array.weight, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        a.setAdapter(adapter);
        a.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
                if (a.getSelectedItem().toString().trim().equals("Kilogram")) {
                    if (!b.getText().toString().isEmpty()) {
                        float value1 = Float.parseFloat(b.getText().toString());
                        float kg = value1;
                        c.setText(Float.toString(kg));
                        float gram = value1 * 1000;
                        d.setText(Float.toString(gram));
                        float carat = value1 * 5000;
                        e.setText(Float.toString(carat));
                        float ton = value1 / 908;
                        f.setText(Float.toString(ton));
                    }

                }



            public void onNothingSelected(AdapterView<?> parent) {
                // Another interface callback
            }
        });
        // Inflate the layout for this fragment
        return v;
    }

Qt: How do I handle the event of the user pressing the 'X' (close) button?

You can attach a SLOT to the

void aboutToQuit();

signal of your QApplication. This signal should be raised just before app closes.

get path for my .exe

In addition:

AppDomain.CurrentDomain.BaseDirectory
Assembly.GetEntryAssembly().Location

How to sort two lists (which reference each other) in the exact same way

I would like to suggest a solution if you need to sort more than 2 lists in sync:

def SortAndSyncList_Multi(ListToSort, *ListsToSync):
    y = sorted(zip(ListToSort, zip(*ListsToSync)))
    w = [n for n in zip(*y)]
    return list(w[0]), tuple(list(a) for a in zip(*w[1]))

IIS7: A process serving application pool 'YYYYY' suffered a fatal communication error with the Windows Process Activation Service

Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789

CSS for grabbing cursors (drag & drop)

You can create your own cursors and set them as the cursor using cursor: url('path-to-your-cursor');, or find Firefox's and copy them (bonus: a nice consistent look in every browser).

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

I do the "in clause" query with spring jdbc like this:

String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";

List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
NamedParameterJdbcTemplate template = 
    new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());

List<Long> list = template.queryForList(sql, paramMap, Long.class);

Disable button in jQuery

This is the simplest way in my opinion:

_x000D_
_x000D_
// All buttons where id contains 'rbutton_'_x000D_
const $buttons = $("button[id*='rbutton_']");_x000D_
_x000D_
//Selected button onclick_x000D_
$buttons.click(function() {_x000D_
    $(this).prop('disabled', true); //disable clicked button_x000D_
});_x000D_
_x000D_
//Enable button onclick_x000D_
$('#enable').click(() =>_x000D_
    $buttons.prop('disabled', false) //enable all buttons_x000D_
);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="rbutton_200">click</button>_x000D_
<button id="rbutton_201">click</button>_x000D_
<button id="rbutton_202">click</button>_x000D_
<button id="rbutton_203">click</button>_x000D_
<button id="rbutton_204">click</button>_x000D_
<button id="rbutton_205">click</button>_x000D_
<button id="enable">enable</button>
_x000D_
_x000D_
_x000D_

How to connect android emulator to the internet

In eclipse go to DDMS

under DDMS select Emulator Control ,which contains Telephony Status in telephony status contain data -->select Home , this will enable your internet connection ,if you want disable internet connection for Emulator then --->select None

(Note: This will enable internet connections only if you PC/laptop on which you are running your eclipse have active internet connections.)

Using Git with Visual Studio

I use Git with Visual Studio for my port of Protocol Buffers to C#. I don't use the GUI - I just keep a command line open as well as Visual Studio.

For the most part it's fine - the only problem is when you want to rename a file. Both Git and Visual Studio would rather that they were the one to rename it. I think that renaming it in Visual Studio is the way to go though - just be careful what you do at the Git side afterwards. Although this has been a bit of a pain in the past, I've heard that it actually should be pretty seamless on the Git side, because it can notice that the contents will be mostly the same. (Not entirely the same, usually - you tend to rename a file when you're renaming the class, IME.)

But basically - yes, it works fine. I'm a Git newbie, but I can get it to do everything I need it to. Make sure you have a git ignore file for bin and obj, and *.user.

In the shell, what does " 2>&1 " mean?

I found this brilliant post on redirection: All about redirections

Redirect both standard output and standard error to a file

$ command &>file

This one-liner uses the &> operator to redirect both output streams - stdout and stderr - from command to file. This is Bash's shortcut for quickly redirecting both streams to the same destination.

Here is how the file descriptor table looks like after Bash has redirected both streams:

Enter image description here

As you can see, both stdout and stderr now point to file. So anything written to stdout and stderr gets written to file.

There are several ways to redirect both streams to the same destination. You can redirect each stream one after another:

$ command >file 2>&1

This is a much more common way to redirect both streams to a file. First stdout is redirected to file, and then stderr is duplicated to be the same as stdout. So both streams end up pointing to file.

When Bash sees several redirections it processes them from left to right. Let's go through the steps and see how that happens. Before running any commands, Bash's file descriptor table looks like this:

Enter image description here

Now Bash processes the first redirection >file. We've seen this before and it makes stdout point to file:

Enter image description here

Next Bash sees the second redirection 2>&1. We haven't seen this redirection before. This one duplicates file descriptor 2 to be a copy of file descriptor 1 and we get:

Enter image description here

Both streams have been redirected to file.

However be careful here! Writing

command >file 2>&1

is not the same as writing:

$ command 2>&1 >file

The order of redirects matters in Bash! This command redirects only the standard output to the file. The stderr will still print to the terminal. To understand why that happens, let's go through the steps again. So before running the command, the file descriptor table looks like this:

Enter image description here

Now Bash processes redirections left to right. It first sees 2>&1 so it duplicates stderr to stdout. The file descriptor table becomes:

Enter image description here

Now Bash sees the second redirect, >file, and it redirects stdout to file:

Enter image description here

Do you see what happens here? Stdout now points to file, but the stderr still points to the terminal! Everything that gets written to stderr still gets printed out to the screen! So be very, very careful with the order of redirects!

Also note that in Bash, writing

$ command &>file

is exactly the same as:

$ command >&file

How to rotate x-axis tick labels in Pandas barplot

Pass param rot=0 to rotate the xticks:

import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()

yields plot:

enter image description here

Is it possible to Turn page programmatically in UIPageViewController?

- (void)moveToPage {

    NSUInteger pageIndex = ((ContentViewController *) [self.pageViewController.viewControllers objectAtIndex:0]).pageIndex;

    pageIndex++;

    ContentViewController *viewController = [self viewControllerAtIndex:pageIndex];

if (viewController == nil) {
        return;
    }
    [self.pageViewController setViewControllers:@[viewController] direction:UIPageViewControllerNavigationDirectionForward animated:YES completion:nil];

}

//now call this method

[self moveToPage];

I hope it works :)

Removing all line breaks and adding them after certain text

I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

Blocks are the way to go. You can have complex parameters, type safety, and it's a lot simpler and safer than most of the old answers here. For example, you could just write:

[MONBlock performBlock:^{[obj setFrame:SOMETHING];} afterDelay:2];

Blocks allow you to capture arbitrary parameter lists, reference objects and variables.

Backing Implementation (basic):

@interface MONBlock : NSObject

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay;

@end

@implementation MONBlock

+ (void)imp_performBlock:(void(^)())pBlock
{
 pBlock();
}

+ (void)performBlock:(void(^)())pBlock afterDelay:(NSTimeInterval)pDelay
{
  [self performSelector:@selector(imp_performBlock:)
             withObject:[pBlock copy]
             afterDelay:pDelay];
}

@end

Example:

int main(int argc, const char * argv[])
{
 @autoreleasepool {
  __block bool didPrint = false;
  int pi = 3; // close enough =p

  [MONBlock performBlock:^{NSLog(@"Hello, World! pi is %i", pi); didPrint = true;} afterDelay:2];

  while (!didPrint) {
   [NSRunLoop.currentRunLoop runUntilDate:[NSDate dateWithTimeInterval:0.1 sinceDate:NSDate.date]];
  }

  NSLog(@"(Bye, World!)");
 }
 return 0;
}

Also see Michael's answer (+1) for another example.

SQL string value spanning multiple lines in query

What's the column "BIO" datatype? What database server (sql/oracle/mysql)? You should be able to span over multiple lines all you want as long as you adhere to the character limit in the column's datatype (ie: varchar(200) ). Try using single quotes, that might make a difference. This works for me:

update table set mycolumn = 'hello world,
my name is carlos.
goodbye.'
where id = 1;

Also, you might want to put in checks for single quotes if you are concatinating the sql string together in C#. If the variable contains single quotes that could escape the code out of the sql statement, therefore, not doing all the lines you were expecting to see.

BTW, you can delimit your SQL statements with a semi colon like you do in C#, just as FYI.

$(document).ready(function() is not working

I just had this issue and it was because of me trying to included jQuery via http while my page was loaded as https.

How to Remove Array Element and Then Re-Index Array?

2020 Benchmark in PHP 7.4

For these who are not satisfied with current answers, I did a little benchmark script, anyone can run from CLI.

We are going to compare two solutions:

unset() with array_values() VS array_splice().

<?php

echo 'php v' . phpversion() . "\n";

$itemsOne = [];
$itemsTwo = [];

// populate items array with 100k random strings
for ($i = 0; $i < 100000; $i++) {
    $itemsOne[] = $itemsTwo[] = sha1(uniqid(true));
}

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    unset($itemsOne[$i]);
    $itemsOne = array_values($itemsOne);
}

$end = microtime(true);

echo 'unset & array_values: ' . ($end - $start) . 's' . "\n";

$start = microtime(true);

for ($i = 0; $i < 10000; $i++) {
    array_splice($itemsTwo, $i, 1);
}

$end = microtime(true);

echo 'array_splice: ' . ($end - $start) . 's' . "\n"; 

As you can see the idea is simple:

  • Create two arrays both with the same 100k items (randomly generated strings)
  • Remove 10k first items from first array using unset() and array_values() to reindex
  • Remove 10k first items from second array using array_splice()
  • Measure time for both methods

Output of the script above on my Dell Latitude i7-6600U 2.60GHz x 4 and 15.5GiB RAM:

php v7.4.8
unset & array_values: 29.089932918549s
array_splice: 17.94264793396s

Verdict: array_splice is almost twice more performant than unset and array_values.

So: array_splice is the winner!

How to split a string and assign it to variables

Since go is flexible an you can create your own python style split ...

package main

import (
    "fmt"
    "strings"
    "errors"
)

type PyString string

func main() {
    var py PyString
    py = "127.0.0.1:5432"
    ip, port , err := py.Split(":")       // Python Style
    fmt.Println(ip, port, err)
}

func (py PyString) Split(str string) ( string, string , error ) {
    s := strings.Split(string(py), str)
    if len(s) < 2 {
        return "" , "", errors.New("Minimum match not found")
    }
    return s[0] , s[1] , nil
}

How to run the Python program forever?

sleep is a good way to avoid overload on the cpu

not sure if it's really clever, but I usually use

while(not sleep(5)):
    #code to execute

sleep method always returns None.

Vue-router redirect on page not found (404)

I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:

const ROUTER_INSTANCE = new VueRouter({
    mode: "history",
    routes: [
        { path: "/", component: HomeComponent },
        // ... other routes ...
        // and finally the default route, when none of the above matches:
        { path: "*", component: PageNotFound }
    ]
})

In the above PageNotFound component definition, you can specify the actual redirect, that will take you out of the app entirely:

Vue.component("page-not-found", {
    template: "",
    created: function() {
        // Redirect outside the app using plain old javascript
        window.location.href = "/my-new-404-page.html";
    }
}

You may do it either on created hook as shown above, or mounted hook also.

Please note:

  1. I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli as it requires server side handling.

  2. Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">. This will fail for your /404-page.html unless your server treats it as a special case and serves the static page.

Let me know if it works!

Update for Vue 3 onward:

You'll need to replace the '*' path property with '/:pathMatch(.*)*' if you're using Vue 3 as the old catch-all path of '*' is no longer supported. The route would then look something like this:

{ path: '/:pathMatch(.*)*', component: PathNotFound },

See the docs for more info on this update.

Get JSON object from URL

Our solution, adding some validations to response so we are sure we have a well formed json object in $json variable

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$result = curl_exec($ch);
curl_close($ch);
if (! $result) {
    return false;
}

$json = json_decode(utf8_encode($result));
if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
    return false;
}

How to loop through a dataset in powershell?

The parser is having trouble concatenating your string. Try this:

write-host 'value is : '$i' '$($ds.Tables[1].Rows[$i][0])

Edit: Using double quotes might also be clearer since you can include the expressions within the quoted string:

write-host "value is : $i $($ds.Tables[1].Rows[$i][0])"

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Does Android support near real time push notification?

I have been looking into this and PubSubHubBub recommended by jamesh is not an option. PubSubHubBub is intended for server to server communications

"I'm behind a NAT. Can I subscribe to a Hub? The hub can't connect to me."

/Anonymous

No, PSHB is a server-to-server protocol. If you're behind NAT, you're not really a server. While we've kicked around ideas for optional PSHB extensions to do hanging gets ("long polling") and/or messagebox polling for such clients, it's not in the core spec. The core spec is server-to-server only.

/Brad Fitzpatrick, San Francisco, CA

Source: http://moderator.appspot.com/#15/e=43e1a&t=426ac&f=b0c2d (direct link not possible)

I've come to the conclusion that the simplest method is to use Comet HTTP push. This is both a simple and well understood solution but it can also be re-used for web applications.

How to draw a circle with given X and Y coordinates as the middle spot of the circle?

drawCircle(int X, int Y, int Radius, ColorFill, Graphics gObj) 

How to create an HTTPS server in Node.js?

The above answers are good but with Express and node this will work fine.

Since express create the app for you, I'll skip that here.

var express = require('express')
  , fs = require('fs')
  , routes = require('./routes');

var privateKey = fs.readFileSync('cert/key.pem').toString();
var certificate = fs.readFileSync('cert/certificate.pem').toString();  

// To enable HTTPS
var app = module.exports = express.createServer({key: privateKey, cert: certificate});

How to POST using HTTPclient content type = application/x-www-form-urlencoded

The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

Decode JSON with unknown structure

The issue I had is that sometimes I will need to get at a value that is deeply nested. Normally you would need to do a type assertion at each level, so I went ahead and just made a method that takes a map[string]interface{} and a string key, and returns the resulting map[string]interface{}.

The issue that cropped up for me was that at some depths you will encounter a Slice instead of Map. So I also added methods to return a Slice from Map, and Map from Slice. I didnt do one for Slice to Slice, but you could easily add that if needed. Here are the methods:

package main
type Slice []interface{}
type Map map[string]interface{}

func (m Map) M(s string) Map {
   return m[s].(map[string]interface{})
}

func (m Map) A(s string) Slice {
   return m[s].([]interface{})
}

func (a Slice) M(n int) Map {
   return a[n].(map[string]interface{})
}

and example code:

package main

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

func main() {
   o, e := os.Open("a.json")
   if e != nil {
      log.Fatal(e)
   }
   in_m := Map{}
   json.NewDecoder(o).Decode(&in_m)
   out_m := in_m.
      M("contents").
      M("sectionListRenderer").
      A("contents").
      M(0).
      M("musicShelfRenderer").
      A("contents").
      M(0).
      M("musicResponsiveListItemRenderer").
      M("navigationEndpoint").
      M("browseEndpoint")
   fmt.Println(out_m)
}

Show red border for all invalid fields after submitting form angularjs

Reference article: Show red color border for invalid input fields angualrjs

I used ng-class on all input fields.like below

<input type="text" ng-class="{submitted:newEmployee.submitted}" placeholder="First Name" data-ng-model="model.firstName" id="FirstName" name="FirstName" required/>

when I click on save button I am changing newEmployee.submitted value to true(you can check it in my question). So when I click on save, a class named submitted gets added to all input fields(there are some other classes initially added by angularjs).

So now my input field contains classes like this

class="ng-pristine ng-invalid submitted"

now I am using below css code to show red border on all invalid input fields(after submitting the form)

input.submitted.ng-invalid
{
  border:1px solid #f00;
}

Thank you !!

Update:

We can add the ng-class at the form element instead of applying it to all input elements. So if the form is submitted, a new class(submitted) gets added to the form element. Then we can select all the invalid input fields using the below selector

form.submitted .ng-invalid
{
    border:1px solid #f00;
}

How do I remove/delete a virtualenv?

If you are using pyenv, it is possible to delete your virtual environment:

$ pyenv virtualenv-delete <name>

Render partial view with dynamic model in Razor view engine and ASP.NET MVC 3

Just found the answer, it appears that the view where I was placing the RenderPartial code had a dynamic model, and thus, MVC couldn't choose the correct method to use. Casting the model in the RenderPartial call to the correct type fixed the issue.

source: Using Html.RenderPartial() in ascx files

PHP remove all characters before specific string

Considering

$string="We have www/audio path where the audio files are stored";  //Considering the string like this

Either you can use

strstr($string, 'www/audio');

Or

$expStr=explode("www/audio",$string);
$resultString="www/audio".$expStr[1];

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

OK, I found this post: http://msdn.microsoft.com/en-us/library/aa479319.aspx

with this very illustrative diagram:

diagram
(source: microsoft.com)

in essence, to get at those exception details i need to store them myself in Global.asax, for later retrieval on my custom error page.

it seems the best way is to do the bulk of the work in Global.asax, with the custom error pages handling helpful content rather than logic.

Add space between <li> elements

Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:

_x000D_
_x000D_
li {_x000D_
  background: red;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
 margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background: silver;_x000D_
  padding: 1px;  _x000D_
  padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.

Node.js: Gzip compression?

While as others have right pointed out using a front end webserver such as nginx can handle this implicitly, another option, is to use nodejitsu's excellent node-http-proxy to serve up your assets.

eg:

httpProxy.createServer(
 require('connect-gzip').gzip(),
 9000, 'localhost'
).listen(8000);

This example demonstrates support for gzip compression through the use of connect middleware module: connect-gzip.

How to check if a value exists in an array in Ruby

it has many ways to find a element in any array but the simplest way is 'in ?' method.

example:
arr = [1,2,3,4]
number = 1
puts "yes #{number} is present in arr" if number.in? arr

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

How connect Postgres to localhost server using pgAdmin on Ubuntu?

if you open the psql console in a terminal window, by typing

$ psql

you're super user username will be shown before the =#, for example:

elisechant=#$

That will be the user name you should use for localhost.

Java stack overflow error - how to increase the stack size in Eclipse?

Add the flag -Xss1024k in the VM Arguments.

You can also increase stack size in mb by using -Xss1m for example .

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

How can I check if an ip is in a network in Python?

I don't know of anything in the standard library, but PySubnetTree is a Python library that will do subnet matching.

Installing a dependency with Bower from URL and specify version

Use a git endpoint instead of a package name:

bower install https://github.com/jquery/jquery.git#2.0.3

Can the :not() pseudo-class have multiple arguments?

Why :not just use two :not:

input:not([type="radio"]):not([type="checkbox"])

Yes, it is intentional

Different ways of loading a file as an InputStream

Plain old Java on plain old Java 7 and no other dependencies demonstrates the difference...

I put file.txt in c:\temp\ and I put c:\temp\ on the classpath.

There is only one case where there is a difference between the two call.

class J {

 public static void main(String[] a) {
    // as "absolute"

    // ok   
    System.err.println(J.class.getResourceAsStream("/file.txt") != null); 

    // pop            
    System.err.println(J.class.getClassLoader().getResourceAsStream("/file.txt") != null); 

    // as relative

    // ok
    System.err.println(J.class.getResourceAsStream("./file.txt") != null); 

    // ok
    System.err.println(J.class.getClassLoader().getResourceAsStream("./file.txt") != null); 

    // no path

    // ok
    System.err.println(J.class.getResourceAsStream("file.txt") != null); 

   // ok
   System.err.println(J.class.getClassLoader().getResourceAsStream("file.txt") != null); 
  }
}

What can cause intermittent ORA-12519 (TNS: no appropriate handler found) errors

I also had the same problem, I searched for the answers many places. I got many similar answers to change the number of process/service handlers. But I thought, what if I forgot to reset it back?

Then I tried using Thread.sleep() method after each of my connection.close();.

I don't know how, but it's working at least for me.

If any one wants to try it out and figure out how it's working then please go ahead. I would also like to know it as I am a beginner in programming world.

How to remove all characters after a specific character in python?

If you want to remove everything after the last occurrence of separator in a string I find this works well:

<separator>.join(string_to_split.split(<separator>)[:-1])

For example, if string_to_split is a path like root/location/child/too_far.exe and you only want the folder path, you can split by "/".join(string_to_split.split("/")[:-1]) and you'll get root/location/child

How to extract public key using OpenSSL?

For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-

openssl rsa -noout -text -inform PEM -in key.pub -pubin

or for the private key file, this:-

openssl rsa -noout -text -in key.private

which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

Understanding colors on Android (six characters)

If you provide 6 hex digits, that means RGB (2 hex digits for each value of red, green and blue).

If you provide 8 hex digits, it's an ARGB (2 hex digits for each value of alpha, red, green and blue respectively).

So by removing the final 55 you're changing from A=B4, R=55, G=55, B=55 (a mostly transparent grey), to R=B4, G=55, B=55 (a fully-non-transparent dusky pinky).

See the "Color" documentation for the supported formats.

Command to get nth line of STDOUT

Yes, the most efficient way (as already pointed out by Jonathan Leffler) is to use sed with print & quit:

set -o pipefail                        # cf. help set
time -p ls -l | sed -n -e '2{p;q;}'    # only print the second line & quit (on Mac OS X)
echo "$?: ${PIPESTATUS[*]}"            # cf. man bash | less -p 'PIPESTATUS'

Installing tensorflow with anaconda in windows

If you have anaconda version 2.7 installed on your windows, then go to anaconda prompt, type these two commands:

  1. Create a conda environment for tensorflow using conda create -n tensorflow_env tensorflow
  2. activate the tensorflow using conda activate tensorflow_env

If it is activated, then the base will be replaced by tensorflow_env i.e. now it will show (tensorflow_env) C:\Users>

You can now use import tensorflow as tf for using tensorflow in your code.

Get Insert Statement for existing row in MySQL

I use the program SQLYOG where I can make a select query, point atscreenshot the results and choose export as sql. This gives me the insert statements.

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

You don't need both hibernate.cfg.xml and persistence.xml in this case. Have you tried removing hibernate.cfg.xml and mapping everything in persistence.xml only?

But as the other answer also pointed out, this is not okay like this:

@Id
@JoinColumn(name = "categoria") 
private String id;

Didn't you want to use @Column instead?

Reading a UTF8 CSV file with Python

The link to the help page is the same for python 2.6 and as far as I know there was no change in the csv module since 2.5 (besides bug fixes). Here is the code that just works without any encoding/decoding (file da.csv contains the same data as the variable data). I assume that your file should be read correctly without any conversions.

test.py:

## -*- coding: utf-8 -*-
#
# NOTE: this first line is important for the version b) read from a string(unicode) variable
#

import csv

data = \
"""0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert"""

# a) read from a file
print 'reading from a file:'
for (f1, f2, f3) in csv.reader(open('da.csv'), dialect=csv.excel):
    print (f1, f2, f3)

# b) read from a string(unicode) variable
print 'reading from a list of strings:'
reader = csv.reader(data.split('\n'), dialect=csv.excel)
for (f1, f2, f3) in reader:
    print (f1, f2, f3)

da.csv:

0665000FS10120684,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Bleu
0665000FS10120689,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Gris
0665000FS10120687,SD1200IS,Appareil photo numérique PowerShot de 10 Mpx de Canon avec trépied (SD1200IS) - Vert

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use Object.entries to get each element of Object in key & value format, then map through them like this:

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}_x000D_
_x000D_
var res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));_x000D_
_x000D_
console.log(res);
_x000D_
_x000D_
_x000D_

But, if you are certain that the keys will be in progressive order you can use Object.values and Array#map to do something like this:

_x000D_
_x000D_
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}; _x000D_
_x000D_
                        // idx is the index, you can use any logic to increment it (starts from 0)_x000D_
let result = Object.values(obj).map((e, idx) => ([++idx, e]));_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How do I get the Date & Time (VBS)

nowreturns the current date and time

how does Request.QueryString work?

The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.

Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

I like to keep is simple when possible. I needed to group by International, filter on all the columns, display the count for each group and hide the group if no items existed.

Plus I did not want to add a custom filter just for something simple like this.

        <tbody>
            <tr ng-show="fusa.length > 0"><td colspan="8"><h3>USA ({{fusa.length}})</h3></td></tr>
            <tr ng-repeat="t in fusa = (usa = (vm.assignmentLookups | filter: {isInternational: false}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>
        <tbody>
            <tr ng-show="fint.length > 0"><td colspan="8"><h3>International ({{fint.length}})</h3></td></tr>
            <tr ng-repeat="t in fint = (int = (vm.assignmentLookups | filter: {isInternational: true}) | filter: vm.searchResultText)">
                <td>{{$index + 1}}</td>
                <td ng-bind-html="vm.highlight(t.title, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.genericName, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.mechanismsOfAction, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.diseaseStateIndication, vm.searchResultText)"></td>
                <td ng-bind-html="vm.highlight(t.assignedTo, vm.searchResultText)"></td>
                <td ng-bind-html="t.lastPublished | date:'medium'"></td>
            </tr>
        </tbody>

How to convert php array to utf8?

A more general function to encode an array is:

/**
 * also for multidemensional arrays
 *
 * @param array $array
 * @param string $sourceEncoding
 * @param string $destinationEncoding
 *
 * @return array
 */
function encodeArray(array $array, string $sourceEncoding, string $destinationEncoding = 'UTF-8'): array
{
    if($sourceEncoding === $destinationEncoding){
        return $array;
    }

    array_walk_recursive($array,
        function(&$array) use ($sourceEncoding, $destinationEncoding) {
            $array = mb_convert_encoding($array, $destinationEncoding, $sourceEncoding);
        }
    );

    return $array;
}

Change a Git remote HEAD to point to something besides master

First, create the new branch you would like to set as your default, for example:

$>git branch main

Next, push that branch to the origin:

$>git push origin main

Now when you login to your GitHub account, you can go to your repository and choose Settings>Default Branch and choose "main."

Then, if you so choose, you can delete the master branch:

$>git push origin :master

How to urlencode data for curl command?

This is the ksh version of orwellophile's answer containing the rawurlencode and rawurldecode functions (link: How to urlencode data for curl command?). I don't have enough rep to post a comment, hence the new post..

#!/bin/ksh93

function rawurlencode
{
    typeset string="${1}"
    typeset strlen=${#string}
    typeset encoded=""

    for (( pos=0 ; pos<strlen ; pos++ )); do
        c=${string:$pos:1}
        case "$c" in
            [-_.~a-zA-Z0-9] ) o="${c}" ;;
            * )               o=$(printf '%%%02x' "'$c")
        esac
        encoded+="${o}"
    done
    print "${encoded}"
}

function rawurldecode
{
    printf $(printf '%b' "${1//%/\\x}")
}

print $(rawurlencode "C++")     # --> C%2b%2b
print $(rawurldecode "C%2b%2b") # --> C++

android:drawableLeft margin and/or padding

TextView has an android:drawablePadding property which should do the trick:

android:drawablePadding

The padding between the drawables and the text.

Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).

This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.

This corresponds to the global attribute resource symbol drawablePadding.

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

How to set background image in Java?

Or try this ;)

try {
  this.setContentPane(
    new JLabel(new ImageIcon(ImageIO.read(new File("your_file.jpeg")))));
} catch (IOException e) {};

npm check and update package if needed

  • To update a single local package:

    1. First find out your outdated packages:

      npm outdated

    2. Then update the package or packages that you want manually as:

      npm update --save package_name

This way it is not necessary to update your local package.json file.

Note that this will update your package to the latest version.

  • If you write some version in your package.json file and do:

    npm update package_name

    In this case you will get just the next stable version (wanted) regarding the version that you wrote in your package.json file.

And with npm list (package_name) you can find out the current version of your local packages.

Event for Handling the Focus of the EditText

Here is the focus listener example.

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean hasFocus) {
        if (hasFocus) {
            Toast.makeText(getApplicationContext(), "Got the focus", Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Lost the focus", Toast.LENGTH_LONG).show();
        }
    }
});

IntelliJ - show where errors are

In IntelliJ Idea 2019 you can find scope "Problems" under the "Project" view. Default scope is "Project".

"Problems" scope

Displaying all table names in php from MySQL database

you need to assign the mysql_query to a variable (eg $result), then display this variable as you would a normal result from the database.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect

Demo: http://www.stoimen.com/jquery.client.plugin/

This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html

And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js

What are the best PHP input sanitizing functions?

Sanitizers

Sanitize is a function to check (and remove) harmful data from user input which can harm the software. Sanitizing user input is the most secure method of user input validation to strip out anything that is not on the whitelist.

PHP Support

5.4.0 - 5.4.45, 5.5.0 - 5.5.38, 5.6.0 - 5.6.40, 7.0.0 - 7.0.33, 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.27, 7.4.0 - 7.4.15, 8.0.0 - 8.0.2

<?php
require_once("path/to/Sanitizers.php");

use Sanitizers\Sanitizers\Sanitizer;

\\ passing `true` in Sanitizer class enables exceptions
$sanitize = new Sanitizer(true);
try {
    echo $sanitize->Username($_GET['username']);
} catch (Exception $e) {
    echo "Could not Sanitize user input." 
    var_dump($e);
}
?>

Download the latest release

See Sanitizers GitHub project.

Easiest way to compare arrays in C#

If you would like to handle null inputs gracefully, and ignore the order of items, try the following solution:

static class Extensions
{
    public static bool ItemsEqual<TSource>(this TSource[] array1, TSource[] array2)
    {
        if (array1 == null && array2 == null)
            return true;
        if (array1 == null || array2 == null)
            return false;
        if (array1.Count() != array2.Count())
            return false;
        return !array1.Except(array2).Any() && !array2.Except(array1).Any();
    }
}

The test code looks like:

public static void Main()
{
    int[] a1 = new int[] { 1, 2, 3 };
    int[] a2 = new int[] { 3, 2, 1 };
    int[] a3 = new int[] { 1, 3 };
    Console.WriteLine(a1.ItemsEqual(a2)); // Output: True.
    Console.WriteLine(a2.ItemsEqual(a3)); // Output: False.
    Console.WriteLine(a3.ItemsEqual(a2)); // Output: False.
   
    int[] a4 = new int[] { 1, 1 };
    int[] a5 = new int[] { 1, 2 };
    Console.WriteLine(a4.ItemsEqual(a5)); // Output: False 
    Console.WriteLine(a5.ItemsEqual(a4)); // Output: False 
    
    int[] a6 = null;
    int[] a7 = null;
    int[] a8 = new int[0];

    Console.WriteLine(a6.ItemsEqual(a7)); // Output: True. No Exception.
    Console.WriteLine(a8.ItemsEqual(a6)); // Output: False. No Exception.
    Console.WriteLine(a7.ItemsEqual(a8)); // Output: False. No Exception.
}

Unlink of file Failed. Should I try again?

In my situation the cause was that I had ran Visual Studio as an administrator earlier in the day. When I went to switch branches the error occurred.

I use GitExtensions and I run it as a regular users and files created by VS while running as an administrator ( run as Administrator, still me though) were not accessible. This was the root of the cause for me. I'm not sure why it happened in this situation because I regularly run VS as administrator on my primary development environment and have not experienced this problem before. But for some reason today the above scenario caused any files generated by VS during that session to be un-editable...you can read them, but not change or delete them and that is exactly what Git is going to do when you switch branches.

To resolve the problem for Git I had to start windows explorer as administrator and take ownership and re give myself permissions to files and directories in question. I don't fully understand why this as I was running explorer as Administrator too but it did.

You can do this for the files individually but I ended up doing this process for the root folder of the branch.

So the exact steps I did to fix the problem are: Went to the top of the branch in windows explorer, right clicked properties of the directory, select the security tab, advanced options which opens the Advanced Security Settings dialog, Selected change ownership at the top (it might show you already own it), I re-selected myself. Then it returns you to the 'Advanced Security Settings' dialog, at the bottom of remember to check the box 'Replace all object...' Then click apply The system cycles through each file and folder fixing ownership and that resolved the problem for me.

For me it had locked out my migrations folder and wouldn't let me switch branches...so I originally just fixed that directory and sub tree which allowed me to switch branches but I had closed VS trying to resolved the issue. When I reopened VS I did not run VS as the Administrator and I found that could not compile the solution now! It was the same\similar issue. It could not compile the solution as all of the obj directories were now non editable... so that is when I did the above steps and all was good again.

Hope this helps someone... ;)

jQuery AJAX Call to PHP Script with JSON Return

Your datatype is wrong, change datatype for dataType.

What are access specifiers? Should I inherit with private, protected or public?

what are Access Specifiers?

There are 3 access specifiers for a class/struct/Union in C++. These access specifiers define how the members of the class can be accessed. Of course, any member of a class is accessible within that class(Inside any member function of that same class). Moving ahead to type of access specifiers, they are:

Public - The members declared as Public are accessible from outside the Class through an object of the class.

Protected - The members declared as Protected are accessible from outside the class BUT only in a class derived from it.

Private - These members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

int main()
{
    MyClass obj;
    obj.a = 10;     //Allowed
    obj.b = 20;     //Not Allowed, gives compiler error
    obj.c = 30;     //Not Allowed, gives compiler error
}

Inheritance and Access Specifiers

Inheritance in C++ can be one of the following types:

  • Private Inheritance
  • Public Inheritance
  • Protected inheritance

Here are the member access rules with respect to each of these:

First and most important rule Private members of a class are never accessible from anywhere except the members of the same class.

Public Inheritance:

All Public members of the Base Class become Public Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

i.e. No change in the Access of the members. The access rules we discussed before are further then applied to these members.

Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:public Base
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Allowed
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Private Inheritance:

All Public members of the Base Class become Private Members of the Derived class &
All Protected members of the Base Class become Private Members of the Derived Class.

An code Example:

Class Base
{
    public:
      int a;
    protected:
      int b;
    private:
      int c;
};

class Derived:private Base   //Not mentioning private is OK because for classes it  defaults to private 
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Not Allowed, Compiler Error, a is private member of Derived now
        b = 20;  //Not Allowed, Compiler Error, b is private member of Derived now
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error

}

Protected Inheritance:

All Public members of the Base Class become Protected Members of the derived class &
All Protected members of the Base Class become Protected Members of the Derived Class.

A Code Example:

Class Base
{
    public:
        int a;
    protected:
        int b;
    private:
        int c;
};

class Derived:protected Base  
{
    void doSomething()
    {
        a = 10;  //Allowed 
        b = 20;  //Allowed
        c = 30;  //Not Allowed, Compiler Error
    }
};

class Derived2:public Derived
{
    void doSomethingMore()
    {
        a = 10;  //Allowed, a is protected member inside Derived & Derived2 is public derivation from Derived, a is now protected member of Derived2
        b = 20;  //Allowed, b is protected member inside Derived & Derived2 is public derivation from Derived, b is now protected member of Derived2
        c = 30;  //Not Allowed, Compiler Error
    }
};

int main()
{
    Derived obj;
    obj.a = 10;  //Not Allowed, Compiler Error
    obj.b = 20;  //Not Allowed, Compiler Error
    obj.c = 30;  //Not Allowed, Compiler Error
}

Remember the same access rules apply to the classes and members down the inheritance hierarchy.


Important points to note:

- Access Specification is per-Class not per-Object

Note that the access specification C++ work on per-Class basis and not per-object basis.
A good example of this is that in a copy constructor or Copy Assignment operator function, all the members of the object being passed can be accessed.

- A Derived class can only access members of its own Base class

Consider the following code example:

class Myclass
{ 
    protected: 
       int x; 
}; 

class derived : public Myclass
{
    public: 
        void f( Myclass& obj ) 
        { 
            obj.x = 5; 
        } 
};

int main()
{
    return 0;
}

It gives an compilation error:

prog.cpp:4: error: ‘int Myclass::x’ is protected

Because the derived class can only access members of its own Base Class. Note that the object obj being passed here is no way related to the derived class function in which it is being accessed, it is an altogether different object and hence derived member function cannot access its members.


What is a friend? How does friend affect access specification rules?

You can declare a function or class as friend of another class. When you do so the access specification rules do not apply to the friended class/function. The class or function can access all the members of that particular class.

So do friends break Encapsulation?

No they don't, On the contrary they enhance Encapsulation!

friendship is used to indicate a intentional strong coupling between two entities.
If there exists a special relationship between two entities such that one needs access to others private or protected members but You do not want everyone to have access by using the public access specifier then you should use friendship.

Create a .tar.bz2 file Linux

You are not indicating what to include in the archive.

Go one level outside your folder and try:

sudo tar -cvjSf folder.tar.bz2 folder

Or from the same folder try

sudo tar -cvjSf folder.tar.bz2 *

Cheers!

Java swing application, close one window and open another when button is clicked

Here is an example:

enter image description here

enter image description here

StartupWindow.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;


public class StartupWindow extends JFrame implements ActionListener
{
    private JButton btn;

    public StartupWindow()
    {
        super("Simple GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btn = new JButton("Open the other JFrame!");
        btn.addActionListener(this);
        btn.setActionCommand("Open");
        add(btn);
        pack();

    }

    @Override
    public void actionPerformed(ActionEvent e)
    {
        String cmd = e.getActionCommand();

        if(cmd.equals("Open"))
        {
            dispose();
            new AnotherJFrame();
        }
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable(){

            @Override
            public void run()
            {
                new StartupWindow().setVisible(true);
            }

        });
    }
}

AnotherJFrame.java

import javax.swing.JFrame;
import javax.swing.JLabel;

public class AnotherJFrame extends JFrame
{
    public AnotherJFrame()
    {
        super("Another GUI");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        add(new JLabel("Empty JFrame"));
        pack();
        setVisible(true);
    }
}

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

SignalR provides ConnectionId for each connection. To find which connection belongs to whom (the user), we need to create a mapping between the connection and the user. This depends on how you identify a user in your application.

In SignalR 2.0, this is done by using the inbuilt IPrincipal.Identity.Name, which is the logged in user identifier as set during the ASP.NET authentication.

However, you may need to map the connection with the user using a different identifier instead of using the Identity.Name. For this purpose this new provider can be used with your custom implementation for mapping user with the connection.

Example of Mapping SignalR Users to Connections using IUserIdProvider

Lets assume our application uses a userId to identify each user. Now, we need to send message to a specific user. We have userId and message, but SignalR must also know the mapping between our userId and the connection.

To achieve this, first we need to create a new class which implements IUserIdProvider:

public class CustomUserIdProvider : IUserIdProvider
{
     public string GetUserId(IRequest request)
    {
        // your logic to fetch a user identifier goes here.

        // for example:

        var userId = MyCustomUserClass.FindUserId(request.User.Identity.Name);
        return userId.ToString();
    }
}

The second step is to tell SignalR to use our CustomUserIdProvider instead of the default implementation. This can be done in the Startup.cs while initializing the hub configuration:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        var idProvider = new CustomUserIdProvider();

        GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => idProvider);          

        // Any connection or hub wire up and configuration should go here
        app.MapSignalR();
    }
}

Now, you can send message to a specific user using his userId as mentioned in the documentation, like:

public class MyHub : Hub
{
   public void Send(string userId, string message)
   {
      Clients.User(userId).send(message);
   }
}

Hope this helps.

How do I log a Python error with debug information?

One nice thing about logging.exception that SiggyF's answer doesn't show is that you can pass in an arbitrary message, and logging will still show the full traceback with all the exception details:

import logging
try:
    1/0
except ZeroDivisionError:
    logging.exception("Deliberate divide by zero traceback")

With the default (in recent versions) logging behaviour of just printing errors to sys.stderr, it looks like this:

>>> import logging
>>> try:
...     1/0
... except ZeroDivisionError:
...     logging.exception("Deliberate divide by zero traceback")
... 
ERROR:root:Deliberate divide by zero traceback
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

Python: TypeError: object of type 'NoneType' has no len()

I was faces this issue but after change object into str, problem solved. str(fname).isalpha():

Command line for looking at specific port

For Windows 8 User : Open Command Prompt, type netstat -an | find "your port number" , enter .

If reply comes like LISTENING then the port is in use, else it is free .

Why is "except: pass" a bad programming practice?

You should use at least except Exception: to avoid catching system exceptions like SystemExit or KeyboardInterrupt. Here's link to docs.

In general you should define explicitly exceptions you want to catch, to avoid catching unwanted exceptions. You should know what exceptions you ignore.

SQL query for getting data for last 3 months

I'd use datediff, and not care about format conversions:

SELECT *
FROM   mytable
WHERE  DATEDIFF(MONTH, my_date_column, GETDATE()) <= 3

How to subtract one month using moment.js?

For substracting in moment.js:

moment().subtract(1, 'months').format('MMM YYYY');

Documentation:

http://momentjs.com/docs/#/manipulating/subtract/

Before version 2.8.0, the moment#subtract(String, Number) syntax was also supported. It has been deprecated in favor of moment#subtract(Number, String).

  moment().subtract('seconds', 1); // Deprecated in 2.8.0
  moment().subtract(1, 'seconds');

As of 2.12.0 when decimal values are passed for days and months, they are rounded to the nearest integer. Weeks, quarters, and years are converted to days or months, and then rounded to the nearest integer.

  moment().subtract(1.5, 'months') == moment().subtract(2, 'months')
  moment().subtract(.7, 'years') == moment().subtract(8, 'months') //.7*12 = 8.4, rounded to 8