Programs & Examples On #Pypy

PyPy is a fast, very compliant, self-hosting implementation of the Python language.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

Because pypy is not 100% compatible, takes 8 gigs of ram to compile, is a moving target, and highly experimental, where cpython is stable, the default target for module builders for 2 decades (including c extensions that don't work on pypy), and already widely deployed.

Pypy will likely never be the reference implementation, but it is a good tool to have.

Find integer index of rows with NaN in pandas dataframe

And just in case, if you want to find the coordinates of 'nan' for all the columns instead (supposing they are all numericals), here you go:

df = pd.DataFrame([[0,1,3,4,np.nan,2],[3,5,6,np.nan,3,3]])

df
   0  1  2    3    4  5
0  0  1  3  4.0  NaN  2
1  3  5  6  NaN  3.0  3

np.where(np.asanyarray(np.isnan(df)))
(array([0, 1]), array([4, 3]))

How to list records with date from the last 10 days?

I would check datatypes.

current_date has "date" datatype, 10 is a number, and Table.date - you need to look at your table.

Determine if 2 lists have the same elements, regardless of order?

Determine if 2 lists have the same elements, regardless of order?

Inferring from your example:

x = ['a', 'b']
y = ['b', 'a']

that the elements of the lists won't be repeated (they are unique) as well as hashable (which strings and other certain immutable python objects are), the most direct and computationally efficient answer uses Python's builtin sets, (which are semantically like mathematical sets you may have learned about in school).

set(x) == set(y) # prefer this if elements are hashable

In the case that the elements are hashable, but non-unique, the collections.Counter also works semantically as a multiset, but it is far slower:

from collections import Counter
Counter(x) == Counter(y)

Prefer to use sorted:

sorted(x) == sorted(y) 

if the elements are orderable. This would account for non-unique or non-hashable circumstances, but this could be much slower than using sets.

Empirical Experiment

An empirical experiment concludes that one should prefer set, then sorted. Only opt for Counter if you need other things like counts or further usage as a multiset.

First setup:

import timeit
import random
from collections import Counter

data = [str(random.randint(0, 100000)) for i in xrange(100)]
data2 = data[:]     # copy the list into a new one

def sets_equal(): 
    return set(data) == set(data2)

def counters_equal(): 
    return Counter(data) == Counter(data2)

def sorted_lists_equal(): 
    return sorted(data) == sorted(data2)

And testing:

>>> min(timeit.repeat(sets_equal))
13.976069927215576
>>> min(timeit.repeat(counters_equal))
73.17287588119507
>>> min(timeit.repeat(sorted_lists_equal))
36.177085876464844

So we see that comparing sets is the fastest solution, and comparing sorted lists is second fastest.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

Your method implementation is ambiguous, try the following , edited your code a little bit and used HttpStatus.NO_CONTENT i.e 204 No Content as in place of HttpStatus.OK

The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation. The response MAY include new or updated metainformation in the form of entity-headers, which if present SHOULD be associated with the requested variant.

Any value of T will be ignored for 204, but not for 404

  public ResponseEntity<?> taxonomyPackageExists( @PathVariable final String key ) {
            LOG.debug( "taxonomyPackageExists queried with key: {0}", key ); //$NON-NLS-1$
            final TaxonomyKey taxonomyKey = TaxonomyKey.fromString( key );
            LOG.debug( "Taxonomy key created: {0}", taxonomyKey ); //$NON-NLS-1$

            if ( this.xbrlInstanceValidator.taxonomyPackageExists( taxonomyKey ) ) {
                LOG.debug( "Taxonomy package with key: {0} exists.", taxonomyKey ); //$NON-NLS-1$
                 return new ResponseEntity<T>(HttpStatus.NO_CONTENT);
            } else {
               LOG.debug( "Taxonomy package with key: {0} does NOT exist.", taxonomyKey ); //$NON-NLS-1$
                return new ResponseEntity<T>( HttpStatus.NOT_FOUND );
            }

    }

How do I get cURL to not show the progress bar?

In curl version 7.22.0 on Ubuntu and 7.24.0 on OSX the solution to not show progress but to show errors is to use both -s (--silent) and -S (--show-error) like so:

curl -sS http://google.com > temp.html

This works for both redirected output > /some/file, piped output | less and outputting directly to the terminal for me.

Update: Since curl 7.67.0 there is a new option --no-progress-meter which does precisely this and nothing else, see clonejo's answer for more details.

How to get file size in Java

Did a quick google. Seems that to find the file size you do this,

long size = f.length();

The differences between the three methods you posted can be found here

getFreeSpace() and getTotalSpace() are pretty self explanatory, getUsableSpace() seems to be the space that the JVM can use, which in most cases will be the same as the amount of free space.

Only local connections are allowed Chrome and Selenium webdriver

First off, What you are seeing is not an error. It is an informational message.

When you run this driver, it will enable your scripts to access this and run commands on Google Chrome.

This can be done via scripts running in the local network (Only local connections are allowed.) or via scripts running on outside networks (All remote connections are allowed.). It is always safer to use the Local Connection option. By default your Chromedriver is accessible via port 9515.

See this answer if you wish to allow all connections instead of just local.


If your Chromedriver only shows the above two messages (as per the question), then there is a problem. It has to show a message like this, which says it started successfully.

Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully.

To troubleshoot this...

Step 1: Check your Chromedriver version

$ chromedriver --version

ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416})

My version is 83.0.4103.39.

Step 2: Check your Chrome Browser version

Open Google Chrome.

Options --> Help --> About Google Chrome

enter image description here

Or open a terminal and run the following command (works on Ubuntu).

$ google-chrome --version

Google Chrome 83.0.4103.61

My version is: Version 83.0.4103.61

Step 3: Compare versions of Chromedriver and Google Chrome

Both these versions are starting with 83, which means they are both compatible. Hence, you should see a message like below, when you run the below command.

$ chromedriver 

Starting ChromeDriver 83.0.4103.39 (ccbf011cb2d2b19b506d844400483861342c20cd-refs/branch-heads/4103@{#416}) on port 9515
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
ChromeDriver was started successfully. 

If your versions mismatch, then you will see the following message. You will not see the line which says, ChromeDriver was started successfully..

$ chromedriver

Starting ChromeDriver 80.0.3987.106 (f68069574609230cf9b635cd784cfb1bf81bb53a-refs/branch-heads/3987@{#882}) on port 9515
Only local connections are allowed.
Please protect ports used by ChromeDriver and related test frameworks to prevent access by malicious code.

Step 4: Download the correct version of Chromedriver

Download the correct version that matches your browser version. Use this page for downloads. After you download, extract the content, and move it to one of the following two folders. Open each of the following two folders and see whether your current Chromedriver is there. If it is on both folders, replace both. And do STEP 3 again.

/usr/bin/chromedriver
/usr/local/bin/chromedriver

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@RequestMapping is a class level

@GetMapping is a method-level

With sprint Spring 4.3. and up things have changed. Now you can use @GetMapping on the method that will handle the http request. The class-level @RequestMapping specification is refined with the (method-level)@GetMapping annotation

Here is an example:

@Slf4j
@Controller
@RequestMapping("/orders")/* The @Request-Mapping annotation, when applied
                            at the class level, specifies the kind of requests 
                            that this controller handles*/  

public class OrderController {

@GetMapping("/current")/*@GetMapping paired with the classlevel
                        @RequestMapping, specifies that when an 
                        HTTP GET request is received for /order, 
                        orderForm() will be called to handle the request..*/

public String orderForm(Model model) {

model.addAttribute("order", new Order());

return "orderForm";
}
}

Prior to Spring 4.3, it was @RequestMapping(method=RequestMethod.GET)

Extra reading from a book authored by Craig Walls Extra reading from a book authored by Craig Walls

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

You're probably missing some dependencies.

Locate the dependencies you're missing with mvn dependency:tree, then install them manually, and build your project with the -o (offline) option.

How to force a view refresh without having it trigger automatically from an observable?

In some circumstances it might be useful to simply remove the bindings and then re-apply:

ko.cleanNode(document.getElementById(element_id))
ko.applyBindings(viewModel, document.getElementById(element_id))

referenced before assignment error in python

def inside():
   global var
   var = 'info'
inside()
print(var)

>>>'info'

problem ended

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

dt = dt.AsEnumerable().GroupBy(r => r.Field<int>("ID")).Select(g => g.First()).CopyToDataTable();

Traversing text in Insert mode

Sorry but vim don't work that way.

You should switch to "normal" mode, navigate and then go back to insert again.

How to change default format at created_at and updated_at value laravel

Laravel 4.x and 5.0

To change the time in the database use: http://laravel.com/docs/4.2/eloquent#timestamps

Providing A Custom Timestamp Format

If you wish to customize the format of your timestamps, you may override the getDateFormat method in your model:

class User extends Eloquent {

    protected function getDateFormat()
    {
        return 'U';
    }

}

Laravel 5.1+

https://laravel.com/docs/5.1/eloquent

If you need to customize the format of your timestamps, set the $dateFormat property on your model. This property determines how date attributes are stored in the database, as well as their format when the model is serialized to an array or JSON:

class Flight extends Model
{
    /**
     * The storage format of the model's date columns.
     *
     * @var string
     */
    protected $dateFormat = 'U';
}

Can I embed a .png image into an html page?

The 64base method works for large images as well, I use that method to embed all the images into my website, and it works every time. I've done with files up to 2Mb size, jpg and png.

How to split one string into multiple strings separated by at least one space in bash shell?

Just use the shells "set" built-in. For example,

set $text

After that, individual words in $text will be in $1, $2, $3, etc. For robustness, one usually does

set -- junk $text
shift

to handle the case where $text is empty or start with a dash. For example:

text="This is          a              test"
set -- junk $text
shift
for word; do
  echo "[$word]"
done

This prints

[This]
[is]
[a]
[test]

How can I get a web site's favicon?

You'll want to tackle this a few ways:

  1. Look for the favicon.ico at the root of the domain

    www.domain.com/favicon.ico

  2. Look for a <link> tag with the rel="shortcut icon" attribute

    <link rel="shortcut icon" href="/favicon.ico" />

  3. Look for a <link> tag with the rel="icon" attribute

    <link rel="icon" href="/favicon.png" />

The latter two will usually yield a higher quality image.


Just to cover all of the bases, there are device specific icon files that might yield higher quality images since these devices usually have larger icons on the device than a browser would need:

<link rel="apple-touch-icon" href="images/touch.png" />

<link rel="apple-touch-icon-precomposed" href="images/touch.png" />


And to download the icon without caring what the icon is you can use a utility like http://www.google.com/s2/favicons which will do all of the heavy lifting:

var client = new System.Net.WebClient();

client.DownloadFile(
    @"http://www.google.com/s2/favicons?domain=stackoverflow.com",
    "stackoverflow.com.ico");

LINQ: combining join and group by

I met the same problem as you.

I push two tables result into t1 object and group t1.

 from p in Products                         
  join bp in BaseProducts on p.BaseProductId equals bp.Id
  select new {
   p,
   bp
  } into t1
 group t1 by t1.p.SomeId into g
 select new ProductPriceMinMax { 
  SomeId = g.FirstOrDefault().p.SomeId, 
  CountryCode = g.FirstOrDefault().p.CountryCode, 
  MinPrice = g.Min(m => m.bp.Price), 
  MaxPrice = g.Max(m => m.bp.Price),
  BaseProductName = g.FirstOrDefault().bp.Name
};

How to clear textarea on click?

<textarea onClick="javascript: this.value='';">Please describe why</textarea>

How can I write data in YAML format in a file?

import yaml

data = dict(
    A = 'a',
    B = dict(
        C = 'c',
        D = 'd',
        E = 'e',
    )
)

with open('data.yml', 'w') as outfile:
    yaml.dump(data, outfile, default_flow_style=False)

The default_flow_style=False parameter is necessary to produce the format you want (flow style), otherwise for nested collections it produces block style:

A: a
B: {C: c, D: d, E: e}

OWIN Security - How to Implement OAuth2 Refresh Tokens

Freddy's answer helped me a lot to get this working. For the sake of completeness here's how you could implement hashing of the token:

private string ComputeHash(Guid input)
{
    byte[] source = input.ToByteArray();

    var encoder = new SHA256Managed();
    byte[] encoded = encoder.ComputeHash(source);

    return Convert.ToBase64String(encoded);
}

In CreateAsync:

var guid = Guid.NewGuid();
...
_refreshTokens.TryAdd(ComputeHash(guid), refreshTokenTicket);
context.SetToken(guid.ToString());

ReceiveAsync:

public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
    Guid token;

    if (Guid.TryParse(context.Token, out token))
    {
        AuthenticationTicket ticket;

        if (_refreshTokens.TryRemove(ComputeHash(token), out ticket))
        {
            context.SetTicket(ticket);
        }
    }
}

Call to a member function fetch_assoc() on boolean in <path>

This error happen usually when tables in the query doesn't exist. Just check the table's spelling in the query, and it will work.

Using Server.MapPath in external C# Classes in ASP.NET

class test
{
public static void useServerPath(string path)
{
   if (File.Exists(path)
{
 \\...... do whatever you wabt
}
else
{
\\.....
}
}

Now when you call the method from the codebehind

for example :

protected void BtAtualizacao_Click(object sender, EventArgs e)
        {
             string path = Server.MapPath("Folder") + "\\anifile.txt";

            test.useServerPath(path);
}

in this way your code is to simple and with one method u can use multiple path for each call :)

Show a popup/message box from a Windows batch file

You can use Zenity. Zenity allows for the execution of dialog boxes in command-line and shell scripts. More info can also be found on Wikipedia.

It is cross-platform: a Windows installer for Windows can be found here.

Get day of week in SQL Server 2005/2008

You may find this version usefull.

-- Test DATA
select @@datefirst
create table #test (datum datetime)
insert #test values ('2013-01-01')
insert #test values ('2013-01-02')
insert #test values ('2013-01-03')
insert #test values ('2013-01-04')
insert #test values ('2013-01-05')
insert #test values ('2013-01-06')
insert #test values ('2013-01-07')
insert #test values ('2013-01-08')
-- Test DATA

select  Substring('Sun,Mon,Tue,Wed,Thu,Fri,Sat,Sun,Mon,Tue,Wed,Thu,Fri,Sat',
        (DATEPART(WEEKDAY,datum)+@@datefirst-1)*4+1,3),Datum
        from #test 

Pandas percentage of total with groupby

I realize there are already good answers here.

I nevertheless would like to contribute my own, because I feel for an elementary, simple question like this, there should be a short solution that is understandable at a glance.

It should also work in a way that I can add the percentages as a new column, leaving the rest of the dataframe untouched. Last but not least, it should generalize in an obvious way to the case in which there is more than one grouping level (e.g., state and country instead of only state).

The following snippet fulfills these criteria:

df['sales_ratio'] = df.groupby(['state'])['sales'].transform(lambda x: x/x.sum())

Note that if you're still using Python 2, you'll have to replace the x in the denominator of the lambda term by float(x).

How does ifstream's eof() work?

The EOF flag is only set after a read operation attempts to read past the end of the file. get() is returning the symbolic constant traits::eof() (which just happens to equal -1) because it reached the end of the file and could not read any more data, and only at that point will eof() be true. If you want to check for this condition, you can do something like the following:

int ch;
while ((ch = inf.get()) != EOF) {
    std::cout << static_cast<char>(ch) << "\n";
}

How to Round to the nearest whole number in C#

You need Math.Round, not Math.Ceiling. Ceiling always "rounds" up, while Round rounds up or down depending on the value after the decimal point.

How to set fake GPS location on IOS real device

it seems with XCode 9.2 the way to import .gpx has changed, I tried the ways described here and did not do. The only way worked for me was to drag and drop the file .gpx to the project navigator window on the left. Then I can choose the country in the simulator item.

Hope this helps to someone.

How to run only one unit test class using Gradle

Run a single test called MyTest:

./gradlew app:testDebug --tests=com.example.MyTest

Open directory using C

Here is a simple way to implement ls command using c. To run use for example ./xls /tmp

    #include<stdio.h>
    #include <dirent.h>
    void main(int argc,char *argv[])
    {
   DIR *dir;
   struct dirent *dent;
   dir = opendir(argv[1]);   

   if(dir!=NULL)
      {
   while((dent=readdir(dir))!=NULL)
                    {
        if((strcmp(dent->d_name,".")==0 || strcmp(dent->d_name,"..")==0 || (*dent->d_name) == '.' ))
            {
            }
       else
              {
        printf(dent->d_name);
        printf("\n");
              }
                    }
       }
       close(dir);
     }

In Gradle, is there a better way to get Environment Variables?

I couldn't get the form suggested by @thoredge to work in Gradle 1.11, but this works for me:

home = System.getenv('HOME')

It helps to keep in mind that anything that works in pure Java will work in Gradle too.

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

Git conflict markers

The line (or lines) between the lines beginning <<<<<<< and ====== here:

<<<<<<< HEAD:file.txt
Hello world
=======

... is what you already had locally - you can tell because HEAD points to your current branch or commit. The line (or lines) between the lines beginning ======= and >>>>>>>:

=======
Goodbye
>>>>>>> 77976da35a11db4580b80ae27e8d65caf5208086:file.txt

... is what was introduced by the other (pulled) commit, in this case 77976da35a11. That is the object name (or "hash", "SHA1sum", etc.) of the commit that was merged into HEAD. All objects in git, whether they're commits (version), blobs (files), trees (directories) or tags have such an object name, which identifies them uniquely based on their content.

How can I pair socks from a pile efficiently?

Here's an Omega(n log n) lower bound in comparison based model. (The only valid operation is comparing two socks.)

Suppose that you know that your 2n socks are arranged this way:

p1 p2 p3 ... pn pf(1) pf(2) ... pf(n)

where f is an unknown permutation of the set {1,2,...,n}. Knowing this cannot make the problem harder. There are n! possible outputs (matchings between first and second half), which means you need log(n!) = Omega(n log n) comparisons. This is obtainable by sorting.

Since you are interested in connections to element distinctness problem: proving the Omega(n log n) bound for element distinctness is harder, because the output is binary yes/no. Here, the output has to be a matching and the number of possible outputs suffices to get a decent bound. However, there's a variant connected to element distinctness. Suppose you are given 2n socks and wonder if they can be uniquely paired. You can get a reduction from ED by sending (a1, a2, ..., an) to (a1, a1, a2, a2, ..., an, an). (Parenthetically, the proof of hardness of ED is very interesting, via topology.)

I think that there should be an Omega(n2) bound for the original problem if you allow equality tests only. My intuition is: Consider a graph where you add an edge after a test, and argue that if the graph is not dense the output is not uniquely determined.

Proper usage of .net MVC Html.CheckBoxFor

I had trouble getting this to work and added another solution for anyone wanting/ needing to use FromCollection.

Instead of:

@Html.CheckBoxFor(model => true, item.TemplateId) 

Format html helper like so:

@Html.CheckBoxFor(model => model.SomeProperty, new { @class = "form-control", Name = "SomeProperty"})

Then in the viewmodel/model wherever your logic is:

public void Save(FormCollection frm)
{   
    // to do instantiate object.

    instantiatedItem.SomeProperty = (frm["SomeProperty"] ?? "").Equals("true", StringComparison.CurrentCultureIgnoreCase);

    // to do and save changes in database.
}

jQuery append() vs appendChild()

The JavaScript appendchild method can be use to append an item to another element. The jQuery Append element does the same work but certainly in less number of lines:

Let us take an example to Append an item in a list:

a) With JavaScript

var n= document.createElement("LI");                 // Create a <li> node
var tn = document.createTextNode("JavaScript");      // Create a text node
n.appendChild(tn);                                   // Append the text to <li>
document.getElementById("myList").appendChild(n);  

b) With jQuery

$("#myList").append("<li>jQuery</li>")

TypeError: 'builtin_function_or_method' object is not subscriptable

Can't believe this thread was going on for so long. You would get this error if you got distracted and used [] instead of (), at least my case.

Pop is a method on the list data type, https://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Therefore, you shouldn't be using pop as if it was a list itself, pop[0]. It's a method that takes an optional parameter representing an index, so as Tushar Palawat pointed out in one of the answers that didn't get approved, the correct adjustment which will fix the example above is:

listb.pop(0)

If you don't believe, run a sample such as:

if __name__ == '__main__':
  listb = ["-test"]
  if( listb[0] == "-test"):
    print(listb.pop(0))

Other adjustments would work as well, but it feels as they are abusing the Python language. This thread needs to get fixed, not to confuse users.

Addition, a.pop() removes and returns the last item in the list. As a result, a.pop()[0] will get the first character of that last element. It doesn't seem that is what the given code snippet is aiming to achieve.

JavaScript: How do I print a message to the error console?

The WebKit Web Inspector also supports Firebug's console API (just a minor addition to Dan's answer).

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

SQL, How to convert VARCHAR to bigint?

I think your code is right. If you run the following code it converts the string '60' which is treated as varchar and it returns integer 60, if there is integer containing string in second it works.

select CONVERT(bigint,'60') as seconds 

and it returns

60

How can I convert String to Int?

You can convert string to an integer value with the help of parse method.

Eg:

int val = Int32.parse(stringToBeParsed);
int x = Int32.parse(1234);

Set focus and cursor to end of text input field / string w. Jquery

You can do this using Input.setSelectionRange, part of the Range API for interacting with text selections and the text cursor:

var searchInput = $('#Search');

// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;

searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);

Demo: Fiddle

Gradle, Android and the ANDROID_HOME SDK location

I've solved the problem. This works for me:

In

/my_current_project/

I've created a file called local.properties and put inside

sdk.dir=/my_current_path_to/sdk

In the console I need to do

set ANDROID_HOME=/my_current_path_to/sdk

Hope this helps.

check if a std::vector contains a certain object?

Checking if v contains the element x:

#include <algorithm>

if(std::find(v.begin(), v.end(), x) != v.end()) {
    /* v contains x */
} else {
    /* v does not contain x */
}

Checking if v contains elements (is non-empty):

if(!v.empty()){
    /* v is non-empty */
} else {
    /* v is empty */
}

Vue.js get selected option on @change

The changed value will be in event.target.value

_x000D_
_x000D_
const app = new Vue({_x000D_
  el: "#app",_x000D_
  data: function() {_x000D_
    return {_x000D_
      message: "Vue"_x000D_
    }_x000D_
  },_x000D_
  methods: {_x000D_
    onChange(event) {_x000D_
      console.log(event.target.value);_x000D_
    }_x000D_
  }_x000D_
})
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <select name="LeaveType" @change="onChange" class="form-control">_x000D_
   <option value="1">Annual Leave/ Off-Day</option>_x000D_
   <option value="2">On Demand Leave</option>_x000D_
</select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dictionary text file

@Future-searchers: you can use aspell to do the dictionary checks, it has bindings in ruby and python. It would make your job much simpler.

How to make a hyperlink in telegram without using bots?

My phone is xiaomi Redmi note 8 with MIUI 11.0.9 . There is no option for create hyperlink :enter image description here So I use Telegram desktop or Telegram X for create hyperlink because Telegram X supports markdown. Type url and send message (in Telegram X) or there is an alternate way which is the easiest!

Select the text using Xiaomi's Word Editor and click in the three dots on the top right corner of the chat. It is usually used for accessing settings but if you select a text and click there, you can see Telegram's own Formatter!

Differences between hard real-time, soft real-time, and firm real-time?

The definition has expanded over the years to the detriment of the term. What is now called "Hard" real-time is what used to be simply called real-time. So systems in which missing timing windows (rather than single-sided time deadlines) would result incorrect data or incorrect behavior should be consider real-time. Systems without that characteristic would be considered non-real-time.

That's not to say that time isn't of interest in non-real-time systems, it just means that timing requirements in such systems don't result in fundamentally incorrect results.

Remove a prefix from a string

What about this (a bit late):

def remove_prefix(s, prefix):
    return s[len(prefix):] if s.startswith(prefix) else s

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

Try something like this:

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

How to remove all callbacks from a Handler?

If you don't have the Runnable references, on the first callback, get the obj of the message, and use removeCallbacksAndMessages() to remove all related callbacks.

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

Store mysql query output into a shell variable

You have the pipe the other way around and you need to echo the query, like this:

myvariable=$(echo "SELECT A, B, C FROM table_a" | mysql db -u $user -p $password)

Another alternative is to use only the mysql client, like this

myvariable=$(mysql db -u $user -p $password -se "SELECT A, B, C FROM table_a")

(-s is required to avoid the ASCII-art)

Now, BASH isn't the most appropriate language to handle this type of scenarios, especially handling strings and splitting SQL results and the like. You have to work a lot to get things that would be very, very simple in Perl, Python or PHP.

For example, how will you get each of A, B and C on their own variable? It's certainly doable, but if you do not understand pipes and echo (very basic shell stuff), it will not be an easy task for you to do, so if at all possible I'd use a better suited language.

Laravel Checking If a Record Exists

In your Controller

$this->validate($request, [
        'email' => 'required|unique:user|email',
    ]); 

In your View - Display Already Exist Message

@if (count($errors) > 0)
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

Conditional logic in AngularJS template

You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?

<div class="from" ng-show="message.from">From: {{message.from.name}}</div>

Android Room - simple select query - Cannot access database on the main thread

For all the RxJava or RxAndroid or RxKotlin lovers out there

Observable.just(db)
          .subscribeOn(Schedulers.io())
          .subscribe { db -> // database operation }

Finding multiple occurrences of a string within a string in Python

Here is my function for finding multiple occurrences. Unlike the other solutions here, it supports the optional start and end parameters for slicing, just like str.index:

def all_substring_indexes(string, substring, start=0, end=None):
    result = []
    new_start = start
    while True:
        try:
            index = string.index(substring, new_start, end)
        except ValueError:
            return result
        else:
            result.append(index)
            new_start = index + len(substring)

Finding local maxima/minima with Numpy in a 1D numpy array

As of SciPy version 1.1, you can also use find_peaks. Below are two examples taken from the documentation itself.

Using the height argument, one can select all maxima above a certain threshold (in this example, all non-negative maxima; this can be very useful if one has to deal with a noisy baseline; if you want to find minima, just multiply you input by -1):

import matplotlib.pyplot as plt
from scipy.misc import electrocardiogram
from scipy.signal import find_peaks
import numpy as np

x = electrocardiogram()[2000:4000]
peaks, _ = find_peaks(x, height=0)
plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.plot(np.zeros_like(x), "--", color="gray")
plt.show()

enter image description here

Another extremely helpful argument is distance, which defines the minimum distance between two peaks:

peaks, _ = find_peaks(x, distance=150)
# difference between peaks is >= 150
print(np.diff(peaks))
# prints [186 180 177 171 177 169 167 164 158 162 172]

plt.plot(x)
plt.plot(peaks, x[peaks], "x")
plt.show()

enter image description here

How to kill a thread instantly in C#?

You can kill instantly doing it in that way:

private Thread _myThread = new Thread(SomeThreadMethod);

private void SomeThreadMethod()
{
   // do whatever you want
}

[SecurityPermissionAttribute(SecurityAction.Demand, ControlThread = true)]
private void KillTheThread()
{
   _myThread.Abort();
}

I always use it and works for me:)

How to make a 3D scatter plot in Python?

You can use matplotlib for this. matplotlib has a mplot3d module that will do exactly what you want.

from matplotlib import pyplot
from mpl_toolkits.mplot3d import Axes3D
import random


fig = pyplot.figure()
ax = Axes3D(fig)

sequence_containing_x_vals = list(range(0, 100))
sequence_containing_y_vals = list(range(0, 100))
sequence_containing_z_vals = list(range(0, 100))

random.shuffle(sequence_containing_x_vals)
random.shuffle(sequence_containing_y_vals)
random.shuffle(sequence_containing_z_vals)

ax.scatter(sequence_containing_x_vals, sequence_containing_y_vals, sequence_containing_z_vals)
pyplot.show()

The code above generates a figure like:

matplotlib 3D image

How to convert string to float?

Unfortunately, there is no way to do this easily. Every solution has its drawbacks.

  1. Use atof() or strtof() directly: this is what most people will tell you to do and it will work most of the time. However, if the program sets a locale or it uses a library that sets the locale (for instance, a graphics library that displays localised menus) and the user has their locale set to a language where the decimal separator is not . (such as fr_FR where the separator is ,) these functions will stop parsing at the . and you will stil get 4.0.

  2. Use atof() or strtof() but change the locale; it's a matter of calling setlocale(LC_ALL|~LC_NUMERIC, ""); before any call to atof() or the likes. The problem with setlocale is that it will be global to the process and you might interfer with the rest of the program. Note that you might query the current locale with setlocale() and restore it after you're done.

  3. Write your own float parsing routine. This might be quite quick if you do not need advanced features such as exponent parsing or hexadecimal floats.

Also, note that the value 4.08 cannot be represented exactly as a float; the actual value you will get is 4.0799999237060546875.

Count number of occurrences for each unique value

select time, coalesce(count(case when activities = 3 then 1 end), 0) as count
from MyTable
group by time

SQL Fiddle Example

Output:

|  TIME | COUNT |
-----------------
| 13:00 |     2 |
| 13:15 |     2 |
| 13:30 |     0 |
| 13:45 |     1 |

If you want to count all the activities in one query, you can do:

select time, 
    coalesce(count(case when activities = 1 then 1 end), 0) as count1,
    coalesce(count(case when activities = 2 then 1 end), 0) as count2,
    coalesce(count(case when activities = 3 then 1 end), 0) as count3,
    coalesce(count(case when activities = 4 then 1 end), 0) as count4,
    coalesce(count(case when activities = 5 then 1 end), 0) as count5
from MyTable
group by time

The advantage of this over grouping by activities, is that it will return a count of 0 even if there are no activites of that type for that time segment.

Of course, this will not return rows for time segments with no activities of any type. If you need that, you'll need to use a left join with table that lists all the possible time segments.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I had this exact error when building a VC++ DLL in Visual Studio 2019:

LNK1104: cannot open file 'C:\Program.obj'

Turned out under project Properties > Linker > Input > Module Definition File, I had specified a def file that had an unmatched double-quote at the end of the filename. Deleting the unmatched double quote resolved the issue.

Get specific line from text file using just shell script

sed:

sed '5!d' file

awk:

awk 'NR==5' file

TypeError: 'dict_keys' object does not support indexing

Why you need to implement shuffle when it already exists? Stay on the shoulders of giants.

import random

d1 = {0:'zero', 1:'one', 2:'two', 3:'three', 4:'four',
     5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine'}

keys = list(d1)
random.shuffle(keys)

d2 = {}
for key in keys: d2[key] = d1[key]

print(d1)
print(d2)

Why do package names often begin with "com"

It's just a namespace definition to avoid collision of class names. The com.domain.package.Class is an established Java convention wherein the namespace is qualified with the company domain in reverse.

Run cmd commands through Java

one of the way to execute cmd from java !

public void executeCmd() {
    String anyCommand="your command";
    try {
        Process process = Runtime.getRuntime().exec("cmd /c start cmd.exe /K " + anyCommand);

    } catch (IOException e) {
        e.printStackTrace();
    }
}

How do I hide certain files from the sidebar in Visual Studio Code?

The "Make Hidden" extension works great!

Make Hidden provides more control over your project's directory by enabling context menus that allow you to perform hide/show actions effortlessly, a view pane explorer to see hidden items and the ability to save workspaces to quickly toggle between bulk hidden items.

Sum up a column from a specific row down

=Sum(C:C)-Sum(C1:C5)

Sum everything then remove the sum of the values in the cells you don't want, no Volatile Offset's, Indirect's, or Array's needed.

Just for fun if you don't like that method you could also use:

=SUM($C$6:INDEX($C:$C,MATCH(9.99999999999999E+307,$C:$C))

The above formula will Sum only from C6 through the last cell in C:C where a match of a number is found. This is also non-volatile, but I believe more costly and sloppy. Just added it in case you'd prefer this anyways.

If you would like to do function like CountA for text using the last text value in a column you could use.

=COUNTIF(C6:INDEX($C:$C,MATCH(REPT("Z",255),$C:$C)),"T")

you could also use other combinations like:

=Sum($C$6:$C$65536) 

or

=CountIF($C$6:$C$65536,"T") 

The above would do what you ask in Excel 2003 and lower

=Sum($C$6:$C$1048576) 

or

=CountIF($C$6:$C$1048576,"T")

Would both work for Excel 2007+

All above functions would simply ignore all the blank values under the last value.

Implementing IDisposable correctly

I see a lot of examples of the Microsoft Dispose pattern which is really an anti-pattern. As many have pointed out the code in the question does not require IDisposable at all. But if you where going to implement it please don't use the Microsoft pattern. Better answer would be following the suggestions in this article:

https://www.codeproject.com/Articles/29534/IDisposable-What-Your-Mother-Never-Told-You-About

The only other thing that would likely be helpful is suppressing that code analysis warning... https://docs.microsoft.com/en-us/visualstudio/code-quality/in-source-suppression-overview?view=vs-2017

CSS submit button weird rendering on iPad/iPhone

Add this code into the css file:

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

This will help.

(13: Permission denied) while connecting to upstream:[nginx]

I’ve run into this problem too. Another solution is to toggle the SELinux boolean value for httpd network connect to on (Nginx uses the httpd label).

setsebool httpd_can_network_connect on

To make the change persist use the -P flag.

setsebool httpd_can_network_connect on -P

You can see a list of all available SELinux booleans for httpd using

getsebool -a | grep httpd

Group list by values

>>> xs = [["A",0], ["B",1], ["C",0], ["D",2], ["E",2]]
>>> xs.sort(key=lambda x: x[1])
>>> reduce(lambda l, x: (l.append([x]) if l[-1][0][1] != x[1] else l[-1].append(x)) or l, xs[1:], [[xs[0]]]) if xs else []
[[['A', 0], ['C', 0]], [['B', 1]], [['D', 2], ['E', 2]]]

Basically, if the list is sorted, it is possible to reduce by looking at the last group constructed by the previous steps - you can tell if you need to start a new group, or modify an existing group. The ... or l bit is a trick that enables us to use lambda in Python. (append returns None. It is always better to return something more useful than None, but, alas, such is Python.)

Python class returning value

If what you want is a way to turn your class into kind of a list without subclassing list, then just make a method that returns a list:

def MyClass():
    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def get_list(self):
        return [self.value1, self.value2...]


>>>print MyClass().get_list()
[1, 2...]

If you meant that print MyClass() will print a list, just override __repr__:

class MyClass():        
    def __init__(self):
        self.value1 = 1
        self.value2 = 2

    def __repr__(self):
        return repr([self.value1, self.value2])

EDIT: I see you meant how to make objects compare. For that, you override the __cmp__ method.

class MyClass():
    def __cmp__(self, other):
        return cmp(self.get_list(), other.get_list())

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

How to increase heap size for jBoss server

Look in your JBoss bin folder for the file run.bat (run.sh on Unix)

look for the line set JAVA_OPTS, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.

If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.

What does %~dp0 mean, and how does it work?

%~dp0 expands to current directory path of the running batch file.

To get clear understanding, let's create a batch file in a directory.

C:\script\test.bat

with contents:

@echo off
echo %~dp0

When you run it from command prompt, you will see this result:

C:\script\

Delete with "Join" in Oracle sql Query

Recently I learned of the following syntax:

DELETE (SELECT *
        FROM productfilters pf
        INNER JOIN product pr
            ON pf.productid = pr.id
        WHERE pf.id >= 200
            AND pr.NAME = 'MARK')

I think it looks much cleaner then other proposed code.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

Passing references to pointers in C++

Welcome to C++11 and rvalue references:

#include <cassert>
#include <string>

using std::string;

void myfunc(string*&& val)
{
    assert(&val);
    assert(val);
    assert(val->c_str());
    // Do stuff to the string pointer
}

// sometime later 
int main () {
    // ...
    string s;
    myfunc(&s);
    // ...
}

Now you have access to the value of the pointer (referred to by val), which is the address of the string.

You can modify the pointer, and no one will care. That is one aspect of what an rvalue is in the first place.

Be careful: The value of the pointer is only valid until myfunc() returns. At last, its a temporary.

Typescript: Type 'string | undefined' is not assignable to type 'string'

if you want to have nullable property change your interface to this:

interface Person {
  name?:string | null,
  age?:string | null,
  gender?:string | null,
  occupation?:string | null,
 }

if being undefined is not the case you can remove question marks (?) from in front of the property names.

How to programmatically tell if a Bluetooth device is connected?

BluetoothAdapter.getDefaultAdapter().isEnabled -> returns true when bluetooth is open

val audioManager = this.getSystemService(Context.AUDIO_SERVICE) as AudioManager

audioManager.isBluetoothScoOn -> returns true when device connected

What does jQuery.fn mean?

In jQuery, the fn property is just an alias to the prototype property.

The jQuery identifier (or $) is just a constructor function, and all instances created with it, inherit from the constructor's prototype.

A simple constructor function:

function Test() {
  this.a = 'a';
}
Test.prototype.b = 'b';

var test = new Test(); 
test.a; // "a", own property
test.b; // "b", inherited property

A simple structure that resembles the architecture of jQuery:

(function() {
  var foo = function(arg) { // core constructor
    // ensure to use the `new` operator
    if (!(this instanceof foo))
      return new foo(arg);
    // store an argument for this example
    this.myArg = arg;
    //..
  };

  // create `fn` alias to `prototype` property
  foo.fn = foo.prototype = {
    init: function () {/*...*/}
    //...
  };

  // expose the library
  window.foo = foo;
})();

// Extension:

foo.fn.myPlugin = function () {
  alert(this.myArg);
  return this; // return `this` for chainability
};

foo("bar").myPlugin(); // alerts "bar"

Notepad++ incrementally replace

I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.

In TextPad's replace dialog, turn on regex; then you could try replacing

<row id="1"/>

by

<row id="\i"/>

Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

Could not resolve this reference. Could not locate the assembly

Maybe it will help someone, but sometimes Name tag might be missing for a reference and it leads that assembly cannot be found when building with MSBuild. Make sure that Name tag is available for particular reference csproj file, for example,

    <ProjectReference Include="..\MyDependency1.csproj">
      <Project>{9A2D95B3-63B0-4D53-91F1-5EFB99B22FE8}</Project>
      <Name>MyDependency1</Name>
    </ProjectReference>

How to remove the first character of string in PHP?

Trims occurrences of every word in an array from the beginning and end of a string + whitespace and optionally extra single characters as per normal trim()

<?php
function trim_words($what, $words, $char_list = '') {
    if(!is_array($words)) return false;
    $char_list .= " \t\n\r\0\x0B"; // default trim chars
    $pattern = "(".implode("|", array_map('preg_quote', $words)).")\b";
    $str = trim(preg_replace('~'.$pattern.'$~i', '', preg_replace('~^'.$pattern.'~i', '', trim($what, $char_list))), $char_list);
    return $str;
}

// for example:
$trim_list = array('AND', 'OR');

$what = ' OR x = 1 AND b = 2 AND ';
print_r(trim_words($what, $trim_list)); // => "x = 1 AND b = 2"

$what = ' ORDER BY x DESC, b ASC, ';
print_r(trim_words($what, $trim_list, ',')); // => "ORDER BY x DESC, b ASC"
?>

force client disconnect from server with socket.io and nodejs

socket.disconnect() can be used only on the client side, not on the server side.

Client.emit('disconnect') triggers the disconnection event on the server, but does not effectively disconnect the client. The client is not aware of the disconnection.

So the question remain : how to force a client to disconnect from server side ?

What is the difference between :focus and :active?

Active is when the user activating that point (Like mouse clicking, if we use tab from field-to-field there is no sign from active style. Maybe clicking need more time, just try hold click on that point), focus is happened after the point is activated. Try this :

<style type="text/css">
  input { font-weight: normal; color: black; }
  input:focus { color: green; outline: 1px solid green; }
  input:active { color: red; outline: 1px solid red; }
</style>

<input type="text"/>
<input type="text"/>

how to assign a block of html code to a javascript variable

Modern Javascript implementations with the template syntax using backticks are also an easy way to assign an HTML block of code to a variable:

    const firstName = 'Sam';
    const fullName = 'Sam Smith';
    const htmlString = `<h1>Hello ${fullName}!</h1><p>This is some content \
        that will display. You can even inject your first name, ${firstName}, \
        in the code.</p><p><a href="http://www.google.com">Search</a> for \
        stuff on the Google website.</p>`;

how to insert datetime into the SQL Database table?

if you got actuall time in mind GETDATE() would be the function what you looking for

Why is processing a sorted array faster than processing an unsorted array?

One way to avoid branch prediction errors is to build a lookup table, and index it using the data. Stefan de Bruijn discussed that in his answer.

But in this case, we know values are in the range [0, 255] and we only care about values >= 128. That means we can easily extract a single bit that will tell us whether we want a value or not: by shifting the data to the right 7 bits, we are left with a 0 bit or a 1 bit, and we only want to add the value when we have a 1 bit. Let's call this bit the "decision bit".

By using the 0/1 value of the decision bit as an index into an array, we can make code that will be equally fast whether the data is sorted or not sorted. Our code will always add a value, but when the decision bit is 0, we will add the value somewhere we don't care about. Here's the code:

// Test
clock_t start = clock();
long long a[] = {0, 0};
long long sum;

for (unsigned i = 0; i < 100000; ++i)
{
    // Primary loop
    for (unsigned c = 0; c < arraySize; ++c)
    {
        int j = (data[c] >> 7);
        a[j] += data[c];
    }
}

double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;
sum = a[1];

This code wastes half of the adds but never has a branch prediction failure. It's tremendously faster on random data than the version with an actual if statement.

But in my testing, an explicit lookup table was slightly faster than this, probably because indexing into a lookup table was slightly faster than bit shifting. This shows how my code sets up and uses the lookup table (unimaginatively called lut for "LookUp Table" in the code). Here's the C++ code:

// Declare and then fill in the lookup table
int lut[256];
for (unsigned c = 0; c < 256; ++c)
    lut[c] = (c >= 128) ? c : 0;

// Use the lookup table after it is built
for (unsigned i = 0; i < 100000; ++i)
{
    // Primary loop
    for (unsigned c = 0; c < arraySize; ++c)
    {
        sum += lut[data[c]];
    }
}

In this case, the lookup table was only 256 bytes, so it fits nicely in a cache and all was fast. This technique wouldn't work well if the data was 24-bit values and we only wanted half of them... the lookup table would be far too big to be practical. On the other hand, we can combine the two techniques shown above: first shift the bits over, then index a lookup table. For a 24-bit value that we only want the top half value, we could potentially shift the data right by 12 bits, and be left with a 12-bit value for a table index. A 12-bit table index implies a table of 4096 values, which might be practical.

The technique of indexing into an array, instead of using an if statement, can be used for deciding which pointer to use. I saw a library that implemented binary trees, and instead of having two named pointers (pLeft and pRight or whatever) had a length-2 array of pointers and used the "decision bit" technique to decide which one to follow. For example, instead of:

if (x < node->value)
    node = node->pLeft;
else
    node = node->pRight;

this library would do something like:

i = (x < node->value);
node = node->link[i];

Here's a link to this code: Red Black Trees, Eternally Confuzzled

How to remove all elements in String array in java?

If example is not final then a simple reassignment would work:

example = new String[example.length];

This assumes you need the array to remain the same size. If that's not necessary then create an empty array:

example = new String[0];

If it is final then you could null out all the elements:

Arrays.fill( example, null );

Why Git is not allowing me to commit even after configuration?

You're setting the global git options, but the local checkout possibly has overrides set. Try setting them again with git config --local <setting> <value>. You can look at the .git/config file in your local checkout to see what local settings the checkout has defined.

What is the most elegant way to check if all values in a boolean array are true?

OK. This is the "most elegant" solution I could come up with on the fly:

boolean allTrue = !Arrays.toString(myArray).contains("f");

Hope that helps!

How do I determine whether my calculation of pi is accurate?

Undoubtedly, for your purposes (which I assume is just a programming exercise), the best thing is to check your results against any of the listings of the digits of pi on the web.

And how do we know that those values are correct? Well, I could say that there are computer-science-y ways to prove that an implementation of an algorithm is correct.

More pragmatically, if different people use different algorithms, and they all agree to (pick a number) a thousand (million, whatever) decimal places, that should give you a warm fuzzy feeling that they got it right.

Historically, William Shanks published pi to 707 decimal places in 1873. Poor guy, he made a mistake starting at the 528th decimal place.

Very interestingly, in 1995 an algorithm was published that had the property that would directly calculate the nth digit (base 16) of pi without having to calculate all the previous digits!

Finally, I hope your initial algorithm wasn't pi/4 = 1 - 1/3 + 1/5 - 1/7 + ... That may be the simplest to program, but it's also one of the slowest ways to do so. Check out the pi article on Wikipedia for faster approaches.

How to set the thumbnail image on HTML5 video?

Add poster="placeholder.png" to the video tag.

<video width="470" height="255" poster="placeholder.png" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.ogg" type="video/ogg">
    <source src="video.webm" type="video/webm">
    <object data="video.mp4" width="470" height="255">
    <embed src="video.swf" width="470" height="255">
    </object>
</video>

Does that work?

git cherry-pick says "...38c74d is a merge but no -m option was given"

Simplify. Cherry-pick the commits. Don't cherry-pick the merge.

Here's a rewrite of the accepted answer that ideally clarifies the advantages/risks of possible approaches:

You're trying to cherry pick fd9f578, which was a merge with two parents.

Instead of cherry-picking a merge, the simplest thing is to cherry pick the commit(s) you actually want from each branch in the merge.

Since you've already merged, it's likely all your desired commits are in your list. Cherry-pick them directly and you don't need to mess with the merge commit.

explanation

The way a cherry-pick works is by taking the diff that a changeset represents (the difference between the working tree at that point and the working tree of its parent), and applying the changeset to your current branch.

If a commit has two or more parents, as is the case with a merge, that commit also represents two or more diffs. The error occurs because of the uncertainty over which diff should apply.

alternatives

If you determine you need to include the merge vs cherry-picking the related commits, you have two options:

  1. (More complicated and obscure; also discards history) you can indicate which parent should apply.

    • Use the -m option to do so. For example, git cherry-pick -m 1 fd9f578 will use the first parent listed in the merge as the base.

    • Also consider that when you cherry-pick a merge commit, it collapses all the changes made in the parent you didn't specify to -m into that one commit. You lose all their history, and glom together all their diffs. Your call.

  2. (Simpler and more familiar; preserves history) you can use git merge instead of git cherry-pick.

    • As is usual with git merge, it will attempt to apply all commits that exist on the branch you are merging, and list them individually in your git log.

Types in MySQL: BigInt(20) vs Int(20)

See http://dev.mysql.com/doc/refman/8.0/en/numeric-types.html

  • INT is a four-byte signed integer.

  • BIGINT is an eight-byte signed integer.

They each accept no more and no fewer values than can be stored in their respective number of bytes. That means 232 values in an INT and 264 values in a BIGINT.

The 20 in INT(20) and BIGINT(20) means almost nothing. It's a hint for display width. It has nothing to do with storage, nor the range of values that column will accept.

Practically, it affects only the ZEROFILL option:

CREATE TABLE foo ( bar INT(20) ZEROFILL );
INSERT INTO foo (bar) VALUES (1234);
SELECT bar from foo;

+----------------------+
| bar                  |
+----------------------+
| 00000000000000001234 |
+----------------------+

It's a common source of confusion for MySQL users to see INT(20) and assume it's a size limit, something analogous to CHAR(20). This is not the case.

Changing project port number in Visual Studio 2013

  • Open Solution file (.sln) in Editable mode (Notepad or notepad++ or any other tool)
  • Find tag name VMDPort and update it to your desired port.

see below snap.

enter image description here

Input mask for numeric and decimal

using jQuery input mask plugin (6 whole and 2 decimal places):

HTML:

<input class="mask" type="text" />

jQuery:

$(".mask").inputmask('Regex', {regex: "^[0-9]{1,6}(\\.\\d{1,2})?$"});

I hope this helps someone

PHP7 : install ext-dom issue

First of all, read the warning! It says do not run composer as root! Secondly, you're probably using Xammp on your local which has the required php libraries as default.

But in your server you're missing ext-dom. php-xml has all the related packages you need. So, you can simply install it by running:

sudo apt-get update
sudo apt install php-xml

Most likely you are missing mbstring too. If you get the error, install this package as well with:

sudo apt-get install php-mbstring

Then run:

composer update
composer require cviebrock/eloquent-sluggable

Iterate through pairs of items in a Python list

You can zip the list with itself sans the first element:

a = [5, 7, 11, 4, 5]

for previous, current in zip(a, a[1:]):
    print(previous, current)

This works even if your list has no elements or only 1 element (in which case zip returns an empty iterable and the code in the for loop never executes). It doesn't work on generators, only sequences (tuple, list, str, etc).

How do I force git to use LF instead of CR+LF under windows?

You can find the solution to this problem at: https://help.github.com/en/github/using-git/configuring-git-to-handle-line-endings

Simplified description of how you can solve this problem on windows:

Global settings for line endings The git config core.autocrlf command is used to change how Git handles line endings. It takes a single argument.

On Windows, you simply pass true to the configuration. For example: C:>git config --global core.autocrlf true

Good luck, I hope I helped.

Find first element in a sequence that matches a predicate

To find first element in a sequence seq that matches a predicate:

next(x for x in seq if predicate(x))

Or (itertools.ifilter on Python 2):

next(filter(predicate, seq))

It raises StopIteration if there is none.


To return None if there is no such element:

next((x for x in seq if predicate(x)), None)

Or:

next(filter(predicate, seq), None)

How do you install GLUT and OpenGL in Visual Studio 2012?

Download the GLUT library. At first step Copy the glut32.dll and paste it in C:\Windows\System32 folder.Second step copy glut.h file and paste it in C:\Program Files\Microsoft Visual Studio\VC\include folder and third step copy glut32.lib and paste it in c:\Program Files\Microsoft Visual Studio\VC\lib folder. Now you can create visual c++ console application project and include glut.h header file then you can write code for GLUT project. If you are using 64 bit windows machine then path and glut library may be different but process is similar.

Random numbers with Math.random() in Java

Math.random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Now it depends on what you want to accomplish. When you want to have Numbers from 1 to 100 for example you just have to add

(int)(Math.random()*100)

So 100 is the range of values. When you want to change the start of the range to 20 to 120 you have to add +20 at the end.

So the formula is:

(int)(Math.random()*range) + min

And you can always calculate the range with max-min, thats why Google gives you that formula.

Adding blank spaces to layout

Below is the simple way to create blank line with line size. Here we can adjust size of the blank line. Try this one.

           <TextView
            android:id="@id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="5dp"/>

Angular 2 Routing run in new tab

Try this please, <a target="_blank" routerLink="/Page2">


Update1: Custom directives to the rescue! Full code is here: https://github.com/pokearound/angular2-olnw

import { Directive, ElementRef, HostListener, Input, Inject } from '@angular/core';

@Directive({ selector: '[olinw007]' })
export class OpenLinkInNewWindowDirective {
    //@Input('olinwLink') link: string; //intro a new attribute, if independent from routerLink
    @Input('routerLink') link: string;
    constructor(private el: ElementRef, @Inject(Window) private win:Window) {
    }
    @HostListener('mousedown') onMouseEnter() {
        this.win.open(this.link || 'main/default');
    }
}

Notice, Window is provided and OpenLinkInNewWindowDirective declared below:

import { AppAboutComponent } from './app.about.component';
import { AppDefaultComponent } from './app.default.component';
import { PageNotFoundComponent } from './app.pnf.component';
import { OpenLinkInNewWindowDirective } from './olinw.directive';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';


const appRoutes: Routes = [
  { path: '', pathMatch: 'full', component: AppDefaultComponent },
  { path: 'home', component: AppComponent },
  { path: 'about', component: AppAboutComponent },
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  declarations: [
    AppComponent, AppAboutComponent, AppDefaultComponent, PageNotFoundComponent, OpenLinkInNewWindowDirective
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule,
    RouterModule.forRoot(appRoutes)
  ],
  providers: [{ provide: Window, useValue: window }],
  bootstrap: [AppComponent]
})
export class AppModule { }

First link opens in new Window, second one will not:

<h1>
    {{title}}
    <ul>
        <li><a routerLink="/main/home" routerLinkActive="active" olinw007> OLNW</a></li>
        <li><a routerLink="/main/home" routerLinkActive="active"> OLNW - NOT</a></li>
    </ul>
    <div style="background-color:#eee;">
        <router-outlet></router-outlet>
    </div>
</h1>

Tada! ..and you are welcome =)

Update2: As of v2.4.10 <a target="_blank" routerLink="/Page2"> works

How can I setup & run PhantomJS on Ubuntu?

Personaly I prefer using npm (see Arnel Bucio answer)

sudo npm install -g phantomjs

but! I noticed that some of npm module still can't see it as global executable.

enter image description here

so!

  • Create new /usr/share/phantomjs/ directory link

    cd /usr/share
    sudo ln -s ../lib/node_modules/phantomjs/lib/phantom phantomjs
    
  • Remove old /usr/bin/phantomjs executable link and create the new one

    cd /usr/bin
    sudo mv phantomjs phantomjs.old
    sudo ln -s ../share/phantomjs .
    

PHP Get name of current directory

echo basename(__DIR__); will return the current directory name only
echo basename(__FILE__); will return the current file name only

How to create XML file with specific structure in Java

Use JAXB: http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    @XmlElement
    public void setAge(int age) {
        this.age = age;
    }

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

}
package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

      } catch (JAXBException e) {
        e.printStackTrace();
      }

    }
}

The calling thread must be STA, because many UI components require this

If you make the call from the main thread, you must add the STAThread attribute to the Main method, as stated in the previous answer.

If you use a separate thread, it needs to be in a STA (single-threaded apartment), which is not the case for background worker threads. You have to create the thread yourself, like this:

Thread t = new Thread(ThreadProc);
t.SetApartmentState(ApartmentState.STA);

t.Start();

with ThreadProc being a delegate of type ThreadStart.

Limiting the number of characters in a JTextField

private void validateInput() {

      if (filenametextfield.getText().length() <= 3 )
        {

          errorMsg2.setForeground(Color.RED);

        }
        else if(filenametextfield.getText().length() >= 3 && filenametextfield.getText().length()<= 25)
        {

             errorMsg2.setForeground(frame.getBackground());
             errorMsg.setForeground(frame2.getBackground());

        } 
        else if(filenametextfield.getText().length() >= 25)
        {

             remove(errorMsg2);
             errorMsg.setForeground(Color.RED);
             filenametextfield.addKeyListener(new KeyAdapter() {
                  public void keyTyped(KeyEvent e) {
                     if(filenametextfield.getText().length()>=25)
                        {
                         e.consume();
                         e.getModifiers();

                        }
                 }
            });
        }


    }

How to convert variable (object) name into String

You can use deparse and substitute to get the name of a function argument:

myfunc <- function(v1) {
  deparse(substitute(v1))
}

myfunc(foo)
[1] "foo"

Updates were rejected because the tip of your current branch is behind its remote counterpart

If you tried all of above and the problem is still not solved then make sure that pushed branch name is unique and not exists in remotes. Error message might be misleading.

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

Sort Go map values by keys

If, like me, you find you want essentially the same sorting code in more than one place, or just want to keep the code complexity down, you can abstract away the sorting itself to a separate function, to which you pass the function that does the actual work you want (which would be different at each call site, of course).

Given a map with key type K and value type V, represented as <K> and <V> below, the common sort function might look something like this Go-code template (which Go version 1 does not support as-is):

/* Go apparently doesn't support/allow 'interface{}' as the value (or
/* key) of a map such that any arbitrary type can be substituted at
/* run time, so several of these nearly-identical functions might be
/* needed for different key/value type combinations. */
func sortedMap<K><T>(m map[<K>]<V>, f func(k <K>, v <V>)) {
    var keys []<K>
    for k, _ := range m {
        keys = append(keys, k)
    }
    sort.Strings(keys)  # or sort.Ints(keys), sort.Sort(...), etc., per <K>
    for _, k := range keys {
        v := m[k]
        f(k, v)
    }
}

Then call it with the input map and a function (taking (k <K>, v <V>) as its input arguments) that is called over the map elements in sorted-key order.

So, a version of the code in the answer posted by Mingu might look like:

package main

import (
    "fmt"
    "sort"
)

func sortedMapIntString(m map[int]string, f func(k int, v string)) {
    var keys []int
    for k, _ := range m {
        keys = append(keys, k)
    }
    sort.Ints(keys)
    for _, k := range keys {
        f(k, m[k])
    }
}

func main() {
    // Create a map for processing
    m := make(map[int]string)
    m[1] = "a"
    m[2] = "c"
    m[0] = "b"

    sortedMapIntString(m,
        func(k int, v string) { fmt.Println("Key:", k, "Value:", v) })
}

The sortedMapIntString() function can be re-used for any map[int]string (assuming the same sort order is desired), keeping each use to just two lines of code.

Downsides include:

  • It's harder to read for people unaccustomed to using functions as first-class
  • It might be slower (I haven't done performance comparisons)

Other languages have various solutions:

  • If the use of <K> and <V> (to denote types for the key and value) looks a bit familiar, that code template is not terribly unlike C++ templates.
  • Clojure and other languages support sorted maps as fundamental data types.
  • While I don't know of any way Go makes range a first-class type such that it could be substituted with a custom ordered-range (in place of range in the original code), I think some other languages provide iterators that are powerful enough to accomplish the same thing.

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

What does the "assert" keyword do?

If you launch your program with -enableassertions (or -ea for short) then this statement

assert cond;

is equivalent to

if (!cond)
    throw new AssertionError();

If you launch your program without this option, the assert statement will have no effect.

For example, assert d >= 0 && d <= s.length();, as posted in your question, is equivalent to

if (!(d >= 0 && d <= s.length()))
    throw new AssertionError();

(If you launched with -enableassertions that is.)


Formally, the Java Language Specification: 14.10. The assert Statement says the following:

14.10. The assert Statement
An assertion is an assert statement containing a boolean expression. An assertion is either enabled or disabled. If the assertion is enabled, execution of the assertion causes evaluation of the boolean expression and an error is reported if the expression evaluates to false. If the assertion is disabled, execution of the assertion has no effect whatsoever.

Where "enabled or disabled" is controlled with the -ea switch and "An error is reported" means that an AssertionError is thrown.


And finally, a lesser known feature of assert:

You can append : "Error message" like this:

assert d != null : "d is null";

to specify what the error message of the thrown AssertionError should be.


This post has been rewritten as an article here.

jquery Ajax call - data parameters are not being passed to MVC Controller action

If you have trouble with caching ajax you can turn it off:

$.ajaxSetup({cache: false});

Multi-line strings in PHP

Another solution is to use output buffering, you can collect everything that is being outputted/echoed and store it in a variable.

<?php
ob_start(); 

?>line1
line2
line3<?php 

$xml = ob_get_clean();

Please note that output buffering might not be the best solution in terms of performance and code cleanliness for this exact case but worth leaving it here for reference.

Include files from parent or other directory

If your server is not resolving the file from the parent directory using

include '../somefilein_parent.php'

try this (using the parent directory relative to the script):

include __DIR__ . "/../somefilein_parent.php";

In Javascript, how do I check if an array has duplicate values?

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

What is the difference between an Instance and an Object?

Java is an object-oriented programming language (OOP). This means, that everything in Java, except of the primitive types is an object.

Now, Java objects are similar to real-world objects. For example we can create a car object in Java, which will have properties like current speed and color; and behavior like: accelerate and park.

That's Object.

enter image description here

Instance, on the other side, is a uniquely initialized copy of that object that looks like Car car = new Car().

Check it out to learn more about Java classes and object

Need a row count after SELECT statement: what's the optimal SQL approach?

Here are some ideas:

  • Go with Approach #1 and resize the array to hold additional results or use a type that automatically resizes as neccessary (you don't mention what language you are using so I can't be more specific).
  • You could execute both statements in Approach #1 within a transaction to guarantee the counts are the same both times if your database supports this.
  • I'm not sure what you are doing with the data but if it is possible to process the results without storing all of them first this might be the best method.

Advantage of switch over if-else statement

I would say use SWITCH. This way you only have to implement differing outcomes. Your ten identical cases can use the default. Should one change all you need to is explicitly implement the change, no need to edit the default. It's also far easier to add or remove cases from a SWITCH than to edit IF and ELSEIF.

switch(numerror){
    ERROR_20 : { fire_special_event(); } break;
    default : { null; } break;
}

Maybe even test your condition (in this case numerror) against a list of possibilities, an array perhaps so your SWITCH isn't even used unless there definately will be an outcome.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

For me the issue resolved when I set the principal section like this:

env.put(Context.SECURITY_PRINCIPAL, userId@domainWithoutProtocolAndPortNo);

A Space between Inline-Block List Items

just remove the breaks between li's in your html code... make the li's in one line only..

How to document a method with parameter(s)?

python doc strings are free-form, you can document it in any way you like.

Examples:

def mymethod(self, foo, bars):
    """
    Does neat stuff!
    Parameters:
      foo - a foo of type FooType to bar with.
      bars - The list of bars
    """

Now, there are some conventions, but python doesn't enforce any of them. Some projects have their own conventions. Some tools to work with docstrings also follow specific conventions.

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Using CSS to insert text

It is, but requires a CSS2 capable browser (all major browsers, IE8+).

.OwnerJoe:before {
  content: "Joe's Task:";
}

But I would rather recommend using Javascript for this. With jQuery:

$('.OwnerJoe').each(function() {
  $(this).before($('<span>').text("Joe's Task: "));
});

In a Git repository, how to properly rename a directory?

From Web Application I think you can't, but you can rename all the folders in Git Client, it will move your files in the new renamed folders, than commit and push to remote repository.

I had a very similar issue: I had to rename different folders from uppercase to lowercase (like Abc -> abc), I've renamed all the folders with a dummy name (like 'abc___') and than committed to remote repository, after that I renamed all the folders to the original name with the lowercase (like abc) and it took them!

jQuery bind/unbind 'scroll' event on $(window)

You need to:

unbind('scroll')

At the moment you are not specifying the event to unbind.

Add rows to CSV File in powershell

I know this is an old thread but it was the first I found when searching. The += solution did not work for me. The code that I did get to work is as below.

#this bit creates the CSV if it does not already exist
$headers = "Name", "Primary Type"
$psObject = New-Object psobject
foreach($header in $headers)
{
 Add-Member -InputObject $psobject -MemberType noteproperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation

#this bit appends a new row to the CSV file
$bName = "My Name"
$bPrimaryType = "My Primary Type"
    $hash = @{
             "Name" =  $bName
             "Primary Type" = $bPrimaryType
              }

$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newrow -append -Force

I was able to use this as a function to loop through a series of arrays and enter the contents into the CSV file.

It works in powershell 3 and above.

What is SYSNAME data type in SQL Server?

Is there use case you can provide?

Anywhere you want to store an object name for use by database maintenance scripts. For example, a script purges old rows from certain tables that have a date column. It's configured with a table that gives table name, column name to filter on, and how many days of history to keep. Another script dumps certain tables to CSV files, and again is configured with a table listing the tables to dump. These configuration tables can use the sysname type to store table and column names.

Import JavaScript file and call functions using webpack, ES6, ReactJS

Named exports:

Let's say you create a file called utils.js, with utility functions that you want to make available for other modules (e.g. a React component). Then you would make each function a named export:

export function add(x, y) {
  return x + y
}

export function mutiply(x, y) {
  return x * y
}

Assuming that utils.js is located in the same directory as your React component, you can use its exports like this:

import { add, multiply } from './utils.js';
...
add(2, 3) // Can be called wherever in your component, and would return 5.

Or if you prefer, place the entire module's contents under a common namespace:

import * as utils from './utils.js'; 
...
utils.multiply(2,3)

Default exports:

If you on the other hand have a module that only does one thing (could be a React class, a normal function, a constant, or anything else) and want to make that thing available to others, you can use a default export. Let's say we have a file log.js, with only one function that logs out whatever argument it's called with:

export default function log(message) {
  console.log(message);
}

This can now be used like this:

import log from './log.js';
...
log('test') // Would print 'test' in the console.

You don't have to call it log when you import it, you could actually call it whatever you want:

import logToConsole from './log.js';
...
logToConsole('test') // Would also print 'test' in the console.

Combined:

A module can have both a default export (max 1), and named exports (imported either one by one, or using * with an alias). React actually has this, consider:

import React, { Component, PropTypes } from 'react';

C# '@' before a String

What is this for and why would I use @":\" instead of ":\"?

Because when you have a long string with many \ you don't need to escape them all and the \n, \r and \f won't work too.

OpenCV Python rotate image by X degrees around specific point

The cv2.warpAffine function takes the shape parameter in reverse order: (col,row) which the answers above do not mention. Here is what worked for me:

import numpy as np

def rotateImage(image, angle):
    row,col = image.shape
    center=tuple(np.array([row,col])/2)
    rot_mat = cv2.getRotationMatrix2D(center,angle,1.0)
    new_image = cv2.warpAffine(image, rot_mat, (col,row))
    return new_image

How do I make a textbox that only accepts numbers?

FAIL-SAFE and simple "recursive" method, which can be used with multiple textboxes.

It blocks the wrong keyboard typed characters and also pasted values etc. It only accepts integer numbers, and the maximum number length is the maximum length of a string type (which is int, really long!)

public void Check_If_Int_On_TextChanged(object sender, EventArgs e)
{
   // This method checks that each inputed character is a number. Any non-numeric
   // characters are removed from the text

   TextBox textbox = (TextBox)sender;

   // If the text is empty, return
   if (textbox.Text.Length == 0) { return; }

   // Check the new Text value if it's only numbers
   byte parsedValue;
   if (!byte.TryParse(textbox.Text[(textbox.Text.Length - 1)].ToString(), out parsedValue))
   {
      // Remove the last character as it wasn't a number
      textbox.Text = textbox.Text.Remove((textbox.Text.Length - 1));

      // Move the cursor to the end of text
      textbox.SelectionStart = textbox.Text.Length;
    }
 }

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

Simple rules of bidirectional relationships:

1.For many-to-one bidirectional relationships, the many side is always the owning side of the relationship. Example: 1 Room has many Person (a Person belongs one Room only) -> owning side is Person

2.For one-to-one bidirectional relationships, the owning side corresponds to the side that contains the corresponding foreign key.

3.For many-to-many bidirectional relationships, either side may be the owning side.

Hope can help you.

Copy Files from Windows to the Ubuntu Subsystem

You should be able to access your windows system under the /mnt directory. For example inside of bash, use this to get to your pictures directory:

cd /mnt/c/Users/<ubuntu.username>/Pictures

Hope this helps!

Convert from enum ordinal to enum type

public enum Suit implements java.io.Serializable, Comparable<Suit>{
  spades, hearts, diamonds, clubs;
  private static final Suit [] lookup  = Suit.values();
  public Suit fromOrdinal(int ordinal) {
    if(ordinal< 1 || ordinal> 3) return null;
    return lookup[value-1];
  }
}

the test class

public class MainTest {
    public static void main(String[] args) {
        Suit d3 = Suit.diamonds;
        Suit d3Test = Suit.fromOrdinal(2);
        if(d3.equals(d3Test)){
            System.out.println("Susses");
        }else System.out.println("Fails");
    }
}

I appreciate that you share with us if you have a more efficient code, My enum is huge and constantly called thousands of times.

Reading RFID with Android phones

A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.

It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.

Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.

They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.

Plotting 4 curves in a single plot, with 3 y-axes

In your case there are 3 extra y axis (4 in total) and the best code that could be used to achieve what you want and deal with other cases is illustrated above:

clear
clc

x = linspace(0,1,10);
N = numel(x);
y = rand(1,N);
y_extra_1 = 5.*rand(1,N)+5;
y_extra_2 = 50.*rand(1,N)+20;
Y = [y;y_extra_1;y_extra_2];

xLimit = [min(x) max(x)];
xWidth = xLimit(2)-xLimit(1);
numberOfExtraPlots = 2;
a = 0.05;
N_ = numberOfExtraPlots+1;

for i=1:N_
    L=1-(numberOfExtraPlots*a)-0.2;
    axesPosition = [(0.1+(numberOfExtraPlots*a)) 0.1 L 0.8];
    if(i==1)
        color = [rand(1),rand(1),rand(1)];
        figure('Units','pixels','Position',[200 200 1200 600])
        axes('Units','normalized','Position',axesPosition,...
            'Color','w','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'NextPlot','add');
        plot(x,Y(i,:),'Color',color);
        xlabel('Time (s)');

        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    else
        color = [rand(1),rand(1),rand(1)];
        axes('Units','normalized','Position',axesPosition,...
            'Color','none','XColor','k','YColor',color,...
            'XLim',xLimit,'YLim',[min(Y(i,:)) max(Y(i,:))],...
            'XTick',[],'XTickLabel',[],'NextPlot','add');
        V = (xWidth*a*(i-1))/L;
        b=xLimit+[V 0];
        x_=linspace(b(1),b(2),10);
        plot(x_,Y(i,:),'Color',color);
        ylab = strcat('Values of dataset 0',num2str(i));
        ylabel(ylab)

        numberOfExtraPlots = numberOfExtraPlots - 1;
    end
end

The code above will produce something like this:

Run Button is Disabled in Android Studio

It was quite silly for me, I just opened the Run > Run Configurations window everything seemed to be fine there, I didn't change anything, when I closed the window the button was enabled.

Best way to detect when a user leaves a web page?

What you can do, is open up a WebSocket connection when the page loads, optionally send data through the WebSocket identifying the current user, and check when that connection is closed on the server.

Add x and y labels to a pandas plot

If you label the columns and index of your DataFrame, pandas will automatically supply appropriate labels:

import pandas as pd
values = [[1, 2], [2, 5]]
df = pd.DataFrame(values, columns=['Type A', 'Type B'], 
                  index=['Index 1', 'Index 2'])
df.columns.name = 'Type'
df.index.name = 'Index'
df.plot(lw=2, colormap='jet', marker='.', markersize=10, 
        title='Video streaming dropout by category')

enter image description here

In this case, you'll still need to supply y-labels manually (e.g., via plt.ylabel as shown in the other answers).

How to get DATE from DATETIME Column in SQL?

You can use

select * 
from transaction 
where (Card_No='123') and (transaction_date = convert(varchar(10),getdate(),101))

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

Generally, the answer to your question is no, you cannot define more than one externally visible function per file. You can return function handles to local functions, though, and a convenient way to do so is to make them fields of a struct. Here is an example:

function funs = makefuns
  funs.fun1=@fun1;
  funs.fun2=@fun2;
end

function y=fun1(x)
  y=x;
end

function z=fun2
  z=1;
end

And here is how it could be used:

>> myfuns = makefuns;
>> myfuns.fun1(5)    
ans =
     5
>> myfuns.fun2()     
ans =
     1

How to switch between frames in Selenium WebDriver using Java

First you have to locate the frame id and define it in a WebElement

For ex:- WebElement fr = driver.findElementById("id");

Then switch to the frame using this code:- driver.switchTo().frame("Frame_ID");

An example script:-

WebElement fr = driver.findElementById("theIframe");

driver.switchTo().frame(fr);

Then to move out of frame use:- driver.switchTo().defaultContent();

Error renaming a column in MySQL

Renaming a column in MySQL :

ALTER TABLE mytable CHANGE current_column_name new_column_name DATATYPE;

How can I use/create dynamic template to compile dynamic Component with Angular 2.0?

I decided to compact everything I learned into one file. There's a lot to take in here especially compared to before RC5. Note that this source file includes the AppModule and AppComponent.

import {
  Component, Input, ReflectiveInjector, ViewContainerRef, Compiler, NgModule, ModuleWithComponentFactories,
  OnInit, ViewChild
} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';

@Component({
  selector: 'app-dynamic',
  template: '<h4>Dynamic Components</h4><br>'
})
export class DynamicComponentRenderer implements OnInit {

  factory: ModuleWithComponentFactories<DynamicModule>;

  constructor(private vcRef: ViewContainerRef, private compiler: Compiler) { }

  ngOnInit() {
    if (!this.factory) {
      const dynamicComponents = {
        sayName1: {comp: SayNameComponent, inputs: {name: 'Andrew Wiles'}},
        sayAge1: {comp: SayAgeComponent, inputs: {age: 30}},
        sayName2: {comp: SayNameComponent, inputs: {name: 'Richard Taylor'}},
        sayAge2: {comp: SayAgeComponent, inputs: {age: 25}}};
      this.compiler.compileModuleAndAllComponentsAsync(DynamicModule)
        .then((moduleWithComponentFactories: ModuleWithComponentFactories<DynamicModule>) => {
          this.factory = moduleWithComponentFactories;
          Object.keys(dynamicComponents).forEach(k => {
            this.add(dynamicComponents[k]);
          })
        });
    }
  }

  addNewName(value: string) {
    this.add({comp: SayNameComponent, inputs: {name: value}})
  }

  addNewAge(value: number) {
    this.add({comp: SayAgeComponent, inputs: {age: value}})
  }

  add(comp: any) {
    const compFactory = this.factory.componentFactories.find(x => x.componentType === comp.comp);
    // If we don't want to hold a reference to the component type, we can also say: const compFactory = this.factory.componentFactories.find(x => x.selector === 'my-component-selector');
    const injector = ReflectiveInjector.fromResolvedProviders([], this.vcRef.parentInjector);
    const cmpRef = this.vcRef.createComponent(compFactory, this.vcRef.length, injector, []);
    Object.keys(comp.inputs).forEach(i => cmpRef.instance[i] = comp.inputs[i]);
  }
}

@Component({
  selector: 'app-age',
  template: '<div>My age is {{age}}!</div>'
})
class SayAgeComponent {
  @Input() public age: number;
};

@Component({
  selector: 'app-name',
  template: '<div>My name is {{name}}!</div>'
})
class SayNameComponent {
  @Input() public name: string;
};

@NgModule({
  imports: [BrowserModule],
  declarations: [SayAgeComponent, SayNameComponent]
})
class DynamicModule {}

@Component({
  selector: 'app-root',
  template: `
        <h3>{{message}}</h3>
        <app-dynamic #ad></app-dynamic>
        <br>
        <input #name type="text" placeholder="name">
        <button (click)="ad.addNewName(name.value)">Add Name</button>
        <br>
        <input #age type="number" placeholder="age">
        <button (click)="ad.addNewAge(age.value)">Add Age</button>
    `,
})
export class AppComponent {
  message = 'this is app component';
  @ViewChild(DynamicComponentRenderer) dcr;

}

@NgModule({
  imports: [BrowserModule],
  declarations: [AppComponent, DynamicComponentRenderer],
  bootstrap: [AppComponent]
})
export class AppModule {}`

Which characters are valid/invalid in a JSON key name?

It is worth mentioning that while starting the keys with numbers is valid, it could cause some unintended issues.

Example:

var testObject = {
    "1tile": "test value"
};
console.log(testObject.1tile); // fails, invalid syntax
console.log(testObject["1tile"]; // workaround

How to make a JTable non-editable

You can override the method isCellEditable and implement as you want for example:

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

or

//instance table model
DefaultTableModel tableModel = new DefaultTableModel() {

   @Override
   public boolean isCellEditable(int row, int column) {
       //Only the third column
       return column == 3;
   }
};

table.setModel(tableModel);

Note for if your JTable disappears

If your JTable is disappearing when you use this it is most likely because you need to use the DefaultTableModel(Object[][] data, Object[] columnNames) constructor instead.

//instance table model
DefaultTableModel tableModel = new DefaultTableModel(data, columnNames) {

    @Override
    public boolean isCellEditable(int row, int column) {
       //all cells false
       return false;
    }
};

table.setModel(tableModel);

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

How do I prompt for Yes/No/Cancel input in a Linux shell script?

The simplest and most widely available method to get user input at a shell prompt is the read command. The best way to illustrate its use is a simple demonstration:

while true; do
    read -p "Do you wish to install this program?" yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

Another method, pointed out by Steven Huwig, is Bash's select command. Here is the same example using select:

echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
    case $yn in
        Yes ) make install; break;;
        No ) exit;;
    esac
done

With select you don't need to sanitize the input – it displays the available choices, and you type a number corresponding to your choice. It also loops automatically, so there's no need for a while true loop to retry if they give invalid input.

Also, Léa Gris demonstrated a way to make the request language agnostic in her answer. Adapting my first example to better serve multiple languages might look like this:

set -- $(locale LC_MESSAGES)
yesptrn="$1"; noptrn="$2"; yesword="$3"; noword="$4"

while true; do
    read -p "Install (${yesword} / ${noword})? " yn
    case $yn in
        ${yesptrn##^} ) make install; break;;
        ${noptrn##^} ) exit;;
        * ) echo "Answer ${yesword} / ${noword}.";;
    esac
done

Obviously other communication strings remain untranslated here (Install, Answer) which would need to be addressed in a more fully completed translation, but even a partial translation would be helpful in many cases.

Finally, please check out the excellent answer by F. Hauri.

jQuery UI - Draggable is not a function?

I went through both your question and a another duplicate.
In the end, the following answer helped me sorting things out:
uncaught-typeerror-draggable-is-not-a-function

To get rid of :

$(".draggable").draggable is not a function anymore

I had to put links to Javascript libraries above the script tag I expected to be working.

My code:

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css"/>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.min.js" />
<script type="text/javascript" src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" />

<script>
    $(function(){
        $("#container-speed").draggable();
    });
</script>

<div class="content">
    <div class="container-fluid">
        <div class="row">
            <div class="rowbackground"style="width: 600px; height: 400px; margin: 0 auto">
                <div id="container-speed" style="width: 300px; height: 200px; float: left"></div>
                <div id="container-rpm" style="width: 300px; height: 200px; float: left"></div>
            </div>
        </div>
    </div>
</div>

C++, How to determine if a Windows Process is running?

JaredPar is right in that you can't know if the process is running. You can only know if the process was running at the moment you checked. It might have died in the mean time.

You also have to be aware the PIDs can be recycled pretty quickly. So just because there's a process out there with your PID, it doesn't mean that it's your process.

Have the processes share a GUID. (Process 1 could generate the GUID and pass it to Process 2 on the command line.) Process 2 should create a named mutex with that GUID. When Process 1 wants to check, it can do a WaitForSingleObject on the mutex with a 0 timeout. If Process 2 is gone, the return code will tell you that the mutex was abandoned, otherwise you'll get a timeout.

How to use Class<T> in Java?

Using the generified version of class Class allows you, among other things, to write things like

Class<? extends Collection> someCollectionClass = someMethod();

and then you can be sure that the Class object you receive extends Collection, and an instance of this class will be (at least) a Collection.

MVC Razor Radio Button

MVC Razor provides one elegant Html Helper called RadioButton with two parameters (this is general, But we can overload it uptil five parameters) i.e. one with the group name and other being the value

<div class="col-md-10">
    Male:   @Html.RadioButton("Gender", "Male")
    Female: @Html.RadioButton("Gender", "Female")
</div>                         

Unknown column in 'field list' error on MySQL Update query

While working on a .Net app build with EF code first, I got this error message when trying to apply my migration where I had a Sql("UPDATE tableName SET columnName = value"); statement.

Turns out I misspelled the columnName.

Choose File Dialog

Was looking for a file/folder browser myself recently and decided to make a new explorer activity (Android library): https://github.com/vaal12/AndroidFileBrowser

Matching Test application https://github.com/vaal12/FileBrowserTestApplication- is a sample how to use.

Allows picking directories and files from phone file structure.

How to change default JRE for all Eclipse workspaces?

Open the Java > Installed JREs preference page. Check the box on the line for the JRE that you want to assign as the default JRE in your workbench. If the JRE you want to assign as the default does not appear in the list, you must add it. Click OK.

Source-http://help.eclipse.org/juno/index.jsp?topic=%2Forg.eclipse.jdt.doc.user%2Ftasks%2Ftask-assign_default_jre.htm

Get current cursor position

GetCursorPos() will return to you the x/y if you pass in a pointer to a POINT structure.

Hiding the cursor can be done with ShowCursor().

How do I check in SQLite whether a table exists?

Note that to check whether a table exists in the TEMP database, you must use sqlite_temp_master instead of sqlite_master:

SELECT name FROM sqlite_temp_master WHERE type='table' AND name='table_name';

Mercurial — revert back to old version and continue from there

The answers above were most useful and I learned a lot. However, for my needs the succinct answer is:

hg revert --all --rev ${1}

hg commit -m "Restoring branch ${1} as default"

where ${1} is the number of the revision or the name of the branch. These two lines are actually part of a bash script, but they work fine on their own if you want to do it manually.

This is useful if you need to add a hot fix to a release branch, but need to build from default (until we get our CI tools right and able to build from branches and later do away with release branches as well).

What is a Memory Heap?

You probably mean heap memory, not memory heap.

Heap memory is essentially a large pool of memory (typically per process) from which the running program can request chunks. This is typically called dynamic allocation.

It is different from the Stack, where "automatic variables" are allocated. So, for example, when you define in a C function a pointer variable, enough space to hold a memory address is allocated on the stack. However, you will often need to dynamically allocate space (With malloc) on the heap and then provide the address where this memory chunk starts to the pointer.

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

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

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

How do I protect javascript files?

I agree with everyone else here: With JS on the client, the cat is out of the bag and there is nothing completely foolproof that can be done.

Having said that; in some cases I do this to put some hurdles in the way of those who want to take a look at the code. This is how the algorithm works (roughly)

  1. The server creates 3 hashed and salted values. One for the current timestamp, and the other two for each of the next 2 seconds. These values are sent over to the client via Ajax to the client as a comma delimited string; from my PHP module. In some cases, I think you can hard-bake these values into a script section of HTML when the page is formed, and delete that script tag once the use of the hashes is over The server is CORS protected and does all the usual SERVER_NAME etc check (which is not much of a protection but at least provides some modicum of resistance to script kiddies).

  2. Also it would be nice, if the the server checks if there was indeed an authenticated user's client doing this

  3. The client then sends the same 3 hashed values back to the server thru an ajax call to fetch the actual JS that I need. The server checks the hashes against the current time stamp there... The three values ensure that the data is being sent within the 3 second window to account for latency between the browser and the server

  4. The server needs to be convinced that one of the hashes is matched correctly; and if so it would send over the crucial JS back to the client. This is a simple, crude "One time use Password" without the need for any database at the back end.

  5. This means, that any hacker has only the 3 second window period since the generation of the first set of hashes to get to the actual JS code.

  6. The entire client code can be inside an IIFE function so some of the variables inside the client are even more harder to read from the Inspector console

    This is not any deep solution: A determined hacker can register, get an account and then ask the server to generate the first three hashes; by doing tricks to go around Ajax and CORS; and then make the client perform the second call to get to the actual code -- but it is a reasonable amount of work.

Moreover, if the Salt used by the server is based on the login credentials; the server may be able to detect who is that user who tried to retreive the sensitive JS (The server needs to do some more additional work regarding the behaviour of the user AFTER the sensitive JS was retreived, and block the person if the person, say for example, did not do some other activity which was expected)

An old, crude version of this was done for a hackathon here: http://planwithin.com/demo/tadr.html That wil not work in case the server detects too much latency, and it goes beyond the 3 second window period

How to use OrderBy with findAll in Spring Data

Yes you can sort using query method in Spring Data.

Ex:ascending order or descending order by using the value of the id field.

Code:

  public interface StudentDAO extends JpaRepository<StudentEntity, Integer> {
    public findAllByOrderByIdAsc();   
}

alternative solution:

    @Repository
public class StudentServiceImpl implements StudentService {
    @Autowired
    private StudentDAO studentDao;

    @Override
    public List<Student> findAll() {
        return studentDao.findAll(orderByIdAsc());
    }
private Sort orderByIdAsc() {
    return new Sort(Sort.Direction.ASC, "id")
                .and(new Sort(Sort.Direction.ASC, "name"));
}
}

Spring Data Sorting: Sorting

convert a list of objects from one type to another using lambda expression

Here's a simple example..

List<char> c = new List<char>() { 'A', 'B', 'C' };

List<string> s = c.Select(x => x.ToString()).ToList();

Java Webservice Client (Best way)

What is the best approach to do this JAVA?

I would personally NOT use Axis 2, even for client side development only. Here is why I stay away from it:

  1. I don't like its architecture and hate its counter productive deployment model.
  2. I find it to be low quality project.
  3. I don't like its performances (see this benchmark against JAX-WS RI).
  4. It's always a nightmare to setup dependencies (I use Maven and I always have to fight with the gazillion of dependencies) (see #2)
  5. Axis sucked big time and Axis2 isn't better. No, this is not a personal opinion, there is a consensus.
  6. I suffered once, never again.

The only reason Axis is still around is IMO because it's used in Eclipse since ages. Thanks god, this has been fixed in Eclipse Helios and I hope Axis2 will finally die. There are just much better stacks.

I read about SAAJ, looks like that will be more granular level of approach?

To do what?

Is there any other way than using the WSDL2Java tool, to generate the code. Maybe wsimport in another option. What are the pros and cons?

Yes! Prefer a JAX-WS stack like CXF or JAX-WS RI (you might also read about Metro, Metro = JAX-WS RI + WSIT), they are just more elegant, simpler, easier to use. In your case, I would just use JAX-WS RI which is included in Java 6 and thus wsimport.

Can someone send the links for some good tutorials on these topics?

That's another pro, there are plenty of (good quality) tutorials for JAX-WS, see for example:

What are the options we need to use while generating the code using the WSDL2Java?

No options, use wsimport :)

See also

Related questions

Compiling dynamic HTML strings from database

You can use

ng-bind-html https://docs.angularjs.org/api/ng/service/$sce

directive to bind html dynamically. However you have to get the data via $sce service.

Please see the live demo at http://plnkr.co/edit/k4s3Bx

var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope,$sce) {
    $scope.getHtml=function(){
   return $sce.trustAsHtml("<b>Hi Rupesh hi <u>dfdfdfdf</u>!</b>sdafsdfsdf<button>dfdfasdf</button>");
   }
});

  <body ng-controller="MainCtrl">
<span ng-bind-html="getHtml()"></span>
  </body>

Converting string to title case

String TitleCaseString(String s)
{
    if (s == null || s.Length == 0) return s;

    string[] splits = s.Split(' ');

    for (int i = 0; i < splits.Length; i++)
    {
        switch (splits[i].Length)
        {
            case 1:
                break;

            default:
                splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
                break;
        }
    }

    return String.Join(" ", splits);
}

How to center a WPF app on screen?

Put this in your window constructor

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

.NET FrameworkSupported in: 4, 3.5, 3.0

.NET Framework Client ProfileSupported in: 4, 3.5 SP1

@Scope("prototype") bean scope not creating new bean

Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!

bitwise XOR of hex numbers in python

Whoa. You're really over-complicating it by a very long distance. Try:

>>> print hex(0x12ef ^ 0xabcd)
0xb922

You seem to be ignoring these handy facts, at least:

  • Python has native support for hexadecimal integer literals, with the 0x prefix.
  • "Hexadecimal" is just a presentation detail; the arithmetic is done in binary, and then the result is printed as hex.
  • There is no connection between the format of the inputs (the hexadecimal literals) and the output, there is no such thing as a "hexadecimal number" in a Python variable.
  • The hex() function can be used to convert any number into a hexadecimal string for display.

If you already have the numbers as strings, you can use the int() function to convert to numbers, by providing the expected base (16 for hexadecimal numbers):

>>> print int("12ef", 16)
4874

So you can do two conversions, perform the XOR, and then convert back to hex:

>>> print hex(int("12ef", 16) ^ int("abcd", 16))
0xb922

Allow only pdf, doc, docx format for file upload?

Better to use change event on input field.

Updated source:

var myfile="";

$('#resume_link').click(function( e ) {
    e.preventDefault();
    $('#resume').trigger('click');
});

$('#resume').on( 'change', function() {
   myfile= $( this ).val();
   var ext = myfile.split('.').pop();
   if(ext=="pdf" || ext=="docx" || ext=="doc"){
       alert(ext);
   } else{
       alert(ext);
   }
});

Updated jsFiddle.

set pythonpath before import statements

As also noted in the docs here.
Go to Python X.X/Lib and add these lines to the site.py there,

import sys
sys.path.append("yourpathstring")

This changes your sys.path so that on every load, it will have that value in it..

As stated here about site.py,

This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.

For other possible methods of adding some path to sys.path see these docs

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

How do I profile memory usage in Python?

Below is a simple function decorator which allows to track how much memory the process consumed before the function call, after the function call, and what is the difference:

import time
import os
import psutil
 
 
def elapsed_since(start):
    return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
 
 
def get_process_memory():
    process = psutil.Process(os.getpid())
    mem_info = process.memory_info()
    return mem_info.rss
 
 
def profile(func):
    def wrapper(*args, **kwargs):
        mem_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        mem_after = get_process_memory()
        print("{}: memory before: {:,}, after: {:,}, consumed: {:,}; exec time: {}".format(
            func.__name__,
            mem_before, mem_after, mem_after - mem_before,
            elapsed_time))
        return result
    return wrapper

Here is my blog which describes all the details. (archived link)

How can I make text appear on next line instead of overflowing?

Try the <wbr> tag - not as elegant as the word-wrap property that others suggested, but it's a working solution until all major browsers (read IE) implement CSS3.

How to show current time in JavaScript in the format HH:MM:SS?

Use this way:

var d = new Date();
localtime = d.toLocaleTimeString('en-US', { hour12: false });

Result: 18:56:31

Cannot find runtime 'node' on PATH - Visual Studio Code and Node.js

I had a similar issue with zsh and nvm on Linux, I fixed it by adding nvm initialization script in ~/.profile and restart login session like this

export NVM_DIR="$HOME/.nvm" 
 [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm 
 [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"

Using psql how do I list extensions installed in a database?

Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions

What is the meaning of {...this.props} in Reactjs

It's called spread attributes and its aim is to make the passing of props easier.

Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.

<Component x={} y={} z={} />

Thus instead you do this, wrap them up in an object and use the spread notation

var props = { x: 1, y: 1, z:1 };
<Component {...props} />

which will unpack it into the props on your component, i.e., you "never" use {... props} inside your render() function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x.

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

How to get text in QlineEdit when QpushButton is pressed in a string?

My first suggestion is to use Designer to create your GUIs. Typing them out yourself sucks, takes more time, and you will definitely make more mistakes than Designer.

Here are some PyQt tutorials to help get you on the right track. The first one in the list is where you should start.

A good guide for figuring out what methods are available for specific classes is the PyQt4 Class Reference. In this case you would look up QLineEdit and see the there is a text method.

To answer your specific question:

To make your GUI elements available to the rest of the object, preface them with self.

import sys
from PyQt4.QtCore import SIGNAL
from PyQt4.QtGui import QDialog, QApplication, QPushButton, QLineEdit, QFormLayout

class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.le = QLineEdit()
        self.le.setObjectName("host")
        self.le.setText("Host")

        self.pb = QPushButton()
        self.pb.setObjectName("connect")
        self.pb.setText("Connect") 

        layout = QFormLayout()
        layout.addWidget(self.le)
        layout.addWidget(self.pb)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"),self.button_click)
        self.setWindowTitle("Learning")

    def button_click(self):
        # shost is a QString object
        shost = self.le.text()
        print shost


app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

Which HTML Parser is the best?

Self plug: I have just released a new Java HTML parser: jsoup. I mention it here because I think it will do what you are after.

Its party trick is a CSS selector syntax to find elements, e.g.:

String html = "<html><head><title>First parse</title></head>"
  + "<body><p>Parsed HTML into a doc.</p></body></html>";
Document doc = Jsoup.parse(html);
Elements links = doc.select("a");
Element head = doc.select("head").first();

See the Selector javadoc for more info.

This is a new project, so any ideas for improvement are very welcome!

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

For those like me who wonder how legacy apps are treated, I did a bit of testing and computation on the subject.

Thanks to @hannes-sverrisson hint, I started on the assumption that a legacy app is treated with a 320x568 view in iPhone 6 and iPhone 6 plus.

The test was made with a simple black background [email protected] with a white border. The background has a size of 640x1136 pixels, and it is black with an inner white border of 1 pixel.

Below are the screenshots provided by the simulator:

On the iPhone 6 screenshot, we can see a 1 pixel margin on top and bottom of the white border, and a 2 pixel margin on the iPhone 6 plus screenshot. This gives us a used space of 1242x2204 on iPhone 6 plus, instead of 1242x2208, and 750x1332 on the iPhone 6, instead of 750x1334.

We can assume that those dead pixels are meant to respect the iPhone 5 aspect ratio:

iPhone 5               640 / 1136 = 0.5634
iPhone 6 (used)        750 / 1332 = 0.5631
iPhone 6 (real)        750 / 1334 = 0.5622
iPhone 6 plus (used)  1242 / 2204 = 0.5635
iPhone 6 plus (real)  1242 / 2208 = 0.5625

Second, it is important to know that @2x resources will be scaled not only on iPhone 6 plus (which expects @3x assets), but also on iPhone 6. This is probably because not scaling the resources would have led to unexpected layouts, due to the enlargement of the view.

However, that scaling is not equivalent in width and height. I tried it with a 264x264 @2x resource. Given the results, I have to assume that the scaling is directly proportional to the pixels / points ratio.

Device         Width scale             Computed width   Screenshot width
iPhone 5        640 /  640 = 1.0                        264 px
iPhone 6        750 /  640 = 1.171875  309.375          309 px
iPhone 6 plus  1242 /  640 = 1.940625  512.325          512 px

Device         Height scale            Computed height  Screenshot height
iPhone 5       1136 / 1136 = 1.0                        264 px
iPhone 6       1332 / 1136 = 1.172535  309.549          310 px
iPhone 6 plus  2204 / 1136 = 1.940141  512.197          512 px

It's important to note the iPhone 6 scaling is not the same in width and height (309x310). This tends to confirm the above theory that scaling is not proportional in width and height, but uses the pixels / points ratio.

I hope this helps.

Can I multiply strings in Java to repeat sequences?

with Dollar:

String s = "123" + $("0").repeat(3); // 123000

How to get the selected value from drop down list in jsp?

use jquery

$("#item").change(function({
    var x=$(this).val();
});

Your value will be in x variable, use this variable value in your jsp, like this {x} this statement will give the value

parent & child with position fixed, parent overflow:hidden bug

As an alternative to using clip you could also use {border-radius: 0.0001px} on a parent element. It works not only with absolute/fixed positioned elements.

How to set max_connections in MySQL Programmatically

You can set max connections using:

set global max_connections = '1 < your number > 100000';

This will set your number of mysql connection unti (Requires SUPER privileges).

WPF popup window

In WPF there is a control named Popup.

Popup myPopup = new Popup();
//(...)
myPopup.IsOpen = true;

Java reading a file into an ArrayList?

    Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/

    enter code here

ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/

while (scr.hasNext()){

list.add(scr.next()); } /*above code is responsible for adding data in arraylist with the help of add function */