Programs & Examples On #Xmonad

xmonad is a tiling window manager for the X Window System, written in the functional programming language Haskell.

How to specify multiple conditions in an if statement in javascript

Wrap them in an extra pair of parens and you're good to go.

if((Type == 2 && PageCount == 0) || (Type == 2 && PageCount == ''))
    PageCount= document.getElementById('<%=hfPageCount.ClientID %>').value;
}

Adding values to an array in java

  • First line : array created.
  • Third line loop started from j = 1 to j = 28123
  • Fourth line you give the variable x value (0) each time the loop is accessed.
  • Fifth line you put the value of j in the index 0.
  • Sixth line you do increment to the value x by 1.(but it will be reset to 0 at line 4)

JQuery Redirect to URL after specified time

This is improved @Vicky solution - it has clearInterval() added so it prevents a loop of reloading if the redirect takes too long:

                            $(document).ready(function () {
                                var myTimer = window.setInterval(function () {
                                    var timeLeft = $("#countdown").html();
                                    if (eval(timeLeft) == 0) {
                                        console.log('Now redirecting');
                                        clearInterval(myTimer);
                                        window.location = ("@Html.Raw(HttpUtility.HtmlDecode(redirectUrl))");
                                    } else {
                                        $("#countdown").html(eval(timeLeft) - eval(1));
                                    }
                                }, 1000);
                            });

Write a function that returns the longest palindrome in a given string

I was asked this question recently. Here's the solution I [eventually] came up with. I did it in JavaScript because it's pretty straightforward in that language.

The basic concept is that you walk the string looking for the smallest multi-character palindrome possible (either a two or three character one). Once you have that, expand the borders on both sides until it stops being a palindrome. If that length is longer than current longest one, store it and move along.

// This does the expanding bit.
function getsize(s, start, end) {
    var count = 0, i, j;
    for (i = start, j = end; i >= 0 && j < s.length; i--, j++) {
        if (s[i] !== s[j]) {
            return count;
        }
        count = j - i + 1; // keeps track of how big the palindrome is
    }
    return count;
}

function getBiggestPalindrome(s) {
    // test for simple cases
    if (s === null || s === '') { return 0; }
    if (s.length === 1) { return 1; }
    var longest = 1;
    for (var i = 0; i < s.length - 1; i++) {
        var c = s[i]; // the current letter
        var l; // length of the palindrome
        if (s[i] === s[i+1]) { // this is a 2 letter palindrome
            l = getsize(s, i, i+1);
        }
        if (i+2 < s.length && s[i] === s[i+2]) { // 3 letter palindrome
            l = getsize(s, i+1, i+1);
        }
        if (l > longest) { longest = l; }
    }
    return longest;
}

This could definitely be cleaned up and optimized a little more, but it should have pretty good performance in all but the worst case scenario (a string of the same letter).

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

How to append rows to an R data frame

Suppose you simply don't know the size of the data.frame in advance. It can well be a few rows, or a few millions. You need to have some sort of container, that grows dynamically. Taking in consideration my experience and all related answers in SO I come with 4 distinct solutions:

  1. rbindlist to the data.frame

  2. Use data.table's fast set operation and couple it with manually doubling the table when needed.

  3. Use RSQLite and append to the table held in memory.

  4. data.frame's own ability to grow and use custom environment (which has reference semantics) to store the data.frame so it will not be copied on return.

Here is a test of all the methods for both small and large number of appended rows. Each method has 3 functions associated with it:

  • create(first_element) that returns the appropriate backing object with first_element put in.

  • append(object, element) that appends the element to the end of the table (represented by object).

  • access(object) gets the data.frame with all the inserted elements.

rbindlist to the data.frame

That is quite easy and straight-forward:

create.1<-function(elems)
{
  return(as.data.table(elems))
}

append.1<-function(dt, elems)
{ 
  return(rbindlist(list(dt,  elems),use.names = TRUE))
}

access.1<-function(dt)
{
  return(dt)
}

data.table::set + manually doubling the table when needed.

I will store the true length of the table in a rowcount attribute.

create.2<-function(elems)
{
  return(as.data.table(elems))
}

append.2<-function(dt, elems)
{
  n<-attr(dt, 'rowcount')
  if (is.null(n))
    n<-nrow(dt)
  if (n==nrow(dt))
  {
    tmp<-elems[1]
    tmp[[1]]<-rep(NA,n)
    dt<-rbindlist(list(dt, tmp), fill=TRUE, use.names=TRUE)
    setattr(dt,'rowcount', n)
  }
  pos<-as.integer(match(names(elems), colnames(dt)))
  for (j in seq_along(pos))
  {
    set(dt, i=as.integer(n+1), pos[[j]], elems[[j]])
  }
  setattr(dt,'rowcount',n+1)
  return(dt)
}

access.2<-function(elems)
{
  n<-attr(elems, 'rowcount')
  return(as.data.table(elems[1:n,]))
}

SQL should be optimized for fast record insertion, so I initially had high hopes for RSQLite solution

This is basically copy&paste of Karsten W. answer on similar thread.

create.3<-function(elems)
{
  con <- RSQLite::dbConnect(RSQLite::SQLite(), ":memory:")
  RSQLite::dbWriteTable(con, 't', as.data.frame(elems))
  return(con)
}

append.3<-function(con, elems)
{ 
  RSQLite::dbWriteTable(con, 't', as.data.frame(elems), append=TRUE)
  return(con)
}

access.3<-function(con)
{
  return(RSQLite::dbReadTable(con, "t", row.names=NULL))
}

data.frame's own row-appending + custom environment.

create.4<-function(elems)
{
  env<-new.env()
  env$dt<-as.data.frame(elems)
  return(env)
}

append.4<-function(env, elems)
{ 
  env$dt[nrow(env$dt)+1,]<-elems
  return(env)
}

access.4<-function(env)
{
  return(env$dt)
}

The test suite:

For convenience I will use one test function to cover them all with indirect calling. (I checked: using do.call instead of calling the functions directly doesn't makes the code run measurable longer).

test<-function(id, n=1000)
{
  n<-n-1
  el<-list(a=1,b=2,c=3,d=4)
  o<-do.call(paste0('create.',id),list(el))
  s<-paste0('append.',id)
  for (i in 1:n)
  {
    o<-do.call(s,list(o,el))
  }
  return(do.call(paste0('access.', id), list(o)))
}

Let's see the performance for n=10 insertions.

I also added a 'placebo' functions (with suffix 0) that don't perform anything - just to measure the overhead of the test setup.

r<-microbenchmark(test(0,n=10), test(1,n=10),test(2,n=10),test(3,n=10), test(4,n=10))
autoplot(r)

Timings for adding n=10 rows

Timings for n=100 rows Timings for n=1000 rows

For 1E5 rows (measurements done on Intel(R) Core(TM) i7-4710HQ CPU @ 2.50GHz):

nr  function      time
4   data.frame    228.251 
3   sqlite        133.716
2   data.table      3.059
1   rbindlist     169.998 
0   placebo         0.202

It looks like the SQLite-based sulution, although regains some speed on large data, is nowhere near data.table + manual exponential growth. The difference is almost two orders of magnitude!

Summary

If you know that you will append rather small number of rows (n<=100), go ahead and use the simplest possible solution: just assign the rows to the data.frame using bracket notation and ignore the fact that the data.frame is not pre-populated.

For everything else use data.table::set and grow the data.table exponentially (e.g. using my code).

Postman - How to see request with headers and body data with variables substituted

If, like me, you are still using the browser version (which will be deprecated soon), have you tried the "Code" button?

enter image description here

This should generate a snippet which contains the entire request Postman is firing. You can even choose the language for the snippet. I find it quite handy when I need to debug stuff.

Hope this helps.

How to display image from URL on Android

InputStream URLcontent = (InputStream) new URL(url).getContent();
Drawable image = Drawable.createFromStream(URLcontent, "your source link");

this has worked for me

How to download Visual Studio 2017 Community Edition for offline installation?

No, there should be an .exe file (vs_Community_xxxxx.exe) directly in you f:\vs2017c directory !

Just start from the this directory, not from a longer path. the packages downloaded are partly having very long path names, it fails if you start from a longer path.

Running the new Intel emulator for Android

I had the same issue, solved it by Installing the Intel Hardware Accelerated Execution Manager. Download it with the SDK Manager, it's in Extras. After this, go to the folder

[Android SDK Root]\extras\intel\Hardware_Accelerated_Execution_Manager

then run IntelHaxm.exe and install.

Here the link of the Intel Hardware Accelerated IntelHaxm.exe for Microsoft Windows,Mac OS* X, and Linux Ubuntu

enter image description here

You'll get the following message if you don't have virtualization enabled in your BIOS:

enter image description here

Turning multi-line string into single comma-separated

You can also print like this:

Just awk: using printf

bash-3.2$ cat sample.log
something1:    +12.0   (some unnecessary trailing data (this must go))
something2:    +15.5   (some more unnecessary trailing data)
something4:    +9.0   (some other unnecessary data)
something1:    +13.5  (blah blah blah)

bash-3.2$ awk ' { if($2 != "") { if(NR==1) { printf $2 } else { printf "," $2 } } }' sample.log
+12.0,+15.5,+9.0,+13.5

How to install and run Typescript locally in npm?

It took me a while to figure out the solution to this problem - it's in the original question. You need to have a script that calls tsc in your package.json file so that you can run:

npm run tsc 

Include -- before you pass in options (or just include them in the script):

npm run tsc -- -v

Here's an example package.json:

{
  "name": "foo",
  "scripts": {
    "tsc": "tsc"
  },
  "dependencies": {
    "typescript": "^1.8.10"
  }
}

rails 3 validation on uniqueness on multiple attributes

Multiple Scope Parameters:

class TeacherSchedule < ActiveRecord::Base
  validates_uniqueness_of :teacher_id, :scope => [:semester_id, :class_id]
end

http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

This should answer Greg's question.

How can I Insert data into SQL Server using VBNet

Function ExtSql(ByVal sql As String) As Boolean
    Dim cnn As SqlConnection
    Dim cmd As SqlCommand
    cnn = New SqlConnection(My.Settings.mySqlConnectionString)
    Try
        cnn.Open()
        cmd = New SqlCommand
        cmd.Connection = cnn
        cmd.CommandType = CommandType.Text
        cmd.CommandText = sql
        cmd.ExecuteNonQuery()
        cnn.Close()
        cmd.Dispose()
    Catch ex As Exception
        cnn.Close()
        Return False
    End Try
    Return True
End Function

[INSTALL_FAILED_NO_MATCHING_ABIS: Failed to extract native libraries, res=-113]

13 September 2018 It worked for me when add more types and set universalApk with false to reduce apk size

splits {
    abi {
        enable true
        reset()
        include 'x86', 'x86_64', 'armeabi', 'armeabi-v7a', 'mips', 'mips64', 'arm64-v8a'
        universalApk false
    }
}

Show hide div using codebehind

You can use a standard ASP.NET Panel and then set it's visible property in your code behind.

<asp:Panel ID="Panel1" runat="server" visible="false" />

To show panel in codebehind:

Panel1.Visible = true;

How to send PUT, DELETE HTTP request in HttpURLConnection?

public  HttpURLConnection getHttpConnection(String url, String type){
        URL uri = null;
        HttpURLConnection con = null;
        try{
            uri = new URL(url);
            con = (HttpURLConnection) uri.openConnection();
            con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
            con.setDoOutput(true);
            con.setDoInput(true);
            con.setConnectTimeout(60000); //60 secs
            con.setReadTimeout(60000); //60 secs
            con.setRequestProperty("Accept-Encoding", "Your Encoding");
            con.setRequestProperty("Content-Type", "Your Encoding");
        }catch(Exception e){
            logger.info( "connection i/o failed" );
        }
        return con;
}

Then in your code :

public void yourmethod(String url, String type, String reqbody){
    HttpURLConnection con = null;
    String result = null;
    try {
        con = conUtil.getHttpConnection( url , type);
    //you can add any request body here if you want to post
         if( reqbody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());
                out.writeBytes(reqbody);
                out.flush();
                out.close();
            }
        con.connect();
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String temp = null;
        StringBuilder sb = new StringBuilder();
        while((temp = in.readLine()) != null){
            sb.append(temp).append(" ");
        }
        result = sb.toString();
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        logger.error(e.getMessage());
    }
//result is the response you get from the remote side
}

How to zoom in/out an UIImage object when user pinches screen?

Shefali's solution for UIImageView works great, but it needs a little modification:

- (void)pinch:(UIPinchGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateEnded
        || gesture.state == UIGestureRecognizerStateChanged) {
        NSLog(@"gesture.scale = %f", gesture.scale);

        CGFloat currentScale = self.frame.size.width / self.bounds.size.width;
        CGFloat newScale = currentScale * gesture.scale;

        if (newScale < MINIMUM_SCALE) {
            newScale = MINIMUM_SCALE;
        }
        if (newScale > MAXIMUM_SCALE) {
            newScale = MAXIMUM_SCALE;
        }

        CGAffineTransform transform = CGAffineTransformMakeScale(newScale, newScale);
        self.transform = transform;
        gesture.scale = 1;
    }
}

(Shefali's solution had the downside that it did not scale continuously while pinching. Furthermore, when starting a new pinch, the current image scale was reset.)

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

Solving Quadratic Equation

# syntaxis:2.7
# solution for quadratic equation
# a*x**2 + b*x + c = 0

d = b**2-4*a*c # discriminant

if d < 0:
    print 'No solutions'
elif d == 0:
    x1 = -b / (2*a)
    print 'The sole solution is',x1
else: # if d > 0
    x1 = (-b + math.sqrt(d)) / (2*a)
    x2 = (-b - math.sqrt(d)) / (2*a)
    print 'Solutions are',x1,'and',x2

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

How do I echo and send console output to a file in a bat script?

I think you want something along the lines of this:

echo Your Msg> YourTxtFile.txt

Or if you want a new line:

echo Your Msg>> YourTxtFile.txt

These commands are great for logs.

Note: This will sometimes glitch and replace the whole text file on my computer.

Another Note: If the file does not exist, it will create the file.

SmartGit Installation and Usage on Ubuntu

Now on the Smartgit webpage (I don't know since when) there is the possibility to download directly the .deb package. Once installed, it will upgrade automagically itself when a new version is released.

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

If all of these advice doesn't work, you should re-create your Server (Tomcat or like that). That solved my problem.

jQuery - selecting elements from inside a element

Have a look here -- to query a sub-element of an element:

$(document.getElementById('parentid')).find('div#' + divID + ' span.child');

Bootstrap 4 File Input

You can try below given snippet to display the selected file name from the file input type.

document.querySelectorAll('input[type=file]').forEach( input => {
    input.addEventListener('change', e => {
        e.target.nextElementSibling.innerText = input.files[0].name;
    });
});

Create array of regex matches

Here's a simple example:

Pattern pattern = Pattern.compile(regexPattern);
List<String> list = new ArrayList<String>();
Matcher m = pattern.matcher(input);
while (m.find()) {
    list.add(m.group());
}

(if you have more capturing groups, you can refer to them by their index as an argument of the group method. If you need an array, then use list.toArray())

Laravel 5: Display HTML with Blade

This works fine for Laravel 5.6

<?php echo "$text"; ?>

In a different way

{!! $text !!}

It will not render HTML code and print as a string.

For more details open link:- Display HTML with Blade

How to detect if CMD is running as Administrator/has elevated privileges?

This trick only requires one command: type net session into the command prompt.

If you are NOT an admin, you get an access is denied message.

System error 5 has occurred.

Access is denied.

If you ARE an admin, you get a different message, the most common being:

There are no entries in the list.

From MS Technet:

Used without parameters, net session displays information about all sessions with the local computer.

Chrome / Safari not filling 100% height of flex parent

Specifying a flex attribute to the container worked for me:

.container {
    flex: 0 0 auto;
}

This ensures the height is set and doesn't grow either.

How to search JSON data in MySQL?

for MySQL all (and 5.7)

SELECT LOWER(TRIM(BOTH 0x22 FROM TRIM(BOTH 0x20 FROM SUBSTRING(SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed)))),LOCATE(0x22,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"'),LOCATE(0x2C,SUBSTRING(json_filed,LOCATE('\"ArrayItem\"',json_filed)+LENGTH('\"ArrayItem\"')+1,LENGTH(json_filed))))),LENGTH(json_filed))))) AS result FROM `table`;

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

How to get the current directory in a C program?

Have you had a look at getcwd()?

#include <unistd.h>
char *getcwd(char *buf, size_t size);

Simple example:

#include <unistd.h>
#include <stdio.h>
#include <limits.h>

int main() {
   char cwd[PATH_MAX];
   if (getcwd(cwd, sizeof(cwd)) != NULL) {
       printf("Current working dir: %s\n", cwd);
   } else {
       perror("getcwd() error");
       return 1;
   }
   return 0;
}

Git's famous "ERROR: Permission to .git denied to user"

I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.

So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.

And I think your problem may be caused by a mistyping error in your accounts name.

Java executors: how to be notified, without blocking, when a task completes?

Define a callback interface to receive whatever parameters you want to pass along in the completion notification. Then invoke it at the end of the task.

You could even write a general wrapper for Runnable tasks, and submit these to ExecutorService. Or, see below for a mechanism built into Java 8.

class CallbackTask implements Runnable {

  private final Runnable task;

  private final Callback callback;

  CallbackTask(Runnable task, Callback callback) {
    this.task = task;
    this.callback = callback;
  }

  public void run() {
    task.run();
    callback.complete();
  }

}

With CompletableFuture, Java 8 included a more elaborate means to compose pipelines where processes can be completed asynchronously and conditionally. Here's a contrived but complete example of notification.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;

public class GetTaskNotificationWithoutBlocking {

  public static void main(String... argv) throws Exception {
    ExampleService svc = new ExampleService();
    GetTaskNotificationWithoutBlocking listener = new GetTaskNotificationWithoutBlocking();
    CompletableFuture<String> f = CompletableFuture.supplyAsync(svc::work);
    f.thenAccept(listener::notify);
    System.out.println("Exiting main()");
  }

  void notify(String msg) {
    System.out.println("Received message: " + msg);
  }

}

class ExampleService {

  String work() {
    sleep(7000, TimeUnit.MILLISECONDS); /* Pretend to be busy... */
    char[] str = new char[5];
    ThreadLocalRandom current = ThreadLocalRandom.current();
    for (int idx = 0; idx < str.length; ++idx)
      str[idx] = (char) ('A' + current.nextInt(26));
    String msg = new String(str);
    System.out.println("Generated message: " + msg);
    return msg;
  }

  public static void sleep(long average, TimeUnit unit) {
    String name = Thread.currentThread().getName();
    long timeout = Math.min(exponential(average), Math.multiplyExact(10, average));
    System.out.printf("%s sleeping %d %s...%n", name, timeout, unit);
    try {
      unit.sleep(timeout);
      System.out.println(name + " awoke.");
    } catch (InterruptedException abort) {
      Thread.currentThread().interrupt();
      System.out.println(name + " interrupted.");
    }
  }

  public static long exponential(long avg) {
    return (long) (avg * -Math.log(1 - ThreadLocalRandom.current().nextDouble()));
  }

}

VBA: How to delete filtered rows in Excel?

As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.

ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)

As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().

How to define two fields "unique" as couple

Django 2.2+

Using the constraints features UniqueConstraint is preferred over unique_together.

From the Django documentation for unique_together:

Use UniqueConstraint with the constraints option instead.
UniqueConstraint provides more functionality than unique_together.
unique_together may be deprecated in the future.

For example:

class Volume(models.Model):
    id = models.AutoField(primary_key=True)
    journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name="Journal")
    volume_number = models.CharField('Volume Number', max_length=100)
    comments = models.TextField('Comments', max_length=4000, blank=True)

    class Meta:
        constraints = [
            models.UniqueConstraint(fields=['journal_id', 'volume_number'], name='name of constraint')
        ]

Disable hover effects on mobile browsers

Hello person from the future, you probably want to use the pointer and/or hover media query. The handheld media query was deprecated.

/* device is using a mouse or similar */
@media (pointer: fine) {
  a:hover {
    background: red;
  }
}

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Best way to import Observable from rxjs

Rxjs v 6.*

It got simplified with newer version of rxjs .

1) Operators

import {map} from 'rxjs/operators';

2) Others

import {Observable,of, from } from 'rxjs';

Instead of chaining we need to pipe . For example

Old syntax :

source.map().switchMap().subscribe()

New Syntax:

source.pipe(map(), switchMap()).subscribe()

Note: Some operators have a name change due to name collisions with JavaScript reserved words! These include:

do -> tap,

catch -> catchError

switch -> switchAll

finally -> finalize


Rxjs v 5.*

I am writing this answer partly to help myself as I keep checking docs everytime I need to import an operator . Let me know if something can be done better way.

1) import { Rx } from 'rxjs/Rx';

This imports the entire library. Then you don't need to worry about loading each operator . But you need to append Rx. I hope tree-shaking will optimize and pick only needed funcionts( need to verify ) As mentioned in comments , tree-shaking can not help. So this is not optimized way.

public cache = new Rx.BehaviorSubject('');

Or you can import individual operators .

This will Optimize your app to use only those files :

2) import { _______ } from 'rxjs/_________';

This syntax usually used for main Object like Rx itself or Observable etc.,

Keywords which can be imported with this syntax

 Observable, Observer, BehaviorSubject, Subject, ReplaySubject

3) import 'rxjs/add/observable/__________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { empty } from 'rxjs/observable/empty';
import { concat} from 'rxjs/observable/concat';

These are usually accompanied with Observable directly. For example

Observable.from()
Observable.of()

Other such keywords which can be imported using this syntax:

concat, defer, empty, forkJoin, from, fromPromise, if, interval, merge, of, 
range, throw, timer, using, zip

4) import 'rxjs/add/operator/_________';

Update for Angular 5

With Angular 5, which uses rxjs 5.5.2+

import { filter } from 'rxjs/operators/filter';
import { map } from 'rxjs/operators/map';

These usually come in the stream after the Observable is created. Like flatMap in this code snippet:

Observable.of([1,2,3,4])
          .flatMap(arr => Observable.from(arr));

Other such keywords using this syntax:

audit, buffer, catch, combineAll, combineLatest, concat, count, debounce, delay, 
distinct, do, every, expand, filter, finally, find , first, groupBy,
ignoreElements, isEmpty, last, let, map, max, merge, mergeMap, min, pluck, 
publish, race, reduce, repeat, scan, skip, startWith, switch, switchMap, take, 
takeUntil, throttle, timeout, toArray, toPromise, withLatestFrom, zip

FlatMap: flatMap is alias to mergeMap so we need to import mergeMap to use flatMap.


Note for /add imports :

We only need to import once in whole project. So its advised to do it at a single place. If they are included in multiple files, and one of them is deleted, the build will fail for wrong reasons.

node.js: read a text file into an array. (Each line an item in the array.)

To read a big file into array you can read line by line or chunk by chunk.

line by line refer to my answer here

var fs = require('fs'),
    es = require('event-stream'),

var lines = [];

var s = fs.createReadStream('filepath')
    .pipe(es.split())
    .pipe(es.mapSync(function(line) {
        //pause the readstream
        s.pause();
        lines.push(line);
        s.resume();
    })
    .on('error', function(err) {
        console.log('Error:', err);
    })
    .on('end', function() {
        console.log('Finish reading.');
        console.log(lines);
    })
);

chunk by chunk refer to this article

var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
    offset += bytesRead;
    var str = chunkBuffer.slice(0, bytesRead).toString();
    var arr = str.split('\n');

    if(bytesRead = chunkSize) {
        // the last item of the arr may be not a full line, leave it to the next chunk
        offset -= arr.pop().length;
    }
    lines.push(arr);
}
console.log(lines);

Laravel 5.1 - Checking a Database Connection

You can also run this:

php artisan migrate:status

It makes a db connection connection to get migrations from migrations table. It'll throw an exception if the connection fails.

JQuery $.ajax() post - data in a java servlet

To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Sending intent to BroadcastReceiver from adb

I've found that the command was wrong, correct command contains "broadcast" instead of "start":

adb shell am broadcast -a com.whereismywifeserver.intent.TEST --es sms_body "test from adb" -n com.whereismywifeserver/.IntentReceiver

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

HTML/Javascript change div content

Get the id of the div whose content you want to change then assign the text as below:

  var myDiv = document.getElementById("divId");
  myDiv.innerHTML = "Content To Show";

How to query for today's date and 7 days before data?

Try this way:

select * from tab
where DateCol between DateAdd(DD,-7,GETDATE() ) and GETDATE() 

Self Join to get employee manager name

Additionally you may want to get managers and their reports count with -

SELECT e2.ename ,count(e1.ename)  FROM employee_s e1 LEFT OUTER JOIN employee_s e2 
ON e1.manager_id = e2.eid
group by e2.ename;

CodeIgniter - How to return Json response from controller

For CodeIgniter 4, you can use the built-in API Response Trait

Here's sample code for reference:

<?php namespace App\Controllers;

use CodeIgniter\API\ResponseTrait;

class Home extends BaseController
{
    use ResponseTrait;

    public function index()
    {
        $data = [
            'data' => 'value1',
            'data2' => 'value2',
        ];

        return $this->respond($data);
    }
}

A cron job for rails: best practices?

I'm using the rake approach (as supported by heroku)

With a file called lib/tasks/cron.rake ..

task :cron => :environment do
  puts "Pulling new requests..."
  EdiListener.process_new_messages
  puts "done."
end

To execute from the command line, this is just "rake cron". This command can then be put on the operating system cron/task scheduler as desired.

Update this is quite an old question and answer! Some new info:

  • the heroku cron service I referenced has since been replaced by Heroku Scheduler
  • for frequent tasks (esp. where you want to avoid the Rails environment startup cost) my preferred approach is to use system cron to call a script that will either (a) poke a secure/private webhook API to invoke the required task in the background or (b) directly enqueue a task on your queuing system of choice

Android Webview - Completely Clear the Cache

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db")

Did the trick

Twitter Bootstrap hide css class and jQuery

I agree with dfsq if all you want to do is show the button. If you want to switch between hiding and showing the button however, it is easier to use:

$("#buttonEditComment").toggleClass("hide");

Checkout multiple git repos into same Jenkins workspace

Checking out more than one repo at a time in a single workspace is not possible with Jenkins + Git Plugin.

As a workaround, you can either have multiple upstream jobs which checkout a single repo each and then copy to your final project workspace (Problematic on a number of levels), or you can set up a shell scripting step which checks out each needed repo to the job workspace at build time.

Previously the Multiple SCM plugin could help with this issue but it is now deprecated. From the Multiple SCM plugin page: "Users should migrate to https://wiki.jenkins-ci.org/display/JENKINS/Pipeline+Plugin . Pipeline offers a better way of checking out of multiple SCMs, and is supported by the Jenkins core development team."

How to set a:link height/width with css?

Thanks to RandomUs 1r for this observation:

changing it to display:inline-block; solves that issue. – RandomUs1r May 14 '13 at 21:59

I tried it myself for a top navigation menu bar, as follows:

First style the "li" element as follows:

display: inline-block;
width: 7em;
text-align: center;

Then style the "a"> element as follows:

width: 100%;

Now the navigation links are all equal width with text centered in each link.

how to read all files inside particular folder

    using System.IO;
    string[] arr=Directory.GetFiles("folderpath","*.Fileextension");
      foreach(string file in arr)
       {

       }

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

How to get TimeZone from android mobile?

All the answers here seem to suggest setting the daylite parameter to false. This is incorrect for many timezones which change abbreviated names depending on the time of the year (e.g. EST vs EDT).

The solution below will give you the correct abbreviation according to the current date for the timezone.

val tz = TimeZone.getDefault()
val isDaylite = tz.inDaylightTime(Date())
val timezone = tz.getDisplayName(isDaylite, TimeZone.SHORT)

MVC4 StyleBundle not resolving images

Maybe I am biased, but I quite like my solution as it doesn't do any transforming, regex's etc and it's has the least amount of code :)

This works for a site hosted as a Virtual Directory in a IIS Web Site and as a root website on IIS

So I created an Implentation of IItemTransform encapsulated the CssRewriteUrlTransform and used VirtualPathUtility to fix the path and call the existing code:

/// <summary>
/// Is a wrapper class over CssRewriteUrlTransform to fix url's in css files for sites on IIS within Virutal Directories
/// and sites at the Root level
/// </summary>
public class CssUrlTransformWrapper : IItemTransform
{
    private readonly CssRewriteUrlTransform _cssRewriteUrlTransform;

    public CssUrlTransformWrapper()
    {
        _cssRewriteUrlTransform = new CssRewriteUrlTransform();
    }

    public string Process(string includedVirtualPath, string input)
    {
        return _cssRewriteUrlTransform.Process("~" + VirtualPathUtility.ToAbsolute(includedVirtualPath), input);
    }
}


//App_Start.cs
public static void Start()
{
      BundleTable.Bundles.Add(new StyleBundle("~/bundles/fontawesome")
                         .Include("~/content/font-awesome.css", new CssUrlTransformWrapper()));
}

Seems to work fine for me?

How do I build a graphical user interface in C++?

Essentially, an operating system's windowing system exposes some API calls that you can perform to do jobs like create a window, or put a button on the window. Basically, you get a suite of header files and you can call functions in those imported libraries, just like you'd do with stdlib and printf.

Each operating system comes with its own GUI toolkit, suite of header files, and API calls, and their own way of doing things. There are also cross platform toolkits like GTK, Qt, and wxWidgets that help you build programs that work anywhere. They achieve this by having the same API calls on each platform, but a different implementation for those API functions that call down to the native OS API calls.

One thing they'll all have in common, which will be different from a CLI program, is something called an event loop. The basic idea there is somewhat complicated, and difficult to compress, but in essence it means that not a hell of a lot is going in in your main class/main function, except:

  • check the event queue if there's any new events
  • if there is, dispatch those events to appropriate handlers
  • when you're done, yield control back to the operating system (usually with some kind of special "sleep" or "select" or "yield" function call)
  • then the yield function will return when the operating system is done, and you have another go around the loop.

There are plenty of resources about event based programming. If you have any experience with JavaScript, it's the same basic idea, except that you, the scripter have no access or control over the event loop itself, or what events there are, your only job is to write and register handlers.

You should keep in mind that GUI programming is incredibly complicated and difficult, in general. If you have the option, it's actually much easier to just integrate an embedded webserver into your program and have an HTML/web based interface. The one exception that I've encountered is Apple's Cocoa+Xcode +interface builder + tutorials that make it easily the most approachable environment for people new to GUI programming that I've seen.

Coloring Buttons in Android with Material Design and AppCompat

I've just created an android library, that allows you to easily modify the button color and the ripple color

https://github.com/xgc1986/RippleButton

<com.xgc1986.ripplebutton.widget.RippleButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/btn"
    android:text="Android button modified in layout"
    android:textColor="@android:color/white"
    app:buttonColor="@android:color/black"
    app:rippleColor="@android:color/white"/>

You don't need to create an style for every button you want wit a different color, allowing you to customize the colors randomly

How do I install and use curl on Windows?

You can build the latest version of curl, openssl, libssh2 and zlib in 3 simple steps by following this tutorial.

Curl is built statically so you do not have to distribute the prerequisite dynamic runtime.

You can also download a prebuilt version (x86 and x64) from SourceForge.

Implode an array with JavaScript?

You can do this in plain JavaScript, use Array.prototype.join:

arrayName.join(delimiter);

Read Session Id using Javascript

The following can be used to retrieve JSESSIONID:

function getJSessionId(){
    var jsId = document.cookie.match(/JSESSIONID=[^;]+/);
    if(jsId != null) {
        if (jsId instanceof Array)
            jsId = jsId[0].substring(11);
        else
            jsId = jsId.substring(11);
    }
    return jsId;
}

Android: failed to convert @drawable/picture into a drawable

In Android Studio your resource(images) file name cannot start with NUMERIC and It cannot contain any BIG character. To solve your problem, do as Aliyah said. Just restart your IDE. This solved my problem too.

BigDecimal setScale and round

There is indeed a big difference, which you should keep in mind. setScale really set the scale of your number whereas round does round your number to the specified digits BUT it "starts from the leftmost digit of exact result" as mentioned within the jdk. So regarding your sample the results are the same, but try 0.0034 instead. Here's my note about that on my blog:

http://araklefeistel.blogspot.com/2011/06/javamathbigdecimal-difference-between.html

adding 1 day to a DATETIME format value

If you want to do this in PHP:

// replace time() with the time stamp you want to add one day to
$startDate = time();
date('Y-m-d H:i:s', strtotime('+1 day', $startDate));

If you want to add the date in MySQL:

-- replace CURRENT_DATE with the date you want to add one day to
SELECT DATE_ADD(CURRENT_DATE, INTERVAL 1 DAY);

Error Code: 1406. Data too long for column - MySQL

This is a step I use with ubuntu. It will allow you to insert more than 45 characters from your input but MySQL will cut your text to 45 characters to insert into the database.

  1. Run command

    sudo nano /etc/mysql/my.cnf

  2. Then paste this code

    [mysqld] sql-mode="NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

  3. restart MySQL

    sudo service mysql restart;

Simple example of threading in C++

There is also a POSIX library for POSIX operating systems. Check for compatability

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <iostream>

void *task(void *argument){
      char* msg;
      msg = (char*)argument;
      std::cout<<msg<<std::endl;
}

int main(){
    pthread_t thread1, thread2;
    int i1,i2;
    i1 = pthread_create( &thread1, NULL, task, (void*) "thread 1");
    i2 = pthread_create( &thread2, NULL, task, (void*) "thread 2");

    pthread_join(thread1,NULL);
    pthread_join(thread2,NULL);
    return 0;

}

compile with -lpthread

http://en.wikipedia.org/wiki/POSIX_Threads

How do I position a div relative to the mouse pointer using jQuery?

var mouseX;
var mouseY;
$(document).mousemove( function(e) {
   mouseX = e.pageX; 
   mouseY = e.pageY;
});  
$(".classForHoverEffect").mouseover(function(){
  $('#DivToShow').css({'top':mouseY,'left':mouseX}).fadeIn('slow');
});

the function above will make the DIV appear over the link wherever that may be on the page. It will fade in slowly when the link is hovered. You could also use .hover() instead. From there the DIV will stay, so if you would like the DIV to disappear when the mouse moves away, then,

$(".classForHoverEffect").mouseout(function(){
  $('#DivToShow').fadeOut('slow');
});

If you DIV is already positioned, you can simply use

$('.classForHoverEffect').hover(function(){
  $('#DivToShow').fadeIn('slow');
});

Also, keep in mind, your DIV style needs to be set to display:none; in order for it to fadeIn or show.

How do you convert a byte array to a hexadecimal string in C?

Slightly modified Yannith version. It is just I like to have it as a return value

_x000D_
_x000D_
typedef struct {_x000D_
   size_t len;_x000D_
   uint8_t *bytes;_x000D_
} vdata;_x000D_
_x000D_
char* vdata_get_hex(const vdata data)_x000D_
{_x000D_
   char hex_str[]= "0123456789abcdef";_x000D_
_x000D_
   char* out;_x000D_
   out = (char *)malloc(data.len * 2 + 1);_x000D_
   (out)[data.len * 2] = 0;_x000D_
   _x000D_
   if (!data.len) return NULL;_x000D_
   _x000D_
   for (size_t i = 0; i < data.len; i++) {_x000D_
      (out)[i * 2 + 0] = hex_str[(data.bytes[i] >> 4) & 0x0F];_x000D_
      (out)[i * 2 + 1] = hex_str[(data.bytes[i]     ) & 0x0F];_x000D_
   }_x000D_
   return out;_x000D_
}
_x000D_
_x000D_
_x000D_

Change the "From:" address in Unix "mail"

On Centos 5.3 I'm able to do:

mail -s "Subject" [email protected] -- -f [email protected] < body

The double dash stops mail from parsing the -f argument and passes it along to sendmail itself.

read.csv warning 'EOF within quoted string' prevents complete reading of file

I'm a new-ish R user and thought I'd post this in case it helps anyone else. I was trying to read in data from a text file (separated with commas) that included a few Spanish characters and it took me forever to figure it out. I knew I needed to use UTF-8 encoding, set the header arg to TRUE, and that I need to set the sep arguemnt to ",", but then I still got hang ups. After reading this post I tried setting the fill arg to TRUE, but then got the same "EOF within quoted string" which I was able to fix in the same manner as above. My successful read.table looks like this:

target <- read.table("target2.txt", fill=TRUE, header=TRUE, quote="", sep=",", encoding="UTF-8")

The result has Spanish language characters and same dims I had originally, so I'm calling it a success! Thanks all!

Define a fixed-size list in Java

If you want to use ArrayList or LinkedList, it seems that the answer is no. Although there are some classes in java that you can set them fixed size, like PriorityQueue, ArrayList and LinkedList can't, because there is no constructor for these two to specify capacity.

If you want to stick to ArrayList/LinkedList, one easy solution is to check the size manually each time.

public void fixedAdd(List<Integer> list, int val, int size) {
    list.add(val);
    if(list.size() > size) list.remove(0);
}

LinkedList is better than ArrayList in this situation. Suppose there are many values to be added but the list size is quite samll, there will be many remove operations. The reason is that the cost of removing from ArrayList is O(N), but only O(1) for LinkedList.

Pretty printing XML with javascript

what about creating a stub node (document.createElement('div') - or using your library equivalent), filling it with the xml string (via innerHTML) and calling simple recursive function for the root element/or the stub element in case you don't have a root. The function would call itself for all the child nodes.

You could then syntax-highlight along the way, be certain the markup is well-formed (done automatically by browser when appending via innerHTML) etc. It wouldn't be that much code and probably fast enough.

Why does corrcoef return a matrix?

corrcoef returns the normalised covariance matrix.

The covariance matrix is the matrix

Cov( X, X )    Cov( X, Y )

Cov( Y, X )    Cov( Y, Y )

Normalised, this will yield the matrix:

Corr( X, X )    Corr( X, Y )

Corr( Y, X )    Corr( Y, Y )

correlation1[0, 0 ] is the correlation between Strategy1Returns and itself, which must be 1. You just want correlation1[ 0, 1 ].

Local storage in Angular 2

To store in LocalStorage :

window.localStorage.setItem(key, data);

To remove an item from LocalStorage :

window.localStorage.removeItem(key);

To get an item from LocalStorage :

window.localStorage.getItem(key);

You can only store a string in LocalStorage; if you have an object, first you have to convert it to string like the following:

window.localStorage.setItem(key, JSON.stringify(obj));

And when you want to get an object from LocalStorage :

const result=JSON.parse(window.localStorage.getItem(key));

All Tips above are the same for SessionStorage.

You can use the following service to work on SessionStorage and LocalStorage. All methods in the service :

getSession(key: string): any
setSession(key: string, value: any): void
removeSession(key: string): void
removeAllSessions(): void
getLocal(key: string): any
setLocal(key: string, value: any): void
removeLocal(key: string): void 
removeAllLocals(): void

Inject this service in your components, services and ...; Do not forget to register the service in your core module.

import { Injectable } from '@angular/core';

@Injectable()
export class BrowserStorageService {

  getSession(key: string): any {
    const data = window.sessionStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setSession(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.sessionStorage.setItem(key, data);
  }

  removeSession(key: string): void {
    window.sessionStorage.removeItem(key);
  }

  removeAllSessions(): void {
    for (const key in window.sessionStorage) {
      if (window.sessionStorage.hasOwnProperty(key)) {
        this.removeSession(key);
      }
    }
  }

  getLocal(key: string): any {
    const data = window.localStorage.getItem(key);
    if (data) {
      return JSON.parse(data);
    } else {
      return null;
    }
  }

  setLocal(key: string, value: any): void {
    const data = value === undefined ? '' : JSON.stringify(value);
    window.localStorage.setItem(key, data);
  }

  removeLocal(key: string): void {
    window.localStorage.removeItem(key);
  }

  removeAllLocals(): void {
    for (const key in window.localStorage) {
      if (window.localStorage.hasOwnProperty(key)) {
        this.removeLocal(key);
      }
    }
  }
}

What is the apply function in Scala?

TLDR for people comming from c++

It's just overloaded operator of ( ) parentheses

So in scala:

class X {
   def apply(param1: Int, param2: Int, param3: Int) : Int = {
     // Do something
   }
}

Is same as this in c++:

class X {
   int operator()(int param1, int param2, int param3) {
      // do something
   }
};

How to place a div on the right side with absolute position

Simple, use absolute positioning, and instead of specifying a top and a left, specify a top and a right!

For example:

#logo_image {
    width:80px;
    height:80px;
    top:10px;
    right:10px;
    z-index: 3;
    position:absolute;
}

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

If you just want to delete the address assigned to the user and not to affect on User entity class you should try something like that:

@Entity
public class User {
   @OneToMany(mappedBy = "addressOwner", cascade = CascadeType.ALL)
   protected Set<Address> userAddresses = new HashSet<>();
}

@Entity 
public class Addresses {
   @ManyToOne(cascade = CascadeType.REFRESH) @JoinColumn(name = "user_id")
   protected User addressOwner;
}

This way you dont need to worry about using fetch in annotations. But remember when deleting the User you will also delete connected address to user object.

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

Visual Studio Error: (407: Proxy Authentication Required)

Using IDE configuration:

  1. Open Visual Studio 2012, click on Tools from the file menu bar and then click Options,

  2. From the Options window, expand the Source Control option, click on Plug-in Selection and make sure that the Current source control plug-in is set to Visual Studio Team Foundation Server.

  3. Next, click on the Visual Studio Team Foundation Server option under Source Control and perform the following steps: Check Use proxy server for file downloads. Enter the host name of your preferred Team Foundation Server 2010 Proxy server. Set the port to 443. Check Use SSL encryption (https) to connect.

  4. Click the OK button.

Using exe.config:

Modify the devenv.exe.config where IDE executable is like this:

<system.net> 
  <defaultProxy>  
   <proxy proxyaddress=”http://proxy:3128”
     bypassonlocal=”True” autoDetect=”True” /> 
   <bypasslist> 
   <add address=”http://URL”/>  
  </bypasslist> 
 </defaultProxy> 

Declare your proxy at proxyaddress and remember bypasslist urls and ip addresses will be excluded from proxy traffic.

Then restart visual studio to update changes.

Why doesn't java.io.File have a close method?

Essentially random access file wraps input and output streams in order to manage the random access. You don't open and close a file, you open and close streams to a file.

In Java, how to find if first character in a string is upper case without regex

If you have to check it out manually you can do int a = s.charAt(0)

If the value of a is between 65 to 90 it is upper case.

How to create a directory and give permission in single command

Don't do: mkdir -m 777 -p a/b/c since that will only set permission 777 on the last directory, c; a and b will be created with the default permission from your umask.

Instead to create any new directories with permission 777, run mkdir -p in a subshell where you override the umask:

(umask u=rwx,g=rwx,o=rwx && mkdir -p a/b/c)

Note that this won't change the permissions if any of a, b and c already exist though.

Polymorphism vs Overriding vs Overloading

Here's an example of polymorphism in pseudo-C#/Java:

class Animal
{
    abstract string MakeNoise ();
}

class Cat : Animal {
    string MakeNoise () {
        return "Meow";
    }
}

class Dog : Animal {
    string MakeNoise () {
        return "Bark";
    }
}

Main () {
   Animal animal = Zoo.GetAnimal ();
   Console.WriteLine (animal.MakeNoise ());
}

The Main function doesn't know the type of the animal and depends on a particular implementation's behavior of the MakeNoise() method.

Edit: Looks like Brian beat me to the punch. Funny we used the same example. But the above code should help clarify the concepts.

Why do I get "Exception; must be caught or declared to be thrown" when I try to compile my Java code?

The first error

java.lang.Exception; must be caught or declared to be thrown byte[] encrypted = encrypt(concatURL);

means that your encrypt method throws an exception that is not being handled or declared by the actionPerformed method where you are calling it. Read all about it at the Java Exceptions Tutorial.

You have a couple of choices that you can pick from to get the code to compile.

  • You can remove throws Exception from your encrypt method and actually handle the exception inside encrypt.
  • You can remove the try/catch block from encrypt and add throws Exception and the exception handling block to your actionPerformed method.

It's generally better to handle an exception at the lowest level that you can, instead of passing it up to a higher level.

The second error just means that you need to add a return statement to whichever method contains line 109 (also encrypt, in this case). There is a return statement in the method, but if an exception is thrown it might not be reached, so you either need to return in the catch block, or remove the try/catch from encrypt, as I mentioned before.

Choose folders to be ignored during search in VS Code

After you setup the search.exclude and file.exclude mentioned on the previous answers, run the command "Clear Editor History" (Use the Command Palette to do that - CTRL + SHIFT + P).

Only after that the excluded files will not appear on your quick open menu.

Update: You can run the command "Clear Command History" too. I forgot about that.

Pythonic way to print list items

Assuming you are fine with your list being printed [1,2,3], then an easy way in Python3 is:

mylist=[1,2,3,'lorem','ipsum','dolor','sit','amet']

print(f"There are {len(mylist):d} items in this lorem list: {str(mylist):s}")

Running this produces the following output:

There are 8 items in this lorem list: [1, 2, 3, 'lorem', 'ipsum', 'dolor', 'sit', 'amet']

How to read data from a zip file without having to unzip the entire file

Here is how a UTF8 text file can be read from a zip archive into a string variable (.NET Framework 4.5 and up):

string zipFileFullPath = "{{TypeYourZipFileFullPathHere}}";
string targetFileName = "{{TypeYourTargetFileNameHere}}";
string text = new string(
            (new System.IO.StreamReader(
             System.IO.Compression.ZipFile.OpenRead(zipFileFullPath)
             .Entries.Where(x => x.Name.Equals(targetFileName,
                                          StringComparison.InvariantCulture))
             .FirstOrDefault()
             .Open(), Encoding.UTF8)
             .ReadToEnd())
             .ToArray());

Commit empty folder structure (with git)

Consider also just doing mkdir -p data/images in your Makefile, if the directory needs to be there during build.

If that's not good enough, just create an empty file in data/images and ignore data.

touch data/images/.gitignore
git add data/images/.gitignore
git commit -m "Add empty .gitignore to keep data/images around"
echo data >> .gitignore
git add .gitignore
git commit -m "Add data to .gitignore"

Excel 2010 VBA - Close file No Save without prompt

If you're not wanting to save changes set savechanges to false

    Sub CloseBook2()
        ActiveWorkbook.Close savechanges:=False
    End Sub

for more examples, http://support.microsoft.com/kb/213428 and i believe in the past I've just used

    ActiveWorkbook.Close False

How can I include a YAML file inside another?

Expanding on @Josh_Bode's answer, here's my own PyYAML solution, which has the advantage of being a self-contained subclass of yaml.Loader. It doesn't depend on any module-level globals, or on modifying the global state of the yaml module.

import yaml, os

class IncludeLoader(yaml.Loader):                                                 
    """                                                                           
    yaml.Loader subclass handles "!include path/to/foo.yml" directives in config  
    files.  When constructed with a file object, the root path for includes       
    defaults to the directory containing the file, otherwise to the current       
    working directory. In either case, the root path can be overridden by the     
    `root` keyword argument.                                                      

    When an included file F contain its own !include directive, the path is       
    relative to F's location.                                                     

    Example:                                                                      
        YAML file /home/frodo/one-ring.yml:                                       
            ---                                                                   
            Name: The One Ring                                                    
            Specials:                                                             
                - resize-to-wearer                                                
            Effects: 
                - !include path/to/invisibility.yml                            

        YAML file /home/frodo/path/to/invisibility.yml:                           
            ---                                                                   
            Name: invisibility                                                    
            Message: Suddenly you disappear!                                      

        Loading:                                                                  
            data = IncludeLoader(open('/home/frodo/one-ring.yml', 'r')).get_data()

        Result:                                                                   
            {'Effects': [{'Message': 'Suddenly you disappear!', 'Name':            
                'invisibility'}], 'Name': 'The One Ring', 'Specials':              
                ['resize-to-wearer']}                                             
    """                                                                           
    def __init__(self, *args, **kwargs):                                          
        super(IncludeLoader, self).__init__(*args, **kwargs)                      
        self.add_constructor('!include', self._include)                           
        if 'root' in kwargs:                                                      
            self.root = kwargs['root']                                            
        elif isinstance(self.stream, file):                                       
            self.root = os.path.dirname(self.stream.name)                         
        else:                                                                     
            self.root = os.path.curdir                                            

    def _include(self, loader, node):                                    
        oldRoot = self.root                                              
        filename = os.path.join(self.root, loader.construct_scalar(node))
        self.root = os.path.dirname(filename)                           
        data = yaml.load(open(filename, 'r'))                            
        self.root = oldRoot                                              
        return data                                                      

Can an ASP.NET MVC controller return an Image?

if (!System.IO.File.Exists(filePath))
    return SomeHelper.EmptyImageResult(); // preventing JSON GET/POST exception
else
    return new FilePathResult(filePath, contentType);

SomeHelper.EmptyImageResult() should return FileResult with existing image (1x1 transparent, for example).

This is easiest way if you have files stored on local drive. If files are byte[] or stream - then use FileContentResult or FileStreamResult as Dylan suggested.

Sorting Values of Set

Use the Integer wrapper class instead of String because it is doing the hard work for you by implementing Comparable<Integer>. Then java.util.Collections.sort(list); would do the trick.

How to select all and copy in vim?

ggVG 

will select from beginning to end

Print an ArrayList with a for-each loop

import java.util.ArrayList;
import java.util.List;

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

How can I pull from remote Git repository and override the changes in my local repository?

As an addendum, if you want to reapply your changes on top of the remote, you can also try:

git pull --rebase origin master

If you then want to undo some of your changes (but perhaps not all of them) you can use:

git reset SHA_HASH

Then do some adjustment and recommit.

Multiple radio button groups in one form

To create a group of inputs you can create a custom html element

window.customElements.define('radio-group', RadioGroup);

https://gist.github.com/robdodson/85deb2f821f9beb2ed1ce049f6a6ed47

to keep selected option in each group, you need to add name attribute to inputs in group, if you not add it then all is one group.

is there any alternative for ng-disabled in angular2?

[attr.disabled]="valid == true ? true : null"

You have to use null to remove attr from html element.

How to add shortcut keys for java code in eclipse

The feature is called "code templates" in Eclipse. You can add templates with:

Window->Preferences->Java->Editor->Templates.

Two good articles:

Also, this SO question:

System.out.println() is already mapped to sysout, so you may save time by learning a few of the existing templates first.

await vs Task.Wait - Deadlock?

Some important facts were not given in other answers:

"async await" is more complex at CIL level and thus costs memory and CPU time.

Any task can be canceled if the waiting time is unacceptable.

In the case "async await" we do not have a handler for such a task to cancel it or monitoring it.

Using Task is more flexible then "async await".

Any sync functionality can by wrapped by async.

public async Task<ActionResult> DoAsync(long id) 
{ 
    return await Task.Run(() => { return DoSync(id); } ); 
} 

"async await" generate many problems. We do not now is await statement will be reached without runtime and context debugging. If first await not reached everything is blocked. Some times even await seems to be reached still everything is blocked:

https://github.com/dotnet/runtime/issues/36063

I do not see why I'm must live with the code duplication for sync and async method or using hacks.

Conclusion: Create Task manually and control them is much better. Handler to Task give more control. We can monitor Tasks and manage them:

https://github.com/lsmolinski/MonitoredQueueBackgroundWorkItem

Sorry for my english.

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

Just disable scroll not hide it?

This will stop the viewport jumping to the top by saving the scroll position and restoring it on enabling scrolling.

CSS

.no-scroll{
  position: fixed; 
  width:100%;
  min-height:100vh;
  top:0;
  left:0;
  overflow-y:scroll!important;
}

JS

var scrollTopPostion = 0;

function scroll_pause(){
  scrollTopPostion = $(window).scrollTop();
  $("body").addClass("no-scroll").css({"top":-1*scrollTopPostion+"px"});
}

function scroll_resume(){
  $("body").removeClass("no-scroll").removeAttr("style");
  $(window).scrollTop(scrollTopPostion);
}

Now all you need to do is to call the functions

$(document).on("click","#DISABLEelementID",function(){
   scroll_pause();
});

$(document).on("click","#ENABLEelementID",function(){
   scroll_resume();
});

Split text with '\r\n'

This worked for me.

using System.IO;

//  

    string readStr = File.ReadAllText(file.FullName);          
    string[] read = readStr.Split(new char[] {'\r','\n'},StringSplitOptions.RemoveEmptyEntries);

libxml install error using pip

** make sure the development packages of libxml2 and libxslt are installed **

From the lxml documentation, assuming you are running a Debian-based distribution :

sudo apt-get install libxml2-dev libxslt-dev python-dev

For Debian based systems, it should be enough to install the known build dependencies of python-lxml or python3-lxml, e.g.

sudo apt-get build-dep python3-lxml

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

Only local connections are allowed Chrome and Selenium webdriver

I was also getting the same issue. I resolved this issue by updating the chromedriver. So if anyone is facing same issue with chrome browser just update your chromedriver.

When is layoutSubviews called?

Building on the previous answer by @BadPirate, I experimented a bit further and came up with some clarifications/corrections. I found that layoutSubviews: will be called on a view if and only if:

  • Its own bounds (not frame) changed.
  • The bounds of one of its direct subviews changed.
  • A subview is added to the view or removed from the view.

Some relevant details:

  • The bounds are considered changed only if the new value is different, including a different origin. Note specifically that is why layoutSubviews: is called whenever a UIScrollView scrolls, as it performs the scrolling by changing its bounds' origin.
  • Changing the frame will only change the bounds if the size has changed, as this is the only thing propagated to the bounds property.
  • A change in bounds of a view that is not yet in a view hierarchy will result in a call to layoutSubviews: when the view is eventually added to a view hierarchy.
  • And just for completeness: these triggers do not directly call layoutSubviews, but rather call setNeedsLayout, which sets/raises a flag. Each iteration of the run loop, for all views in the view hierarchy, this flag is checked. For each view where the flag is found raised, layoutSubviews: is called on it and the flag is reset. Views higher up the hierarchy will be checked/called first.

Center form submit buttons HTML / CSS

Try this :

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<head>
    <style type="text/css">
        #btn_s{
            width:100px;
        }

        #btn_i {
            width:125px;
        }
        #formbox {
            width:400px;
            margin:auto 0;
            text-align: center;
        }
    </style>
</head>
<body>
    <form method="post" action="">
        <div id="formbox">
            <input value="Search" title="Search" type="submit" id="btn_s"> 
            <input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit" id="btn_i">
        </div>
    </form>
</body>

This has 2 examples, you can use the one that fits best in your situation.

  • use text-align:center on the parent container, or create a container for this.
  • if the container has to have a fixed size, use auto left and right margins to center it in the parent container.

note that auto is used with single blocks to center them in the parent space by distrubuting the empty space to the left and right.

Access parent DataContext from DataTemplate

RelativeSource vs. ElementName

These two approaches can achieve the same result,

RelativeSource

Binding="{Binding Path=DataContext.MyBindingProperty, 
          RelativeSource={RelativeSource AncestorType={x:Type Window}}}"

This method looks for a control of a type Window (in this example) in the visual tree and when it finds it you basically can access it's DataContext using the Path=DataContext..... The Pros about this method is that you don't need to be tied to a name and it's kind of dynamic, however, changes made to your visual tree can affect this method and possibly break it.

ElementName

Binding="{Binding Path=DataContext.MyBindingProperty, ElementName=MyMainWindow}

This method referes to a solid static Name so as long as your scope can see it, you're fine.You should be sticking to your naming convention not to break this method of course.The approach is qute simple and all you need is to specify a Name="..." for your Window/UserControl.

Although all three types (RelativeSource, Source, ElementName) are capable of doing the same thing, but according to the following MSDN article, each one better be used in their own area of specialty.

How to: Specify the Binding Source

Find the brief description of each plus a link to a more details one in the table on the bottom of the page.

How to clean node_modules folder of packages that are not in package.json?

First globally install rimraf

npm install rimraf -g

go to the path using cmd where your node_modules folder and apply below command

rimraf node_modules

set dropdown value by text using jquery

$("#HowYouKnow").val("GOOGLE");

Command-line Git on Windows

As @birryree said, add msysgit's binary to your PATH, or use Git Bash (installed with msysgit as far as I remember) which is better than Windows' console and similar to the Unix one.

Jquery validation plugin - TypeError: $(...).validate is not a function

If using VueJS, import all the js dependencies for jQuery extensions first, then import $ second...

import "../assets/js/jquery-2.2.3.min.js"
import "../assets/js/jquery-ui-1.12.1.min.js"
import "../assets/js/jquery.validate.min.js"
import $ from "jquery";

You then need to use jquery from a javascript function called from a custom wrapper defined globally in the VueJS prototype method.

This safeguards use of jQuery and jQuery UI from fighting with VueJS.

Vue.prototype.$fValidateTag = function( sTag, rRules ) 
{
    return ValidateTag( sTag, rRules );
};

function ValidateTag( sTag, rRules )
{
    Var rTagT = $( sTag );
    return rParentTag.validate( sTag, rRules );
}

Flask-SQLAlchemy how to delete all rows in a single table

Flask-Sqlalchemy

Delete All Records

#for all records
db.session.query(Model).delete()
db.session.commit()

Deleted Single Row

here DB is the object Flask-SQLAlchemy class. It will delete all records from it and if you want to delete specific records then try filter clause in the query. ex.

#for specific value
db.session.query(Model).filter(Model.id==123).delete()
db.session.commit()

Delete Single Record by Object

record_obj = db.session.query(Model).filter(Model.id==123).first()
db.session.delete(record_obj)
db.session.commit()

https://flask-sqlalchemy.palletsprojects.com/en/2.x/queries/#deleting-records

What's a standard way to do a no-op in python?

Use pass for no-op:

if x == 0:
  pass
else:
  print "x not equal 0"

And here's another example:

def f():
  pass

Or:

class c:
  pass

How can I shrink the drawable on a button?

I tried the techniques of this post but didnot find any of them so attractive. My solution was to use an imageview and textview and align the imageview top and bottom to the textview. This way I got the desired result. Here's some code:

<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="48dp" >


    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignTop="@+id/textViewTitle"
        android:layout_alignBottom="@+id/textViewTitle"
        android:src="@drawable/ic_back" />

    <TextView
        android:id="@+id/textViewBack"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/textViewTitle"
        android:layout_alignBottom="@+id/textViewTitle"
        android:layout_toRightOf="@+id/imageView1"
        android:text="Back"
        android:textColor="@color/app_red"
        android:textSize="@dimen/title_size" />
</RelativeLayout>

Could not load file or assembly 'System.Web.WebPages.Razor, Version=2.0.0.0

by installing AspNetMVC4Setup.exe ( Here is the link :https://www.microsoft.com/en-us/download/details.aspx?id=30683) solves the issue.

by restart/reinstalling Microsoft.AspNet.Mvc Package doesn't help me.

Can Android Studio be used to run standard Java projects?

Easy way to run a java program in Android Studio would be,

  1. Create a java Class says "Test.java" in Android Studio.

  2. Write your code eg, a Hello World program to test.

  3. Right-click on the Java class and:

  • select the option Run 'Test.main()'

or

  • press CTRL + SHIFT + F10 (on windows) or control + R (on Mac)

There you have your Java code running below.

Replacing from match to end-of-line

awk

awk '{gsub(/two.*/,"")}1' file

Ruby

ruby -ne 'print $_.gsub(/two.*/,"")' file

How to change column order in a table using sql query in sql server 2005?

Use

SELECT * FROM TABLE1

which displays the default column order of the table.

If you want to change the order of the columns.

Specify the column name to display correspondingly

SELECT COLUMN1, COLUMN5, COLUMN4, COLUMN3, COULMN2 FROM TABLE1

Will Google Android ever support .NET?

Miguel de Icaza's announced on his blog on the 17th of Feb 2010 that they are starting work on mono for android which will be called MonoDroid.

This will be similar to MonoTouch on the iphone but for android instead.

It will provide binding to the android UI, so apps will look and feel live native android apps. This will require you to write an android specific UI.

You will however be able to reuse you existing lower level libraries without the need to recompile.

How to get previous month and year relative to today, using strtotime and date?

I think you've found a bug in the strtotime function. Whenever I have to work around this, I always find myself doing math on the month/year values. Try something like this:

$LastMonth = (date('n') - 1) % 12;
$Year      =  date('Y') - !$LastMonth;

What is the most efficient way to deep clone an object in JavaScript?

Hope this helps.

function deepClone(obj) {
    /*
     * Duplicates an object 
     */

    var ret = null;
    if (obj !== Object(obj)) { // primitive types
        return obj;
    }
    if (obj instanceof String || obj instanceof Number || obj instanceof Boolean) { // string objecs
        ret = obj; // for ex: obj = new String("Spidergap")
    } else if (obj instanceof Date) { // date
        ret = new obj.constructor();
    } else
        ret = Object.create(obj.constructor.prototype);

    var prop = null;
    var allProps = Object.getOwnPropertyNames(obj); //gets non enumerables also


    var props = {};
    for (var i in allProps) {
        prop = allProps[i];
        props[prop] = false;
    }

    for (i in obj) {
        props[i] = i;
    }

    //now props contain both enums and non enums 
    var propDescriptor = null;
    var newPropVal = null; // value of the property in new object
    for (i in props) {
        prop = obj[i];
        propDescriptor = Object.getOwnPropertyDescriptor(obj, i);

        if (Array.isArray(prop)) { //not backward compatible
            prop = prop.slice(); // to copy the array
        } else
        if (prop instanceof Date == true) {
            prop = new prop.constructor();
        } else
        if (prop instanceof Object == true) {
            if (prop instanceof Function == true) { // function
                if (!Function.prototype.clone) {
                    Function.prototype.clone = function() {
                        var that = this;
                        var temp = function tmp() {
                            return that.apply(this, arguments);
                        };
                        for (var ky in this) {
                            temp[ky] = this[ky];
                        }
                        return temp;
                    }
                }
                prop = prop.clone();

            } else // normal object 
            {
                prop = deepClone(prop);
            }

        }

        newPropVal = {
            value: prop
        };
        if (propDescriptor) {
            /*
             * If property descriptors are there, they must be copied
             */
            newPropVal.enumerable = propDescriptor.enumerable;
            newPropVal.writable = propDescriptor.writable;

        }
        if (!ret.hasOwnProperty(i)) // when String or other predefined objects
            Object.defineProperty(ret, i, newPropVal); // non enumerable

    }
    return ret;
}

https://github.com/jinujd/Javascript-Deep-Clone

Break when a value changes using the Visual Studio debugger

You can probably make a clever use of the DebugBreak() function.

How can I loop through all rows of a table? (MySQL)

Since the suggestion of a loop implies the request for a procedure type solution. Here is mine.

Any query which works on any single record taken from a table can be wrapped in a procedure to make it run through each row of a table like so:

First delete any existing procedure with the same name, and change the delimiter so your SQL doesn't try to run each line as you're trying to write the procedure.

DROP PROCEDURE IF EXISTS ROWPERROW;
DELIMITER ;;

Then here's the procedure as per your example (table_A and table_B used for clarity)

CREATE PROCEDURE ROWPERROW()
BEGIN
DECLARE n INT DEFAULT 0;
DECLARE i INT DEFAULT 0;
SELECT COUNT(*) FROM table_A INTO n;
SET i=0;
WHILE i<n DO 
  INSERT INTO table_B(ID, VAL) SELECT (ID, VAL) FROM table_A LIMIT i,1;
  SET i = i + 1;
END WHILE;
End;
;;

Then dont forget to reset the delimiter

DELIMITER ;

And run the new procedure

CALL ROWPERROW();

You can do whatever you like at the "INSERT INTO" line which I simply copied from your example request.

Note CAREFULLY that the "INSERT INTO" line used here mirrors the line in the question. As per the comments to this answer you need to ensure that your query is syntactically correct for which ever version of SQL you are running.

In the simple case where your ID field is incremented and starts at 1 the line in the example could become:

INSERT INTO table_B(ID, VAL) VALUES(ID, VAL) FROM table_A WHERE ID=i;

Replacing the "SELECT COUNT" line with

SET n=10;

Will let you test your query on the first 10 record in table_A only.

One last thing. This process is also very easy to nest across different tables and was the only way I could carry out a process on one table which dynamically inserted different numbers of records into a new table from each row of a parent table.

If you need it to run faster then sure try to make it set based, if not then this is fine. You could also rewrite the above in cursor form but it may not improve performance. eg:

DROP PROCEDURE IF EXISTS cursor_ROWPERROW;
DELIMITER ;;

CREATE PROCEDURE cursor_ROWPERROW()
BEGIN
  DECLARE cursor_ID INT;
  DECLARE cursor_VAL VARCHAR;
  DECLARE done INT DEFAULT FALSE;
  DECLARE cursor_i CURSOR FOR SELECT ID,VAL FROM table_A;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
  OPEN cursor_i;
  read_loop: LOOP
    FETCH cursor_i INTO cursor_ID, cursor_VAL;
    IF done THEN
      LEAVE read_loop;
    END IF;
    INSERT INTO table_B(ID, VAL) VALUES(cursor_ID, cursor_VAL);
  END LOOP;
  CLOSE cursor_i;
END;
;;

Remember to declare the variables you will use as the same type as those from the queried tables.

My advise is to go with setbased queries when you can, and only use simple loops or cursors if you have to.

How to Deserialize XML document

Try this Generic Class For Xml Serialization & Deserialization.

public class SerializeConfig<T> where T : class
{
    public static void Serialize(string path, T type)
    {
        var serializer = new XmlSerializer(type.GetType());
        using (var writer = new FileStream(path, FileMode.Create))
        {
            serializer.Serialize(writer, type);
        }
    }

    public static T DeSerialize(string path)
    {
        T type;
        var serializer = new XmlSerializer(typeof(T));
        using (var reader = XmlReader.Create(path))
        {
            type = serializer.Deserialize(reader) as T;
        }
        return type;
    }
}

List distinct values in a vector in R

Do you mean unique:

R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4

How to add a new row to an empty numpy array

Here is my solution:

arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)

CSS Background Image Not Displaying

Make sure your body has a height, f.ex:

body { 
    background: url(/img/debut_dark.png) repeat;
    min-height: 100%;
}

comparing two strings in ruby

Here are some:

"Ali".eql? "Ali"
=> true

The spaceship (<=>) method can be used to compare two strings in relation to their alphabetical ranking. The <=> method returns 0 if the strings are identical, -1 if the left hand string is less than the right hand string, and 1 if it is greater:

"Apples" <=> "Apples"
=> 0

"Apples" <=> "Pears"
=> -1

"Pears" <=> "Apples"
=> 1

A case insensitive comparison may be performed using the casecmp method which returns the same values as the <=> method described above:

"Apples".casecmp "apples"
=> 0

JavaScript string encryption and decryption?

Modern browsers now support the crypto.subtle API, which provides native encryption and decryption functions (async no less!) using one of these method: AES-CBC, AES-CTR, AES-GCM, or RSA-OAEP.

https://www.w3.org/TR/WebCryptoAPI/#dfn-Crypto

Viewing contents of a .jar file

Use WinRar. It will open the folder structure for you in intact manner. Also allows in-archive editing, while preserving paths.

Afterall, a JAR file is a ZIP archive only.

Where does Android emulator store SQLite database?

The databases are stored as SQLite files in /data/data/PACKAGE/databases/DATABASEFILE where:

You can see (copy from/to filesystem) the database file in the emulator selecting DDMS perspective, in the File Explorer tab.

Command not found after npm install in zsh

add source /home/YOUUSERNAME/.bash_profile at the beginning of ~/.zshrc

And all missing commands will be detected.

For Mac users : add source /Users/YOUUSERNAME/.bash_profile

Can I have an IF block in DOS batch file?

You can indeed place create a block of statements to execute after a conditional. But you have the syntax wrong. The parentheses must be used exactly as shown:

if <statement> (
    do something
) else (
    do something else
)

However, I do not believe that there is any built-in syntax for else-if statements. You will unfortunately need to create nested blocks of if statements to handle that.


Secondly, that %GPMANAGER_FOUND% == true test looks mighty suspicious to me. I don't know what the environment variable is set to or how you're setting it, but I very much doubt that the code you've shown will produce the result you're looking for.


The following sample code works fine for me:

@echo off

if ERRORLEVEL == 0 (
    echo GP Manager is up
    goto Continue7
)
echo GP Manager is down
:Continue7

Please note a few specific details about my sample code:

  • The space added between the end of the conditional statement, and the opening parenthesis.
  • I am setting @echo off to keep from seeing all of the statements printed to the console as they execute, and instead just see the output of those that specifically begin with echo.
  • I'm using the built-in ERRORLEVEL variable just as a test. Read more here

PowerShell says "execution of scripts is disabled on this system."

Set-ExecutionPolicy RemoteSigned

Executing this command in administrator mode in powershell will solve the problem.

Is it possible to iterate through JSONArray?

Not with an iterator.

For org.json.JSONArray, you can do:

for (int i = 0; i < arr.length(); i++) {
  arr.getJSONObject(i);
}

For javax.json.JsonArray, you can do:

for (int i = 0; i < arr.size(); i++) {
  arr.getJsonObject(i);
}

An unhandled exception occurred during the execution of the current web request. ASP.NET

Incomplete information: we need to know which line is throwing the NullReferenceException in order to tell precisely where the problem lies.

Obviously, you are using an uninitialized variable (i.e., a variable that has been declared but not initialized) and try to access one of its non-static method/property/whatever.

Solution: - Find the line that is throwing the exception from the exception details - In this line, check that every variable you are using has been correctly initialized (i.e., it is not null)

Good luck.

How to exit from ForEach-Object in PowerShell

You have two options to abruptly exit out of ForEach-Object pipeline in PowerShell:

  1. Apply exit logic in Where-Object first, then pass objects to Foreach-Object, or
  2. (where possible) convert Foreach-Object into a standard Foreach looping construct.

Let's see examples: Following scripts exit out of Foreach-Object loop after 2nd iteration (i.e. pipeline iterates only 2 times)":

Solution-1: use Where-Object filter BEFORE Foreach-Object:

[boolean]$exit = $false;
1..10 | Where-Object {$exit -eq $false} | Foreach-Object {
     if($_ -eq 2) {$exit = $true}    #OR $exit = ($_ -eq 2);
     $_;
}

OR

1..10 | Where-Object {$_ -le 2} | Foreach-Object {
     $_;
}

Solution-2: Converted Foreach-Object into standard Foreach looping construct:

Foreach ($i in 1..10) { 
     if ($i -eq 3) {break;}
     $i;
}

PowerShell should really provide a bit more straightforward way to exit or break out from within the body of a Foreach-Object pipeline. Note: return doesn't exit, it only skips specific iteration (similar to continue in most programming languages), here is an example of return:

Write-Host "Following will only skip one iteration (actually iterates all 10 times)";
1..10 | Foreach-Object {
     if ($_ -eq 3) {return;}  #skips only 3rd iteration.
     $_;
}

HTH

How to percent-encode URL parameters in Python?

In Python 3, urllib.quote has been moved to urllib.parse.quote and it does handle unicode by default.

>>> from urllib.parse import quote
>>> quote('/test')
'/test'
>>> quote('/test', safe='')
'%2Ftest'
>>> quote('/El Niño/')
'/El%20Ni%C3%B1o/'

Convert integer into byte array (Java)

Simple solution which properly handles ByteOrder:

ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();

Hadoop cluster setup - java.net.ConnectException: Connection refused

In my experaince

15/02/22 18:23:04 WARN util.NativeCodeLoader: Unable to load native-hadoop
library for your platform... using builtin-java classes where applicable

You may have 64 bit version OS, and hadoop installation 32bit. refer this

java.net.ConnectException: Call From marta-komputer/127.0.1.1 to
localhost:9000 failed on connection exception: java.net.ConnectException: 
connection refused; For more details see:   
http://wiki.apache.org/hadoop/ConnectionRefused

this problem refers to your ssh public key authorization. please provide details about your ssh set up.

Please refer this link to check the complete steps.

also provide info if

cat $HOME/.ssh/authorized_keys

returns any result or not.

How to clear a chart from a canvas so that hover events cannot be triggered?

This is the only thing that worked for me:

document.getElementById("chartContainer").innerHTML = '&nbsp;';
document.getElementById("chartContainer").innerHTML = '<canvas id="myCanvas"></canvas>';
var ctx = document.getElementById("myCanvas").getContext("2d");

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

In Visual Studio 2019 Just remove Debug profile and create new one Do the Trick

  1. Go to Project properties In debug tab
  2. try first Changing ports Web Server Settings
  3. if Changing ports not worked then Remove Debug Profile and Create new One-Warning Make Sure You Know Previous Settings

WARNING: sanitizing unsafe style value url

In my case, I got the image URL before getting to the display component and want to use it as the background image so to use that URL I have to tell Angular that it's safe and can be used.

In .ts file

userImage: SafeStyle;
ngOnInit(){
    this.userImage = this.sanitizer.bypassSecurityTrustStyle('url(' + sessionStorage.getItem("IMAGE") + ')');
}

In .html file

<div mat-card-avatar class="nav-header-image" [style.background-image]="userImage"></div>

Print Currency Number Format in PHP

sprintf() is the PHP function for all sorts of string formatting http://php.net/manual/en/function.sprintf.php

I use this function:

function formatDollars($dollars){
  return '$ '.sprintf('%0.2f', $dollars);
}

Apache POI Excel - how to configure columns to be expanded?

You can try something like this:

HSSFSheet summarySheet = wb.createSheet();
summarySheet.setColumnWidth(short column, short width);

Here params are:column number in sheet and its width But,the units of width are pretty small, you can try 4000 for example.

How to fix ReferenceError: primordials is not defined in node

I fixed this issue on Windows 10 by uninstalling node from Add or remove programs -> Node.js

Then I installed version 11.15.0 from https://nodejs.org/download/release/v11.15.0/

Choose node-v11.15.0-x64.msi if your running windows 64bit.

How to disable editing of elements in combobox for c#?

Use the ComboStyle property:

comboBox.DropDownStyle = ComboBoxStyle.DropDownList;

Find index of last occurrence of a substring in a string

If you don't wanna use rfind then this will do the trick/

def find_last(s, t):
    last_pos = -1
    while True:
        pos = s.find(t, last_pos + 1)
        if pos == -1:
            return last_pos
        else:
            last_pos = pos

Reusing output from last command in Bash

I think using script command might help. Something like,

  1. script -c bash -qf fifo_pid

  2. Using bash features to set after parsing.

How to submit a form on enter when the textarea has focus?

Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

<input type="text" value="...">

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

<textarea name="area"></textarea>

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

How can I make a program wait for a variable change in javascript?

I would recommend a wrapper that will handle value being changed. For example you can have JavaScript function, like this:

?function Variable(initVal, onChange)
{
    this.val = initVal;          //Value to be stored in this object
    this.onChange = onChange;    //OnChange handler

    //This method returns stored value
    this.GetValue = function()  
    {
        return this.val;
    }

    //This method changes the value and calls the given handler       
    this.SetValue = function(value)
    {
        this.val = value;
        this.onChange();
    }


}

And then you can make an object out of it that will hold value that you want to monitor, and also a function that will be called when the value gets changed. For example, if you want to be alerted when the value changes, and initial value is 10, you would write code like this:

var myVar = new Variable(10, function(){alert("Value changed!");});

Handler function(){alert("Value changed!");} will be called (if you look at the code) when SetValue() is called.

You can get value like so:

alert(myVar.GetValue());

You can set value like so:

myVar.SetValue(12);

And immediately after, an alert will be shown on the screen. See how it works: http://jsfiddle.net/cDJsB/

Create a custom callback in JavaScript

When calling the callback function, we could use it like below:

consumingFunction(callbackFunctionName)

Example:

// Callback function only know the action,
// but don't know what's the data.
function callbackFunction(unknown) {
  console.log(unknown);
}

// This is a consuming function.
function getInfo(thenCallback) {
  // When we define the function we only know the data but not
  // the action. The action will be deferred until excecuting.
  var info = 'I know now';
  if (typeof thenCallback === 'function') {
    thenCallback(info);    
  }
}

// Start.
getInfo(callbackFunction); // I know now

This is the Codepend with full example.

Disable native datepicker in Google Chrome

The code above doesn't set the value of the input element nor does it fire a change event. The code below works in Chrome and Firefox (not tested in other browsers):

$('input[type="date"]').click(function(e){
     e.preventDefault();
}).datepicker({
    onSelect: function(dateText){
        var d = new Date(dateText),
        dv = d.getFullYear().toString().pad(4)+'-'+(d.getMonth()+1).toString().pad(2)+'-'+d.getDate().toString().pad(2);
        $(this).val(dv).trigger('change');
    }
});

pad is a simple custom String method to pad strings with zeros (required)

git - pulling from specific branch

if you want to pull from a specific branch all you have to do is

git pull 'remote_name' 'branch_name'

NOTE: Make sure you commit your code first.

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

Replace tabs with spaces in vim

Try

set expandtab

for soft tabs.

To fix pre-existing tabs:

:%s/\t/  /g

I used two spaces since you already set your tabstop to 2 spaces.

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

Go to the preview version of tomcat e.g. : tomcat 8.3 and copy catalina.jar file and paste into the existing tomcat which you have facing the issue

Switch: Multiple values in one case?

Separate the business rules for age from the actions e.g. (NB just typed, not checked)

enum eAgerange { eChild, eYouth, eAdult, eAncient};
eAgeRange ar;
if(age <= 8) ar = eChild;
else if(age <= 15) ar = eYouth;
else if(age <= 100) ar = eAdult;
else ar = eAncient;
switch(ar)
{
 case eChild: 
     // action
 case eYouth:
     // action
 case eAdult:
     // action
 case eAncient:
     // action
 default: throw new NotImplementedException($"Oops {ar.ToString()} not handled");
}   

`

RelativeLayout center vertical

use

 android:layout_centerVertical="true"

Get current URL/URI without some of $_GET variables

I don't know about doing it in Yii, but you could just do this, and it should work anywhere (largely lifted from my answer here):

// Get HTTP/HTTPS (the possible values for this vary from server to server)
$myUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] && !in_array(strtolower($_SERVER['HTTPS']),array('off','no'))) ? 'https' : 'http';
// Get domain portion
$myUrl .= '://'.$_SERVER['HTTP_HOST'];
// Get path to script
$myUrl .= $_SERVER['REQUEST_URI'];
// Add path info, if any
if (!empty($_SERVER['PATH_INFO'])) $myUrl .= $_SERVER['PATH_INFO'];

$get = $_GET; // Create a copy of $_GET
unset($get['lg']); // Unset whatever you don't want
if (count($get)) { // Only add a query string if there's anything left
  $myUrl .= '?'.http_build_query($get);
}

echo $myUrl;

Alternatively, you could pass the result of one of the Yii methods into parse_url(), and manipulate the result to re-build what you want.

Merging arrays with the same keys

Two entries in an array can't share a key, you'll need to change the key for the duplicate

How can I make Bootstrap columns all the same height?

I use this super easy solution with clearfix, which doesn't have any side effects.

Here is an example on AngularJS:

<div ng-repeat-start="item in list">
    <div class="col-lg-4 col-md-6 col-sm-12 col-xs-12"></div>
</div>
<div ng-repeat-end>
    <div ng-if="$index % 3 == 2" class="clearfix visible-lg"></div>
    <div ng-if="$index % 2 == 1" class="clearfix visible-md"></div>
</div>

And one more example on PHP:

<?php foreach ($list as $i => $item): ?>
    <div class="col-lg-4 col-md-6 col-sm-12 col-xs-12"></div>
    <div class="clearfix visible-md"></div>
    <?php if ($i % 2 === 1): ?>
        <div class="clearfix visible-lg"></div>
    <?php endif; ?>
<?php endforeach; ?>

JSchException: Algorithm negotiation fail

The complete steps to add the algorithms to the RECEIVING server (the one you are connecting to). I'm assuming this is a Linux server.

sudo /etc/ssh/sshd_config

Add this to the file (it can be at the end):

KexAlgorithms [email protected],ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1,diffie-hellman-group-exchange-sha1,diffie-hellman-group1-sha1

Then restart the SSH server:

sudo service sshd restart

Efficient method to generate UUID String in JAVA (UUID.randomUUID().toString() without the dashes)

A simple solution is

UUID.randomUUID().toString().replace("-", "")

(Like the existing solutions, only that it avoids the String#replaceAll call. Regular expression replacement is not required here, so String#replace feels more natural, though technically it still is implemented with regular expressions. Given that the generation of the UUID is more costly than the replacement, there should not be a significant difference in runtime.)

Using the UUID class is probably fast enough for most scenarios, though I would expect that some specialized hand-written variant, which does not need the postprocessing, to be faster. Anyway, the bottleneck of the overall computation will normally be the random number generator. In case of the UUID class, it uses SecureRandom.

Which random number generator to use is also a trade-off that depends on the application. If it is security-sensitive, SecureRandom is, in general, the recommendation. Otherwise, ThreadLocalRandom is an alternative (faster than SecureRandom or the old Random, but not cryptographically secure).

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Use this code ,which helped me to open all types of files ...

 private void openFile(File url) {

    try {

        Uri uri = Uri.fromFile(url);

        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (url.toString().contains(".doc") || url.toString().contains(".docx")) {
            // Word document
            intent.setDataAndType(uri, "application/msword");
        } else if (url.toString().contains(".pdf")) {
            // PDF file
            intent.setDataAndType(uri, "application/pdf");
        } else if (url.toString().contains(".ppt") || url.toString().contains(".pptx")) {
            // Powerpoint file
            intent.setDataAndType(uri, "application/vnd.ms-powerpoint");
        } else if (url.toString().contains(".xls") || url.toString().contains(".xlsx")) {
            // Excel file
            intent.setDataAndType(uri, "application/vnd.ms-excel");
        } else if (url.toString().contains(".zip")) {
            // ZIP file
            intent.setDataAndType(uri, "application/zip");
        } else if (url.toString().contains(".rar")){
            // RAR file
            intent.setDataAndType(uri, "application/x-rar-compressed");
        } else if (url.toString().contains(".rtf")) {
            // RTF file
            intent.setDataAndType(uri, "application/rtf");
        } else if (url.toString().contains(".wav") || url.toString().contains(".mp3")) {
            // WAV audio file
            intent.setDataAndType(uri, "audio/x-wav");
        } else if (url.toString().contains(".gif")) {
            // GIF file
            intent.setDataAndType(uri, "image/gif");
        } else if (url.toString().contains(".jpg") || url.toString().contains(".jpeg") || url.toString().contains(".png")) {
            // JPG file
            intent.setDataAndType(uri, "image/jpeg");
        } else if (url.toString().contains(".txt")) {
            // Text file
            intent.setDataAndType(uri, "text/plain");
        } else if (url.toString().contains(".3gp") || url.toString().contains(".mpg") ||
                url.toString().contains(".mpeg") || url.toString().contains(".mpe") || url.toString().contains(".mp4") || url.toString().contains(".avi")) {
            // Video files
            intent.setDataAndType(uri, "video/*");
        } else {
            intent.setDataAndType(uri, "*/*");
        }

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(context, "No application found which can open the file", Toast.LENGTH_SHORT).show();
    }
}

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

Foreach value from POST from form

First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters

In addition, you don't have to use variable variable names (that sounds odd), instead:

foreach($_POST as $key => $value) {
  echo "POST parameter '$key' has '$value'";
}

To ensure that you have only parameters beginning with 'item_name' you can check it like so:

$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
  // do something
}

How to find a whole word in a String in java

Looking back at the original question, we need to find some given keywords in a given sentence, count the number of occurrences and know something about where. I don't quite understand what "where" means (is it an index in the sentence?), so I'll pass that one... I'm still learning java, one step at a time, so I'll see to that one in due time :-)

It must be noticed that common sentences (as the one in the original question) can have repeated keywords, therefore the search cannot just ask if a given keyword "exists or not" and count it as 1 if it does exist. There can be more then one of the same. For example:

// Base sentence (added punctuation, to make it more interesting):
String sentence = "Say that 123 of us will come by and meet you, "
                + "say, at the woods of 123woods.";

// Split it (punctuation taken in consideration, as well):
java.util.List<String> strings = 
                       java.util.Arrays.asList(sentence.split(" |,|\\."));

// My keywords:
java.util.ArrayList<String> keywords = new java.util.ArrayList<>();
keywords.add("123woods");
keywords.add("come");
keywords.add("you");
keywords.add("say");

By looking at it, the expected result would be 5 for "Say" + "come" + "you" + "say" + "123woods", counting "say" twice if we go lowercase. If we don't, then the count should be 4, "Say" being excluded and "say" included. Fine. My suggestion is:

// Set... ready...?
int counter = 0;

// Go!
for(String s : strings)
{
    // Asking if the sentence exists in the keywords, not the other
    // around, to find repeated keywords in the sentence.
    Boolean found = keywords.contains(s.toLowerCase());
    if(found)
    {
        counter ++;
        System.out.println("Found: " + s);
    }
}

// Statistics:
if (counter > 0)
{
    System.out.println("In sentence: " + sentence + "\n"
                     + "Count: " + counter);
}

And the results are:

Found: Say
Found: come
Found: you
Found: say
Found: 123woods
In sentence: Say that 123 of us will come by and meet you, say, at the woods of 123woods.
Count: 5

Round to 5 (or other number) in Python

round(x[, n]): values are rounded to the closest multiple of 10 to the power minus n. So if n is negative...

def round5(x):
    return int(round(x*2, -1)) / 2

Since 10 = 5 * 2, you can use integer division and multiplication with 2, rather than float division and multiplication with 5.0. Not that that matters much, unless you like bit shifting

def round5(x):
    return int(round(x << 1, -1)) >> 1

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
     writeJson("JsonFile.json");
     readgson("JsonFile.json");
}
public static void readgson(String file) {
    try {
        System.out.println( "Reading JSON file from Java program" );

        FileReader fileReader = new FileReader( file );
        com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );

        Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
        if ( keys.isEmpty() ) {
            System.out.println( "Empty JSON Object" );
        }else {
            Map<String, Object> map = json_UnKnown_Format( keys );
            System.out.println("Json 2 Map : "+map);
        }

    } catch (IOException ex) {
        System.out.println("Input File Does not Exists.");
    }
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    for (Entry<String, JsonElement> entry : keys) {
        String keyEntry = entry.getKey();
        System.out.println(keyEntry + " : ");
        JsonElement valuesEntry =  entry.getValue();
        if (valuesEntry.isJsonNull()) {
            System.out.println(valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonPrimitive()) {
            System.out.println("P - "+valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonArray()) {
            JsonArray array = valuesEntry.getAsJsonArray();
            List<Object> array2List = new ArrayList<Object>();
            for (JsonElement jsonElements : array) {
                System.out.println("A - "+jsonElements);
                array2List.add(jsonElements);
            }
            jsonMap.put(keyEntry, array2List);
        }else if (valuesEntry.isJsonObject()) {             
             com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());                    
             Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
             jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
        }
    }
    return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {

    JSONObject json = new JSONObject();

    json.put("Key1", "Value");
    json.put("Key2", 777); // Converts to "777"
    json.put("Key3", null);
    json.put("Key4", false);

        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Array-Value1");
        jsonArray.put(10); 
        jsonArray.put("Array-Value2");

    json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Obj-Key1", 20);
        jsonObj.put("Obj-Key2", "Value2");
        jsonObj.put(4, "Value2"); // Converts to "4"

    json.put("InnerObject", jsonObj);

        JSONObject jsonObjArray = new JSONObject();
            JSONArray objArray = new JSONArray();
            objArray.put("Obj-Array1");
            objArray.put(0, "Obj-Array3");
        jsonObjArray.put("ObjectArray", objArray);

    json.put("InnerObjectArray", jsonObjArray);

        Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
        sortedTree.put("Sorted1", 10);
        sortedTree.put("Sorted2", 103);
        sortedTree.put("Sorted3", 14);

    json.put("TreeMap", sortedTree);        

    try {
        System.out.println("Writting JSON into file ...");
        System.out.println(json);
        FileWriter jsonFileWriter = new FileWriter(file);
        jsonFileWriter.write(json.toJSONString());
        jsonFileWriter.flush();
        jsonFileWriter.close();
        System.out.println("Done");

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

}

Test credit card numbers for use with PayPal sandbox

A bit late in the game but just in case it helps anyone.

If you are testing using the Sandbox and on the payment page you want to test payments NOT using a PayPal account but using the "Pay with Debit or Credit Card option" (i.e. when a regular Joe/Jane, NOT PayPal users, want to buy your stuff) and want to save yourself some time: just go to a site like http://www.getcreditcardnumbers.com/ and get numbers from there. You can use any Expiry date (in the future) and any numeric CCV (123 works).

The "test credit card numbers" in the PayPal documentation are just another brick in their infuriating wall of convoluted stuff.

I got the url above from PayPal's tech support.

Tested using a simple Hosted button and IPN. Good luck.

Concat all strings inside a List<string> using LINQ

By using LINQ, this should work;

string delimiter = ",";
List<string> items = new List<string>() { "foo", "boo", "john", "doe" };
Console.WriteLine(items.Aggregate((i, j) => i + delimiter + j));

class description:

public class Foo
{
    public string Boo { get; set; }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string delimiter = ",";
        List<Foo> items = new List<Foo>() { new Foo { Boo = "ABC" }, new Foo { Boo = "DEF" },
            new Foo { Boo = "GHI" }, new Foo { Boo = "JKL" } };

        Console.WriteLine(items.Aggregate((i, j) => new Foo{Boo = (i.Boo + delimiter + j.Boo)}).Boo);
        Console.ReadKey();

    }
}

And here is my best :)

items.Select(i => i.Boo).Aggregate((i, j) => i + delimiter + j)

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

It's also easy to use Alien as a libc/msvcrt wrapper:

> luarocks install alien

Then from lua:

require 'alien'

if alien.platform == "windows" then
    -- untested!!
    libc = alien.load("msvcrt.dll")
else
    libc = alien.default
end 

usleep = libc.usleep
usleep:types('int', 'uint')

function sleep(ms)
    while ms > 1000 do
        usleep(1000)
        ms = ms - 1000
    end
    usleep(1000 * ms)
end

print('hello')
sleep(500)  -- sleep 500 ms
print('world')

Caveat lector: I haven't tried this on MSWindows; I don't even know if msvcrt has a usleep()

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I resolved this issue by adding jackson-json data binding to my pom.

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.6.3</version>
</dependency>

Can I access a form in the controller?

To be able to access the form in your controller, you have to add it to a dummy scope object.

Something like $scope.dummy = {}

For your situation this would mean something like:

<form name="dummy.customerForm">

In your controller you will be able to access the form by:

$scope.dummy.customerForm

and you will be able to do stuff like

$scope.dummy.customerForm.$setPristine()

WIKI LINK

Having a '.' in your models will ensure that prototypal inheritance is in play. So, use <input type="text" ng-model="someObj.prop1"> rather than <input type="text" ng-model="prop1">

If you really want/need to use a primitive, there are two workarounds:

1.Use $parent.parentScopeProperty in the child scope. This will prevent the child scope from creating its own property. 2.Define a function on the parent scope, and call it from the child, passing the primitive value up to the parent (not always possible)

Output an Image in PHP

$file = '../image.jpg';
$type = 'image/jpeg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

How to increase the gap between text and underlining in CSS

I know it's an old question, but for single line text setting display: inline-block and then setting the height has worked well for me to control the distance between a border and the text.

Run / Open VSCode from Mac Terminal

I just want to pull out Benjamin Pasero's answer from inside his comment as it seems the best solution. It is the tip given on the Setting up Visual Studio Code page where it says ...

If you want to run VS Code from the terminal, append the following to your ~/.bash_profile file (~/.zshrc in case you use zsh).

code () { VSCODE_CWD="$PWD" open -n -b "com.microsoft.VSCode" --args $* ;}

Now, you can simply type code . in any folder to start editing files in that folder. [Or code test.txt to go to work on the test.txt file]

What .NET collection provides the fastest search

If you don't need ordering, try HashSet<Record> (new to .Net 3.5)

If you do, use a List<Record> and call BinarySearch.

toggle show/hide div with button?

JavaScript - Toggle Element.styleMDN

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
  display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

About the ^ bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset

JavaScript - Toggle .classList.toggle()

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function() {
  content.classList.toggle("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle

.toggle()Docs; .fadeToggle()Docs; .slideToggle()Docs

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggle();                 // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
  display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

jQuery - Toggle .toggleClass()Docs

.toggle() toggles an element's display "block"/"none" values

_x000D_
_x000D_
$("#toggle").on("click", function(){
  $("#content").toggleClass("show");
});
_x000D_
#content{
  display:none;
}
#content.show{
  display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
_x000D_
_x000D_

HTML5 - Toggle using <summary> and <details>

(unsupported on IE and Opera Mini)

_x000D_
_x000D_
<details>
  <summary>TOGGLE</summary>
  <p>Some content...</p>
</details>
_x000D_
_x000D_
_x000D_

HTML - Toggle using checkbox

_x000D_
_x000D_
[id^=toggle],
[id^=toggle] + *{
  display:none;
}
[id^=toggle]:checked + *{
  display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>

<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
_x000D_
_x000D_

HTML - Switch using radio

_x000D_
_x000D_
[id^=switch],
[id^=switch] + *{
  display:none;
}
[id^=switch]:checked + *{
  display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>

<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>

<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_

CSS - Switch using :target

(just to make sure you have it in your arsenal)

_x000D_
_x000D_
[id^=switch] + *{
  display:none;
}
[id^=switch]:target + *{
  display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>

<i id="switch1"></i>
<div>1 Merol Muspi ...</div>

<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
_x000D_
_x000D_


Animating class transition

If you pick one of JS / jQuery way to actually toggle a className, you can always add animated transitions to your element, here's a basic example:

_x000D_
_x000D_
var toggle  = document.getElementById("toggle");
var content = document.getElementById("content");

toggle.addEventListener("click", function(){
  content.classList.toggle("appear");
}, false);
_x000D_
#content{
  /* DON'T USE DISPLAY NONE/BLOCK! Instead: */
  background: #cf5;
  padding: 10px;
  position: absolute;
  visibility: hidden;
  opacity: 0;
          transition: 0.6s;
  -webkit-transition: 0.6s;
          transform: translateX(-100%);
  -webkit-transform: translateX(-100%);
}
#content.appear{
  visibility: visible;
  opacity: 1;
          transform: translateX(0);
  -webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
_x000D_
_x000D_

sqlite3.OperationalError: unable to open database file

Run into the error on Windows, added assert os.path.exists, double checked the path, run the script as administrator, nothing helped.

Turns out if you add your folders to the Windows Defender's Ransomware Protection, you can no longer use other programs to write there unless you add these programs to the Controlled Folder Access' whitelist.

Solution - check if your folder has been added to the Windows Defender's Ransomware Protection and remove it for faster fix.

How to create a inset box-shadow only on one side?

try it, maybe useful...

box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 3px #cbc9c9;
                    -webkit-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -o-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -moz-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;  

above CSS cause you have a box shadow in bottom.
you can red more Here

How to Return partial view of another controller by controller?

Simply you could use:

PartialView("../ABC/XXX")

Check if a radio button is checked jquery

  $('#submit_button').click(function() {
    if (!$("input[@name='name']:checked").val()) {
       alert('Nothing is checked!');
        return false;
    }
    else {
      alert('One of the radio buttons is checked!');
    }
  });

HashSet vs LinkedHashSet

HashSet don't maintain the order of insertion item
LinkedHashSet maintain the order of insertion item

Example

Set<String> set = ...;// using new HashSet<>() OR new LinkedHashSet<>()
set.add("2");
set.add("1");
set.add("ab");
for(String value : set){
   System.out.println(value);
}  

HashSet output

1
ab
2

LinkedHashSet output

2
1
ab

How to split a string after specific character in SQL Server and update this value to specific column

From: http://www.sql-server-helper.com/error-messages/msg-536.aspx

To use function LEFT if not all data is in the form '1/12' you need this in the second line above:

Set Col2 = LEFT(Col1, ISNULL(NULLIF(CHARINDEX('/', Col1) - 1, -1), LEN(Col1)))

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

I think amazon definition is straight and simple to understand.

"Continuous delivery is a software development methodology where the release process is automated. Every software change is automatically built, tested, and deployed to production. Before the final push to production, a person, an automated test, or a business rule decides when the final push should occur. Although every successful software change can be immediately released to production with continuous delivery, not all changes need to be released right away.

Continuous integration is a software development practice where members of a team use a version control system and integrate their work frequently to the same location, such as a master branch. Each change is built and verified by tests and other verifications in order to detect any integration errors as quickly as possible. Continuous integration is focused on automatically building and testing code, as compared to continuous delivery, which automates the entire software release process up to production."

Please check out http://docs.aws.amazon.com/codepipeline/latest/userguide/concepts.html

Create boolean column in MySQL with false as default value?

Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.

ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'

How to split a file into equal parts, without breaking individual lines?

I made a bash script, that given a number of parts as input, split a file

#!/bin/sh

parts_total="$2";
input="$1";

parts=$((parts_total))
for i in $(seq 0 $((parts_total-2))); do
  lines=$(wc -l "$input" | cut -f 1 -d" ")
  #n is rounded, 1.3 to 2, 1.6 to 2, 1 to 1
  n=$(awk  -v lines=$lines -v parts=$parts 'BEGIN { 
    n = lines/parts;
    rounded = sprintf("%.0f", n);
    if(n>rounded){
      print rounded + 1;
    }else{
      print rounded;
    }
  }');
  head -$n "$input" > split${i}
  tail -$((lines-n)) "$input" > .tmp${i}
  input=".tmp${i}"
  parts=$((parts-1));
done
mv .tmp$((parts_total-2)) split$((parts_total-1))
rm .tmp*

I used head and tail commands, and store in tmp files, for split the files

#10 means 10 parts
sh mysplitXparts.sh input_file 10

or with awk, where 0.1 is 10% => 10 parts, or 0.334 is 3 parts

awk -v size=$(wc -l < input) -v perc=0.1 '{
  nfile = int(NR/(size*perc)); 
  if(nfile >= 1/perc){
    nfile--;
  } 
  print > "split_"nfile
}' input

HTML button calling an MVC Controller and Action method

This is how you can submit your form to a specific controller and action method in Razor.

 <input type="submit" value="Upload" onclick="location.href='@Url.Action("ActionName", "ControllerName")'" />

How can I clear or empty a StringBuilder?

delete is not overly complicated :

myStringBuilder.delete(0, myStringBuilder.length());

You can also do :

myStringBuilder.setLength(0);

How to execute python file in linux

1.save your file name as hey.py with the below given hello world script

#! /usr/bin/python
print('Hello, world!')

2.open the terminal in that directory

$ python hey.py

or if you are using python3 then

$ python3 hey.py