Programs & Examples On #Deltawalker

Remove file extension from a file name string

if you want to use String operation then you can use the function lastIndexOf( ) which Searches for the last occurrence of a character or substring. Java has numerous string functions.

What is the default Precision and Scale for a Number in Oracle?

Oracle stores numbers in the following way: 1 byte for power, 1 byte for the first significand digit (that is one before the separator), the rest for the other digits.

By digits here Oracle means centesimal digits (i. e. base 100)

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 125, '9'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('7', 125, '7'))
  2  /

1 row inserted

SQL> INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))
  2  /

INSERT INTO t_numtest VALUES (LPAD('9', 126, '9'))

ORA-01426: numeric overflow

SQL> SELECT DUMP(num) FROM t_numtest;

DUMP(NUM)
--------------------------------------------------------------------------------
Typ=2 Len=2: 255,11
Typ=2 Len=21: 255,8,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,78,79

As we can see, the maximal number here is 7.(7) * 10^124, and he have 19 centesimal digits for precision, or 38 decimal digits.

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

It looks like the string contains an array with a single MyStok object in it. If you remove square brackets from both ends of the input, you should be able to deserialize the data as a single object:

MyStok myobj = JSON.Deserialize<MyStok>(sc.Substring(1, sc.Length-2));

You could also deserialize the array into a list of MyStok objects, and take the object at index zero.

var myobjList = JSON.Deserialize<List<MyStok>>(sc);
var myObj = myobjList[0];

How to resolve git error: "Updates were rejected because the tip of your current branch is behind"

I would do it this this way:

  1. Stage all unstaged changes.

    git add .
    
  2. Stash the changes.

    git stash save
    
  3. Sync with remote.

    git pull -r
    
  4. Reapply the local changes.

    git stash pop
    

    or

    git stash apply
    

Dictionary of dictionaries in Python?

dictionary's setdefault is a good way to update an existing dict entry if it's there, or create a new one if it's not all in one go:

Looping style:

# This is our sample data
data = [("Milter", "Miller", 4), ("Milter", "Miler", 4), ("Milter", "Malter", 2)]

# dictionary we want for the result
dictionary = {}

# loop that makes it work
for realName, falseName, position in data:
    dictionary.setdefault(realName, {})[falseName] = position

dictionary now equals:

{'Milter': {'Malter': 2, 'Miler': 4, 'Miller': 4}}

How do you find what version of libstdc++ library is installed on your linux machine?

What exactly do you want to know?

The shared library soname? That's part of the filename, libstdc++.so.6, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname.

The minor revision number? You should be able to get that by simply checking what the symlink points to:

$ ls -l  /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16

That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6 version, which corresponds to the GLIBCXX_3.4.16 symbol versions.

Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++ and libstdc++.so you can get that from:

$ g++ -dumpversion
4.6.3

Or, on most distros, you can just ask the package manager. On my Fedora host that's

$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686

As other answers have said, you can map releases to library versions by checking the ABI docs

Visual Studio Code how to resolve merge conflicts with git?

After trial and error I discovered that you need to stage the file that had the merge conflict, then you can commit the merge.

How can I simulate an array variable in MySQL?

Inspired by the function ELT(index number, string1, string2, string3,…),I think the following example works as an array example:

set @i := 1;
while @i <= 3
do
  insert into table(val) values (ELT(@i ,'val1','val2','val3'...));
set @i = @i + 1;
end while;

Hope it help.

AngularJS. How to call controller function from outside of controller component

I am an Ionic framework user and the one I found that would consistently provide the current controller's $scope is:

angular.element(document.querySelector('ion-view[nav-view="active"]')).scope()

I suspect this can be modified to fit most scenarios regardless of framework (or not) by finding the query that will target the specific DOM element(s) that are available only during a given controller instance.

How to remove a virtualenv created by "pipenv run"

I know that question is a bit old but

In root of project where Pipfile is located you could run

pipenv --venv

which returns

/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

and then remove this env by typing

rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU

How to overlay image with color in CSS?

Use mutple backgorund on the element, and use a linear-gradient as your color overlay by declaring both start and end color-stops as the same value.

Note that layers in a multi-background declaration are read much like they are rendered, top-to-bottom, so put your overlay first, then your bg image:

#header {
  background: 
    linear-gradient(to bottom, rgba(100, 100, 0, 0.5), rgba(100, 100, 0, 0.5)) cover,
    url(../img/bg.jpg) 0 0 no-repeat fixed;
  height: 100%;
  overflow: hidden;
  color: #FFFFFF
}

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

It also happen when you type wrong name of DB

ex : xxx-db-dev to xxx-dev-db

Sometime, it's just a stupid mistake . I take about more than 1 hours to find out this :( because i just try alot of difficult thing first

Is it possible to reference one CSS rule within another?

Just add the classes to your html

<div class="someDiv radius opacity"></div>

ActiveMQ or RabbitMQ or ZeroMQ or

Why did you miss Sparrow, Starling, Kestrel, Amazon SQS, Beanstalkd, Kafka, IronMQ ?

Message Queue Servers

Message queue servers are available in various languages, Erlang (RabbitMQ), C (beanstalkd), Ruby (Starling or Sparrow), Scala (Kestrel, Kafka) or Java (ActiveMQ). A short overview can be found here

Sparrow

  • written by Alex MacCaw
  • Sparrow is a lightweight queue written in Ruby that “speaks memcache”

Starling

Kestrel

  • written by Robey Pointer
  • Starling clone written in Scala (a port of Starling from Ruby to Scala)
  • Queues are stored in memory, but logged on disk

RabbitMQ

  • RabbitMQ is a Message Queue Server in Erlang
  • stores jobs in memory (message queue)

Apache ActiveMQ

  • ActiveMQ is an open source message broker in Java

Beanstalkd

Amazon SQS

Kafka

  • Written at LinkedIn in Scala
  • Used by LinkedIn to offload processing of all page and other views
  • Defaults to using persistence, uses OS disk cache for hot data (has higher throughput then any of the above having persistence enabled)
  • Supports both on-line as off-line processing

ZMQ

  • The socket library that acts as a concurrency framework
  • Faster than TCP, for clustered products and supercomputing
  • Carries messages across inproc, IPC, TCP, and multicast
  • Connect N-to-N via fanout, pubsub, pipeline, request-reply
  • Asynch I/O for scalable multicore message-passing apps

EagleMQ

  • EagleMQ is an open source, high-performance and lightweight queue manager.
  • Written in C
  • Stores all data in memory and support persistence.
  • It has its own protocol. Supports work with queues, routes and channels.

IronMQ

  • IronMQ
  • Written in Go
  • Fully managed queue service
  • Available both as cloud version and on-premise

I hope that this will be helpful for us. source

How to create Select List for Country and States/province in MVC

So many ways to do this... for #NetCore use Lib..

    using System;
    using System.Collections.Generic;
    using System.Linq; // only required when .AsEnumerable() is used
    using System.ComponentModel.DataAnnotations;
    using Microsoft.AspNetCore.Mvc.Rendering;

Model...

namespace MyProject.Models
{
  public class MyModel
  {
    [Required]
    [Display(Name = "State")]
    public string StatePick { get; set; }
    public string state { get; set; }
    [StringLength(35, ErrorMessage = "State cannot be longer than 35 characters.")]
    public SelectList StateList { get; set; }
  }
}

Controller...

namespace MyProject.Controllers
{
    /// <summary>
    /// create SelectListItem from strings
    /// </summary>
    /// <param name="isValue">defaultValue is SelectListItem.Value is true, SelectListItem.Text if false</param>
    /// <returns></returns>
    private SelectListItem newItem(string value, string text, string defaultValue = "", bool isValue = false)
    {
        SelectListItem ss = new SelectListItem();
        ss.Text = text;
        ss.Value = value;

        // select default by Value or Text
        if (isValue && ss.Value == defaultValue || !isValue && ss.Text == defaultValue)
        {
            ss.Selected = true;
        }

        return ss;
    }

    /// <summary>
    /// this pulls the state name from _context and sets it as the default for the selectList
    /// </summary>
    /// <param name="myState">sets default value for list of states</param>
    /// <returns></returns>
    private SelectList getStateList(string myState = "")
    {
        List<SelectListItem> states = new List<SelectListItem>();
        SelectListItem chosen = new SelectListItem();

        // set default selected state to OHIO
        string defaultValue = "OH";
        if (!string.IsNullOrEmpty(myState))
        {
            defaultValue = myState;
        }

        try
        {
            states.Add(newItem("AL", "Alabama", defaultValue, true));
            states.Add(newItem("AK", "Alaska", defaultValue, true));
            states.Add(newItem("AZ", "Arizona", defaultValue, true));
            states.Add(newItem("AR", "Arkansas", defaultValue, true));
            states.Add(newItem("CA", "California", defaultValue, true));
            states.Add(newItem("CO", "Colorado", defaultValue, true));
            states.Add(newItem("CT", "Connecticut", defaultValue, true));
            states.Add(newItem("DE", "Delaware", defaultValue, true));
            states.Add(newItem("DC", "District of Columbia", defaultValue, true));
            states.Add(newItem("FL", "Florida", defaultValue, true));
            states.Add(newItem("GA", "Georgia", defaultValue, true));
            states.Add(newItem("HI", "Hawaii", defaultValue, true));
            states.Add(newItem("ID", "Idaho", defaultValue, true));
            states.Add(newItem("IL", "Illinois", defaultValue, true));
            states.Add(newItem("IN", "Indiana", defaultValue, true));
            states.Add(newItem("IA", "Iowa", defaultValue, true));
            states.Add(newItem("KS", "Kansas", defaultValue, true));
            states.Add(newItem("KY", "Kentucky", defaultValue, true));
            states.Add(newItem("LA", "Louisiana", defaultValue, true));
            states.Add(newItem("ME", "Maine", defaultValue, true));
            states.Add(newItem("MD", "Maryland", defaultValue, true));
            states.Add(newItem("MA", "Massachusetts", defaultValue, true));
            states.Add(newItem("MI", "Michigan", defaultValue, true));
            states.Add(newItem("MN", "Minnesota", defaultValue, true));
            states.Add(newItem("MS", "Mississippi", defaultValue, true));
            states.Add(newItem("MO", "Missouri", defaultValue, true));
            states.Add(newItem("MT", "Montana", defaultValue, true));
            states.Add(newItem("NE", "Nebraska", defaultValue, true));
            states.Add(newItem("NV", "Nevada", defaultValue, true));
            states.Add(newItem("NH", "New Hampshire", defaultValue, true));
            states.Add(newItem("NJ", "New Jersey", defaultValue, true));
            states.Add(newItem("NM", "New Mexico", defaultValue, true));
            states.Add(newItem("NY", "New York", defaultValue, true));
            states.Add(newItem("NC", "North Carolina", defaultValue, true));
            states.Add(newItem("ND", "North Dakota", defaultValue, true));
            states.Add(newItem("OH", "Ohio", defaultValue, true));
            states.Add(newItem("OK", "Oklahoma", defaultValue, true));
            states.Add(newItem("OR", "Oregon", defaultValue, true));
            states.Add(newItem("PA", "Pennsylvania", defaultValue, true));
            states.Add(newItem("RI", "Rhode Island", defaultValue, true));
            states.Add(newItem("SC", "South Carolina", defaultValue, true));
            states.Add(newItem("SD", "South Dakota", defaultValue, true));
            states.Add(newItem("TN", "Tennessee", defaultValue, true));
            states.Add(newItem("TX", "Texas", defaultValue, true));
            states.Add(newItem("UT", "Utah", defaultValue, true));
            states.Add(newItem("VT", "Vermont", defaultValue, true));
            states.Add(newItem("VA", "Virginia", defaultValue, true));
            states.Add(newItem("WA", "Washington", defaultValue, true));
            states.Add(newItem("WV", "West Virginia", defaultValue, true));
            states.Add(newItem("WI", "Wisconsin", defaultValue, true));
            states.Add(newItem("WY", "Wyoming", defaultValue, true));

            foreach (SelectListItem state in states)
            {
                if (state.Selected)
                {
                    chosen = state;
                    break;
                }
            }
        }
        catch (Exception err)
        {
            string ss = "ERR!   " + err.Source + "   " + err.GetType().ToString() + "\r\n" + err.Message.Replace("\r\n", "   ");
            ss = this.sendError("Online getStateList Request", ss, _errPassword);
            // return error
        }

        // .AsEnumerable() is not required in the pass.. it is an extension of Linq
        SelectList myList = new SelectList(states.AsEnumerable(), "Value", "Text", chosen);

        object val = myList.SelectedValue;

        return myList;
    }

    public ActionResult pickState(MyModel pData)
    {
        if (pData.StateList == null)
        {
            if (String.IsNullOrEmpty(pData.StatePick)) // state abbrev, value collected onchange
            {
                pData.StateList = getStateList();
            }
            else
            {
                pData.StateList = getStateList(pData.StatePick);
            }

            // assign values to state list items
            try
            {
                SelectListItem si = (SelectListItem)pData.StateList.SelectedValue;
                pData.state = si.Value;
                pData.StatePick = si.Value;
            }
            catch { }
        } 
    return View(pData);
    }
}

pickState.cshtml...

@model MyProject.Models.MyModel

@{
ViewBag.Title = "United States of America";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>@ViewBag.Title - Where are you...</h2>

@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)

<fieldset>

    <div class="editor-label">
        @Html.DisplayNameFor(model => model.state)
    </div>
    <div class="display-field">            
        @Html.DropDownListFor(m => m.StatePick, Model.StateList, new { OnChange = "state.value = this.value;" })
        @Html.EditorFor(model => model.state)
        @Html.ValidationMessageFor(model => model.StateList)
    </div>         
</fieldset>
}

<div>
@Html.ActionLink("Back to List", "Index")
</div>

Setting Java heap space under Maven 2 on Windows

You are looking for 2 options to java:

  • -Xmx maximum heap size
  • -Xms starting heap size

Put them in your command line invocation of the java executable, like this:

java -Xms512M -Xmx1024M my.package.MainClass

Keep in mind that you may want the starting and max heap sizes to be the same, depending on the application, as it avoids resizing the heap during runtime (which can take up time in applications that need to be responsive). Resizing the heap can entail moving a lot of objects around and redoing bookkeeping.

For every-day projects, make them whatever you think is good enough. Profile for help.

Can a for loop increment/decrement by more than one?

Andrew Whitaker's answer is true, but you can use any expression for any part.
Just remember the second (middle) expression should evaluate so it can be compared to a boolean true or false.

When I use a for loop, I think of it as

for (var i = 0; i < 10; ++i) {
    /* expression */
}

as being

var i = 0;
while( i < 10 ) {
    /* expression */
    ++i;
}

How can I get a list of users from active directory?

Certainly the credit goes to @Harvey Kwok here, but I just wanted to add this example because in my case I wanted to get an actual List of UserPrincipals. It's probably more efficient to filter this query upfront, but in my small environment, it's just easier to pull everything and then filter as needed later from my list.

Depending on what you need, you may not need to cast to DirectoryEntry, but some properties are not available from UserPrincipal.

using (var searcher = new PrincipalSearcher(new UserPrincipal(new PrincipalContext(ContextType.Domain, Environment.UserDomainName))))
{
    List<UserPrincipal> users = searcher.FindAll().Select(u => (UserPrincipal)u).ToList();
    foreach(var u in users)
        {
            DirectoryEntry d = (DirectoryEntry)u.GetUnderlyingObject();
            Console.WriteLine(d.Properties["GivenName"]?.Value?.ToString() + d.Properties["sn"]?.Value?.ToString());
        }
}

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Adding a slide effect to bootstrap dropdown

For Bootstrap 3, this variation on the answers above makes the mobile slideUp() animation smoother; the answers above have choppy animation because Bootstrap removes the .open class from the toggle's parent immediately, so this code restores the class until the slideUp() animation is finished.

// Add animations to topnav dropdowns
// based on https://stackoverflow.com/a/19339162
// and https://stackoverflow.com/a/52231970

$('.dropdown')
  .on('show.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
  })
  .on('hide.bs.dropdown', function() {
    $(this).find('.dropdown-menu').first().stop(true, false).slideUp(300, function() {
      $(this).parent().removeClass('open');
    });
  })
  .on('hidden.bs.dropdown', function() {
    $(this).addClass('open');
  });

Key differences:

  • In the hide.bs.dropdown event handler I'm using .stop()'s default value (false) for its second argument (jumpToEnd)
  • The hidden.bs.dropdown event handler restores the .open class to the dropdown toggle's parent, and it does this pretty much immediately after the class has been first removed. Meanwhile the slideUp() animation is still running, and just like in the answers above, its "the-animation-is-completed" callback is responsible for finally removing the .open class from its parent.
  • Methods are chained together because the selector for each event handler is the same

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

Applying Comic Sans Ms font style

You need to use quote marks.

font-family: "Comic Sans MS", cursive, sans-serif;

Although you really really shouldn't use comic sans. The font has massive stigma attached to it's use; it's not seen as professional at all.

How to detect iPhone 5 (widescreen devices)?

In Swift, iOS 8+ project I like to make an extension on UIScreen, like:

extension UIScreen {

    var isPhone4: Bool {
        return self.nativeBounds.size.height == 960;
    }

    var isPhone5: Bool {
        return self.nativeBounds.size.height == 1136;
    }

    var isPhone6: Bool {
        return self.nativeBounds.size.height == 1334;
    }

    var isPhone6Plus: Bool {
        return self.nativeBounds.size.height == 2208;
    }

}

(NOTE: nativeBounds is in pixels).

And then the code will be like:

if UIScreen.mainScreen().isPhone4 {
    // do smth on the smallest screen
}

So the code makes it clear that this is a check for the main screen, not for the device model.

Why does Java have transient fields?

To allow you to define variables that you don't want to serialize.

In an object you may have information that you don't want to serialize/persist (perhaps a reference to a parent factory object), or perhaps it doesn't make sense to serialize. Marking these as 'transient' means the serialization mechanism will ignore these fields.

How to extend an existing JavaScript array with another array, without creating a new array

Use Array.extend instead of Array.push for > 150,000 records.

if (!Array.prototype.extend) {
  Array.prototype.extend = function(arr) {
    if (!Array.isArray(arr)) {
      return this;
    }

    for (let record of arr) {
      this.push(record);
    }

    return this;
  };
}

Difference between Relative path and absolute path in javascript

Completely relative:

<img src="kitten.png"/>

this is a relative path indeed.

Absolute in all respects:

<img src="http://www.foo.com/images/kitten.png"/>

this is a URL, and it can be seen in some way as an absolute path, but it's not representative for this matter.

The difference between relative and absolute paths is that when using relative paths you take as reference the current working directory while with absolute paths you refer to a certain, well known directory. Relative paths are useful when you make some program that has to use resources from certain folders that can be opened using the working directory as a starting point.

Example of relative paths:

  • image.png, which is the equivalent to .\image.png (in Windows) or ./image.png (anywhere else). The . explicitly specifies that you're expressing a path relative to the current working directory, but this is implied whenever the path doesn't begin at a root directory (designated with a slash), so you don't have to use it necessarily (except in certain contexts where a default directory (or a list of directories to search) will be applied unless you explicitly specify some directory).

  • ..\images\image2.jpg This way you can access resources from directories one step up the folders tree.  The ..\ means you've exited the current folder, entering the directory that contains both the working and images folders.  Again, use \ in Windows and / anywhere else.

Example of absolute paths:

  • D:\documents\something.doc
  • E:\music\good_music.mp3

and so on.

Oracle PL/SQL - Raise User-Defined Exception With Custom SQLERRM

You could use RAISE_APPLICATION_ERROR like this:

DECLARE
    ex_custom       EXCEPTION;
BEGIN
    RAISE ex_custom;
EXCEPTION
    WHEN ex_custom THEN
        RAISE_APPLICATION_ERROR(-20001,'My exception was raised');
END;
/

That will raise an exception that looks like:

ORA-20001: My exception was raised

The error number can be anything between -20001 and -20999.

Remote origin already exists on 'git push' to a new repository

I just faced this issue myself and I just removed it by removing the origin. the origin is removed by this command

git remove rm origin

try implementing this command.

Gradle: Could not determine java version from '11.0.2'

I was facing the same issue in Docker setup, while I was trying to install Gradle-2.4 with JDL 11.0.7. I have to install a later version to fix the issue.

Here is the Working Dockerfile

FROM openjdk:11.0.7-jdk
RUN apt-get update && apt-get install -y unzip
WORKDIR /gradle
RUN curl -L https://services.gradle.org/distributions/gradle-6.5.1-bin.zip -o gradle-6.5.1-bin.zip
RUN unzip gradle-6.5.1-bin.zip
ENV GRADLE_HOME=/gradle/gradle-6.5.1
ENV PATH=$PATH:$GRADLE_HOME/bin
RUN gradle --version

Integrating Dropzone.js into existing HTML form with other fields

Further to what sqram was saying, Dropzone has an additional undocumented option, "hiddenInputContainer". All you have to do is set this option to the selector of the form you want the hidden file field to be appended to. And voila! The ".dz-hidden-input" file field that Dropzone normally adds to the body magically moves into your form. No altering the Dropzone source code.

Now while this works to move the Dropzone file field into your form, the field has no name. So you will need to add:

_this.hiddenFileInput.setAttribute("name", "field_name[]");

to dropzone.js after this line:

_this.hiddenFileInput = document.createElement("input");

around line 547.

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

Although I am sure Saurabh's answer will work for most other people, I did want to identify the extra steps I had to take in order to get my apk installed.

I tried pushing to the device with the following result:

? adb push AppClient.TestOnly.App3.apk \tmp\
failed to copy 'AppClient.TestOnly.App3.apk' to '\tmp\': Read-only file system

After looking around to change the filesystem RW permissions I ended up executing the following commands:

? adb shell
255|shell@android:/ $ su
shell@android:/ # mount -o remount,rw /
mount -o remount,rw /

I got this when I tried to push again:

? adb push AppClient.TestOnly.App3.apk /tmp
failed to copy 'AppClient.TestOnly.App3.apk' to '/tmp': Permission denied

I was able to push to the sdcard:

? adb push AppClient.TestOnly.App3.apk /sdcard/
3178 KB/s (99747 bytes in 0.030s)

At which point I was able to execute Saurabh's command:

shell@android:/ # pm install -t /sdcard/AppClient.TestOnly.App3.apk
pm install -t /sdcard/AppClient.TestOnly.App3.apk
        pkg: /sdcard/AppClient.TestOnly.App3.apk
Success

How to count the number of files in a directory using Python

An answer with pathlib and without loading the whole list to memory:

from pathlib import Path

path = Path('.')

print(sum(1 for _ in path.glob('*')))  # Files and folders, not recursive
print(sum(1 for _ in path.glob('**/*')))  # Files and folders, recursive

print(sum(1 for x in path.glob('*') if x.is_file()))  # Only files, not recursive
print(sum(1 for x in path.glob('**/*') if x.is_file()))  # Only files, recursive

How can I create a memory leak in Java?

Lapsed Listerners is a good example of memory leaks: Object is added as a Listener. All references to the object are nulled when the object is not needed anymore. However, forgetting to remove the object from the Listener list keeps the object alive and even responding to events, thereby wasting both memory and CPU. See http://www.drdobbs.com/jvm/java-qa/184404011

How to find sitemap.xml path on websites?

There is no standard, so there is no guarantee. With that said, its common for the sitemap to be self labeled and on the root, like this:

example.com/sitemap.xml

Case is sensitive on some servers, so keep that in mind. If its not there, look in the robots file on the root:

example.com/robots.txt

If you don't see it listed in the robots file head to Google and search this:

site:example.com filetype:xml

This will limit the results to XML files on your target domain. At this point its trial-and-error and based on the specifics of the website you are working with. If you get several pages of results from the Google search phrase above then try to limit the results further:

filetype:xml site:example.com inurl:sitemap

or

filetype:xml site:example.com inurl:products

If you still can't find it you can right-click > "View Source" and do a search (aka: "control find" or Ctrl + F) for .xml to see if there is a reference to it in the code.

Create a file if it doesn't exist

Be warned, each time the file is opened with this method the old data in the file is destroyed regardless of 'w+' or just 'w'.

import os

with open("file.txt", 'w+') as f:
    f.write("file is opened for business")

How to split one string into multiple variables in bash shell?

If you know it's going to be just two fields, you can skip the extra subprocesses like this:

var1=${STR%-*}
var2=${STR#*-}

What does this do? ${STR%-*} deletes the shortest substring of $STR that matches the pattern -* starting from the end of the string. ${STR#*-} does the same, but with the *- pattern and starting from the beginning of the string. They each have counterparts %% and ## which find the longest anchored pattern match. If anyone has a helpful mnemonic to remember which does which, let me know! I always have to try both to remember.

Get generic type of java.util.List

Expanding on Steve K's answer:

/** 
* Performs a forced cast.  
* Returns null if the collection type does not match the items in the list.
* @param data The list to cast.
* @param listType The type of list to cast to.
*/
static <T> List<? super T> castListSafe(List<?> data, Class<T> listType){
    List<T> retval = null;
    //This test could be skipped if you trust the callers, but it wouldn't be safe then.
    if(data!=null && !data.isEmpty() && listType.isInstance(data.iterator().next().getClass())) {
        @SuppressWarnings("unchecked")//It's OK, we know List<T> contains the expected type.
        List<T> foo = (List<T>)data;
        return retval;
    }
    return retval;
}
Usage:

protected WhateverClass add(List<?> data) {//For fluant useage
    if(data==null) || data.isEmpty(){
       throw new IllegalArgumentException("add() " + data==null?"null":"empty" 
       + " collection");
    }
    Class<?> colType = data.iterator().next().getClass();//Something
    aMethod(castListSafe(data, colType));
}

aMethod(List<Foo> foo){
   for(Foo foo: List){
      System.out.println(Foo);
   }
}

aMethod(List<Bar> bar){
   for(Bar bar: List){
      System.out.println(Bar);
   }
}

How do I select an element that has a certain class?

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors

If '<selector>' is an Angular component, then verify that it is part of this module

Had the same issue, found that the template component tags worked with <app-[component-name]></app-[component-name]>. So, if your component is called mycomponent.component.ts:

@Component({
  selector: 'my-app',
  template: `
    <h1>Hello {{name}}</h1>
    <h4>Something</h4>
    <app-mycomponent></app-mycomponent>
  `,

LINQ Joining in C# with multiple conditions

As far as I know you can only join this way:

var query = from obj_i in set1
join obj_j in set2 on 
    new { 
      JoinProperty1 = obj_i.SomeField1,
      JoinProperty2 = obj_i.SomeField2,
      JoinProperty3 = obj_i.SomeField3,
      JoinProperty4 = obj_i.SomeField4
    } 
    equals 
    new { 
      JoinProperty1 = obj_j.SomeOtherField1,
      JoinProperty2 = obj_j.SomeOtherField2,
      JoinProperty3 = obj_j.SomeOtherField3,
      JoinProperty4 = obj_j.SomeOtherField4
    }

The main requirements are: Property names, types and order in the anonymous objects you're joining on must match.

You CAN'T use ANDs, ORs, etc. in joins. Just object1 equals object2.

More advanced stuff in this LinqPad example:

class c1 
    {
    public int someIntField;
    public string someStringField;
    }
    
class c2 
    {
    public Int64 someInt64Property {get;set;}
    private object someField;
    public string someStringFunction(){return someField.ToString();}
    }
    
void Main()
{
    var set1 = new List<c1>();
    var set2 = new List<c2>();
    
    var query = from obj_i in set1
    join obj_j in set2 on 
        new { 
                JoinProperty1 = (Int64) obj_i.someIntField,
                JoinProperty2 = obj_i.someStringField
            } 
        equals 
        new { 
                JoinProperty1 = obj_j.someInt64Property,
                JoinProperty2 = obj_j.someStringFunction()
            }
    select new {obj1 = obj_i, obj2 = obj_j};
}

Addressing names and property order is straightforward, addressing types can be achieved via casting/converting/parsing/calling methods etc. This might not always work with LINQ to EF or SQL or NHibernate, most method calls definitely won't work and will fail at run-time, so YMMV (Your Mileage May Vary). This is because they are copied to public read-only properties in the anonymous objects, so as long as your expression produces values of correct type the join property - you should be fine.

AngularJS dynamic routing

Here is another solution that works good.

(function() {
    'use strict';

    angular.module('cms').config(route);
    route.$inject = ['$routeProvider'];

    function route($routeProvider) {

        $routeProvider
            .when('/:section', {
                templateUrl: buildPath
            })
            .when('/:section/:page', {
                templateUrl: buildPath
            })
            .when('/:section/:page/:task', {
                templateUrl: buildPath
            });



    }

    function buildPath(path) {

        var layout = 'layout';

        angular.forEach(path, function(value) {

            value = value.charAt(0).toUpperCase() + value.substring(1);
            layout += value;

        });

        layout += '.tpl';

        return 'client/app/layouts/' + layout;

    }

})();

What does this expression language ${pageContext.request.contextPath} exactly do in JSP EL?

Include <%@ page isELIgnored="false"%> on top of your jsp page.

If list index exists, do X

I need to code such that if a certain list index exists, then run a function.

You already know how to test for this and in fact are already performing such tests in your code.

The valid indices for a list of length n are 0 through n-1 inclusive.

Thus, a list has an index i if and only if the length of the list is at least i + 1.

Search code inside a Github project

I search the source code inside of Github Repositories with the free Sourcegraph Chrome Extension ... But I Downloaded Chrome First, I knew other browsers support it though, such as - and maybe just only - Firefox.

I skimmed through SourceForge's Chrome Extension Docs and then also I looked at just what I needed for searching for directory names with Github's Search Engine itself, by reading some of Github's Codebase Searching Doc

How to find the largest file in a directory and its subdirectories?

That is quite simpler way to do it:

ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***

And you'll get this: 8445 examples.desktop

How to get multiline input from user

raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:

Python 3

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

Python 2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)

Laravel Eloquent Sum of relation's column

this is not your answer but is for those come here searching solution for another problem. I wanted to get sum of a column of related table conditionally. In my database Deals has many Activities I wanted to get the sum of the "amount_total" from Activities table where activities.deal_id = deal.id and activities.status = paid so i did this.

$query->withCount([
'activity AS paid_sum' => function ($query) {
            $query->select(DB::raw("SUM(amount_total) as paidsum"))->where('status', 'paid');
        }
    ]);

it returns

"paid_sum_count" => "320.00"

in Deals attribute.

This it now the sum which i wanted to get not the count.

No internet on Android emulator - why and how to fix?

Allow the ADB to access the network by opening it on the firewall

If you are using winvista and above, go to Windows Advance Firewall under Administrative tool in Control Panel and enable it from there

how to insert datetime into the SQL Database table?

You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

INSERT INTO MyTable (MyDate) Values (GetDate())

If it is not today's date then you should be able to use a string and specify the date format:

INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

You do not always need to convert the string either, often you can just do something like:

INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

How do I fix an "Invalid license data. Reinstall is required." error in Visual C# 2010 Express?

If you're here from Google and are experiencing this issue with GFI MailEssentials's config export tool, check to make sure you aren't trying to open WebMon.SettingsImporterTool.exe.xml instead of WebMon.SettingsImporterTool.exe

If you have "hide common file extensions" enabled, you will see the .exe but not the .xml

Google reCAPTCHA: How to get user response and validate in the server side?

Hi curious you can validate your google recaptcha at client side also 100% work for me to verify your google recaptcha just see below code
This code at the html body:

 <div class="g-recaptcha" id="rcaptcha" style="margin-left: 90px;" data-sitekey="my_key"></div>
 <span id="captcha" style="margin-left:100px;color:red" />

This code put at head section on call get_action(this) method form button:

function get_action(form) {

var v = grecaptcha.getResponse();
if(v.length == 0)
{
    document.getElementById('captcha').innerHTML="You can't leave Captcha Code empty";
    return false;
}
 if(v.length != 0)
 {
    document.getElementById('captcha').innerHTML="Captcha completed";
    return true; 
 }
}

How to move table from one tablespace to another in oracle 11g

I tried many scripts but they didn't work for all objects. You can't move clustered objects from one tablespace to another. For that you will have to use expdp, so I will suggest expdp is the best option to move all objects to a different tablespace.

Below is the command:

nohup expdp \"/ as sysdba\" DIRECTORY=test_dir DUMPFILE=users.dmp LOGFILE=users.log TABLESPACES=USERS &

You can check this link for details.

How do you push a Git tag to a branch using a refspec?

For pushing a single tag: git push <reponame> <tagname>

For instance, git push production 1.0.0. Tags are not bound to branches, they are bound to commits.

When you want to have the tag's content in the master branch, do that locally on your machine. I would assume that you continued developing in your local master branch. Then just a git push origin master should suffice.

How to declare a type as nullable in TypeScript?

You can just implement a user-defined type like the following:

type Nullable<T> = T | undefined | null;

var foo: Nullable<number> = 10; // ok
var bar: Nullable<number> = true; // type 'true' is not assignable to type 'Nullable<number>'
var baz: Nullable<number> = null; // ok

var arr1: Nullable<Array<number>> = [1,2]; // ok
var obj: Nullable<Object> = {}; // ok

 // Type 'number[]' is not assignable to type 'string[]'. 
 // Type 'number' is not assignable to type 'string'
var arr2: Nullable<Array<string>> = [1,2];

How can I convert uppercase letters to lowercase in Notepad++

Just select the text you want to change, right click and select UPPERCASE or lowercase depending on what you want.

How to deep watch an array in angularjs?

In my case, I needed to watch a service, which contains an address object also watched by several other controllers. I was stuck in a loop until I added the 'true' parameter, which seems to be the key to success when watching objects.

$scope.$watch(function() {
    return LocationService.getAddress();
}, function(address) {
    //handle address object
}, true);

Virtual member call in a constructor

Yes, it's generally bad to call virtual method in the constructor.

At this point, the objet may not be fully constructed yet, and the invariants expected by methods may not hold yet.

In Typescript, How to check if a string is Numeric

The way to convert a string to a number is with Number, not parseFloat.

Number('1234') // 1234
Number('9BX9') // NaN

You can also use the unary plus operator if you like shorthand:

+'1234' // 1234
+'9BX9' // NaN

Be careful when checking against NaN (the operator === and !== don't work as expected with NaN). Use:

 isNaN(+maybeNumber) // returns true if NaN, otherwise false

How do I spool to a CSV formatted file using SQLPLUS?

You can explicitly format the query to produce a delimited string with something along the lines of:

select '"'||foo||'","'||bar||'"'
  from tab

And set up the output options as appropriate. As an option, the COLSEP variable on SQLPlus will let you produce delimited files without having to explicitly generate a string with the fields concatenated together. However, you will have to put quotes around strings on any columns that might contain embedded comma characters.

Increment variable value by 1 ( shell programming)

The way to use expr:

i=0
i=`expr $i + 1`

the way to use i++

((i++)); echo $i;

Tested in gnu bash

CSS - display: none; not working

Another trick is to use

.class {
position: absolute;
visibility:hidden;
display:none;
}

This is not likely to mess up your flow (because it takes it out of flow) and makes sure that the user can't see it, and then if display:none works later on it will be working. Keep in mind that visibility:hidden may not remove it from screen readers.

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

How can I import Swift code to Objective-C?

Checkout the pre-release notes about Swift and Objective C in the same project

https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/BuildingCocoaApps/MixandMatch.html#//apple_ref/doc/uid/TP40014216-CH10-XID_75

You should be importing

#import "SCLAlertView-Swift.h"

List all files from a directory recursively with Java

it feels like it's stupid access the filesystem and get the contents for every subdirectory instead of getting everything at once.

Your feeling is wrong. That's how filesystems work. There is no faster way (except when you have to do this repeatedly or for different patterns, you can cache all the file paths in memory, but then you have to deal with cache invalidation i.e. what happens when files are added/removed/renamed while the app runs).

Android java.exe finished with non-zero exit value 1

I got this error after transferring my project from my laptop to my desktop in Android Studio.

My solution was to restart Android Studio, then clean the project and finally execute the project.

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date +%s

This works fine for me on OS X Lion.

Is there any 'out-of-the-box' 2D/3D plotting library for C++?

MathGL have many plot types, C/Fortran interface and basic data analysis

How to generate a random string in Ruby

This solution generates a string of easily readable characters for activation codes; I didn't want people confusing 8 with B, 1 with I, 0 with O, L with 1, etc.

# Generates a random string from a set of easily readable characters
def generate_activation_code(size = 6)
  charset = %w{ 2 3 4 6 7 9 A C D E F G H J K M N P Q R T V W X Y Z}
  (0...size).map{ charset.to_a[rand(charset.size)] }.join
end

How can I convert String[] to ArrayList<String>

List<String> list = Arrays.asList(array);

The list returned will be backed by the array, it acts like a bridge, so it will be fixed-size.

PowerMockito mock single static method and return object

What you want to do is a combination of part of 1 and all of 2.

You need to use the PowerMockito.mockStatic to enable static mocking for all static methods of a class. This means make it possible to stub them using the when-thenReturn syntax.

But the 2-argument overload of mockStatic you are using supplies a default strategy for what Mockito/PowerMock should do when you call a method you haven't explicitly stubbed on the mock instance.

From the javadoc:

Creates class mock with a specified strategy for its answers to interactions. It's quite advanced feature and typically you don't need it to write decent tests. However it can be helpful when working with legacy systems. It is the default answer so it will be used only when you don't stub the method call.

The default default stubbing strategy is to just return null, 0 or false for object, number and boolean valued methods. By using the 2-arg overload, you're saying "No, no, no, by default use this Answer subclass' answer method to get a default value. It returns a Long, so if you have static methods which return something incompatible with Long, there is a problem.

Instead, use the 1-arg version of mockStatic to enable stubbing of static methods, then use when-thenReturn to specify what to do for a particular method. For example:

import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

class ClassWithStatics {
  public static String getString() {
    return "String";
  }

  public static int getInt() {
    return 1;
  }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassWithStatics.class)
public class StubJustOneStatic {
  @Test
  public void test() {
    PowerMockito.mockStatic(ClassWithStatics.class);

    when(ClassWithStatics.getString()).thenReturn("Hello!");

    System.out.println("String: " + ClassWithStatics.getString());
    System.out.println("Int: " + ClassWithStatics.getInt());
  }
}

The String-valued static method is stubbed to return "Hello!", while the int-valued static method uses the default stubbing, returning 0.

calling a java servlet from javascript

I really recommend you use jquery for the javascript calls and some implementation of JSR311 like jersey for the service layer, which would delegate to your controllers.

This will help you with all the underlying logic of handling the HTTP calls and your data serialization, which is a big help.

How to dynamically add a style for text-align using jQuery

function add_question(){ var count=document.getElementById("nofquest").value; var container = document.getElementById("container"); // Clear previous contents of the container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } for (i=1;i

how to set center of the textboxes

Leap year calculation

In the Gregorian calendar 3 criteria must be taken into account to identify leap years:

  1. The year is evenly divisible by 4;
  2. If the year can be evenly divided by 100, it is NOT a leap year, unless;
  3. The year is also evenly divisible by 400. Then it is a leap year. Why the year divided by 100 is not leap year

How to check if one of the following items is in a list?

Best I could come up with:

any([True for e in (1, 2) if e in a])

Check if item is in an array / list

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.

Write to CSV file and export it?

How to write to a file (easy search in Google) ... 1st Search Result

As far as creation of the file each time a user accesses the page ... each access will act on it's own behalf. You business case will dictate the behavior.

Case 1 - same file but does not change (this type of case can have multiple ways of being defined)

  • You would have logic that created the file when needed and only access the file if generation is not needed.

Case 2 - each user needs to generate their own file

  • You would decide how you identify each user, create a file for each user and access the file they are supposed to see ... this can easily merge with Case 1. Then you delete the file after serving the content or not if it requires persistence.

Case 3 - same file but generation required for each access

  • Use Case 2, this will cause a generation each time but clean up once accessed.

How to get jQuery dropdown value onchange event

Add try this code .. Its working grt.......

_x000D_
_x000D_
<body>_x000D_
<?php_x000D_
 if (isset($_POST['nav'])) {_x000D_
   header("Location: $_POST[nav]");_x000D_
 }_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
    <select name="nav">_x000D_
        <option value="">Go to page...</option>_x000D_
        <option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
        <option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
        <option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
    </select>_x000D_
    <input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
    $("#submit").hide();_x000D_
_x000D_
    $("#page-changer select").change(function() {_x000D_
        window.location = $("#page-changer select option:selected").val();_x000D_
    })_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
_x000D_
_x000D_

MySQL TEXT vs BLOB vs CLOB

TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).

As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.

BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.

How to set an environment variable from a Gradle build?

This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)                
    }    
}

How to Read and Write from the Serial Port

Note that usage of a SerialPort.DataReceived event is optional. You can set proper timeout using SerialPort.ReadTimeout and continuously call SerialPort.Read() after you wrote something to a port until you get a full response.

Moreover you can use SerialPort.BaseStream property to extract an underlying Stream instance. The benefit of using a Stream is that you can easily utilize various decorators with it:

var port = new SerialPort();
// LoggingStream inherits Stream, implements IDisposable, needen abstract methods and 
// overrides needen virtual methods. 
Stream portStream = new LoggingStream(port.BaseStream);
portStream.Write(...); // Logs write buffer.
portStream.Read(...); // Logs read buffer.

For more information check:

App crashing when trying to use RecyclerView on android 5.0

I had this problem when using Butterknife library. I had:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(rootView);

But the correct version is:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(this, rootView);

Python division

Either way, it's integer division. 10/90 = 0. In the second case, you're merely casting 0 to a float.

Try casting one of the operands of "/" to be a float:

float(20-10) / (100-10)

Bootstrap 4 responsive tables won't take up 100% width

It seems as though the "sr-only" element and its styles inside of the table are what's causing this bug. At least I had the same issue and after months of banging our head against the wall that's what we determined the cause was, though I still don't understand why. Adding left:0 to the "sr-only" styles fixed it.

Check if an HTML input element is empty or has no value entered by user

You want:

if (document.getElementById('customx').value === ""){
    //do something
}

The value property will give you a string value and you need to compare that against an empty string.

Operation must use an updatable query. (Error 3073) Microsoft Access

I had the same issue.

My solution is to first create a table from the non updatable query and then do the update from table to table and it works.

jQuery: How can I show an image popup onclick of the thumbnail?

prettyPhoto is a jQuery lightbox clone. Not only does it support images, it also support for videos, flash, YouTube, iframes and ajax. It’s a full blown media lightbox

Converting stream of int's to char's in java

It depends on what you mean by "convert an int to char".

If you simply want to cast the value in the int, you can cast it using Java's typecast notation:

int i = 97; // 97 is 'a' in ASCII
char c = (char) i; // c is now 'a'

If you mean transforming the integer 1 into the character '1', you can do it like this:

if (i >= 0 && i <= 9) {
char c = Character.forDigit(i, 10);
....
}

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How to convert a .eps file to a high quality 1024x1024 .jpg?

For vector graphics, ImageMagick has both a render resolution and an output size that are independent of each other.

Try something like

convert -density 300 image.eps -resize 1024x1024 image.jpg

Which will render your eps at 300dpi. If 300 * width > 1024, then it will be sharp. If you render it too high though, you waste a lot of memory drawing a really high-res graphic only to down sample it again. I don't currently know of a good way to render it at the "right" resolution in one IM command.

The order of the arguments matters! The -density X argument needs to go before image.eps because you want to affect the resolution that the input file is rendered at.

This is not super obvious in the manpage for convert, but is hinted at:

SYNOPSIS

convert [input-option] input-file [output-option] output-file

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

Finally I got work around to the above problem. angular-strap has exactly the same feature that I am expecting. Just by applying date-format="MM/dd/yyyy" date-type="string" I got my expected behavior of updating ng-model in given format.

<div class="bs-example" style="padding-bottom: 24px;" append-source>
    <form name="datepickerForm" class="form-inline" role="form">
      <!-- Basic example -->
      <div class="form-group" ng-class="{'has-error': datepickerForm.date.$invalid}">
        <label class="control-label"><i class="fa fa-calendar"></i> Date <small>(as date)</small></label>
        <input type="text"  autoclose="true"  class="form-control" ng-model="selectedDate" name="date" date-format="MM/dd/yyyy" date-type="string" bs-datepicker>
      </div>
      <hr>
      {{selectedDate}}
     </form>
</div>

here is working plunk link

Reasons for a 409/Conflict HTTP error when uploading a file to sharepoint using a .NET WebRequest?

I is because you are using predefined variables to naming your filename. change your filename from e.g register.asp to registerUser.asp. That will solve your issue

jQuery dialog popup

You can use the following script. It worked for me

The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.

 $(function () {
        modalPosition();
        $(window).resize(function () {
            modalPosition();
        });
        $('.openModal').click(function (e) {
            $('.modal, .modal-backdrop').fadeIn('fast');
            e.preventDefault();
        });
        $('.close-modal').click(function (e) {
            $('.modal, .modal-backdrop').fadeOut('fast');
        });
    });
    function modalPosition() {
        var width = $('.modal').width();
        var pageWidth = $(window).width();
        var x = (pageWidth / 2) - (width / 2);
        $('.modal').css({ left: x + "px" });
    }

Refer:- Modal popup using jquery in asp.net

Running an Excel macro via Python?

Just a quick note with a xlsm with spaces.

file = 'file with spaces.xlsm'
excel_macro.Application.Run('\'' + file + '\'' + "!Module1.Macro1")

ConcurrentModificationException for ArrayList

While iterating through the loop, you are trying to change the List value in the remove() operation. This will result in ConcurrentModificationException.

Follow the below code, which will achieve what you want and yet will not throw any exceptions

private String toString(List aDrugStrengthList) {
        StringBuilder str = new StringBuilder();
    List removalList = new ArrayList();
    for (DrugStrength aDrugStrength : aDrugStrengthList) {
        if (!aDrugStrength.isValidDrugDescription()) {
            removalList.add(aDrugStrength);
        }
    }
    aDrugStrengthList.removeAll(removalList);
    str.append(aDrugStrengthList);
    if (str.indexOf("]") != -1) {
        str.insert(str.lastIndexOf("]"), "\n          " );
    }
    return str.toString();
}

exit application when click button - iOS

exit(X), where X is a number (according to the doc) should work. But it is not recommended by Apple and won't be accepted by the AppStore. Why? Because of these guidelines (one of my app got rejected):

We found that your app includes a UI control for quitting the app. This is not in compliance with the iOS Human Interface Guidelines, as required by the App Store Review Guidelines.

Please refer to the attached screenshot/s for reference.

The iOS Human Interface Guidelines specify,

"Always Be Prepared to Stop iOS applications stop when people press the Home button to open a different application or use a device feature, such as the phone. In particular, people don’t tap an application close button or select Quit from a menu. To provide a good stopping experience, an iOS application should:

Save user data as soon as possible and as often as reasonable because an exit or terminate notification can arrive at any time.

Save the current state when stopping, at the finest level of detail possible so that people don’t lose their context when they start the application again. For example, if your app displays scrolling data, save the current scroll position."

> It would be appropriate to remove any mechanisms for quitting your app.

Plus, if you try to hide that function, it would be understood by the user as a crash.

How to get the pure text without HTML element using JavaScript?

function get_content(){
 var returnInnerHTML = document.getElementById('A').innerHTML + document.getElementById('B').innerHTML + document.getElementById('A').innerHTML;
 document.getElementById('txt').innerHTML = returnInnerHTML;
}

That should do it.

Is it possible to use the SELECT INTO clause with UNION [ALL]?

Try something like this: Create the final object table, tmpFerdeen with the structure of the union.

Then

INSERT INTO tmpFerdeen (
SELECT top(100)* 
FROM Customers
UNION All
SELECT top(100)* 
FROM CustomerEurope
UNION All
SELECT top(100)* 
FROM CustomerAsia
UNION All
SELECT top(100)* 
FROM CustomerAmericas
)

How to write data with FileOutputStream without losing old data?

Use the constructor that takes a File and a boolean

FileOutputStream(File file, boolean append) 

and set the boolean to true. That way, the data you write will be appended to the end of the file, rather than overwriting what was already there.

SSL cert "err_cert_authority_invalid" on mobile chrome only

I had the same probleme but the response made by Mike A helped me to figure it out: I had a my certificate, an intermediate certificate (Gandi) , an other intermediate (UserTrustRSA) and finally the RootCA certificate (AddTrust).

So first i made a chain file with Gandi+UserTrustRSA+AddTrust and specified it with SSLCertificateChainFile. But it didn't worked.

So i tried MikeA answer by just putting AddTruct cert in a file and specified it with SSLCACertificateFile and removing SSLCertificateChainFile.But it didn't worked.

So finnaly i made a chain file with only Gandi+UserTrustRSA specified by SSLCertificateChainFile and the other file with only the RootCA specified by SSLCACertificateFile and it worked.

#   Server Certificate:
SSLCertificateFile /etc/ssl/apache/myserver.cer

#   Server Private Key:
SSLCertificateKeyFile /etc/ssl/apache/myserver.key

#   Server Certificate Chain:
SSLCertificateChainFile /etc/ssl/apache/Gandi+UserTrustRSA.pem

#   Certificate Authority (CA):
SSLCACertificateFile /etc/ssl/apache/AddTrust.pem

Seems logical when you read but hope it helps.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

How can I create an array/list of dictionaries in python?

This is how I did it and it works:

dictlist = [dict() for x in range(n)]

It gives you a list of n empty dictionaries.

How to test enum types?

If you use all of the months in your code, your IDE won't let you compile, so I think you don't need unit testing.

But if you are using them with reflection, even if you delete one month, it will compile, so it's valid to put a unit test.

What is the difference between MacVim and regular Vim?

MacVim is just Vim. Anything you are used to do in Vim will work exactly the same way in MacVim.

MacVim is more integrated in the whole OS than Vim in the Terminal or even GVim in Linux, it follows a lot of Mac OS X's conventions.

If you work mainly with GUI apps (YummyFTP + GitX + Charles, for example) you may prefer MacVim.

If you work mainly with CLI apps (ssh + svn + tcpdump, for example) you may prefer vim in the terminal.

Entering and leaving one realm (CLI) for the other (GUI) and vice-versa can be "expensive".

I use both MacVim and Vim depending on the task and the context: if I'm in CLI-land I'll just type vim filename and if I'm in GUI-land I'll just invoke Quicksilver and launch MacVim.

When I switched from TextMate I kind of liked the fact that MacVim supported almost all of the regular shortcuts Mac users are accustomed to. I added some of my own, mimiking TextMate but, since I was working in multiple environments I forced my self to learn the vim way. Now I use both MacVim and Vim almost exactly the same way. Using one or the other is just a question of context for me.

Also, like El Isra said, the default vim (CLI) in OS X is slightly outdated. You may install an up-to-date version via MacPorts or you can install MacVim and add an alias to your .profile:

alias vim='/path/to/MacVim.app/Contents/MacOS/Vim'

to have the same vim in MacVim and Terminal.app.

Another difference is that many great colorschemes out there work out of the box in MacVim but look terrible in the Terminal.app which only supports 8 colors (+ highlights) but you can use iTerm — which can be set up to support 256 colors — instead of Terminal.

So… basically my advice is to just use both.

EDIT: I didn't try it but the latest version of Terminal.app (in 10.7) is supposed to support 256 colors. I'm still on 10.6.x at work so I'll still use iTerm2 for a while.

EDIT: An even better way to use MacVim's CLI executable in your shell is to move the mvim script bundled with MacVim somewhere in your $PATH and use this command:

$ mvim -v

EDIT: Yes, Terminal.app now supports 256 colors. So if you don't need iTerm2's advanced features you can safely use the default terminal emulator.

How do I add space between two variables after a print in Python

This is a stupid/hacky way

print count,    
print conv

Format an Integer using Java String Format

Use %03d in the format specifier for the integer. The 0 means that the number will be zero-filled if it is less than three (in this case) digits.

See the Formatter docs for other modifiers.

How to make a function wait until a callback has been called using node.js

Using async and await it is lot more easy.

router.post('/login',async (req, res, next) => {
i = await queries.checkUser(req.body);
console.log('i: '+JSON.stringify(i));
});

//User Available Check
async function checkUser(request) {
try {
    let response = await sql.query('select * from login where email = ?', 
    [request.email]);
    return response[0];

    } catch (err) {
    console.log(err);

  }

}

How to close IPython Notebook properly?

Option 1

Open a different console and run

jupyter notebook stop [PORT]

The default [PORT] is 8888, so, assuming that Jupyter Notebooks is running on port 8888, just run

jupyter notebook stop

If it is on port 9000, then

jupyter notebook stop 9000

Option 2 (Source)

  1. Check runtime folder location

    jupyter --paths
    
  2. Remove all files in the runtime folder

    rm -r [RUNTIME FOLDER PATH]/*
    
  3. Use top to find any Jupyter Notebook running processes left and if so kill their PID.

    top | grep jupyter &
    kill [PID]
    

One can boilt it down to

TARGET_PORT=8888
kill -9 $(lsof -n -i4TCP:$TARGET_PORT | cut -f 2 -d " ")

Note: If one wants to launch one's Notebook on a specific IP/Port

jupyter notebook --ip=[ADD_IP] --port=[ADD_PORT] --allow-root &

Border around specific rows in a table?

If you set the border-collapse style to collapse on the parent table you should be able to style the tr: (styles are inline for demo)

<table style="border-collapse: collapse;">
  <tr>
    <td>No Border</td>
  </tr>
  <tr style="border:2px solid #f00;">
    <td>Border</td>
  </tr>
  <tr>
    <td>No Border</td>
  </tr>
</table>

Output:

HTML output

How to install trusted CA certificate on Android device?

If you have a rooted device, you can use a Magisk Module to move User Certs to System so it will be Trusted Certificate

https://github.com/yochananmarqos/Move-Certificates

preg_match(); - Unknown modifier '+'

You need to use delimiters with regexes in PHP. You can use the often used /, but PHP lets you use any matching characters, so @ and # are popular.

Further Reading.

If you are interpolating variables inside your regex, be sure to pass the delimiter you chose as the second argument to preg_quote().

LINQ Inner-Join vs Left-Join

I the following error message when faced this same problem:

The type of one of the expressions in the join clause is incorrect. Type inference failed in the call to 'GroupJoin'.

Solved when I used the same property name, it worked.

(...)

join enderecoST in db.PessoaEnderecos on 
    new 
      {  
         CD_PESSOA          = nf.CD_PESSOA_ST, 
         CD_ENDERECO_PESSOA = nf.CD_ENDERECO_PESSOA_ST 
      } equals 
    new 
    { 
         enderecoST.CD_PESSOA, 
         enderecoST.CD_ENDERECO_PESSOA 
    } into eST

(...)

How to add bootstrap in angular 6 project?

npm install --save bootstrap

afterwards, inside angular.json (previously .angular-cli.json) inside the project's root folder, find styles and add the bootstrap css file like this:

for angular 6

"styles": [
          "../node_modules/bootstrap/dist/css/bootstrap.min.css",
          "styles.css"
],

for angular 7

"styles": [
          "node_modules/bootstrap/dist/css/bootstrap.min.css",
          "src/styles.css"
],

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

How to get Git to clone into current directory

Do

git clone https://[email protected]/user/projectname.git .

Directory must be empty

Refresh DataGridView when updating data source

Try this Code

List itemStates = new List();

for (int i = 0; i < 10; i++)
{ 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = itemStates;
    dataGridView1.DataBind();
    System.Threading.Thread.Sleep(500);
}

Using os.walk() to recursively traverse directories in Python

You could also recursively walk through a folder and lists all it's contents using pathlib.Path()

from pathlib import Path


def check_out_path(target_path, level=0):
    """"
    This function recursively prints all contents of a pathlib.Path object
    """
    def print_indented(folder, level):
        print('\t' * level + folder)

    print_indented(target_path.name, level)
    for file in target_path.iterdir():
        if file.is_dir():
            check_out_path(file, level+1)
        else:
            print_indented(file.name, level+1)


my_path = Path(r'C:\example folder')
check_out_path(my_path)

Output:

example folder
    folder
        textfile3.txt
    textfile1.txt
    textfile2.txt

Replacing few values in a pandas dataframe column with another value

loc function can be used to replace multiple values, Documentation for it : loc

df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'

How to declare an array of objects in C#

I guess GameObject is a reference type. Default for reference types is null => you have an array of nulls.

You need to initialize each member of the array separatedly.

houses[0] = new GameObject(..);

Only then can you access the object without compilation errors.

So you can explicitly initalize the array:

for (int i = 0; i < houses.Length; i++)
{
    houses[i] = new GameObject();
}

or you can change GameObject to value type.

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Allow scroll but hide scrollbar

I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

Just add

::-webkit-scrollbar {display:none;}

To your id or class of the div you're using the scroll bar with.

Here is a helpful link Custom Scroll Bar in Webkit

How to enable Ad Hoc Distributed Queries

You may check the following command

sp_configure 'show advanced options', 1;
RECONFIGURE;
GO  --Added        
sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

SELECT a.*
FROM OPENROWSET('SQLNCLI', 'Server=Seattle1;Trusted_Connection=yes;',
     'SELECT GroupName, Name, DepartmentID
      FROM AdventureWorks2012.HumanResources.Department
      ORDER BY GroupName, Name') AS a;
GO

Or this documentation link

HTTP status code for update and delete?

Since the question delves into if DELETE "should" return 200 vs 204 it is worth considering that some people recommend returning an entity with links so the preference is for 200.

"Instead of returning 204 (No Content), the API should be helpful and suggest places to go. In this example I think one obvious link to provide is to" 'somewhere.com/container/' (minus 'resource') "- the container from which the client just deleted a resource. Perhaps the client wishes to delete more resources, so that would be a helpful link."

http://blog.ploeh.dk/2013/04/30/rest-lesson-learned-avoid-204-responses/

If a client encounters a 204 response, it can either give up, go to the entry point of the API, or go back to the previous resource it visited. Neither option is particularly good.

Personally I would not say 204 is wrong (neither does the author; he says "annoying") because good caching at the client side has many benefits. Best is to be consistent either way.

Angular 2 filter/search list

Slight modification to @Mosche answer, for handling if there exist no filter element.

TS:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filterFromList'
})
export class FilterPipe implements PipeTransform {
    public transform(value, keys: string, term: string) {

        if (!term) {
            return value
        }
        let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
        return res.length ? res : [-1];

    }
}

Now, in your HTML you can check via '-1' value, for no results.

HTML:

<div *ngFor="let item of list | filterFromList: 'attribute': inputVariableModel">
            <mat-list-item *ngIf="item !== -1">
                <h4 mat-line class="inline-block">
                 {{item}}
                </h4>
            </mat-list-item>
            <mat-list-item *ngIf="item === -1">
                No Matches
            </mat-list-item>
        </div>

Best way to create a temp table with same columns and type as a permanent table

Clone Temporary Table Structure to New Physical Table in SQL Server

enter image description here

we will see how to Clone Temporary Table Structure to New Physical Table in SQL Server.This is applicable for both Azure SQL db and on-premises.

Demo SQL Script

IF OBJECT_ID('TempDB..#TempTable') IS NOT NULL
    DROP TABLE #TempTable;

SELECT 1 AS ID,'Arul' AS Names
INTO
#TempTable;

SELECT * FROM #TempTable;

METHOD 1

SELECT * INTO TempTable1 FROM #TempTable WHERE 1=0;

EXEC SP_HELP TempTable1;

enter image description here

METHOD 2

SELECT TOP 0 * INTO TempTable1 FROM #TempTable;

EXEC SP_HELP TempTable1;

enter image description here

Where does the .gitignore file belong?

When in doubt just place it in the root of your repository. See https://help.github.com/articles/ignoring-files/ for more information.

C# Telnet Library

Here is my code that is finally working

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Threading;

class TelnetTest
{

    static void Main(string[] args)
    {
        TelnetTest tt = new TelnetTest();

        tt.tcpClient = new TcpClient("myserver", 23);
        tt.ns = tt.tcpClient.GetStream();

        tt.connectHost("admin", "admin");
        tt.sendCommand();

        tt.tcpClient.Close();
    }

public void connectHost(string user, string passwd) {
    bool i = true;
    while (i)
    {
        Console.WriteLine("Connecting.....");
        Byte[] output = new Byte[1024];
        String responseoutput = String.Empty;
        Byte[] cmd = System.Text.Encoding.ASCII.GetBytes("\n");
        ns.Write(cmd, 0, cmd.Length);

        Thread.Sleep(1000);
        Int32 bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.WriteLine("Responseoutput: " + responseoutput);
        Regex objToMatch = new Regex("login:");
        if (objToMatch.IsMatch(responseoutput)) {
           cmd = System.Text.Encoding.ASCII.GetBytes(user + "\r");
           ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write(responseoutput);
        objToMatch = new Regex("Password");
        if (objToMatch.IsMatch(responseoutput))
        {
            cmd = System.Text.Encoding.ASCII.GetBytes(passwd + "\r");
            ns.Write(cmd, 0, cmd.Length);
        }

        Thread.Sleep(1000);
        bytes = ns.Read(output, 0, output.Length);
        responseoutput = System.Text.Encoding.ASCII.GetString(output, 0, bytes);
        Console.Write("Responseoutput: " + responseoutput);

        objToMatch = new Regex("#");
        if (objToMatch.IsMatch(responseoutput))
        {
            i = false;
        }

    }

    Console.WriteLine("Just works");
}
}

Timeout on a function call

timeout-decorator don't work on windows system as , windows didn't support signal well.

If you use timeout-decorator in windows system you will get the following

AttributeError: module 'signal' has no attribute 'SIGALRM'

Some suggested to use use_signals=False but didn't worked for me.

Author @bitranox created the following package:

pip install https://github.com/bitranox/wrapt-timeout-decorator/archive/master.zip

Code Sample:

import time
from wrapt_timeout_decorator import *

@timeout(5)
def mytest(message):
    print(message)
    for i in range(1,10):
        time.sleep(1)
        print('{} seconds have passed'.format(i))

def main():
    mytest('starting')


if __name__ == '__main__':
    main()

Gives the following exception:

TimeoutError: Function mytest timed out after 5 seconds

Bootstrap col-md-offset-* not working

Should be :

<h2 class="col-md-4 col-md-offset-1">Browse.</h2>
<h2 class="col-md-4 col-md-offset-2">create.</h2>
<h2 class="col-md-4 col-md-offset-3">share.</h2>

Inner join of DataTables in C#

this function will join 2 tables with a known join field, but this cannot allow 2 fields with the same name on both tables except the join field, a simple modification would be to save a dictionary with a counter and just add number to the same name filds.

public static DataTable JoinDataTable(DataTable dataTable1, DataTable dataTable2, string joinField)
{
    var dt = new DataTable();
    var joinTable = from t1 in dataTable1.AsEnumerable()
                            join t2 in dataTable2.AsEnumerable()
                                on t1[joinField] equals t2[joinField]
                            select new { t1, t2 };

    foreach (DataColumn col in dataTable1.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    dt.Columns.Remove(joinField);

    foreach (DataColumn col in dataTable2.Columns)
        dt.Columns.Add(col.ColumnName, typeof(string));

    foreach (var row in joinTable)
    {
        var newRow = dt.NewRow();
        newRow.ItemArray = row.t1.ItemArray.Union(row.t2.ItemArray).ToArray();
        dt.Rows.Add(newRow);
    }
    return dt;
}

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

How do I post button value to PHP?

Give them all a name that is the same

For example

<input type="button" value="a" name="btn" onclick="a" />
<input type="button" value="b" name="btn" onclick="b" />

Then in your php use:

$val = $_POST['btn']

Edit, as BalusC said; If you're not going to use onclick for doing any javascript (for example, sending the form) then get rid of it and use type="submit"

Codeigniter $this->input->post() empty while $_POST is working correctly

You are missing the parent constructor. When your controller is loaded you must Call the parent CI_Controller class constructor in your controller constructor

How to fix "unable to open stdio.h in Turbo C" error?

Do this: Open your turboc2 folder you have tc.exe file inside, beside this file you find another file as named as ' tcinst.exe ' open it.

You will see the installation menu:

select as-- > Option > Directory > Include directory

Here you have to change the path of the directory to the path where your INCLUDE folder is located. Same way change the path to library directory also over restart your tc.exe.

How to get an HTML element's style values in javascript?

You can make function getStyles that'll take an element and other arguments are properties that's values you want.

const convertRestArgsIntoStylesArr = ([...args]) => {
    return args.slice(1);
}

const getStyles = function () {
    const args = [...arguments];
    const [element] = args;

    let stylesProps = [...args][1] instanceof Array ? args[1] : convertRestArgsIntoStylesArr(args);

    const styles = window.getComputedStyle(element);
    const stylesObj = stylesProps.reduce((acc, v) => {
        acc[v] = styles.getPropertyValue(v);
        return acc;
    }, {});

    return stylesObj;
};

Now, you can use this function like this:

const styles = getStyles(document.body, "height", "width");

OR

const styles = getStyles(document.body, ["height", "width"]);

Add back button to action bar

After setting actionBar.setHomeButtonEnabled(true);

Add the following code:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            // app icon in action bar clicked; goto parent activity.
            this.finish();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Can jQuery provide the tag name?

Since I've hit this question once before and it didn't help me in my case (I didn't have a this, but instead had a jQuery selector instance). Calling get() will get you the HTML element, by which you can get the nodeName as mentioned above.

this.nodeName; // In a event handler, 'this' is usually the element the event is called on

or

$('.hello:first-child').get(0).nodeName; // Use 'get' or simply access the jQuery Object like an array
$('.hello:first-child')[0].nodeName;     // will get you the original DOM element object

Regex to get the words after matching string

Here's a quick Perl script to get what you need. It needs some whitespace chomping.

#!/bin/perl

$sample = <<END;
Subject:
  Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
  Account Name:       ChamaraKer
  Account Domain:     JIC
  Logon ID:       0x1fffb

Object:
  Object Server:  Security
  Object Type:    File
  Object Name:    D:\\ApacheTomcat\\apache-tomcat-6.0.36\\logs\\localhost.2013- 07-01.log
  Handle ID:  0x11dc
END

my @sample_lines = split /\n/, $sample;
my $path;

foreach my $line (@sample_lines) {
  ($path) = $line =~ m/Object Name:([^s]+)/g;
  if($path) {
    print $path . "\n";
  }
}

How to add a footer to the UITableView?

I'm specifically seeing in my code that

self.theTable.tableFooterView = tableFooter;

works and

[self.theTable.tableFooterView addSubview:tableFooter];

does not work. So stick to the former and look elsewhere for the possible bug. HTH

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

I wrote a class to normalize the data in my dictionary. The 'element' in the NormalizeData class below, needs to be of dict type. And you need to replace in the __iterate() with either your custom class object or any other object type that you would like to normalize.

class NormalizeData:

    def __init__(self, element):
        self.element = element

    def execute(self):
        if isinstance(self.element, dict):
            self.__iterate()
        else:
            return

    def __iterate(self):
        for key in self.element:
            if isinstance(self.element[key], <ClassName>):
                self.element[key] = str(self.element[key])

            node = NormalizeData(self.element[key])
            node.execute()

how to attach url link to an image?

Alternatively,

<style type="text/css">
#example {
    display: block;
    width: 30px;
    height: 10px;
    background: url(../images/example.png) no-repeat;
    text-indent: -9999px;
}
</style>

<a href="http://www.example.com" id="example">See an example!</a>

More wordy, but it may benefit SEO, and it will look like nice simple text with CSS disabled.

Button inside of anchor link works in Firefox but not in Internet Explorer?

You cannot have a button inside an a tag. You can do some javascript to make it work however.

What is the OR operator in an IF statement

The reason this is wrong:

if (title == "User greeting" || "User name") {do stuff};

is because what that's saying is

If title equals the string "User greeting"

or just "User name" (not if title equals the string "User name"). The part after your or would be like writing

if ("User name")

which c# doesn't know what to do with. It can't figure out how to get a boolean out of "User name"

How to output JavaScript with PHP

You want to do this:

<html>
<body>
<?php

print '
<script type="text/javascript">
document.write("Hello World!")
</script>
';

?>
</body>
</html>

How to copy selected files from Android with adb pull

As to the short script, the following runs on my Linux host

#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"

while read MYFILE ; do
    adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")

"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.

Which concurrent Queue implementation should I use in Java?

Basically the difference between them are performance characteristics and blocking behavior.

Taking the easiest first, ArrayBlockingQueue is a queue of a fixed size. So if you set the size at 10, and attempt to insert an 11th element, the insert statement will block until another thread removes an element. The fairness issue is what happens if multiple threads try to insert and remove at the same time (in other words during the period when the Queue was blocked). A fairness algorithm ensures that the first thread that asks is the first thread that gets. Otherwise, a given thread may wait longer than other threads, causing unpredictable behavior (sometimes one thread will just take several seconds because other threads that started later got processed first). The trade-off is that it takes overhead to manage the fairness, slowing down the throughput.

The most important difference between LinkedBlockingQueue and ConcurrentLinkedQueue is that if you request an element from a LinkedBlockingQueue and the queue is empty, your thread will wait until there is something there. A ConcurrentLinkedQueue will return right away with the behavior of an empty queue.

Which one depends on if you need the blocking. Where you have many producers and one consumer, it sounds like it. On the other hand, where you have many consumers and only one producer, you may not need the blocking behavior, and may be happy to just have the consumers check if the queue is empty and move on if it is.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

Parsing CSV files in C#, with header

In a business application, i use the Open Source project on codeproject.com, CSVReader.

It works well, and has good performance. There is some benchmarking on the link i provided.

A simple example, copied from the project page:

using (CsvReader csv = new CsvReader(new StreamReader("data.csv"), true))
{
    int fieldCount = csv.FieldCount;
    string[] headers = csv.GetFieldHeaders();

    while (csv.ReadNextRecord())
    {
        for (int i = 0; i < fieldCount; i++)
            Console.Write(string.Format("{0} = {1};", headers[i], csv[i]));

        Console.WriteLine();
    }
}

As you can see, it's very easy to work with.

HTML - Display image after selecting filename

This can be done using HTML5, but will only work in browsers that support it. Here's an example.

Bear in mind you'll need an alternative method for browsers that don't support this. I've had a lot of success with this plugin, which takes a lot of the work out of your hands.

How to remove word wrap from textarea?

I found a way to make a textarea with all this working at the same time:

  • With horizontal scrollbar
  • Supporting multiline text
  • Text not wrapping

It works well on:

  • Chrome 15.0.874.120
  • Firefox 7.0.1
  • Opera 11.52 (1100)
  • Safari 5.1 (7534.50)
  • IE 8.0.6001.18702

Let me explain how i get to that: I was using Chrome inspector integrated tool and I saw values on CSS styles, so I try these values, instead of normal ones... trial & errors till I got it reduced to minimum and here it is for anyone that wants it.

In the CSS section I used just this for Chrome, Firefox, Opera and Safari:

textarea {
  white-space:nowrap;
  overflow:scroll;
}

In the CSS section I used just this for IE:

textarea {
  overflow:scroll;
}

It was a bit tricky, but there is the CSS.

An (x)HTML tag like this:

<textarea id="myTextarea" rows="10" cols="15"></textarea>

And at the end of the <head> section a JavaScript like this:

 window.onload=function(){
   document.getElementById("myTextarea").wrap='off';
 }

The JavaScript is for making the W3C validator passing XHTML 1.1 Strict, since the wrap attribute is not official and thus cannot be an (x)HTML tag directly, but most browsers handle it, so after loading the page it sets that attribute.

Hope this can be tested on more browsers and versions and help someone to improve it and makes it fully cross-browser for all versions.

How to clone ArrayList and also clone its contents?

The package import org.apache.commons.lang.SerializationUtils;

There is a method SerializationUtils.clone(Object);

Example

this.myObjectCloned = SerializationUtils.clone(this.object);

Maximum number of records in a MySQL database table

Row Size Limits

The maximum row size for a given table is determined by several factors:
  • The internal representation of a MySQL table has a maximum row size limit of 65,535 bytes, even if the storage engine is capable of supporting larger rows. BLOB and TEXT columns only contribute 9 to 12 bytes toward the row size limit because their contents are stored separately from the rest of the row.

  • The maximum row size for an InnoDB table, which applies to data stored locally within a database page, is slightly less than half a page. For example, the maximum row size is slightly less than 8KB for the default 16KB InnoDB page size, which is defined by the innodb_page_size configuration option. “Limits on InnoDB Tables”.

  • If a row containing variable-length columns exceeds the InnoDB maximum row size, InnoDB selects variable-length columns for external off-page storage until the row fits within the InnoDB row size limit. The amount of data stored locally for variable-length columns that are stored off-page differs by row format. For more information, see “InnoDB Row Storage and Row Formats”.
  • Different storage formats use different amounts of page header and trailer data, which affects the amount of storage available for rows.

Cast Object to Generic Type for returning

If you do not want to depend on throwing exception (which you probably should not) you can try this:

public static <T> T cast(Object o, Class<T> clazz) {
    return clazz.isInstance(o) ? clazz.cast(o) : null;
}

Floating point vs integer calculations on modern hardware

TIL This varies (a lot). Here are some results using gnu compiler (btw I also checked by compiling on machines, gnu g++ 5.4 from xenial is a hell of a lot faster than 4.6.3 from linaro on precise)

Intel i7 4700MQ xenial

short add: 0.822491
short sub: 0.832757
short mul: 1.007533
short div: 3.459642
long add: 0.824088
long sub: 0.867495
long mul: 1.017164
long div: 5.662498
long long add: 0.873705
long long sub: 0.873177
long long mul: 1.019648
long long div: 5.657374
float add: 1.137084
float sub: 1.140690
float mul: 1.410767
float div: 2.093982
double add: 1.139156
double sub: 1.146221
double mul: 1.405541
double div: 2.093173

Intel i3 2370M has similar results

short add: 1.369983
short sub: 1.235122
short mul: 1.345993
short div: 4.198790
long add: 1.224552
long sub: 1.223314
long mul: 1.346309
long div: 7.275912
long long add: 1.235526
long long sub: 1.223865
long long mul: 1.346409
long long div: 7.271491
float add: 1.507352
float sub: 1.506573
float mul: 2.006751
float div: 2.762262
double add: 1.507561
double sub: 1.506817
double mul: 1.843164
double div: 2.877484

Intel(R) Celeron(R) 2955U (Acer C720 Chromebook running xenial)

short add: 1.999639
short sub: 1.919501
short mul: 2.292759
short div: 7.801453
long add: 1.987842
long sub: 1.933746
long mul: 2.292715
long div: 12.797286
long long add: 1.920429
long long sub: 1.987339
long long mul: 2.292952
long long div: 12.795385
float add: 2.580141
float sub: 2.579344
float mul: 3.152459
float div: 4.716983
double add: 2.579279
double sub: 2.579290
double mul: 3.152649
double div: 4.691226

DigitalOcean 1GB Droplet Intel(R) Xeon(R) CPU E5-2630L v2 (running trusty)

short add: 1.094323
short sub: 1.095886
short mul: 1.356369
short div: 4.256722
long add: 1.111328
long sub: 1.079420
long mul: 1.356105
long div: 7.422517
long long add: 1.057854
long long sub: 1.099414
long long mul: 1.368913
long long div: 7.424180
float add: 1.516550
float sub: 1.544005
float mul: 1.879592
float div: 2.798318
double add: 1.534624
double sub: 1.533405
double mul: 1.866442
double div: 2.777649

AMD Opteron(tm) Processor 4122 (precise)

short add: 3.396932
short sub: 3.530665
short mul: 3.524118
short div: 15.226630
long add: 3.522978
long sub: 3.439746
long mul: 5.051004
long div: 15.125845
long long add: 4.008773
long long sub: 4.138124
long long mul: 5.090263
long long div: 14.769520
float add: 6.357209
float sub: 6.393084
float mul: 6.303037
float div: 17.541792
double add: 6.415921
double sub: 6.342832
double mul: 6.321899
double div: 15.362536

This uses code from http://pastebin.com/Kx8WGUfg as benchmark-pc.c

g++ -fpermissive -O3 -o benchmark-pc benchmark-pc.c

I've run multiple passes, but this seems to be the case that general numbers are the same.

One notable exception seems to be ALU mul vs FPU mul. Addition and subtraction seem trivially different.

Here is the above in chart form (click for full size, lower is faster and preferable):

Chart of above data

Update to accomodate @Peter Cordes

https://gist.github.com/Lewiscowles1986/90191c59c9aedf3d08bf0b129065cccc

i7 4700MQ Linux Ubuntu Xenial 64-bit (all patches to 2018-03-13 applied)
    short add: 0.773049
    short sub: 0.789793
    short mul: 0.960152
    short div: 3.273668
      int add: 0.837695
      int sub: 0.804066
      int mul: 0.960840
      int div: 3.281113
     long add: 0.829946
     long sub: 0.829168
     long mul: 0.960717
     long div: 5.363420
long long add: 0.828654
long long sub: 0.805897
long long mul: 0.964164
long long div: 5.359342
    float add: 1.081649
    float sub: 1.080351
    float mul: 1.323401
    float div: 1.984582
   double add: 1.081079
   double sub: 1.082572
   double mul: 1.323857
   double div: 1.968488
AMD Opteron(tm) Processor 4122 (precise, DreamHost shared-hosting)
    short add: 1.235603
    short sub: 1.235017
    short mul: 1.280661
    short div: 5.535520
      int add: 1.233110
      int sub: 1.232561
      int mul: 1.280593
      int div: 5.350998
     long add: 1.281022
     long sub: 1.251045
     long mul: 1.834241
     long div: 5.350325
long long add: 1.279738
long long sub: 1.249189
long long mul: 1.841852
long long div: 5.351960
    float add: 2.307852
    float sub: 2.305122
    float mul: 2.298346
    float div: 4.833562
   double add: 2.305454
   double sub: 2.307195
   double mul: 2.302797
   double div: 5.485736
Intel Xeon E5-2630L v2 @ 2.4GHz (Trusty 64-bit, DigitalOcean VPS)
    short add: 1.040745
    short sub: 0.998255
    short mul: 1.240751
    short div: 3.900671
      int add: 1.054430
      int sub: 1.000328
      int mul: 1.250496
      int div: 3.904415
     long add: 0.995786
     long sub: 1.021743
     long mul: 1.335557
     long div: 7.693886
long long add: 1.139643
long long sub: 1.103039
long long mul: 1.409939
long long div: 7.652080
    float add: 1.572640
    float sub: 1.532714
    float mul: 1.864489
    float div: 2.825330
   double add: 1.535827
   double sub: 1.535055
   double mul: 1.881584
   double div: 2.777245

How to update nested state properties in React

stateUpdate = () => {
    let obj = this.state;
    if(this.props.v12_data.values.email) {
      obj.obj_v12.Customer.EmailAddress = this.props.v12_data.values.email
    }
    this.setState(obj)
}

Initialize a vector array of strings

In C++0x you will be able to initialize containers just like arrays

http://www2.research.att.com/~bs/C++0xFAQ.html#init-list

ExpressionChangedAfterItHasBeenCheckedError Explained

In my case, I had an async property in LoadingService with a BehavioralSubject isLoading

Using the [hidden] model works, but *ngIf fails

    <h1 [hidden]="!(loaderService.isLoading | async)">
        THIS WORKS FINE
        (Loading Data)
    </h1>

    <h1 *ngIf="!(loaderService.isLoading | async)">
        THIS THROWS ERROR
        (Loading Data)
    </h1>

Concept of void pointer in C programming

Here is a brief pointer on void pointers: https://www.learncpp.com/cpp-tutorial/613-void-pointers/

6.13 — Void pointers

Because the void pointer does not know what type of object it is pointing to, it cannot be dereferenced directly! Rather, the void pointer must first be explicitly cast to another pointer type before it is dereferenced.

If a void pointer doesn't know what it's pointing to, how do we know what to cast it to? Ultimately, that is up to you to keep track of.

Void pointer miscellany

It is not possible to do pointer arithmetic on a void pointer. This is because pointer arithmetic requires the pointer to know what size object it is pointing to, so it can increment or decrement the pointer appropriately.

Assuming the machine's memory is byte-addressable and does not require aligned accesses, the most generic and atomic (closest to the machine level representation) way of interpreting a void* is as a pointer-to-a-byte, uint8_t*. Casting a void* to a uint8_t* would allow you to, for example, print out the first 1/2/4/8/however-many-you-desire bytes starting at that address, but you can't do much else.

uint8_t* byte_p = (uint8_t*)p;
for (uint8_t* i = byte_p; i < byte_p + 8; i++) {
  printf("%x ",*i);
}

How do I load the contents of a text file into a javascript variable?

here is how I did it in jquery:

jQuery.get('http://localhost/foo.txt', function(data) {
    alert(data);
});

port forwarding in windows

nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:

events {}

http {
     server {

        listen 192.168.1.111:4422;

        location / {
            proxy_pass http://192.168.2.33:80/;
        }
     }
}

How to convert unsigned long to string

you can write a function which converts from unsigned long to str, similar to ltostr library function.

char *ultostr(unsigned long value, char *ptr, int base)
{
  unsigned long t = 0, res = 0;
  unsigned long tmp = value;
  int count = 0;

  if (NULL == ptr)
  {
    return NULL;
  }

  if (tmp == 0)
  {
    count++;
  }

  while(tmp > 0)
  {
    tmp = tmp/base;
    count++;
  }

  ptr += count;

  *ptr = '\0';

  do
  {
    res = value - base * (t = value / base);
    if (res < 10)
    {
      * -- ptr = '0' + res;
    }
    else if ((res >= 10) && (res < 16))
    {
        * --ptr = 'A' - 10 + res;
    }
  } while ((value = t) != 0);

  return(ptr);
}

you can refer to my blog here which explains implementation and usage with example.

Match groups in Python

this is not a regex solution.

alist={"I love ":""He loves"","Je t'aime ":"Il aime","Ich liebe ":"Er liebt"}
for k in alist.keys():
    if k in statement:
       print alist[k],statement.split(k)[1:]

Regex select all text between tags

In Python, setting the DOTALL flag will capture everything, including newlines.

If the DOTALL flag has been specified, this matches any character including a newline. docs.python.org

#example.py using Python 3.7.4  
import re

str="""Everything is awesome! <pre>Hello,
World!
    </pre>
"""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set 
pattern = re.compile(r"<pre>(.*)</pre>",re.DOTALL)
matches = pattern.search(str)

print(matches.group(1))

python example.py

Hello,
World!

Capturing text between all opening and closing tags in a document

To capture text between all opening and closing tags in a document, finditer is useful. In the example below, three opening and closing <pre> tags are present in the string.

#example2.py using Python 3.7.4
import re

# str contains three <pre>...</pre> tags
str = """In two different ex-
periments, the authors had subjects chat and solve the <pre>Desert Survival Problem</pre> with a
humorous or non-humorous computer. In both experiments the computer made pre-
programmed comments, but in study 1 subjects were led to believe they were interact-
ing with another person. In the <pre>humor conditions</pre> subjects received a number of funny
comments, for instance: “The mirror is probably too small to be used as a signaling
device to alert rescue teams to your location. Rank it lower. (On the other hand, it
offers <pre>endless opportunity for self-reflection</pre>)”."""

# Normally (.*) will not capture newlines, but here re.DOTATLL is set
# The question mark in (.*?) indicates non greedy matching.
pattern = re.compile(r"<pre>(.*?)</pre>",re.DOTALL)

matches = pattern.finditer(str)


for i,match in enumerate(matches):
    print(f"tag {i}: ",match.group(1))

python example2.py

tag 0:  Desert Survival Problem
tag 1:  humor conditions
tag 2:  endless opportunity for self-reflection

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Good Patterns For VBA Error Handling

My personal view on a statement made earlier in this thread:

And just for fun:

On Error Resume Next is the devil incarnate and to be avoided, as it silently hides errors.

I'm using the On Error Resume Next on procedures where I don't want an error to stop my work and where any statement does not depend on the result of the previous statements.

When I'm doing this I add a global variable debugModeOn and I set it to True. Then I use it this way:

If not debugModeOn Then On Error Resume Next

When I deliver my work, I set the variable to false, thus hiding the errors only to the user and showing them during testing.

Also using it when doing something that may fail like calling the DataBodyRange of a ListObject that may be empty:

On Error Resume Next
Sheet1.ListObjects(1).DataBodyRange.Delete
On Error Goto 0

Instead of:

If Sheet1.ListObjects(1).ListRows.Count > 0 Then 
    Sheet1.ListObjects(1).DataBodyRange.Delete
End If

Or checking existence of an item in a collection:

On Error Resume Next
Err.Clear
Set auxiliarVar = collection(key)

' Check existence (if you try to retrieve a nonexistant key you get error number 5)
exists = (Err.Number <> 5)

Why use pip over easy_install?

As an addition to fuzzyman's reply:

pip won't install binary packages and isn't well tested on Windows.

As Windows doesn't come with a compiler by default pip often can't be used there. easy_install can install binary packages for Windows.

Here is a trick on Windows:

  • you can use easy_install <package> to install binary packages to avoid building a binary

  • you can use pip uninstall <package> even if you used easy_install.

This is just a work-around that works for me on windows. Actually I always use pip if no binaries are involved.

See the current pip doku: http://www.pip-installer.org/en/latest/other-tools.html#pip-compared-to-easy-install

I will ask on the mailing list what is planned for that.

Here is the latest update:

The new supported way to install binaries is going to be wheel! It is not yet in the standard, but almost. Current version is still an alpha: 1.0.0a1

https://pypi.python.org/pypi/wheel

http://wheel.readthedocs.org/en/latest/

I will test wheel by creating an OS X installer for PySide using wheel instead of eggs. Will get back and report about this.

cheers - Chris

A quick update:

The transition to wheel is almost over. Most packages are supporting wheel.

I promised to build wheels for PySide, and I did that last summer. Works great!

HINT: A few developers failed so far to support the wheel format, simply because they forget to replace distutils by setuptools. Often, it is easy to convert such packages by replacing this single word in setup.py.

bash export command

SHELL is an environment variable, and so it's not the most reliable for what you're trying to figure out. If your tool is using a shell which doesn't set it, it will retain its old value.

Use ps to figure out what's really going on.

Posting form to different MVC post action depending on the clicked submit button

BEST ANSWER 1:

ActionNameSelectorAttribute mentioned in

  1. How do you handle multiple submit buttons in ASP.NET MVC Framework?

  2. ASP.Net MVC 4 Form with 2 submit buttons/actions

http://weblogs.asp.net/scottgu/archive/2007/12/09/asp-net-mvc-framework-part-4-handling-form-edit-and-post-scenarios.aspx

ANSWER 2

Reference: dotnet-tricks - Handling multiple submit buttons on the same form - MVC Razor

Second Approach

Adding a new Form for handling Cancel button click. Now, on Cancel button click we will post the second form and will redirect to the home page.

Third Approach: Client Script

<button name="ClientCancel" type="button" 
    onclick=" document.location.href = $('#cancelUrl').attr('href');">Cancel (Client Side)
</button>
<a id="cancelUrl" href="@Html.AttributeEncode(Url.Action("Index", "Home"))" 
style="display:none;"></a>

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Whenever I set debug="off" in my web.config and run my mvc4 application i would end up with ...

<script src="/bundles/jquery?v=<some long string>"></script>

in my html code and a JavaScript error

Expected ';'

There were 2 ways to get rid of the javascript error

  1. set BundleTable.EnableOptimizations = false in BundleConfig.cs

OR

  1. I ended up using NuGet Package Manager to update WebGrease.dll. It works fine irrespective if debug= "true" or debug = "false".

Bin size in Matplotlib (Histogram)

I use quantiles to do bins uniform and fitted to sample:

bins=df['Generosity'].quantile([0,.05,0.1,0.15,0.20,0.25,0.3,0.35,0.40,0.45,0.5,0.55,0.6,0.65,0.70,0.75,0.80,0.85,0.90,0.95,1]).to_list()

plt.hist(df['Generosity'], bins=bins, normed=True, alpha=0.5, histtype='stepfilled', color='steelblue', edgecolor='none')

enter image description here

Adding n hours to a date in Java?

Using the newish java.util.concurrent.TimeUnit class you can do it like this

Date oldDate = new Date(); // oldDate == current time
Date newDate = new Date(oldDate.getTime() + TimeUnit.HOURS.toMillis(2)); // Add 2 hours

How to extract a string between two delimiters

Try as

String s = "ABC[ This is to extract ]";
        Pattern p = Pattern.compile(".*\\[ *(.*) *\\].*");
        Matcher m = p.matcher(s);
        m.find();
        String text = m.group(1);
        System.out.println(text);

Regex to match only uppercase "words" with some exceptions

Don't do things like [A-Z] or [0-9]. Do \p{Lu} and \d instead. Of course, this is valid for perl based regex flavours. This includes java.

I would suggest that you don't make some huge regex. First split the text in sentences. then tokenize it (split into words). Use a regex to check each token/word. Skip the first token from sentence. Check if all tokens are uppercase beforehand and skip the whole sentence if so, or alter the regex in this case.

How to Right-align flex item?

margin-left: auto works well. But clean flex box solution would be space-between in the main class. Space between works well if there is two or more elements. I have added a solution for single element as well.

_x000D_
_x000D_
.main { display: flex; justify-content: space-between; }
.a, .b, .c { background: #efefef; border: 1px solid #999; padding: 0.25rem; margin: 0.25rem;}
.b { flex: 1; text-align: center; }

.c-wrapper {
  display: flex;
  flex: 1;
  justify-content: flex-end;
}

.c-wrapper2 {
  display: flex;
  flex: 1;
  flex-flow: row-reverse;
}
_x000D_
<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="b"><a href="#">Some title centered</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>

<div class="main">
    <div class="a"><a href="#">Home</a></div>
    <div class="c"><a href="#">Contact</a></div>
</div>

<div class="main">
    <div class="c-wrapper">
      <a class="c" href="#">Contact</a>
      <a class="c" href="#">Contact2</a>
    </div>
</div>
<div class="main">
    <div class="c-wrapper2">
      <span class="c">Contact</span>
      <span class="c">Contact2</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to parse this string in Java?

In this case, why not use new File("prefix/dir1/dir2/dir3/dir4") and go from there?

Change private static final field using Java reflection

Assuming no SecurityManager is preventing you from doing this, you can use setAccessible to get around private and resetting the modifier to get rid of final, and actually modify a private static final field.

Here's an example:

import java.lang.reflect.*;

public class EverythingIsTrue {
   static void setFinalStatic(Field field, Object newValue) throws Exception {
      field.setAccessible(true);

      Field modifiersField = Field.class.getDeclaredField("modifiers");
      modifiersField.setAccessible(true);
      modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

      field.set(null, newValue);
   }
   public static void main(String args[]) throws Exception {      
      setFinalStatic(Boolean.class.getField("FALSE"), true);

      System.out.format("Everything is %s", false); // "Everything is true"
   }
}

Assuming no SecurityException is thrown, the above code prints "Everything is true".

What's actually done here is as follows:

  • The primitive boolean values true and false in main are autoboxed to reference type Boolean "constants" Boolean.TRUE and Boolean.FALSE
  • Reflection is used to change the public static final Boolean.FALSE to refer to the Boolean referred to by Boolean.TRUE
  • As a result, subsequently whenever a false is autoboxed to Boolean.FALSE, it refers to the same Boolean as the one refered to by Boolean.TRUE
  • Everything that was "false" now is "true"

Related questions


Caveats

Extreme care should be taken whenever you do something like this. It may not work because a SecurityManager may be present, but even if it doesn't, depending on usage pattern, it may or may not work.

JLS 17.5.3 Subsequent Modification of Final Fields

In some cases, such as deserialization, the system will need to change the final fields of an object after construction. final fields can be changed via reflection and other implementation dependent means. The only pattern in which this has reasonable semantics is one in which an object is constructed and then the final fields of the object are updated. The object should not be made visible to other threads, nor should the final fields be read, until all updates to the final fields of the object are complete. Freezes of a final field occur both at the end of the constructor in which the final field is set, and immediately after each modification of a final field via reflection or other special mechanism.

Even then, there are a number of complications. If a final field is initialized to a compile-time constant in the field declaration, changes to the final field may not be observed, since uses of that final field are replaced at compile time with the compile-time constant.

Another problem is that the specification allows aggressive optimization of final fields. Within a thread, it is permissible to reorder reads of a final field with those modifications of a final field that do not take place in the constructor.

See also

  • JLS 15.28 Constant Expression
    • It's unlikely that this technique works with a primitive private static final boolean, because it's inlineable as a compile-time constant and thus the "new" value may not be observable

Appendix: On the bitwise manipulation

Essentially,

field.getModifiers() & ~Modifier.FINAL

turns off the bit corresponding to Modifier.FINAL from field.getModifiers(). & is the bitwise-and, and ~ is the bitwise-complement.

See also


Remember Constant Expressions

Still not being able to solve this?, have fallen onto depression like I did for it? Does your code looks like this?

public class A {
    private final String myVar = "Some Value";
}

Reading the comments on this answer, specially the one by @Pshemo, it reminded me that Constant Expressions are handled different so it will be impossible to modify it. Hence you will need to change your code to look like this:

public class A {
    private final String myVar;

    private A() {
        myVar = "Some Value";
    }
}

if you are not the owner of the class... I feel you!

For more details about why this behavior read this?

React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing

try

_x000D_
_x000D_
const MyFunctionnalComponent: React.FC = props => {_x000D_
  useEffect(() => {_x000D_
    // Using an IIFE_x000D_
    (async function anyNameFunction() {_x000D_
      await loadContent();_x000D_
    })();_x000D_
  }, []);_x000D_
  return <div></div>;_x000D_
};
_x000D_
_x000D_
_x000D_

Can you have if-then-else logic in SQL?

there is a case statement, but i think the below is more accurate/efficient/easier to read for what you want.

select 
  product
  ,coalesce(t4.price,t2.price, t3.price) as price
from table1 t1
left join table1 t2 on t1.product = t2.product and t2.customer =2
left join table1 t3 on t1.product = t3.product and t3.company =3
left join table1 t4 on t1.product = t4.product and t4.project =1

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

Add this to your pom.xml file:

<project ....>
    <properties>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>
</project>

Where 1.7 is the Java version you intend to use. This overwrites the Maven compiler setting, so it's good to debug from here.

How do I run a command on an already existing Docker container?

I am running windows container and I need to look inside the docker container for files and folder created and copied.

In order to do that I used following docker entrypoint command to get the command prompt running inside the container or attach to the container.

ENTRYPOINT ["C:\\Windows\\System32\\cmd.exe", "-D", "FOREGROUND"]

That helped me both to the command prompt attach to container and to keep the container a live. :)

adding 1 day to a DATETIME format value

Using server request time to Add days. Working as expected.

25/08/19 => 27/09/19

$timestamp = $_SERVER['REQUEST_TIME'];
$dateNow = date('d/m/y', $timestamp);
$newDate = date('d/m/y', strtotime('+2 day', $timestamp));

Here '+2 days' to add any number of days.

Send Outlook Email Via Python?

import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'To address'
mail.Subject = 'Message subject'
mail.Body = 'Message body'
mail.HTMLBody = '<h2>HTML Message body</h2>' #this field is optional

# To attach a file to the email (optional):
attachment  = "Path to the attachment"
mail.Attachments.Add(attachment)

mail.Send()

Will use your local outlook account to send.

Note if you are trying to do something not mentioned above, look at the COM docs properties/methods: https://msdn.microsoft.com/en-us/vba/outlook-vba/articles/mailitem-object-outlook. In the code above, mail is a MailItem Object.

Best way to simulate "group by" from bash?

sort ip_addresses | uniq -c

This will print the count first, but other than that it should be exactly what you want.

Access Database opens as read only

The main reason for this is when the database is open somewhere else.

This could be as already said by many others:

  • not being closed properly somewhere
  • already open somewhere

When recently I had the same problem although different versions, I started to search for the reason.

In my case I had an excel file that queried data from the database.

In case the excel file is opened before the database, access would give this error.

Conclusion:

Check all files/connections related to the database. An open ODBC connection or query used in excel (my case) open the mdb file and will make it readonly.

How to set value of input text using jQuery

$(document).ready(function () {
    $('#EmployeeId').val("fgg");

    //Or
    $('.textBoxEmployeeNumber > input').val("fgg");

    //Or
    $('.textBoxEmployeeNumber').find('input').val("fgg");
});

How to get all registered routes in Express?

app._router.stack.forEach(function(r){
  if (r.route && r.route.path){
    console.log(r.route.path)
  }
})

Automatically creating directories with file output

The os.makedirs function does this. Try the following:

import os
import errno

filename = "/foo/bar/baz.txt"
if not os.path.exists(os.path.dirname(filename)):
    try:
        os.makedirs(os.path.dirname(filename))
    except OSError as exc: # Guard against race condition
        if exc.errno != errno.EEXIST:
            raise

with open(filename, "w") as f:
    f.write("FOOBAR")

The reason to add the try-except block is to handle the case when the directory was created between the os.path.exists and the os.makedirs calls, so that to protect us from race conditions.


In Python 3.2+, there is a more elegant way that avoids the race condition above:

import os

filename = "/foo/bar/baz.txt"
os.makedirs(os.path.dirname(filename), exist_ok=True)
with open(filename, "w") as f:
    f.write("FOOBAR")

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

I know this is an old post, but a good time to use PrimaryKeyColumn would be if you wanted a unidirectional relationship or had multiple tables all sharing the same id.

In general this is a bad idea and it would be better to use foreign key relationships with JoinColumn.

Having said that, if you are working on an older database that used a system like this then that would be a good time to use it.

Read a file in Node.js

var fs = require('fs');
var path = require('path');

exports.testDir = path.dirname(__filename);
exports.fixturesDir = path.join(exports.testDir, 'fixtures');
exports.libDir = path.join(exports.testDir, '../lib');
exports.tmpDir = path.join(exports.testDir, 'tmp');
exports.PORT = +process.env.NODE_COMMON_PORT || 12346;

// Read File
fs.readFile(exports.tmpDir+'/start.html', 'utf-8', function(err, content) {
  if (err) {
    got_error = true;
  } else {
    console.log('cat returned some content: ' + content);
    console.log('this shouldn\'t happen as the file doesn\'t exist...');
    //assert.equal(true, false);
  }
});

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

What is the best way to know if all the variables in a Class are null?

The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isNull() {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                Object value = f.get(this);
                if (value != null) {
                    return false;
                }
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return true;

    }

    public static void main(String args[]) {
        System.out.println(new User().isNull());
    }
}

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

If you need performance, then you must test on your environment. No other way.

Here example code:

int tmp = 0;
String s = new String(new byte[64*1024]);
{
    long st = System.nanoTime();
    for(int i = 0, n = s.length(); i < n; i++) {
        tmp += s.charAt(i);
    }
    st = System.nanoTime() - st;
    System.out.println("1 " + st);
}

{
    long st = System.nanoTime();
    char[] ch = s.toCharArray();
    for(int i = 0, n = ch.length; i < n; i++) {
        tmp += ch[i];
    }
    st = System.nanoTime() - st;
    System.out.println("2 " + st);
}
{
    long st = System.nanoTime();
    for(char c : s.toCharArray()) {
        tmp += c;
    }
    st = System.nanoTime() - st;
    System.out.println("3 " + st);
}
System.out.println("" + tmp);

On Java online I get:

1 10349420
2 526130
3 484200
0

On Android x86 API 17 I get:

1 9122107
2 13486911
3 12700778
0

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

It means the object you are trying to access None. None is a Null variable in python. This type of error is occure de to your code is something like this.

x1 = None
print(x1.something)

#or

x1 = None
x1.someother = "Hellow world"

#or
x1 = None
x1.some_func()

# you can avoid some of these error by adding this kind of check
if(x1 is not None):
    ... Do something here
else:
    print("X1 variable is Null or None")

Unable to load Private Key. (PEM routines:PEM_read_bio:no start line:pem_lib.c:648:Expecting: ANY PRIVATE KEY)

Create CA certificate

openssl genrsa -out privateKey.pem 4096
openssl req -new -x509 -nodes -days 3600 -key privateKey.pem -out caKey.pem

How do I check to see if my array includes an object?

If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

unless @suggested_horses.any? {|h| h.id == horse.id }
  @suggested_horses << horse
end

How to show progress bar while loading, using ajax

I did it like this

CSS

html {
    -webkit-transition: background-color 1s;
    transition: background-color 1s;
}
html, body {
    /* For the loading indicator to be vertically centered ensure */
    /* the html and body elements take up the full viewport */
    min-height: 100%;
}
html.loading {
    /* Replace #333 with the background-color of your choice */
    /* Replace loading.gif with the loading image of your choice */
    background: #333 url('/Images/loading.gif') no-repeat 50% 50%;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: background-color 0;
    transition: background-color 0;
}
body {
    -webkit-transition: opacity 1s ease-in;
    transition: opacity 1s ease-in;
}
html.loading body {
    /* Make the contents of the body opaque during loading */
    opacity: 0;

    /* Ensures that the transition only runs in one direction */
    -webkit-transition: opacity 0;
    transition: opacity 0;
}

JS

$(document).ready(function () {
   $(document).ajaxStart(function () {     
       $("html").addClass("loading");
    });
    $(document).ajaxStop(function () {        
        $("html").removeClass("loading");
    });
    $(document).ajaxError(function () {       
        $("html").removeClass("loading");
    }); 
});