Programs & Examples On #Waitforexit

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

While trying out the final suggestion above, I discovered an even simpler solution. All I had to do was cache the process handle. As soon as I did that, $process.ExitCode worked correctly. If I didn't cache the process handle, $process.ExitCode was null.

example:

$proc = Start-Process $msbuild -PassThru
$handle = $proc.Handle # cache proc.Handle
$proc.WaitForExit();

if ($proc.ExitCode -ne 0) {
    Write-Warning "$_ exited with status code $($proc.ExitCode)"
}

Executing Batch File in C#

This should work. You could try to dump out the contents of the output and error streams in order to find out what's happening:

static void ExecuteCommand(string command)
{
    int exitCode;
    ProcessStartInfo processInfo;
    Process process;

    processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    // *** Redirect the output ***
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    process = Process.Start(processInfo);
    process.WaitForExit();

    // *** Read the streams ***
    // Warning: This approach can lead to deadlocks, see Edit #2
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    exitCode = process.ExitCode;

    Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
    process.Close();
}

static void Main()
{
    ExecuteCommand("echo testing");
}   

* EDIT *

Given the extra information in your comment below, I was able to recreate the problem. There seems to be some security setting that results in this behaviour (haven't investigated that in detail).

This does work if the batch file is not located in C:\Windows\System32. Try moving it to some other location, e.g. the location of your executable. Note that keeping custom batch files or executables in the Windows directory is bad practice anyway.

* EDIT 2 * It turns out that if the streams are read synchronously, a deadlock can occur, either by reading synchronously before WaitForExit or by reading both stderr and stdout synchronously one after the other.

This should not happen if using the asynchronous read methods instead, as in the following example:

static void ExecuteCommand(string command)
{
    var processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = false;
    processInfo.RedirectStandardError = true;
    processInfo.RedirectStandardOutput = true;

    var process = Process.Start(processInfo);

    process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("output>>" + e.Data);
    process.BeginOutputReadLine();

    process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) =>
        Console.WriteLine("error>>" + e.Data);
    process.BeginErrorReadLine();

    process.WaitForExit();

    Console.WriteLine("ExitCode: {0}", process.ExitCode);
    process.Close();
}

Hide console window from Process.Start C#

I've had bad luck with this answer, with the process (Wix light.exe) essentially going out to lunch and not coming home in time for dinner. However, the following worked well for me:

Process p = new Process();
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// etc, then start process

How to run console application from Windows Service?

As pierre said, there is no way to have a user interface for a windows service (or no easy way). What I do in that kind of situation is to have a settings file that is read from the service on whatever interval the service operates on and have a standalone application that makes changes to the settings file.

How to execute an .SQL script file using c#

This works for me:

public void updatedatabase()
{

    SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
    try
    {

        conn.Open();

        string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));

        // split script on GO command
        IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
        foreach (string commandString in commandStrings)
        {
            if (commandString.Trim() != "")
            {
                new SqlCommand(commandString, conn).ExecuteNonQuery();
            }
        }
        lblmsg.Text = "Database updated successfully.";

    }
    catch (SqlException er)
    {
        lblmsg.Text = er.Message;
        lblmsg.ForeColor = Color.Red;
    }
    finally
    {
        conn.Close();
    }
}

Execute multiple command lines with the same process using .NET

You could also tell MySQL to execute the commands in the given file, like so:

mysql --user=root --password=sa casemanager < CaseManager.sql

How to execute a .bat file from a C# windows form app?

For the problem you're having about the batch file asking the user if the destination is a folder or file, if you know the answer in advance, you can do as such:

If destination is a file: echo f | [batch file path]

If folder: echo d | [batch file path]

It will essentially just pipe the letter after "echo" to the input of the batch file.

How to spawn a process and capture its STDOUT in .NET?

You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.

ProcessStartInfo hanging on "WaitForExit"? Why?

Workaround I ended up using to avoid all the complexity:

var outputFile = Path.GetTempFileName();
info = new System.Diagnostics.ProcessStartInfo("TheProgram.exe", String.Join(" ", args) + " > " + outputFile + " 2>&1");
info.CreateNoWindow = true;
info.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
info.UseShellExecute = false;
System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText(outputFile)); //need the StandardOutput contents

So I create a temp file, redirect both the output and error to it by using > outputfile > 2>&1 and then just read the file after the process has finished.

The other solutions are fine for scenarios where you want to do other stuff with the output, but for simple stuff this avoids a lot of complexity.

How to create war files

**Making War file in Eclips Gaynemed of grails web project **

1.Import project:

2.Change the datasource.groovy file

Like this: url="jdbc:postgresql://18.247.120.101:8432/PGMS"

2.chnge AppConfig.xml

3.kill the Java from Task Manager:

  1. run clean comand in eclips

  2. run 'prod war' fowllowed by project name.

  3. Check the log file and find the same .war file in directory of workbench with same date.

How can I give eclipse more memory than 512M?

You can copy this to your eclipse.ini file to have 1024M:

-clean -showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Xms512m
-Xmx1024m
-XX:PermSize=128m
-XX:MaxPermSize=256m 

Cross-thread operation not valid: Control 'textBox1' accessed from a thread other than the thread it was created on

Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.

Helper Method

    /// <summary>
    /// Helper method to determin if invoke required, if so will rerun method on correct thread.
    /// if not do nothing.
    /// </summary>
    /// <param name="c">Control that might require invoking</param>
    /// <param name="a">action to preform on control thread if so.</param>
    /// <returns>true if invoke required</returns>
    public bool ControlInvokeRequired(Control c,Action a)
    {
        if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
        else return false;

        return true;
    }

Sample Usage

    // usage on textbox
    public void UpdateTextBox1(String text)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
        textBox1.Text = ellapsed;
    }

    //Or any control
    public void UpdateControl(Color c,String s)
    {
        //Check if invoke requied if so return - as i will be recalled in correct thread
        if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
        myControl.Text = s;
        myControl.BackColor = c;
    }

Java random numbers using a seed

The easy way is to use:

Random rand = new Random(System.currentTimeMillis());

This is the best way to generate Random numbers.

HTML Table different number of columns in different rows

Colspan:

<table>
   <tr>
      <td> Row 1 Col 1</td>
      <td> Row 1 Col 2</td>
</tr>
<tr>
      <td colspan=2> Row 2 Long Col</td>
</tr>
</table>

How to iterate over a string in C?

sizeof(source) returns sizeof a pointer as source is declared as char *. Correct way to use it is strlen(source).

Next:

printf("%s",source[i]); 

expects string. i.e %s expects string but you are iterating in a loop to print each character. Hence use %c.

However your way of accessing(iterating) a string using the index i is correct and hence there are no other issues in it.

Using jq to parse and display multiple fields in a json serially

my approach will be (your json example is not well formed.. guess thats only a sample)

jq '.Front[] | [.Name,.Out,.In,.Groups] | join("|")'  front.json  > output.txt

returns something like this

"new.domain.com-80|8.8.8.8|192.168.2.2:80|192.168.3.29:80 192.168.3.30:80"
"new.domain.com -443|8.8.8.8|192.168.2.2:443|192.168.3.29:443 192.168.3.30:443"

and grep the output with regular expression.

Clearing state es6 React

In some circumstances, it's sufficient to just set all values of state to null.

If you're state is updated in such a way, that you don't know what might be in there, you might want to use

this.setState(Object.assign(...Object.keys(this.state).map(k => ({[k]: null}))))

Which will change the state as follows

{foo: 1, bar: 2, spam: "whatever"} > {foo: null, bar: null, spam: null}

Not a solution in all cases, but works well for me.

iOS for VirtualBox

Additional to the above - the QEMU website has good documentation about setting up an ARM based emulator: http://qemu.weilnetz.de/qemu-doc.html#ARM-System-emulator

how to setup ssh keys for jenkins to publish via ssh

You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.

Generating the SSH Key Pair

On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:

On the Target Server

On the target server, you will need to place the content of the public key (id_rsa.pub per the above article) into the .ssh/authorized_keys file under the home directory of the user which Jenkins will be using for deployment.

In Jenkins

Using "Publish over SSH" Plugin

Ref: https://plugins.jenkins.io/publish-over-ssh/

Visit: Jenkins > Manage Jenkins > Configure System > Publish over SSH

  • If the private key is encrypted, then you will need to enter the passphrase for the key into the "Passphrase" field, otherwise leave it alone.
  • Leave the "Path to key" field empty as this will be ignored anyway when you use a pasted key (next step)
  • Copy and paste the contents of the private key (id_rsa per the above article) into the "Key" field
  • Under "SSH Servers", "Add" a new server configuration for your target server.

Using Stored Global Credentials

Visit: Jenkins > Credentials > System > Global credentials (unrestricted) > Add Credentials

  • Kind: "SSH Username with private key"
  • Scope: "Global"
  • ID: [CREAT A UNIQUE ID FOR THIS KEY]
  • Description: [optionally, enter a decription]
  • Username: [USERNAME JENKINS WILL USE TO CONNECT TO REMOTE SERVER]
  • Private Key: [select "Enter directly"]
  • Key: [paste the contents of the private key (id_rsa per the above article)]
  • Passphrase: [enter the passphrase for the key, or leave it blank if the key is not encrypted]

Table fixed header and scrollable body

I had a lot of trouble getting the stickytableheaders library to work. Doing a bit more searching, I found floatThead is an actively maintained alternative with recent updates and better documentation.

Can I set enum start value in Java?

If you want emulate enum of C/C++ (base num and nexts incrementals):

enum ids {
    OPEN, CLOSE;
    //
    private static final int BASE_ORDINAL = 100;
    public int getCode() {
        return ordinal() + BASE_ORDINAL;
    }
};

public class TestEnum {
    public static void main (String... args){
        for (ids i : new ids[] { ids.OPEN, ids.CLOSE }) {
            System.out.println(i.toString() + " " + 
                i.ordinal() + " " + 
                i.getCode());
        }
    }
}
OPEN 0 100
CLOSE 1 101

Setting dropdownlist selecteditem programmatically

Well if I understood correctly your question. The Solution for setting the value for a given dropdownlist will be:

dropdownlist1.Text="Your Value";

This will work only if the value is existing in the data-source of the dropdownlist.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

To resolve this problem in Visual Studio 2012, I right click the project, properties -> "signing", and then uncheck the "Sign the ClickOnce manifests".

PHP - Get bool to echo false when false

You can use a ternary operator

echo false ? 'true' : 'false';

How to use PHP to connect to sql server

Use localhost instead of your IP address.

e.g,

$myServer = "localhost";

And also double check your mysql username and password.

css3 transition animation on load?

I think I have found a sort of work around for the OP question - instead of a transition beginning 'on.load' of the page - I found that using an animation for an opacity fade in had the same effect, (I was looking for the same thing as OP).

So I wanted to have the body text fade in from white(same as site background) to black text colour on page load - and I've only been coding since Monday so I was looking for an 'on.load' style thing code, but don't know JS yet - so here is my code that worked well for me.

#main p {
  animation: fadein 2s;
}
@keyframes fadein {
  from { opacity: 0}
  to   { opacity: 1}
}

And for whatever reason, this doesn't work for .class only #id's(at least not on mine)

Hope this helps - as I know this site helps me a lot!

Getting list of Facebook friends with latest API

This is live version of PHP Code to get your friends from Facebook

<?php
    $user = $facebook->getUser();


    if ($user) {
        $user_profile = $facebook->api('/me');
        $friends = $facebook->api('/me/friends');

        echo '<ul>';
        foreach ($friends["data"] as $value) {
            echo '<li>';
            echo '<div class="pic">';
            echo '<img src="https://graph.facebook.com/' . $value["id"] . '/picture"/>';
            echo '</div>';
            echo '<div class="picName">'.$value["name"].'</div>'; 
            echo '</li>';
        }
        echo '</ul>';
    }
?>

Regex Letters, Numbers, Dashes, and Underscores

Depending on your regex variant, you might be able to do simply this:

([\w-]+)

Also, you probably don't need the parentheses unless this is part of a larger expression.

Binding to static property

There could be two ways/syntax to bind a static property. If p is a static property in class MainWindow, then binding for textbox will be:

1.

<TextBox Text="{x:Static local:MainWindow.p}" />

2.

<TextBox Text="{Binding Source={x:Static local:MainWindow.p},Mode=OneTime}" />

How do I display a MySQL error in PHP for a long query that depends on the user input?

Try something like this:

$link = @new mysqli($this->host, $this->user, $this->pass)
$statement = $link->prepare($sqlStatement);
                if(!$statement)
                {
                    $this->debug_mode('query', 'error', '#Query Failed<br/>' . $link->error);
                    return false;
                }

Toggle input disabled attribute using jQuery

This is fairly simple with the callback syntax of attr:

$("#product1 :checkbox").click(function(){
  $(this)
   .closest('tr') // find the parent row
       .find(":input[type='text']") // find text elements in that row
           .attr('disabled',function(idx, oldAttr) {
               return !oldAttr; // invert disabled value
           })
           .toggleClass('disabled') // enable them
       .end() // go back to the row
       .siblings() // get its siblings
           .find(":input[type='text']") // find text elements in those rows
               .attr('disabled',function(idx, oldAttr) {
                   return !oldAttr; // invert disabled value
               })
               .removeClass('disabled'); // disable them
});

What should my Objective-C singleton look like?

static mySingleton *obj=nil;

@implementation mySingleton

-(id) init {
    if(obj != nil){     
        [self release];
        return obj;
    } else if(self = [super init]) {
        obj = self;
    }   
    return obj;
}

+(mySingleton*) getSharedInstance {
    @synchronized(self){
        if(obj == nil) {
            obj = [[mySingleton alloc] init];
        }
    }
    return obj;
}

- (id)retain {
    return self;
}

- (id)copy {
    return self;
}

- (unsigned)retainCount {
    return UINT_MAX;  // denotes an object that cannot be released
}

- (void)release {
    if(obj != self){
        [super release];
    }
    //do nothing
}

- (id)autorelease {
    return self;
}

-(void) dealloc {
    [super dealloc];
}
@end

How can I get new selection in "select" in Angular 2?

I was has same problem and i solved using the below code :

(change)="onChange($event.target.value)"

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

LINQ .Any VS .Exists - What's the difference?

The difference is that Any is an extension method for any IEnumerable<T> defined on System.Linq.Enumerable. It can be used on any IEnumerable<T> instance.

Exists does not appear to be an extension method. My guess is that coll is of type List<T>. If so Exists is an instance method which functions very similar to Any.

In short, the methods are essentially the same. One is more general than the other.

  • Any also has an overload which takes no parameters and simply looks for any item in the enumerable.
  • Exists has no such overload.

How to sort an array in descending order in Ruby

What about:

 a.sort {|x,y| y[:bar]<=>x[:bar]}

It works!!

irb
>> a = [
?>   { :foo => 'foo', :bar => 2 },
?>   { :foo => 'foo', :bar => 3 },
?>   { :foo => 'foo', :bar => 5 },
?> ]
=> [{:bar=>2, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>5, :foo=>"foo"}]

>>  a.sort {|x,y| y[:bar]<=>x[:bar]}
=> [{:bar=>5, :foo=>"foo"}, {:bar=>3, :foo=>"foo"}, {:bar=>2, :foo=>"foo"}]

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

Striking a similar issue using CakePHP to output a JavaScript script-block using PHP's native json_encode. $contractorCompanies contains values that have single quotation marks and as explained above and expected json_encode($contractorCompanies) doesn't escape them because its valid JSON.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".(json_encode($contractorCompanies)."' );"); ?>

By adding addslashes() around the JSON encoded string you then escape the quotation marks allowing Cake / PHP to echo the correct javascript to the browser. JS errors disappear.

<?php $this->Html->scriptBlock("var contractorCompanies = jQuery.parseJSON( '".addslashes(json_encode($contractorCompanies))."' );"); ?>

How to manually set REFERER header in Javascript?

You can not change the REFERRER property. What you are asking is to spoof the request.

Just in case you want the referrer to be set like you have opened a url directly or for the fist time{http referrer=null} then reload the page

location.reload();

How to maximize a plt.show() window using Python

I usually use

mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)

before the call to plt.show(), and I get a maximized window. This works for the 'wx' backend only.

EDIT:

for Qt4Agg backend, see kwerenda's answer.

Swift add icon/image in UITextField

I don't think that frame-based solutions are a good approach, because it won't be available on an iPad in some cases. The ideal solution would be to add constraints from imageView to textfield right view, but it's not that easy. The right view does not appear to be in textfield view hierarchy unless it is required, so you need to do the following:

    private let countryTextField: UITextField = {
        let countryTextField = UITextField()
        countryTextField.translatesAutoresizingMaskIntoConstraints = false
        countryTextField.rightViewMode = .always
        
        let button = UIButton(type: .system)
        button.setImage(UIImage(named: "yourImageName"), for: .normal)
        button.translatesAutoresizingMaskIntoConstraints = false
        
        countryTextField.rightView = button
        countryTextField.setNeedsLayout() //Add rightView in textField hierarchy
        countryTextField.layoutIfNeeded() //Add rightView in textField hierarchy
        
        button.topAnchor.constraint(equalTo: countryTextField.topAnchor).isActive = true
        button.bottomAnchor.constraint(equalTo: countryTextField.bottomAnchor).isActive = true
        button.widthAnchor.constraint(equalTo: countryTextField.heightAnchor).isActive = true
        
        return countryTextField
    }()

And the result on any device is:

TextField right view

Also, my solution works with textfield left view.

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

It's possible that you're creating your controls on the wrong thread. Consider the following documentation from MSDN:

This means that InvokeRequired can return false if Invoke is not required (the call occurs on the same thread), or if the control was created on a different thread but the control's handle has not yet been created.

In the case where the control's handle has not yet been created, you should not simply call properties, methods, or events on the control. This might cause the control's handle to be created on the background thread, isolating the control on a thread without a message pump and making the application unstable.

You can protect against this case by also checking the value of IsHandleCreated when InvokeRequired returns false on a background thread. If the control handle has not yet been created, you must wait until it has been created before calling Invoke or BeginInvoke. Typically, this happens only if a background thread is created in the constructor of the primary form for the application (as in Application.Run(new MainForm()), before the form has been shown or Application.Run has been called.

Let's see what this means for you. (This would be easier to reason about if we saw your implementation of SafeInvoke also)

Assuming your implementation is identical to the referenced one with the exception of the check against IsHandleCreated, let's follow the logic:

public static void SafeInvoke(this Control uiElement, Action updater, bool forceSynchronous)
{
    if (uiElement == null)
    {
        throw new ArgumentNullException("uiElement");
    }

    if (uiElement.InvokeRequired)
    {
        if (forceSynchronous)
        {
            uiElement.Invoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
        else
        {
            uiElement.BeginInvoke((Action)delegate { SafeInvoke(uiElement, updater, forceSynchronous); });
        }
    }
    else
    {    
        if (uiElement.IsDisposed)
        {
            throw new ObjectDisposedException("Control is already disposed.");
        }

        updater();
    }
}

Consider the case where we're calling SafeInvoke from the non-gui thread for a control whose handle has not been created.

uiElement is not null, so we check uiElement.InvokeRequired. Per the MSDN docs (bolded) InvokeRequired will return false because, even though it was created on a different thread, the handle hasn't been created! This sends us to the else condition where we check IsDisposed or immediately proceed to call the submitted action... from the background thread!

At this point, all bets are off re: that control because its handle has been created on a thread that doesn't have a message pump for it, as mentioned in the second paragraph. Perhaps this is the case you're encountering?

Setting Android Theme background color

Okay turned out that I made a really silly mistake. The device I am using for testing is running Android 4.0.4, API level 15.

The styles.xml file that I was editing is in the default values folder. I edited the styles.xml in values-v14 folder and it works all fine now.

compareTo with primitives -> Integer / int

For pre 1.7 i would say an equivalent to Integer.compare(x, y) is:

Integer.valueOf(x).compareTo(y);

Show hide fragment in android

In addittion, you can do in a Fragment (for example when getting server data failed):

 getView().setVisibility(View.GONE);

how to check the dtype of a column in python pandas

You can access the data-type of a column with dtype:

for y in agg.columns:
    if(agg[y].dtype == np.float64 or agg[y].dtype == np.int64):
          treat_numeric(agg[y])
    else:
          treat_str(agg[y])

Fastest way to convert string to integer in PHP

integer excract from any string

$in = 'tel.123-12-33';

preg_match_all('!\d+!', $in, $matches);
$out =  (int)implode('', $matches[0]);

//$out ='1231233';

Detect click inside/outside of element with single event handler

In JavaScript (via jQuery):

_x000D_
_x000D_
$(function() {_x000D_
  $("body").click(function(e) {_x000D_
    if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {_x000D_
      alert("Inside div");_x000D_
    } else {_x000D_
      alert("Outside div");_x000D_
    }_x000D_
  });_x000D_
})
_x000D_
#myDiv {_x000D_
  background: #ff0000;_x000D_
  width: 25vw;_x000D_
  height: 25vh;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"></div>
_x000D_
_x000D_
_x000D_

How to use S_ISREG() and S_ISDIR() POSIX Macros?

You're using S_ISREG() and S_ISDIR() correctly, you're just using them on the wrong thing.

In your while((dit = readdir(dip)) != NULL) loop in main, you're calling stat on currentPath over and over again without changing currentPath:

if(stat(currentPath, &statbuf) == -1) {
    perror("stat");
    return errno;
}

Shouldn't you be appending a slash and dit->d_name to currentPath to get the full path to the file that you want to stat? Methinks that similar changes to your other stat calls are also needed.

How to dispatch a Redux action with a timeout?

It is simple. Use trim-redux package and write like this in componentDidMount or other place and kill it in componentWillUnmount.

componentDidMount() {
  this.tm = setTimeout(function() {
    setStore({ age: 20 });
  }, 3000);
}

componentWillUnmount() {
  clearTimeout(this.tm);
}

How to stop text from taking up more than 1 line?

Sometimes using &nbsp; instead of spaces will work. Clearly it has drawbacks, though.

Is it possible to start a shell session in a running container (without ssh)

first, get the container id of the desired container by

docker ps

you will get something like this:

CONTAINER ID        IMAGE                  COMMAND             CREATED             STATUS                          PORTS                    NAMES
3ac548b6b315        frontend_react-web     "npm run start"     48 seconds ago      Up 47 seconds                   0.0.0.0:3000->3000/tcp   frontend_react-web_1

now copy this container id and run the following command:

docker exec -it container_id sh

docker exec -it 3ac548b6b315 sh

php REQUEST_URI

You can either use regex, or keep on using str_replace.

Eg.

$url = parse_url($_SERVER['REQUEST_URI']);

if ($url != '/') {
    parse_str($url['query']);
    echo $id;
    echo $othervar;
}

Output will be: http://www.testing.com/123/123

Xcode warning: "Multiple build commands for output file"

React-Native users. goto file -> workspace settings -> build system -> change it to legacy build system. and it should build fine now. React-Native isn't compatible with the new file system yet.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Enable cross-origin requests in ASP.NET Web API click for more info

Enable CORS in the WebService app. First, add the CORS NuGet package. In Visual Studio, from the Tools menu, select NuGet Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

Install-Package Microsoft.AspNet.WebApi.Cors

This command installs the latest package and updates all dependencies, including the core Web API libraries. Use the -Version flag to target a specific version. The CORS package requires Web API 2.0 or later.

Open the file App_Start/WebApiConfig.cs. Add the following code to the WebApiConfig.Register method:

using System.Web.Http;
namespace WebService
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // New code
            config.EnableCors();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Next, add the [EnableCors] attribute to your controller/ controller methods

using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Cors;

namespace WebService.Controllers
{
    [EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
    public class TestController : ApiController
    {
        // Controller methods not shown...
    }
}

Enable Cross-Origin Requests (CORS) in ASP.NET Core

What is the purpose of willSet and didSet in Swift?

My understanding is that set and get are for computed properties (no backing from stored properties)

if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property

Example 1 (read only property) - with warning:

var test : Int {
    get {
        return test
    }
}

This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".

Example 2. Conditional read/write - with warning

var test : Int {
    get {
        return test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        //(prevents same value being set)
        if (aNewValue != test) {
            test = aNewValue
        }
    }
}

Similar problem - you cannot do this as it's recursively calling the setter. Also, note this code will not complain about no initialisers as there is no stored property to initialise.

Example 3. read/write computed property - with backing store

Here is a pattern that allows conditional setting of an actual stored property

//True model data
var _test : Int = 0

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Note The actual data is called _test (although it could be any data or combination of data) Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable

Example 4. Using will and did set

//True model data
var _test : Int = 0 {

    //First this
    willSet {
        println("Old value is \(_test), new value is \(newValue)")
    }

    //value is set

    //Finaly this
    didSet {
        println("Old value is \(oldValue), new value is \(_test)")
    }
}

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Here we see willSet and didSet intercepting a change in an actual stored property. This is useful for sending notifications, synchronisation etc... (see example below)

Example 5. Concrete Example - ViewController Container

//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
    willSet {
        //REMOVE OLD VC
        println("Property will set")
        if (_childVC != nil) {
            _childVC!.willMoveToParentViewController(nil)
            self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
            _childVC!.view.removeFromSuperview()
            _childVC!.removeFromParentViewController()
        }
        if (newValue) {
            self.addChildViewController(newValue)
        }

    }

    //I can't see a way to 'stop' the value being set to the same controller - hence the computed property

    didSet {
        //ADD NEW VC
        println("Property did set")
        if (_childVC) {
//                var views  = NSDictionaryOfVariableBindings(self.view)    .. NOT YET SUPPORTED (NSDictionary bridging not yet available)

            //Add subviews + constraints
            _childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false)       //For now - until I add my own constraints
            self.view.addSubview(_childVC!.view)
            let views = ["view" : _childVC!.view] as NSMutableDictionary
            let layoutOpts = NSLayoutFormatOptions(0)
            let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|",  options: layoutOpts, metrics: NSDictionary(), views: views)
            let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
            self.view.addConstraints(lc1)
            self.view.addConstraints(lc2)

            //Forward messages to child
            _childVC!.didMoveToParentViewController(self)
        }
    }
}


//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
    get {
        return _childVC
    }
    set(suggestedVC) {
        if (suggestedVC != _childVC) {
            _childVC = suggestedVC
        }
    }
}

Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)

I hope this helps, and please someone shout if I've made a mistake anywhere here!

php how to go one level up on dirname(__FILE__)

dirname(__DIR__,level);
dirname(__DIR__,1);

level is how many times will you go back to the folder

Visual Studio Code always asking for git credentials

This has been working for me:
1. Set credential hepler to store
$ git config --global credential.helper store
2. then verify if you want:
$ git config --global credential.helper store

Simple example when using git bash quoted from Here (works for current repo only, use --global for all repos)

$ git config credential.helper store
$ git push http://example.com/repo.git
Username: < type your username >
Password: < type your password >

[several days later]
$ git push http://example.com/repo.git
[your credentials are used automatically]

Will work for VS Code too.

More detailed example and advanced usage here.

Note: Username & Passwords are not encrypted and stored in plain text format so use it on your personal computer only.

Gradle, Android and the ANDROID_HOME SDK location

I faced the same issue, though I had local.properties file in my main module, and ANDROID_HOME environment variable set at system level.

What fixed this problem was when I copied the local.properties file which was in my main project module to the root of the whole project (i.e the directory parent to your main module)

Try copying the local.properties file inside modules and the root directory. Should work.

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

Use these following commands, this will solve the error:

sudo apt-get install postgresql

then fire:

sudo apt-get install python-psycopg2

and last:

sudo apt-get install libpq-dev

Jquery, checking if a value exists in array or not

http://api.jquery.com/jQuery.inArray/

if ($.inArray('example', myArray) != -1)
{
  // found it
}

Text to speech(TTS)-Android

// variable declaration
TextToSpeech tts;

// TextToSpeech initialization, must go within the onCreate method
tts = new TextToSpeech(getActivity(), new TextToSpeech.OnInitListener() {
 @Override
 public void onInit(int i) {
  if (i == TextToSpeech.SUCCESS) {
   int result = tts.setLanguage(Locale.US);
   if (result == TextToSpeech.LANG_MISSING_DATA ||
    result == TextToSpeech.LANG_NOT_SUPPORTED) {
    Log.e("TTS", "Lenguage not supported");
   }
  } else {
   Log.e("TTS", "Initialization failed");
  }
 }
});

// method call
public void buttonSpeak().setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View view) {
  speak();
 }
});
}

private void speak() {
 tts.speak("Text to Speech Test", TextToSpeech.QUEUE_ADD, null);
}

@Override
public void onDestroy() {
 if (tts != null) {
  tts.stop();
  tts.shutdown();
 }
 super.onDestroy();
}

taken from: Text to Speech Youtube Tutorial

Can't connect to local MySQL server through socket homebrew

I had same problem. After trying all these methods without success I did the following:

tail -f the-mysql-or-maria-db-error-file.err

in another console:

brew services restart mariadb

I saw the following error:

"MAC HOMEBREW Crash recovery failed. Either correct the problem (if it's, for example, out of memory error) and restart, or delete tc log and start mysqld with"

So I changed the tc.log extesion to tc.log.txt and restart mariadb

brew services restart mariadb

and done!

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

How do you create a daemon in Python?

After a few years and many attempts (I tried all the answers given here, but all of them had minor drawbacks at the end), now I realize that there is a better way than wanting to start, stop, restart a daemon directly from Python: use the OS tools instead.

For example, for Linux, instead of doing python myapp start and python myapp stop, I do this to start the app:

screen -S myapp python myapp.py    
CTRL+A, D to detach

or screen -dmS myapp python myapp.py to start and detach it in one command.

Then:

screen -r myapp

to attach to this terminal again. Once in the terminal, it's possible to use CTRL+C to stop it.

What's the difference between integer class and numeric class in R

There are multiple classes that are grouped together as "numeric" classes, the 2 most common of which are double (for double precision floating point numbers) and integer. R will automatically convert between the numeric classes when needed, so for the most part it does not matter to the casual user whether the number 3 is currently stored as an integer or as a double. Most math is done using double precision, so that is often the default storage.

Sometimes you may want to specifically store a vector as integers if you know that they will never be converted to doubles (used as ID values or indexing) since integers require less storage space. But if they are going to be used in any math that will convert them to double, then it will probably be quickest to just store them as doubles to begin with.

How can I measure the similarity between two images?

You'll need pattern recognition for that. To determine small differences between two images, Hopfield nets work fairly well and are quite easy to implement. I don't know any available implementations, though.

Bootstrap: Position of dropdown menu relative to navbar item

Boostrap has a class for that called navbar-right. So your code will look as follows:

<ul class="nav navbar-right">
    <li class="dropdown">
      <a class="dropdown-toggle" href="#" data-toggle="dropdown">Link</a>
      <ul class="dropdown-menu">
         <li>...</li>
      </ul>
    </li>
</ul>

java: ArrayList - how can I check if an index exists?

a simple way to do this:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

Page Redirect after X seconds wait using JavaScript

$(document).ready(function() {
    window.setTimeout(function(){window.location.href = "https://www.google.co.in"},5000);
});

sending email via php mail function goes to spam

If you are sending this through your own mail server you might need to add a "Sender" header which will contain an email address of from your own domain. Gmail will probably be spamming the email because the FROM address is a gmail address but has not been sent from their own server.

Automating the InvokeRequired code pattern

Lee's approach can be simplified further

public static void InvokeIfRequired(this Control control, MethodInvoker action)
{
    // See Update 2 for edits Mike de Klerk suggests to insert here.

    if (control.InvokeRequired) {
        control.Invoke(action);
    } else {
        action();
    }
}

And can be called like this

richEditControl1.InvokeIfRequired(() =>
{
    // Do anything you want with the control here
    richEditControl1.RtfText = value;
    RtfHelpers.AddMissingStyles(richEditControl1);
});

There is no need to pass the control as parameter to the delegate. C# automatically creates a closure.


UPDATE:

According to several other posters Control can be generalized as ISynchronizeInvoke:

public static void InvokeIfRequired(this ISynchronizeInvoke obj,
                                         MethodInvoker action)
{
    if (obj.InvokeRequired) {
        var args = new object[0];
        obj.Invoke(action, args);
    } else {
        action();
    }
}

DonBoitnott pointed out that unlike Control the ISynchronizeInvoke interface requires an object array for the Invoke method as parameter list for the action.


UPDATE 2

Edits suggested by Mike de Klerk (see comment in 1st code snippet for insert point):

// When the form, thus the control, isn't visible yet, InvokeRequired  returns false,
// resulting still in a cross-thread exception.
while (!control.Visible)
{
    System.Threading.Thread.Sleep(50);
}

See ToolmakerSteve's comment below for concerns about this suggestion.

How do you connect to a MySQL database using Oracle SQL Developer?

Here's another extremely detailed walkthrough that also shows you the entire process, including what values to put in the connection dialogue after the JDBC driver is installed: http://rpbouman.blogspot.com/2007/01/oracle-sql-developer-11-supports-mysql.html

Calculate MD5 checksum for a file

I know this question was already answered, but this is what I use:

using (FileStream fStream = File.OpenRead(filename)) {
    return GetHash<MD5>(fStream)
}

Where GetHash:

public static String GetHash<T>(Stream stream) where T : HashAlgorithm {
    StringBuilder sb = new StringBuilder();

    MethodInfo create = typeof(T).GetMethod("Create", new Type[] {});
    using (T crypt = (T) create.Invoke(null, null)) {
        byte[] hashBytes = crypt.ComputeHash(stream);
        foreach (byte bt in hashBytes) {
            sb.Append(bt.ToString("x2"));
        }
    }
    return sb.ToString();
}

Probably not the best way, but it can be handy.

How to deploy a Java Web Application (.war) on tomcat?

As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webappdirectory.

Now, if Tomcat is installed and running on bilgin.ath.cx (as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80 on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk?, mod_proxy?). You should either give us more details or discuss this with your hosting provider.

Update: As expected, the bilgin.ath.cx is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties file to configure the workers and the httpd.conf for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount directive in Apache httpd.conf for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.

1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)

How to scale images to screen size in Pygame

You can scale the image with pygame.transform.scale:

import pygame
picture = pygame.image.load(filename)
picture = pygame.transform.scale(picture, (1280, 720))

You can then get the bounding rectangle of picture with

rect = picture.get_rect()

and move the picture with

rect = rect.move((x, y))
screen.blit(picture, rect)

where screen was set with something like

screen = pygame.display.set_mode((1600, 900))

To allow your widgets to adjust to various screen sizes, you could make the display resizable:

import os
import pygame
from pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((500, 500), HWSURFACE | DOUBLEBUF | RESIZABLE)
pic = pygame.image.load("image.png")
screen.blit(pygame.transform.scale(pic, (500, 500)), (0, 0))
pygame.display.flip()
while True:
    pygame.event.pump()
    event = pygame.event.wait()
    if event.type == QUIT:
        pygame.display.quit()
    elif event.type == VIDEORESIZE:
        screen = pygame.display.set_mode(
            event.dict['size'], HWSURFACE | DOUBLEBUF | RESIZABLE)
        screen.blit(pygame.transform.scale(pic, event.dict['size']), (0, 0))
        pygame.display.flip()

jQuery equivalent of JavaScript's addEventListener method

As of jQuery 1.7, .on() is now the preferred method of binding events, rather than .bind():

From http://api.jquery.com/bind/:

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to .bind() occurs. For more flexible event binding, see the discussion of event delegation in .on() or .delegate().

The documentation page is located at http://api.jquery.com/on/

How to make a movie out of images in python

Here is a minimal example using moviepy. For me this was the easiest solution.

import os
import moviepy.video.io.ImageSequenceClip
image_folder='folder_with_images'
fps=1

image_files = [image_folder+'/'+img for img in os.listdir(image_folder) if img.endswith(".png")]
clip = moviepy.video.io.ImageSequenceClip.ImageSequenceClip(image_files, fps=fps)
clip.write_videofile('my_video.mp4')

How do I link to part of a page? (hash?)

On 12 March 2020, a draft has been added by WICG for Text Fragments, and now you can link to text on a page as if you were searching for it by adding the following to the hash

#:~:text=<Text To Link to>

Working example on Chrome Version 81.0.4044.138:

Click on this link Should reload the page and highlight the link's text

How to start and stop android service from a adb shell?

You may get an error "*Error: app is in background *" while using

adb shell am startservice 

in Oreo (26+). This requires services in the foreground. Use the following.

adb shell am start-foreground-service com.some.package.name/.YourServiceSubClassName

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

hibernate could not get next sequence value

For anyone using FluentNHibernate (my version is 2.1.2), it's just as repetitive but this works:

public class UserMap : ClassMap<User>
{
    public UserMap()
    {
        Table("users");
        Id(x => x.Id).Column("id").GeneratedBy.SequenceIdentity("users_id_seq");

float:left; vs display:inline; vs display:inline-block; vs display:table-cell;

I prefer inline-block, but float are still useful way to put together HTML elemenets, specially when we have elements which one should stick to the left and one to the right, float working better with writing less lines, while inline-block working well in many other cases.

enter image description here

In MVC, how do I return a string result?

There Are 2 ways to return a string from the controller to the view:

First

You could return only the string, but it will not be included in your .cshtml file. it will be just a string appearing in your browser.


Second

You could return a string as the Model object of View Result.

Here is the code sample to do this:

public class HomeController : Controller
{
    // GET: Home
    // this will return just a string, not html
    public string index()
    {
        return "URL to show";
    }

    public ViewResult AutoProperty()
    {   
        string s = "this is a string ";
        // name of view , object you will pass
        return View("Result", s);

    }
}

In the view file to run AutoProperty, It will redirect you to the Result view and will send s
code to the view

<!--this will make this file accept string as it's model-->
@model string

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Result</title>
</head>
<body>
    <!--this will represent the string -->
    @Model
</body>
</html>

I run this at http://localhost:60227/Home/AutoProperty.

Python time measure function

First and foremost, I highly suggest using a profiler or atleast use timeit.

However if you wanted to write your own timing method strictly to learn, here is somewhere to get started using a decorator.

Python 2:

def timing(f):
    def wrap(*args):
        time1 = time.time()
        ret = f(*args)
        time2 = time.time()
        print '%s function took %0.3f ms' % (f.func_name, (time2-time1)*1000.0)
        return ret
    return wrap

And the usage is very simple, just use the @timing decorator:

@timing
def do_work():
  #code

Python 3:

def timing(f):
    def wrap(*args, **kwargs):
        time1 = time.time()
        ret = f(*args, **kwargs)
        time2 = time.time()
        print('{:s} function took {:.3f} ms'.format(f.__name__, (time2-time1)*1000.0))

        return ret
    return wrap

Note I'm calling f.func_name to get the function name as a string(in Python 2), or f.__name__ in Python 3.

Asynchronous method call in Python?

You could use eventlet. It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.

Here's an example of a super minimal crawler:

urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
     "https://wiki.secondlife.com/w/images/secondlife.jpg",
     "http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]

import eventlet
from eventlet.green import urllib2

def fetch(url):

  return urllib2.urlopen(url).read()

pool = eventlet.GreenPool()

for body in pool.imap(fetch, urls):
  print "got body", len(body)

Where is array's length property defined?

Arrays are special objects in java, they have a simple attribute named length which is final.

There is no "class definition" of an array (you can't find it in any .class file), they're a part of the language itself.

10.7. Array Members

The members of an array type are all of the following:

  • The public final field length, which contains the number of components of the array. length may be positive or zero.
  • The public method clone, which overrides the method of the same name in class Object and throws no checked exceptions. The return type of the clone method of an array type T[] is T[].

    A clone of a multidimensional array is shallow, which is to say that it creates only a single new array. Subarrays are shared.

  • All the members inherited from class Object; the only method of Object that is not inherited is its clone method.

Resources:

How to tell if a JavaScript function is defined

This worked for me

if( cb && typeof( eval( cb ) ) === "function" ){
    eval( cb + "()" );
}

How can you encode a string to Base64 in JavaScript?

Contributing with a minified polyfill for window.atob + window.btoa that I'm currently using.

(function(){function t(t){this.message=t}var e="undefined"!=typeof exports?exports:this,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.prototype=Error(),t.prototype.name="InvalidCharacterError",e.btoa||(e.btoa=function(e){for(var o,n,a=0,i=r,c="";e.charAt(0|a)||(i="=",a%1);c+=i.charAt(63&o>>8-8*(a%1))){if(n=e.charCodeAt(a+=.75),n>255)throw new t("'btoa' failed: The string to be encoded contains characters outside of the Latin1 range.");o=o<<8|n}return c}),e.atob||(e.atob=function(e){if(e=e.replace(/=+$/,""),1==e.length%4)throw new t("'atob' failed: The string to be decoded is not correctly encoded.");for(var o,n,a=0,i=0,c="";n=e.charAt(i++);~n&&(o=a%4?64*o+n:n,a++%4)?c+=String.fromCharCode(255&o>>(6&-2*a)):0)n=r.indexOf(n);return c})})();

iPhone 5 CSS media query

Another useful media feature is device-aspect-ratio.

Note that the iPhone 5 does not have a 16:9 aspect ratio. It is in fact 40:71.

iPhone < 5:
@media screen and (device-aspect-ratio: 2/3) {}

iPhone 5:
@media screen and (device-aspect-ratio: 40/71) {}

iPhone 6:
@media screen and (device-aspect-ratio: 375/667) {}

iPhone 6 Plus:
@media screen and (device-aspect-ratio: 16/9) {}

iPad:
@media screen and (device-aspect-ratio: 3/4) {}

Reference:
Media Queries @ W3C
iPhone Model Comparison
Aspect Ratio Calculator

Can't find System.Windows.Media namespace?

For Visual Studio 2017

Find "References" in Solution explorer

Right click "References"

Choose "Add Reference..."

Find "Presentation.Core" list and check checkbox

Click OK

Changing ViewPager to enable infinite page scrolling

Thank you for your answer Shereef.

I solved it a little bit differently.

I changed the code of the ViewPager class of the android support library. The method setCurrentItem(int)

changes the page with animation. This method calls an internal method that requires the index and a flag enabling smooth scrolling. This flag is boolean smoothScroll. Extending this method with a second parameter boolean smoothScroll solved it for me. Calling this method setCurrentItem(int index, boolean smoothScroll) allowed me to make it scroll indefinitely.

Here is a full example:

Please consider that only the center page is shown. Moreover did I store the pages seperately, allowing me to handle them with more ease.

private class Page {
  View page;
  List<..> data;
}
// page for predecessor, current, and successor
Page[] pages = new Page[3];




mDayPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
        }

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

        @Override
        public void onPageScrollStateChanged(int state) {

            if (state == ViewPager.SCROLL_STATE_IDLE) {

                if (mFocusedPage == 0) {
                    // move some stuff from the 
                                            // center to the right here
                    moveStuff(pages[1], pages[2]);

                    // move stuff from the left to the center 
                    moveStuff(pages[0], pages[1]);
                    // retrieve new stuff and insert it to the left page
                    insertStuff(pages[0]);
                }
                else if (mFocusedPage == 2) {


                    // move stuff from the center to the left page
                    moveStuff(pages[1], pages[0]); 
                    // move stuff from the right to the center page
                    moveStuff(pages[2], pages[1]); 
                    // retrieve stuff and insert it to the right page
                                            insertStuff(pages[2]);
                }

                // go back to the center allowing to scroll indefinitely
                mDayPager.setCurrentItem(1, false);
            }
        }
    });

However, without Jon Willis Code I wouldn't have solved it myself.

EDIT: here is a blogpost about this:

Maven – Always download sources and javadocs

For the sources on dependency level ( pom.xml) you can add :

<classifier>sources</classifier>

Number format in excel: Showing % value without multiplying with 100

Here's a simple way:

=NUMBERVALUE( CONCAT(5.66,"%") )

Just concatenate a % symbol after the number. By itself, this output would be text, so we also tuck the CONCAT function inside the NUMBERVALUE function.

p.s., in old excel, you might need to type the full word "CONCATENATE"

Resource interpreted as Document but transferred with MIME type application/json warning in Chrome Developer Tools

I was facing the same error. The solution that worked for me is:

From the server end, while returning JSON response, change the content-type: text/html

Now the browsers (Chrome, Firefox and IE8) do not give an error.

CSS selector - element with a given child

Update 2019

The :has() pseudo-selector is propsed in the CSS Selectors 4 spec, and will address this use case once implemented.

To use it, we will write something like:

.foo > .bar:has(> .baz) { /* style here */ }

In a structure like:

<div class="foo">
  <div class="bar">
    <div class="baz">Baz!</div>
  </div>
</div>

This CSS will target the .bar div - because it both has a parent .foo and from its position in the DOM, > .baz resolves to a valid element target.


Original Answer (left for historical purposes) - this portion is no longer accurate

For completeness, I wanted to point out that in the Selectors 4 specification (currently in proposal), this will become possible. Specifically, we will gain Subject Selectors, which will be used in the following format:

!div > span { /* style here */

The ! before the div selector indicates that it is the element to be styled, rather than the span. Unfortunately, no modern browsers (as of the time of this posting) have implemented this as part of their CSS support. There is, however, support via a JavaScript library called Sel, if you want to go down the path of exploration further.

Creating a div element in jQuery

As of jQuery 1.4 you can pass attributes to a self-closed element like so:

jQuery('<div/>', {
    id: 'some-id',
    "class": 'some-class',
    title: 'now this div has a title!'
}).appendTo('#mySelector');

Here it is in the Docs

Examples can be found at jQuery 1.4 Released: The 15 New Features you Must Know .

Jquery - How to get the style display attribute "none / block"

You could try:

$j('div.contextualError.ckgcellphone').css('display')

Passing parameters from jsp to Spring Controller method

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:

convert date string to mysql datetime field

I assume we are talking about doing this in Bash?

I like to use sed to load the date values into an array so I can break down each field and do whatever I want with it. The following example assumes and input format of mm/dd/yyyy...

DATE=$2
DATE_ARRAY=(`echo $DATE | sed -e 's/\// /g'`)
MONTH=(`echo ${DATE_ARRAY[0]}`)
DAY=(`echo ${DATE_ARRAY[1]}`)
YEAR=(`echo ${DATE_ARRAY[2]}`)
LOAD_DATE=$YEAR$MONTH$DAY

you also may want to read up on the date command in linux. It can be very useful: http://unixhelp.ed.ac.uk/CGI/man-cgi?date

Hope that helps... :)

-Ryan

EXCEL VBA Check if entry is empty or not 'space'

Most terse version I can think of

Len(Trim(TextBox1.Value)) = 0

If you need to do this multiple times, wrap it in a function

Public Function HasContent(text_box as Object) as Boolean
    HasContent = (Len(Trim(text_box.Value)) > 0)
End Function

Usage

If HasContent(TextBox1) Then
    ' ...

Case Insensitive String comp in C

You can get an idea, how to implement an efficient one, if you don't have any in the library, from here

It use a table for all 256 chars.

  • in that table for all chars, except letters - used its ascii codes.
  • for upper case letter codes - the table list codes of lower cased symbols.

then we just need to traverse a strings and compare our table cells for a given chars:

const char *cm = charmap,
        *us1 = (const char *)s1,
        *us2 = (const char *)s2;
while (cm[*us1] == cm[*us2++])
    if (*us1++ == '\0')
        return (0);
return (cm[*us1] - cm[*--us2]);

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

How do I center list items inside a UL element?

I have run into this issue before and found that sometimes padding is the issue.

By removing padding from the ul, any li's set to inline-block will be nicely centred:

_x000D_
_x000D_
* {_x000D_
 box-sizing: border-box;_x000D_
}_x000D_
_x000D_
ul {_x000D_
 width: 120px;_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
 border: 1px solid black;_x000D_
}_x000D_
_x000D_
li {_x000D_
 display: inline-block;_x000D_
}_x000D_
_x000D_
ul.no_pad {_x000D_
 padding: 0;_x000D_
}_x000D_
_x000D_
p {_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
}_x000D_
_x000D_
.break {_x000D_
 margin: 50px 10px;_x000D_
}
_x000D_
<div>  _x000D_
  <p>With Padding (Default Style)</p>_x000D_
            <ul class="with_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
  <div class="break"></div>_x000D_
  <p>No Padding (Padding: 0)</p>_x000D_
   <ul class="no_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
 <div>
_x000D_
_x000D_
_x000D_

Hope that helps anyone running into this same issue :)

Cheers,

Jake

how to display variable value in alert box?

document.getElementById('one').innerText;
alert(content);

It does not print the value; But, if done this way

document.getElementById('one').value;
alert(content);

SQL: Two select statements in one query

You can combine data from the two tables, order by goals highest first and then choose the top two like this:

MySQL

select *
from (
  select * from tblMadrid
  union all
  select * from tblBarcelona
) alldata
order by goals desc
limit 0,2;

SQL Server

select top 2 *
from (
  select * from tblMadrid
  union all
  select * from tblBarcelona
) alldata
order by goals desc;

If you only want Messi and Ronaldo

select * from tblBarcelona where name = 'messi'
union all
select * from tblMadrid where name = 'ronaldo'

To ensure that messi is at the top of the result, you can do something like this:

select * from (
  select * from tblBarcelona where name = 'messi'
  union all
  select * from tblMadrid where name = 'ronaldo'
) stars
order by name;

Get RETURN value from stored procedure in SQL

This should work for you. Infact the one which you are thinking will also work:-

 .......
 DECLARE @returnvalue INT

 EXEC @returnvalue = SP_One
 .....

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

assume you have a partial view called _contact.cshtml, your contact can be a legal (name) or a physical subject (first name, lastname). your view should take care about what's rendered and that can be achived with javascript. so delayed rendering and JS inside view may be needed.

the only way i think, how it can be ommitted, is when we create an unobtrusive way of handling such UI concerns.

also note that MVC 6 will have a so called View Component, even MVC futures had some similar stuff and Telerik also supports such a thing...

Header and footer in CodeIgniter

I tried almost all the answers proposed on this page and many other stuff. The best option I finally keeped on all my websites is the following architecture:

A single view

I display only one view in the browser. Here is my main view (/views/page.php):

<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
    <head>
        <?= $header ?? '' ?>
    </head>
    <body>
        <div style="width:1200px">
                <?= $content ?? '' ?>
        </div> 
    </body>
</html>

Controllers deal with multiple views

Of course, I had several views but they are concatenated to build the $header and the $content variables. Here is my controller:

$data['header'] = $this->load->view('templates/google-analytics', '', TRUE)
                 .$this->load->view('templates/javascript', '', TRUE)
                 .$this->load->view('templates/css', '', TRUE);


$data['content'] = $this->load->view('templates/navbar', '', TRUE)
                  .$this->load->view('templates/alert', $myData, TRUE)
                  .$this->load->view('home/index', $myData, TRUE)
                  .$this->load->view('home/footer', '', TRUE)
                  .$this->load->view('templates/modal-login', '', TRUE);

$this->load->view('templates/page', $data);
  • Look how beautiful and clear is the source code.
  • You no longer have HTML markup opened in one view and closed in another.
  • Each view is now dedicated to one and only one stuff.
  • Look how views are concatenated: method chaining pattern, or should we say: concatanated chaining pattern!
  • You can add optional parts (for example a third $javascript variable at the end of the body)
  • I frequently extend CI_Controller to overload $this->load->view with extra parameters dedicated to my application to keep my controllers clean.
  • If you are always loading the same views on several pages (this is finally the answer to the question), two options depending on your needs:
    • load views in views
    • extend CI_Controller or CI_Loader

I'm so proud of this architecture...

Maximum Length of Command Line String

From the Microsoft documentation: Command prompt (Cmd. exe) command-line string limitation

On computers running Microsoft Windows XP or later, the maximum length of the string that you can use at the command prompt is 8191 characters.

Random string generation with upper case letters and digits

Sometimes 0 (zero) & O (letter O) can be confusing. So I use

import uuid
uuid.uuid4().hex[:6].upper().replace('0','X').replace('O','Y')

git push says "everything up-to-date" even though I have local changes

Maybe you're pushing a new local branch?

A new local branch must be pushed explicitly:

git push origin your-new-branch-name

Just one of those things about git... You clone a repo, make a branch, commit some changes, push... "Everything is up to date". I understand why it happens, but this workflow is extremely unfriendly to newcomers.

Add Foreign Key to existing table

To add a foreign key (grade_id) to an existing table (users), follow the following steps:

ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);

Python concatenate text files

If you have a lot of files in the directory then glob2 might be a better option to generate a list of filenames rather than writing them by hand.

import glob2

filenames = glob2.glob('*.txt')  # list of all .txt files in the directory

with open('outfile.txt', 'w') as f:
    for file in filenames:
        with open(file) as infile:
            f.write(infile.read()+'\n')

Using Chrome's Element Inspector in Print Preview Mode?

Since Chrome 32 you have the CSS media option in the Screen section of the drawer Emulation tab.

Just enable it, select print as the target media type, and - behold - your page is rendered [almost] the way it will be printed.

Use Esc to bring up the drawer if it's not visible.

Align printf output in Java

Format specifications for printf and printf-like methods take an optional width parameter.

System.out.printf( "%10d. %25s $%25.2f\n",
                   i + 1, BOOK_TYPE[i], COST[i] );

Adjust widths to desired values.

Set Page Title using PHP

I know this is an old post but having read this I think this solution is much simpler (though technically it solves the problem with Javascript not PHP).

    <html>
    <head>
    <title>Ultan.me - Unset</title>
    <script type="text/javascript">
        function setTitle( text ) {
            document.title = text;
        }
    </script>
    <!-- other head info -->
    </head>

    <?php 
    // Make the call to the DB to get the title text. See OP post for example
    $title_text = "Ultan.me - DB Title";

    // Use body onload to set the title of the page
    print "<body onload=\"setTitle( '$title_text' )\"   >";

    // Rest of your code here
    print "<p>Either use php to print stuff</p>";
    ?>
    <p>or just drop in and out of php</p>
    <?php

    // close the html page
    print "</body></html>";
    ?>

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

Delete all records in a table of MYSQL in phpMyAdmin

An interesting fact.

I was sure TRUNCATE will always perform better, but in my case, for a db with approx 30 tables with foreign keys, populated with only a few rows, it took about 12 seconds to TRUNCATE all tables, as opposed to only a few hundred milliseconds to DELETE the rows. Setting the auto increment adds about a second in total, but it's still a lot better.

So I would suggest try both, see which works faster for your case.

What issues should be considered when overriding equals and hashCode in Java?

Still amazed that none recommended the guava library for this.

 //Sample taken from a current working project of mine just to illustrate the idea

    @Override
    public int hashCode(){
        return Objects.hashCode(this.getDate(), this.datePattern);
    }

    @Override
    public boolean equals(Object obj){
        if ( ! obj instanceof DateAndPattern ) {
            return false;
        }
        return Objects.equal(((DateAndPattern)obj).getDate(), this.getDate())
                && Objects.equal(((DateAndPattern)obj).getDate(), this.getDatePattern());
    }

Printing hexadecimal characters in C

You are seeing the ffffff because char is signed on your system. In C, vararg functions such as printf will promote all integers smaller than int to int. Since char is an integer (8-bit signed integer in your case), your chars are being promoted to int via sign-extension.

Since c0 and 80 have a leading 1-bit (and are negative as an 8-bit integer), they are being sign-extended while the others in your sample don't.

char    int
c0 -> ffffffc0
80 -> ffffff80
61 -> 00000061

Here's a solution:

char ch = 0xC0;
printf("%x", ch & 0xff);

This will mask out the upper bits and keep only the lower 8 bits that you want.

Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

I was getting the same error when trying to copy a file. Closing a channel associated with the target file solved the problem.

Path destFile = Paths.get("dest file");
SeekableByteChannel destFileChannel = Files.newByteChannel(destFile);
//...
destFileChannel.close();  //removing this will throw java.nio.file.AccessDeniedException:
Files.copy(Paths.get("source file"), destFile);

How can we draw a vertical line in the webpage?

<hr> is not from struts. It is just an HTML tag.

So, take a look here: http://www.microbion.co.uk/web/vertline.htm This link will give you a couple of tips.

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Vojta described the "Angular way", but if you really need to make this work, @urbanek recently posted a workaround using ng-init:

<input type="text" ng-model="rootFolders" ng-init="rootFolders='Bob'" value="Bob">

https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ

Do HttpClient and HttpClientHandler have to be disposed between requests?

Please take a read on my answer to a very similar question posted below. It should be clear that you should treat HttpClient instances as singletons and re-used across requests.

What is the overhead of creating a new HttpClient per call in a WebAPI client?

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

"Bitmap too large to be uploaded into a texture"

Changing the image file to drawable-nodpi folder from drawable folder worked for me.

how to use "AND", "OR" for RewriteCond on Apache?

After many struggles and to achive a general, flexible and more readable solution, in my case I ended up saving the ORs results into ENV variables and doing the ANDs of those variables.

# RESULT_ONE = A OR B
RewriteRule ^ - [E=RESULT_ONE:False]
RewriteCond ...A... [OR]
RewriteCond ...B...
RewriteRule ^ - [E=RESULT_ONE:True]

# RESULT_TWO = C OR D
RewriteRule ^ - [E=RESULT_TWO:False]
RewriteCond ...C... [OR]
RewriteCond ...D...
RewriteRule ^ - [E=RESULT_TWO:True]

# if ( RESULT_ONE AND RESULT_TWO ) then ( RewriteRule ...something... )
RewriteCond %{ENV:RESULT_ONE} =True
RewriteCond %{ENV:RESULT_TWO} =True
RewriteRule ...something...

Requirements:

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.

ie...

setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

Can Flask have optional URL parameters?

@user.route('/<user_id>', defaults={'username': default_value})
@user.route('/<user_id>/<username>')
def show(user_id, username):
   #
   pass

Uninstall Django completely

Use Python shell to find out the path of Django:

>>> import django
>>> django
<module 'django' from '/usr/local/lib/python2.7/dist-packages/django/__init__.pyc'>

Then remove it manually:

sudo rm -rf /usr/local/lib/python2.7/dist-packages/django/

Java best way for string find and replace?

Simply include the Apache Commons Lang JAR and use the org.apache.commons.lang.StringUtils class. You'll notice lots of methods for replacing Strings safely and efficiently.

You can view the StringUtils API at the previously linked website.

"Don't reinvent the wheel"

How and when to use SLEEP() correctly in MySQL?

SELECT ...
SELECT SLEEP(5);
SELECT ...

But what are you using this for? Are you trying to circumvent/reinvent mutexes or transactions?

Cannot find module '../build/Release/bson'] code: 'MODULE_NOT_FOUND' } js-bson: Failed to load c++ bson extension, using pure JS version

This worked for me:

Go to the file (in your project):

node_modules/mongoose/node_modules/mongodb/node_modules/bson/ext/index.js

and change:

bson = require('../build/Release/bson');

to:

bson = require('bson');

Reference: https://github.com/mongodb/js-bson/issues/118

Convert datatable to JSON in C#

You can use the same way as specified by Alireza Maddah and if u want to use two data table into one json array following is the way:

public string ConvertDataTabletoString()
{
DataTable dt = new DataTable();
DataTable dt1 = new DataTable();
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Initial Catalog=master;Integrated Security=true"))
{
    using (SqlCommand cmd = new SqlCommand("select title=City,lat=latitude,lng=longitude,description from LocationDetails", con))
    {
        con.Open();
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
        Dictionary<string, object> row;
        foreach (DataRow dr in dt.Rows)
        {
            row = new Dictionary<string, object>();
            foreach (DataColumn col in dt.Columns)
            {
                row.Add(col.ColumnName, dr[col]);
            }
            rows.Add(row);
        }
        SqlCommand cmd1 = new SqlCommand("_another_query_", con);
                SqlDataAdapter da1 = new SqlDataAdapter(cmd1);
                da1.Fill(dt1);
                System.Web.Script.Serialization.JavaScriptSerializer serializer1 = new System.Web.Script.Serialization.JavaScriptSerializer();
                Dictionary<string, object> row1;
                foreach (DataRow dr in dt1.Rows) //use the old variable rows only
                {
                    row1 = new Dictionary<string, object>();
                    foreach (DataColumn col in dt1.Columns)
                    {
                        row1.Add(col.ColumnName, dr[col]);
                    }
                    rows.Add(row1); // Finally You can add into old json array in this way
                }
        return serializer.Serialize(rows);
    }
}
}

The same way can be used for as many as data tables as you want.

How to extract the decimal part from a floating point number in C?

You use the modf function:

double integral;
double fractional = modf(some_double, &integral);

You can also cast it to an integer, but be warned you may overflow the integer. The result is not predictable then.

Using Html.ActionLink to call action on different controller

An alternative solution would be to use the Url helper object to set the href attribute of an <a> tag like:

<a href="@Url.Action("Details", "Product",new { id=item.ID }) )">Details</a>

How to install an APK file on an Android phone?

If you have access to a Gmail account on the phone then an easy way (in terms of minimal set up effort) is to mail the .apk file to that Gmail account.

If you then access that account from the native Gmail app on the phone it recognises that the attachment is an app and offers an "Install" button.

As per other responses this approach also requires that you have selected USB debugging on the device.

Try this - it is remarkably easy ;-)

How to SHUTDOWN Tomcat in Ubuntu?

If you installed tomcat manually, run the shutdown.sh(/.../tomcat/bin) from the terminal to shut it down easily.

How to debug (only) JavaScript in Visual Studio?

For debugging JavaScript code in VS2015, there is no need for

  1. Enabling script debugging in IE Options -> Advanced tab
  2. Writing debugger statement in JavaScript code

Attaching IE didn't work, but here is a workaround.

Select IE

enter image description here

and press F5. This will attach both worker process and IE as shown here- enter image description here

If you are not interested in debugging server code, detach it from Processes window. enter image description here

You will still face the slowness when you press F5 and all your server code compiles and loads up in VS. Note that you can detach and attach again the IE instance launched from VS. JavaScript breakpoints are hit the same way they are in server side code.

Animation CSS3: display + opacity

display: is not transitionable. You'll probably need to use jQuery to do what you want to do.

redirect COPY of stdout to log file from within bash script itself

Solution for busybox, macOS bash, and non-bash shells

The accepted answer is certainly the best choice for bash. I'm working in a Busybox environment without access to bash, and it does not understand the exec > >(tee log.txt) syntax. It also does not do exec >$PIPE properly, trying to create an ordinary file with the same name as the named pipe, which fails and hangs.

Hopefully this would be useful to someone else who doesn't have bash.

Also, for anyone using a named pipe, it is safe to rm $PIPE, because that unlinks the pipe from the VFS, but the processes that use it still maintain a reference count on it until they are finished.

Note the use of $* is not necessarily safe.

#!/bin/sh

if [ "$SELF_LOGGING" != "1" ]
then
    # The parent process will enter this branch and set up logging

    # Create a named piped for logging the child's output
    PIPE=tmp.fifo
    mkfifo $PIPE

    # Launch the child process with stdout redirected to the named pipe
    SELF_LOGGING=1 sh $0 $* >$PIPE &

    # Save PID of child process
    PID=$!

    # Launch tee in a separate process
    tee logfile <$PIPE &

    # Unlink $PIPE because the parent process no longer needs it
    rm $PIPE    

    # Wait for child process, which is running the rest of this script
    wait $PID

    # Return the error code from the child process
    exit $?
fi

# The rest of the script goes here

Center/Set Zoom of Map to cover all visible Markers?

You need to use the fitBounds() method.

var markers = [];//some array
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
 bounds.extend(markers[i]);
}

map.fitBounds(bounds);

Documentation from developers.google.com/maps/documentation/javascript:

fitBounds(bounds[, padding])

Parameters:

`bounds`:  [`LatLngBounds`][1]|[`LatLngBoundsLiteral`][1]
`padding` (optional):  number|[`Padding`][1]

Return Value: None

Sets the viewport to contain the given bounds.
Note: When the map is set to display: none, the fitBounds function reads the map's size as 0x0, and therefore does not do anything. To change the viewport while the map is hidden, set the map to visibility: hidden, thereby ensuring the map div has an actual size.

Convert LocalDate to LocalDateTime or java.sql.Timestamp

tl;dr

The Joda-Time project is in maintenance-mode, now supplanted by java.time classes.

  • Just use java.time.Instant class.
  • No need for:
    • LocalDateTime
    • java.sql.Timestamp
    • Strings

Capture current moment in UTC.

Instant.now()  

To store that moment in database:

myPreparedStatement.setObject( … , Instant.now() )  // Writes an `Instant` to database.

To retrieve that moment from datbase:

myResultSet.getObject( … , Instant.class )  // Instantiates a `Instant`

To adjust the wall-clock time to that of a particular time zone.

instant.atZone( z )  // Instantiates a `ZonedDateTime`

LocalDateTime is the wrong class

Other Answers are correct, but they fail to point out that LocalDateTime is the wrong class for your purpose.

In both java.time and Joda-Time, a LocalDateTime purposely lacks any concept of time zone or offset-from-UTC. As such, it does not represent a moment, and is not a point on the timeline. A LocalDateTime represents a rough idea about potential moments along a range of about 26-27 hours.

Use a LocalDateTime for either when the zone/offset is unknown (not a good situation), or when the zone-offset is indeterminate. For example, “Christmas starts at first moment of December 25, 2018” would be represented as a LocalDateTime.

Use a ZonedDateTime to represent a moment in a particular time zone. For example, Christmas starting in any particular zone such as Pacific/Auckland or America/Montreal would be represented with a ZonedDateTime object.

For a moment always in UTC, use Instant.

Instant instant = Instant.now() ;  // Capture the current moment in UTC.

Apply a time zone. Same moment, same point on the timeline, but viewed with a different wall-clock time.

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, different wall-clock time.

So, if I can just convert between LocalDate and LocalDateTime,

No, wrong strategy. If you have a date-only value, and you want a date-time value, you must specify a time-of-day. That time-of-day may not be valid on that date for a particular zone – in which case ZonedDateTime class automatically adjusts the time-of-day as needed.

LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ;
LocalTime lt = LocalTime.of( 14 , 0 ) ;  // 14:00 = 2 PM.
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z ) ;

If you want the first moment of the day as your time-of-day, let java.time determine that moment. Do not assume the day starts at 00:00:00. Anomalies such as Daylight Saving Time (DST) mean the day may start at another time such as 01:00:00.

ZonedDateTime zdt = ld.atStartOfDay( z ) ;

java.sql.Timestamp is the wrong class

The java.sql.Timestamp is part of the troublesome old date-time classes that are now legacy, supplanted entirely by the java.time classes. That class was used to represent a moment in UTC with a resolution of nanoseconds. That purpose is now served with java.time.Instant.

JDBC 4.2 with getObject/setObject

As of JDBC 4.2 and later, your JDBC driver can directly exchange java.time objects with the database by calling:

For example:

myPreparedStatement.setObject( … , instant ) ;

… and …

Instant instant = myResultSet.getObject( … , Instant.class ) ;

Convert legacy ? modern

If you must interface with old code not yet updated to java.time, convert back and forth using new methods added to the old classes.

Instant instant = myJavaSqlTimestamp.toInstant() ;  // Going from legacy class to modern class.

…and…

java.sql.Timestamp myJavaSqlTimestamp = java.sql.Timestamp.from( instant ) ;  // Going from modern class to legacy class.

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

SQL Inner join more than two tables

A possible solution:

SELECT Company.Company_Id,Company.Company_Name,
    Invoice_Details.Invoice_No, Product_Details.Price
  FROM Company inner join Invoice_Details
    ON Company.Company_Id=Invoice_Details.Company_Id
 INNER JOIN Product_Details
        ON Invoice_Details.Invoice_No= Product_Details.Invoice_No
 WHERE Price='60000';

-- tets changes

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Getting attribute using XPath

Here is the snippet of getting the attribute value of "lang" with XPath and VTD-XML.

import com.ximpleware.*;
public class getAttrVal {
    public static void main(String s[]) throws VTDException{
        VTDGen vg = new VTDGen();
        if (!vg.parseFile("input.xml", false)){
            return ;
        }
        VTDNav vn = vg.getNav();
        AutoPilot ap = new AutoPilot(vn);
        ap.selectXPath("/bookstore/book/title/@lang");
        System.out.println(" lang's value is ===>"+ap.evalXPathToString());
    }
}

JavaFX Panel inside Panel auto resizing

I was designing a GUI in SceneBuilder, trying to make the main container adapt to whatever the window size is. It should always be 100% wide.

This is where you can set these values in SceneBuilder:

AnchorPane Constraints in SceneBuilder

Toggling the dotted/red lines will actually just add/remove the attributes that Korki posted in his solution (AnchorPane.topAnchor etc.).

Environment variables in Mac OS X

Synchronize OS X environment variables for command line and GUI applications from a single source with osx-env-sync.

I also posted an answer to a related question here.

How to remove foreign key constraint in sql server?

To remove all the constraints from the DB:

SELECT 'ALTER TABLE ' + Table_Name  +' DROP CONSTRAINT ' + Constraint_Name
FROM Information_Schema.CONSTRAINT_TABLE_USAGE

change html text from link with jquery

You need J-query library to do this simply:

<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>

First you need to put your element in div like this:

<div id="divClickHere">
<a id="a_tbnotesverbergen" href="#nothing">click here</a>
</div>

Then you should write this J-Query Code:

<script type="text/javascript">
$(document).ready(function(){
$("#a_tbnotesverbergen").click(function(){
$("#divClickHere a").text('Your new text');
});
});
</script>

MySQL - Operand should contain 1 column(s)

Your subquery is selecting two columns, while you are using it to project one column (as part of the outer SELECT clause). You can only select one column from such a query in this context.

Consider joining to the users table instead; this will give you more flexibility when selecting what columns you want from users.

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
COUNT( posts.solved_post ) AS solved_post,
users.username AS posted_by,
users.id AS posted_by_id

FROM topics

LEFT OUTER JOIN posts ON posts.topic_id = topics.id
LEFT OUTER JOIN users ON users.id = posts.posted_by

WHERE topics.cat_id = :cat
GROUP BY topics.id

installation app blocked by play protect

If you are using some trackers like google analytics or amplitude and you are trying to release your app in another platforms other than Google Play, this errors appears for users. So there are two possible solutions:

  1. Use special trackers in your app (firebase and appmetrica are tested and are ok)
  2. Release your app in Google Play

Running Python on Windows for Node.js dependencies

Example : pg_config not executable / error node-gyp

Solution : On windows just try to add PATH Env -> C:\Program Files\PostgreSQL\12\bin

Work for me, Now i can use npm i pg-promise for example or other dependencies.

How to indent HTML tags in Notepad++

In Notepad++ v7.8.9 you can use the Tab key to increase the indention level, and use Shift + Tab to decrease the indentation level.

Accessing certain pixel RGB value in openCV

A piece of code is easier for people who have such problem. I share my code and you can use it directly. Please note that OpenCV store pixels as BGR.

cv::Mat vImage_; 

if(src_)
{
    cv::Vec3f vec_;

    for(int i = 0; i < vHeight_; i++)
        for(int j = 0; j < vWidth_; j++)
        {
            vec_ = cv::Vec3f((*src_)[0]/255.0, (*src_)[1]/255.0, (*src_)[2]/255.0);//Please note that OpenCV store pixels as BGR.

            vImage_.at<cv::Vec3f>(vHeight_-1-i, j) = vec_;

            ++src_;
        }
}

if(! vImage_.data ) // Check for invalid input
    printf("failed to read image by OpenCV.");
else
{
    cv::namedWindow( windowName_, CV_WINDOW_AUTOSIZE);
    cv::imshow( windowName_, vImage_); // Show the image.
}

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Npm Error - No matching version found for

Try removing package-lock.json file first

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

How to break out of nested loops?

bool stop = false;
for (int i = 0; (i < 1000) && !stop; i++)
{
    for (int j = 0; (j < 1000) && !stop; j++)
    {
        if (condition)
            stop = true;
    }
}

How to pass arguments to Shell Script through docker run

with this script in file.sh

#!/bin/bash
echo Your container args are: "$@"

and this Dockerfile

FROM ubuntu:14.04
COPY ./file.sh /
ENTRYPOINT ["/file.sh"]

you should be able to:

% docker build -t test .
% docker run test hello world
Your container args are: hello world

What is the ultimate postal code and zip regex?

There is none.

Postal/zip codes around the world don't follow a common pattern. In some countries they are made up by numbers, in others they can be combinations of numbers an letters, some can contain spaces, others dots, the number of characters can vary from two to at least six...

What you could do (theoretically) is create a seperate regex for every country in the world, not recommendable IMO. But you would still be missing on the validation part: Zip code 12345 may exist, but 12346 not, maybe 12344 doesn't exist either. How do you check for that with a regex?

You can't.

How can I simulate a click to an anchor tag?

well, you can very quickly test the click dispatch via jQuery like so

$('#link-id').click();

If you're still having problem with click respecting the target, you can always do this

$('#link-id').click( function( event, anchor )
{
  window.open( anchor.href, anchor.target, '' );
  event.preventDefault();
  return false;
});

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

Change color of Button when Mouse is over

<Button Content="Click" Width="200" Height="50">
<Button.Style>
    <Style TargetType="{x:Type Button}">
        <Setter Property="Background" Value="LightBlue" />
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Border x:Name="Border" Background="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </Border>
                    <ControlTemplate.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Background" Value="LightGreen" TargetName="Border" />
                        </Trigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Button.Style>

Make an image width 100% of parent div, but not bigger than its own width

You should set the max width and if you want you can also set some padding on one of the sides. In my case the max-width: 100% was good but the image was right next to the end of the screen.

  max-width: 100%;
  padding-right: 30px;
  /*add more paddings if needed*/

What is the best free SQL GUI for Linux for various DBMS systems

I use SQLite Database Browser for SQLite3 currently and it's pretty useful. Works across Windows/OS X/Linux and is lightweight and fast. Slightly unstable with executing SQL on the DB if it's incorrectly formatted.

Edit: I have recently discovered SQLite Manager, a plugin for Firefox. Obviously you need to run Firefox, but you can close all windows and just run it "standalone". It's very feature complete, amazingly stable and it remembers your databases! It has tonnes of features so I've moved away from SQLite Database Browser as the instability and lack of features is too much to bear.

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

Foreign Key naming scheme

This is probably over-kill, but it works for me. It helps me a great deal when I am dealing with VLDBs especially. I use the following:

CONSTRAINT [FK_ChildTableName_ChildColName_ParentTableName_PrimaryKeyColName]

Of course if for some reason you are not referencing a primary key you must be referencing a column contained in a unique constraint, in this case:

CONSTRAINT [FK_ChildTableName_ChildColumnName_ParentTableName_ColumnInUniqueConstaintName]

Can it be long, yes. Has it helped keep info clear for reports, or gotten me a quick jump on that the potential issue is during a prod-alert 100% would love to know peoples thoughts on this naming convention.

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

homebrew Installer

Assuming you installed PostgreSQL with homebrew as referenced in check status of postgresql server Mac OS X and how to start postgresql server on mac os x: you can use the brew uninstall postgresql command.

EnterpriseDB Installer

If you used the EnterpriseDB installer then see the other answer in this thread.

The EnterpriseDB installer is what you get if you follow "download" links from the main Postgres web site. The Postgres team releases only source code, so the EnterpriseDB.com company builds installers as a courtesy to the community.

Postgres.app

You may have also used Postgres.app.

This double-clickable Mac app contains the Postgres engine.

How to send an email with Python?

Here is an example on Python 3.x, much simpler than 2.x:

import smtplib
from email.message import EmailMessage
def send_mail(to_email, subject, message, server='smtp.example.cn',
              from_email='[email protected]'):
    # import smtplib
    msg = EmailMessage()
    msg['Subject'] = subject
    msg['From'] = from_email
    msg['To'] = ', '.join(to_email)
    msg.set_content(message)
    print(msg)
    server = smtplib.SMTP(server)
    server.set_debuglevel(1)
    server.login(from_email, 'password')  # user & password
    server.send_message(msg)
    server.quit()
    print('successfully sent the mail.')

call this function:

send_mail(to_email=['[email protected]', '[email protected]'],
          subject='hello', message='Your analysis has done!')

below may only for Chinese user:

If you use 126/163, ????, you need to set"???????", like below:

enter image description here

ref: https://stackoverflow.com/a/41470149/2803344 https://docs.python.org/3/library/email.examples.html#email-examples

setup script exited with error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

below answer worked for me, you can try:

sudo apt-get install python3-lxml

Push an associative item into an array in JavaScript

JavaScript doesn't have associate arrays. You need to use Objects instead:

var obj = {};
var name = "name";
var val = 2;
obj[name] = val;
console.log(obj);?

To get value you can use now different ways:

console.log(obj.name);?
console.log(obj[name]);?
console.log(obj["name"]);?

Using variables inside a bash heredoc

As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.

Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE

Demo: https://ideone.com/rMF2XA

Note that any of the quoting mechanisms -- \____HERE or "____HERE" or '____HERE' -- will disable all variable interpolation, and turn the here-document into a piece of literal text.

A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.

local=$(uname)
ssh -t remote <<:
    echo "$local is the value from the host which ran the ssh command"
    # Prevent here doc from expanding locally; remote won't see backslash
    remote=\$(uname)
    # Same here
    echo "\$remote is the value from the host we ssh:ed to"
:

Can't find keyplane that supports type 4 for keyboard iPhone-Portrait-NumberPad; using 3876877096_Portrait_iPhone-Simple-Pad_Default

I too had this problem after updating to the latest Xcode Beta. The settings on the simulator are refreshed, so the laptop (external) keyboard was being detected. If you simply press:

iOS Simulator -> Hardware -> Keyboard -> Connect Hardware Keyboard

so that the entry is UNchecked then the software keyboard will be displayed once again.

How can I convert a string to a number in Perl?

$var += 0

probably what you want. Be warned however, if $var is string could not be converted to numeric, you'll get the error, and $var will be reset to 0:

my $var = 'abc123';
print "var = $var\n";
$var += 0;
print "var = $var\n";

logs

var = abc123
Argument "abc123" isn't numeric in addition (+) at test.pl line 7.
var = 0

Changing capitalization of filenames in Git

Sometimes you want to change the capitalization of a lot of file names on a case insensitive filesystem (e.g. on OS X or Windows). Doing git mv commands will tire quickly. To make things a bit easier this is what I do:

  1. Move all files outside of the directory to, let’s, say the desktop.
  2. Do a git add . -A to remove all files.
  3. Rename all files on the desktop to the proper capitalization.
  4. Move all the files back to the original directory.
  5. Do a git add .. Git should see that the files are renamed.

Now you can make a commit saying you have changed the file name capitalization.

Disable html5 video autoplay

I'd remove the autoplay attribute, since if the browser encounters it, it autoplays!

autoplay is a HTML boolean attribute, but be aware that the values true and false are not allowed. To represent a false value, you must omit the attribute.

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

Also, the type goes inside the source, like this:

<video width="640" height="480" controls preload="none">
   <source src="http://example.com/mytestfile.mp4" type="video/mp4">
   Your browser does not support the video tag.
</video>

References:

Android java.lang.NoClassDefFoundError

Try going to Project -> Properties -> Java Build Path -> Order & Export And Confirm Android Private Libraries are checked for your project and for all other library projects you are using in your Application.

Run a string as a command within a Bash script

./me casts raise_dead()

I was looking for something like this, but I also needed to reuse the same string minus two parameters so I ended up with something like:

my_exe ()
{
    mysql -sN -e "select $1 from heat.stack where heat.stack.name=\"$2\";"
}

This is something I use to monitor openstack heat stack creation. In this case I expect two conditions, an action 'CREATE' and a status 'COMPLETE' on a stack named "Somestack"

To get those variables I can do something like:

ACTION=$(my_exe action Somestack)
STATUS=$(my_exe status Somestack)
if [[ "$ACTION" == "CREATE" ]] && [[ "$STATUS" == "COMPLETE" ]]
...

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

Got it to work by transitioning the padding as well as the width.

JSFiddle: http://jsfiddle.net/tuybk748/1/

<div class='label gray'>+
</div><!-- must be connected to prevent gap --><div class='contents-wrapper'>
    <div class="gray contents">These are the contents of this div</div>
</div>
.gray {
    background: #ddd;
}
.contents-wrapper, .label, .contents {
    display: inline-block;
}
.label, .contents {
    overflow: hidden; /* must be on both divs to prevent dropdown behavior */
    height: 20px;
}
.label {
    padding: 10px 10px 15px;
}
.contents {
    padding: 10px 0px 15px; /* no left-right padding at beginning */
    white-space: nowrap; /* keeps text all on same line */
    width: 0%;
    -webkit-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -moz-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    -o-transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
    transition: width 1s ease-in-out, padding-left 1s ease-in-out, 
        padding-right 1s ease-in-out;
}
.label:hover + .contents-wrapper .contents {
    width: 100%;
    padding-left: 10px;
    padding-right: 10px;
}

How to remove all elements in String array in java?

Usually someone uses collections if something frequently changes.

E.g.

    List<String> someList = new ArrayList<String>();
    // initialize list
    someList.add("Mango");
    someList.add("....");
    // remove all elements
    someList.clear();
    // empty list

An ArrayList for example uses a backing Array. The resizing and this stuff is handled automatically. In most cases this is the appropriate way.

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If You are trying to access it through Data Connections in Visual Studio 2015, and getting the above Error, Then Go to Advanced and set TrustServerCertificate=True for error to go away.

What is a StackOverflowError?

This is a typical case of java.lang.StackOverflowError... The method is recursively calling itself with no exit in doubleValue(), floatValue(), etc.

Rational.java

    public class Rational extends Number implements Comparable<Rational> {
        private int num;
        private int denom;

        public Rational(int num, int denom) {
            this.num = num;
            this.denom = denom;
        }

        public int compareTo(Rational r) {
            if ((num / denom) - (r.num / r.denom) > 0) {
                return +1;
            } else if ((num / denom) - (r.num / r.denom) < 0) {
                return -1;
            }
            return 0;
        }

        public Rational add(Rational r) {
            return new Rational(num + r.num, denom + r.denom);
        }

        public Rational sub(Rational r) {
            return new Rational(num - r.num, denom - r.denom);
        }

        public Rational mul(Rational r) {
            return new Rational(num * r.num, denom * r.denom);
        }

        public Rational div(Rational r) {
            return new Rational(num * r.denom, denom * r.num);
        }

        public int gcd(Rational r) {
            int i = 1;
            while (i != 0) {
                i = denom % r.denom;
                denom = r.denom;
                r.denom = i;
            }
            return denom;
        }

        public String toString() {
            String a = num + "/" + denom;
            return a;
        }

        public double doubleValue() {
            return (double) doubleValue();
        }

        public float floatValue() {
            return (float) floatValue();
        }

        public int intValue() {
            return (int) intValue();
        }

        public long longValue() {
            return (long) longValue();
        }
    }

Main.java

    public class Main {

        public static void main(String[] args) {

            Rational a = new Rational(2, 4);
            Rational b = new Rational(2, 6);

            System.out.println(a + " + " + b + " = " + a.add(b));
            System.out.println(a + " - " + b + " = " + a.sub(b));
            System.out.println(a + " * " + b + " = " + a.mul(b));
            System.out.println(a + " / " + b + " = " + a.div(b));

            Rational[] arr = {new Rational(7, 1), new Rational(6, 1),
                    new Rational(5, 1), new Rational(4, 1),
                    new Rational(3, 1), new Rational(2, 1),
                    new Rational(1, 1), new Rational(1, 2),
                    new Rational(1, 3), new Rational(1, 4),
                    new Rational(1, 5), new Rational(1, 6),
                    new Rational(1, 7), new Rational(1, 8),
                    new Rational(1, 9), new Rational(0, 1)};

            selectSort(arr);

            for (int i = 0; i < arr.length - 1; ++i) {
                if (arr[i].compareTo(arr[i + 1]) > 0) {
                    System.exit(1);
                }
            }


            Number n = new Rational(3, 2);

            System.out.println(n.doubleValue());
            System.out.println(n.floatValue());
            System.out.println(n.intValue());
            System.out.println(n.longValue());
        }

        public static <T extends Comparable<? super T>> void selectSort(T[] array) {

            T temp;
            int mini;

            for (int i = 0; i < array.length - 1; ++i) {

                mini = i;

                for (int j = i + 1; j < array.length; ++j) {
                    if (array[j].compareTo(array[mini]) < 0) {
                        mini = j;
                    }
                }

                if (i != mini) {
                    temp = array[i];
                    array[i] = array[mini];
                    array[mini] = temp;
                }
            }
        }
    }

Result

    2/4 + 2/6 = 4/10
    Exception in thread "main" java.lang.StackOverflowError
    2/4 - 2/6 = 0/-2
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
    2/4 * 2/6 = 4/24
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
    2/4 / 2/6 = 12/8
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
        at com.xetrasu.Rational.doubleValue(Rational.java:64)
        at com.xetrasu.Rational.doubleValue(Rational.java:64)

Here is the source code of StackOverflowError in OpenJDK 7

Get current directory name (without full path) in a Bash script

I strongly prefer using gbasename, which is part of GNU coreutils.

How to split a data frame?

You could also use

data2 <- data[data$sum_points == 2500, ]

This will make a dataframe with the values where sum_points = 2500

It gives :

airfoils sum_points field_points   init_t contour_t   field_t
...
491        5       2500         5625 0.000086  0.004272  6.321774
498        5       2500         5625 0.000087  0.004507  6.325083
504        5       2500         5625 0.000088  0.004370  6.336034
603        5        250        10000 0.000072  0.000525  1.111278
577        5        250        10000 0.000104  0.000559  1.111431
587        5        250        10000 0.000072  0.000528  1.111524
606        5        250        10000 0.000079  0.000538  1.111685
....
> data2 <- data[data$sum_points == 2500, ]
> data2
airfoils sum_points field_points   init_t contour_t   field_t
108        5       2500          625 0.000082  0.004329  0.733109
106        5       2500          625 0.000102  0.004564  0.733243
117        5       2500          625 0.000087  0.004321  0.733274
112        5       2500          625 0.000081  0.004428  0.733587

Simplest code for array intersection in javascript

How about just using associative arrays?

function intersect(a, b) {
    var d1 = {};
    var d2 = {};
    var results = [];
    for (var i = 0; i < a.length; i++) {
        d1[a[i]] = true;
    }
    for (var j = 0; j < b.length; j++) {
        d2[b[j]] = true;
    }
    for (var k in d1) {
        if (d2[k]) 
            results.push(k);
    }
    return results;
}

edit:

// new version
function intersect(a, b) {
    var d = {};
    var results = [];
    for (var i = 0; i < b.length; i++) {
        d[b[i]] = true;
    }
    for (var j = 0; j < a.length; j++) {
        if (d[a[j]]) 
            results.push(a[j]);
    }
    return results;
}

How to Parse JSON Array with Gson

you can get List value without using Type object.

EvalClassName[] evalClassName;
ArrayList<EvalClassName> list;
evalClassName= new Gson().fromJson(JSONArrayValue.toString(),EvalClassName[].class);
list = new ArrayList<>(Arrays.asList(evalClassName));

I have tested it and it is working.

Naming convention - underscore in C++ and C# variables

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

How to launch Windows Scheduler by command-line?

You might want to have look at simple command line scheduler "at":


C:\Documents and Settings\mahendra.patil>at/?

The AT command schedules commands and programs to run on a computer at a specified time and date. The Schedule service must be running to use the AT command.

AT [\\computername] [ [id] [/DELETE] | /DELETE [/YES]]
AT [\\computername] time [/INTERACTIVE]
    [ /EVERY:date[,...] | /NEXT:date[,...]] "command"

\computername Specifies a remote computer. Commands are scheduled on the local computer if this parameter is omitted.

id Is an identification number assigned to a scheduled command.

/delete Cancels a scheduled command. If id is omitted, all the scheduled commands on the computer are canceled.

/yes Used with cancel all jobs command when no further confirmation is desired.

time Specifies the time when command is to run.

/interactive Allows the job to interact with the desktop of the user who is logged on at the time the job runs.

/every:date[,...] Runs the command on each specified day(s) of the week or month. If date is omitted, the current day of the month is assumed.

/next:date[,...] Runs the specified command on the next occurrence of the day (for example, next Thursday). If date is omitted, the current day of the month is assumed.

"command" Is the Windows NT command, or batch program to be run.

Detect if a NumPy array contains at least one non-numeric value?

This should be faster than iterating and will work regardless of shape.

numpy.isnan(myarray).any()

Edit: 30x faster:

import timeit
s = 'import numpy;a = numpy.arange(10000.).reshape((100,100));a[10,10]=numpy.nan'
ms = [
    'numpy.isnan(a).any()',
    'any(numpy.isnan(x) for x in a.flatten())']
for m in ms:
    print "  %.2f s" % timeit.Timer(m, s).timeit(1000), m

Results:

  0.11 s numpy.isnan(a).any()
  3.75 s any(numpy.isnan(x) for x in a.flatten())

Bonus: it works fine for non-array NumPy types:

>>> a = numpy.float64(42.)
>>> numpy.isnan(a).any()
False
>>> a = numpy.float64(numpy.nan)
>>> numpy.isnan(a).any()
True

Inserting image into IPython notebook markdown

minrk's answer is right.

However, I found that the images appeared broken in Print View (on my Windows machine running the Anaconda distribution of IPython version 0.13.2 in a Chrome browser)

The workaround for this was to use <img src="../files/image.png"> instead.

This made the image appear correctly in both Print View and the normal iPython editing view.

UPDATE: as of my upgrade to iPython v1.1.0 there is no more need for this workaround since the print view no longer exists. In fact, you must avoid this workaround since it prevents the nbconvert tool from finding the files.

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

Trim string in JavaScript?

Here it is in TypeScript:

var trim: (input: string) => string = String.prototype.trim
    ? ((input: string) : string => {
        return (input || "").trim();
    })
    : ((input: string) : string => {
        return (input || "").replace(/^\s+|\s+$/g,"");
    })

It will fall back to the regex if the native prototype is not available.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

How to set JAVA_HOME for multiple Tomcat instances?

If you are a Windows user, put the content below in a setenv.bat file that you must create in Tomcat bin directory.

set JAVA_HOME=C:\Program Files\Java\jdk1.6.x

If you are a Linux user, put the content below in a setenv.sh file that you must create in Tomcat bin directory.

JAVA_HOME=/usr/java/jdk1.6.x

Position absolute but relative to parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 0;
}

#son2 {
   position: absolute;
   bottom: 0;
}

This works because position: absolute means something like "use top, right, bottom, left to position yourself in relation to the nearest ancestor who has position: absolute or position: relative."

So we make #father have position: relative, and the children have position: absolute, then use top and bottom to position the children.

Writing string to a file on a new line every time

Use "\n":

file.write("My String\n")

See the Python manual for reference.

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

Installation error: INSTALL_FAILED_OLDER_SDK

Received the same error , the problem was difference in the version of Android SDK which AVD was using and the version in AndroidManifest file. I could solve it by correcting the

android:minSdkVersion="16"

to match with AVD.

How to use sed to replace only the first occurrence in a file?

You could use awk to do something similar..

awk '/#include/ && !done { print "#include \"newfile.h\""; done=1;}; 1;' file.c

Explanation:

/#include/ && !done

Runs the action statement between {} when the line matches "#include" and we haven't already processed it.

{print "#include \"newfile.h\""; done=1;}

This prints #include "newfile.h", we need to escape the quotes. Then we set the done variable to 1, so we don't add more includes.

1;

This means "print out the line" - an empty action defaults to print $0, which prints out the whole line. A one liner and easier to understand than sed IMO :-)

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

How to install PyQt5 on Windows?

One of the most (probably the most) easiest way to install site-packages like PyQt5 is installing one of the versions of Anaconda. You can just install many of site-packages by installing it. List of avaliable site-packages with Anaconda versions can be checked here.

  1. Dowload Anaconda3 or Anaconda2
  2. Install it.
  3. Add PyQt5's path inside Anaconda installation to your System Environment Variables.

For example:

PATH: ....; C:\Anaconda3\Lib\site-packages\PyQt5; ...
  1. It is ready to use.

How to set a Header field on POST a form?

If you are using JQuery with Form plugin, you can use:

$('#myForm').ajaxSubmit({
    headers: {
        "foo": "bar"
    }
});

Source: https://stackoverflow.com/a/31955515/9469069