Programs & Examples On #Ctest

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

Delay/Wait in a test case of Xcode UI testing

Edit:

It actually just occurred to me that in Xcode 7b4, UI testing now has expectationForPredicate:evaluatedWithObject:handler:

Original:

Another way is to spin the run loop for a set amount of time. Really only useful if you know how much (estimated) time you'll need to wait for

Obj-C: [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow: <<time to wait in seconds>>]]

Swift: NSRunLoop.currentRunLoop().runMode(NSDefaultRunLoopMode, beforeDate: NSDate(timeIntervalSinceNow: <<time to wait in seconds>>))

This is not super useful if you need to test some conditions in order to continue your test. To run conditional checks, use a while loop.

Java ElasticSearch None of the configured nodes are available

NoNodeAvailableException[None of the configured nodes are available: [{#transport#-1}{UfB9geJCR--spyD7ewmoXQ}{192.168.1.245}{192.168.1.245:9300}]]

In my case it was the difference in versions. If you check the logs in elasticsearch cluster you will see.

Elasticsearch logs

[node1] exception caught on transport layer [NettyTcpChannel{localAddress=/192.168.1.245:9300, remoteAddress=/172.16.1.47:65130}], closing connection
java.lang.IllegalStateException: Received message from unsupported version: [5.0.0] minimal compatible version is: [5.6.0]

I was using elasticsearch client and transport version 5.1.1. And my elasticsearch cluster version was in 6. So I changes my library version to 5.4.3.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

How do I import a Swift file from another Swift file?

Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.

Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.

java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder

You need to encode your parameter's values before concatenating them to URL.
Backslash \ is special character which have to be escaped as %5C

Escaping example:

String paramValue = "param\\with\\backslash";
String yourURLStr = "http://host.com?param=" + java.net.URLEncoder.encode(paramValue, "UTF-8");
java.net.URL url = new java.net.URL(yourURLStr);

The result is http://host.com?param=param%5Cwith%5Cbackslash which is properly formatted url string.

How can I tell Moq to return a Task?

Your method doesn't have any callbacks so there is no reason to use .CallBack(). You can simply return a Task with the desired values using .Returns() and Task.FromResult, e.g.:

MyType someValue=...;
mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.FromResult(someValue));

Update 2014-06-22

Moq 4.2 has two new extension methods to assist with this.

mock.Setup(arg=>arg.DoSomethingAsync())
    .ReturnsAsync(someValue);

mock.Setup(arg=>arg.DoSomethingAsync())        
    .ThrowsAsync(new InvalidOperationException());

Update 2016-05-05

As Seth Flowers mentions in the other answer, ReturnsAsync is only available for methods that return a Task<T>. For methods that return only a Task,

.Returns(Task.FromResult(default(object)))

can be used.

As shown in this answer, in .NET 4.6 this is simplified to .Returns(Task.CompletedTask);, e.g.:

mock.Setup(arg=>arg.DoSomethingAsync())        
    .Returns(Task.CompletedTask);

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

works:

<style name="MyApp" parent="Theme.AppCompat.Light">
</style>
<style name="MyApp" parent="@style/Theme.AppCompat.Light">
</style>
<style name="Theme.AppCompat.Light.MyApp">
</style>

How to pass multiple arguments in processStartInfo?

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = @"/c -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer"

use /c as a cmd argument to close cmd.exe once its finish processing your commands

Unit testing private methods in C#

Ermh... Came along here with exactly the same problem: Test a simple, but pivotal private method. After reading this thread, it appears to be like "I want to drill this simple hole in this simple piece of metal, and I want to make sure the quality meets the specs", and then comes "Okay, this is not to easy. First of all, there is no proper tool to do so, but you could build a gravitational-wave observatory in your garden. Read my article at http://foobar.brigther-than-einstein.org/ First, of course, you have to attend some advanced quantum physics courses, then you need tons of ultra-cool nitrogenium, and then, of course, my book available at Amazon"...

In other words...

No, first things first.

Each and every method, may it private, internal, protected, public has to be testable. There has to be a way to implement such tests without such ado as was presented here.

Why? Exactly because of the architectural mentions done so far by some contributors. Perhaps a simple reiteration of software principles may clear up some missunderstandings.

In this case, the usual suspects are: OCP, SRP, and, as always, KIS.

But wait a minute. The idea of making everything publicly available is more of less political and a kind of an attitude. But. When it comes to code, even in then Open Source Community, this is no dogma. Instead, "hiding" something is good practice to make it easier to come familiar with a certain API. You would hide, for example, the very core calculations of your new-to-market digital thermometer building block--not to hide the maths behind the real measured curve to curious code readers, but to prevent your code from becoming dependent on some, perhaps suddenly important users who could not resist using your formerly private, internal, protected code to implement their own ideas.

What am I talking about?

private double TranslateMeasurementIntoLinear(double actualMeasurement);

It's easy to proclaim the Age of Aquarius or what is is been called nowadays, but if my piece of sensor gets from 1.0 to 2.0, the implementation of Translate... might change from a simple linear equation that is easily understandable and "re-usable" for everybody, to a pretty sophisticated calculation that uses analysis or whatever, and so I would break other's code. Why? Because they didn't understand the very priciples of software coding, not even KIS.

To make this fairy tale short: We need a simple way to test private methods--without ado.

First: Happy new year everyone!

Second: Rehearse your architect lessons.

Third: The "public" modifier is religion, not a solution.

inject bean reference into a Quartz job in Spring?

A solution from Hary https://stackoverflow.com/a/37797575/4252764 works very well. It's simpler, doesn't need so many special factory beans, and support multiple triggers and jobs. Would just add that Quartz job can be made to be generic, with specific jobs implemented as regular Spring beans.

public interface BeanJob {
  void executeBeanJob();
}

public class GenericJob implements Job {

  @Override
  public void execute(JobExecutionContext context) throws JobExecutionException {
    JobDataMap dataMap = context.getMergedJobDataMap();
    ((BeanJob)dataMap.get("beanJob")).executeBeanJob();    
  }

}

@Component
public class RealJob implements BeanJob {
  private SomeService service;

  @Autowired
  public RealJob(SomeService service) {
    this.service = service;
  }

  @Override
  public void executeBeanJob() {
      //do do job with service
  }

}

How do I configure PyCharm to run py.test tests?

With 2018.3 it appears to automatically detect that I'm using pytest, which is nice, but it still doesn't allow running from the top level of the project. I had to run pytest for each tests directory individually.

However, I found that I could choose one of the configurations and manually edit it to run at the root of the project and that this worked. I have to manually choose it in the Configurations drop-down - can't right click on the root folder in the Project pane. But at least it allows me to run all tests at once.

Testing whether a value is odd or even

var isOdd = x => Boolean(x % 2);
var isEven = x => !isOdd(x);

Rotating videos with FFmpeg

Smartphone: Recored a video in vertical format

Want to send it to a webside it was 90° to the left (anti clockwise, landscape format) hmm.

ffmpeg -i input.mp4 -vf "rotate=0" output.mp4

does it. I got vertical format back again

debian buster: ffmpeg --version ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers

Using PropertyInfo.GetValue()

In your example propertyInfo.GetValue(this, null) should work. Consider altering GetNamesAndTypesAndValues() as follows:

public void GetNamesAndTypesAndValues()
{
  foreach (PropertyInfo propertyInfo in allClassProperties)
  {
    Console.WriteLine("{0} [type = {1}] [value = {2}]",
      propertyInfo.Name,
      propertyInfo.PropertyType,
      propertyInfo.GetValue(this, null));
  }
}

Good way to encapsulate Integer.parseInt()

What about forking the parseInt method?

It's easy, just copy-paste the contents to a new utility that returns Integer or Optional<Integer> and replace throws with returns. It seems there are no exceptions in the underlying code, but better check.

By skipping the whole exception handling stuff, you can save some time on invalid inputs. And the method is there since JDK 1.0, so it is not likely you will have to do much to keep it up-to-date.

Different ways of clearing lists

Doing alist = [] does not clear the list, just creates an empty list and binds it to the variable alist. The old list will still exist if it had other variable bindings.

To actually clear a list in-place, you can use any of these ways:

  1. alist.clear() # Python 3.3+, most obvious
  2. del alist[:]
  3. alist[:] = []
  4. alist *= 0 # fastest

See the Mutable Sequence Types documentation page for more details.

Java, Check if integer is multiple of a number

//More Efficiently
public class Multiples {
    public static void main(String[]args) {

        int j = 5;

        System.out.println(j % 4 == 0);

    }
}

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

For me it wasn't an angular problem. Was a field of type DateTime in the DB that has a value of (0000-00-00) and my model cannot bind that property correct so I changed to a valid value like (2019-08-12).

I'm using .net core, OData v4 and MySql (EF pomelo connector)

How to fix C++ error: expected unqualified-id

There should be no semicolon here:

class WordGame;

...but there should be one at the end of your class definition:

...
private:
    string theWord;
}; // <-- Semicolon should be at the end of your class definition

Get page title with Selenium WebDriver using Java

If you're using Selenium 2.0 / Webdriver you can call driver.getTitle() or driver.getPageSource() if you want to search through the actual page source.

Where is adb.exe in windows 10 located?

Since you already have Android Studio installed, and require the environment variable ANDROID_HOME to be set, the easy way to do this is to add %ANDROID_HOME%\platform-tools to your path.

Text in a flex container doesn't wrap in IE11

I had the same issue and the point is that the element was not adapting its width to the container.

Instead of using width:100%, be consistent (don't mix the floating model and the flex model) and use flex by adding this:

.child { align-self: stretch; }

Or:

.parent { align-items: stretch; }

This worked for me.

vuetify center items into v-flex

<v-layout justify-center>
  <v-card-actions>
    <v-btn primary>
     <span>SignUp</span>
    </v-btn>`enter code here`
  </v-card-actions>
</v-layout>

Android Debug Bridge (adb) device - no permissions

Try "android update adb" command. It helps me with samsung galaxy gear.

Parse large JSON file in Nodejs

If you have control over the input file, and it's an array of objects, you can solve this more easily. Arrange to output the file with each record on one line, like this:

[
   {"key": value},
   {"key": value},
   ...

This is still valid JSON.

Then, use the node.js readline module to process them one line at a time.

var fs = require("fs");

var lineReader = require('readline').createInterface({
    input: fs.createReadStream("input.txt")
});

lineReader.on('line', function (line) {
    line = line.trim();

    if (line.charAt(line.length-1) === ',') {
        line = line.substr(0, line.length-1);
    }

    if (line.charAt(0) === '{') {
        processRecord(JSON.parse(line));
    }
});

function processRecord(record) {
    // Process the records one at a time here! 
}

CSS border less than 1px

A pixel is the smallest unit value to render something with, but you can trick thickness with optical illusions by modifying colors (the eye can only see up to a certain resolution too).

Here is a test to prove this point:

_x000D_
_x000D_
div { border-color: blue; border-style: solid; margin: 2px; }

div.b1 { border-width: 1px; }
div.b2 { border-width: 0.1em; }
div.b3 { border-width: 0.01em; }
div.b4 { border-width: 1px; border-color: rgb(160,160,255); }
_x000D_
<div class="b1">Some text</div>
<div class="b2">Some text</div>
<div class="b3">Some text</div>
<div class="b4">Some text</div>
_x000D_
_x000D_
_x000D_

Output

enter image description here

Which gives the illusion that the last DIV has a smaller border width, because the blue border blends more with the white background.


Edit: Alternate solution

Alpha values may also be used to simulate the same effect, without the need to calculate and manipulate RGB values.

_x000D_
_x000D_
.container {
  border-style: solid;
  border-width: 1px;
  
  margin-bottom: 10px;
}

.border-100 { border-color: rgba(0,0,255,1); }
.border-75 { border-color: rgba(0,0,255,0.75); }
.border-50 { border-color: rgba(0,0,255,0.5); }
.border-25 { border-color: rgba(0,0,255,0.25); }
_x000D_
<div class="container border-100">Container 1 (alpha = 1)</div>
<div class="container border-75">Container 2 (alpha = 0.75)</div>
<div class="container border-50">Container 3 (alpha = 0.5)</div>
<div class="container border-25">Container 4 (alpha = 0.25)</div>
_x000D_
_x000D_
_x000D_

How to Set JPanel's Width and Height?

Board.setPreferredSize(new Dimension(x, y));
.
.
//Main.add(Board, BorderLayout.CENTER);
Main.add(Board, BorderLayout.CENTER);
Main.setLocations(x, y);
Main.pack();
Main.setVisible(true);

Docker CE on RHEL - Requires: container-selinux >= 2.9

I followed many links including the official documentation, however it all ended up in this error:

Requires: container-selinux >= 2.9
You could try using --skip-broken to work around the problem
You could try running: rpm -Va --nofiles --nodigest

The only way it worked for me is as follows (yum upgrade worked I guess):

yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo

yum upgrade docker-ce

What is the iBeacon Bluetooth Profile

If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:

{
    kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}

See this answer for more information.

How do I format a Microsoft JSON date?

In jQuery 1.5, as long as you have json2.js to cover for older browsers, you can deserialize all dates coming from Ajax as follows:

(function () {
    var DATE_START = "/Date(";
    var DATE_START_LENGTH = DATE_START.length;

    function isDateString(x) {
        return typeof x === "string" && x.startsWith(DATE_START);
    }

    function deserializeDateString(dateString) {
        var dateOffsetByLocalTime = new Date(parseInt(dateString.substr(DATE_START_LENGTH)));
        var utcDate = new Date(dateOffsetByLocalTime.getTime() - dateOffsetByLocalTime.getTimezoneOffset() * 60 * 1000);
        return utcDate;
    }

    function convertJSONDates(key, value) {
      if (isDateString(value)) {
        return deserializeDateString(value);
      }
      return value;
    }

    window.jQuery.ajaxSetup({
      converters: {
        "text json": function(data) {
          return window.JSON.parse(data, convertJSONDates);
        }
      }
    });
}());

I included logic that assumes you send all dates from the server as UTC (which you should); the consumer then gets a JavaScript Date object that has the proper ticks value to reflect this. That is, calling getUTCHours(), etc. on the date will return the same value as it did on the server, and calling getHours() will return the value in the user's local timezone as determined by their browser.

This does not take into account WCF format with timezone offsets, though that would be relatively easy to add.

Merge (with squash) all changes from another branch as a single commit

Using git merge --squash <feature branch> as the accepted answer suggests does the trick but it will not show the merged branch as actually merged.

Therefore an even better solution is to:

  • Create a new branch from the latest master, commit in the master branch where the feature branch initiated.
  • Merge <feature branch> into the above using git merge --squash
  • Merge the newly created branch into master. This way, the feature branch will contain only one commit and the merge will be represented in a short and tidy illustration.

This wiki explains the procedure in detail.

In the following example, the left hand screenshot is the result of qgit and the right hand screenshot is the result of:

git log --graph --decorate --pretty=oneline --abbrev-commit

Both screenshots show the same range of commits in the same repository. Nonetheless, the right one is more compact thanks to --squash.

  • Over time, the master branch deviated from db.
  • When the db feature was ready, a new branch called tag was created in the same commit of master that db has its root.
  • From tag a git merge --squash db was performed and then all changes were staged and committed in a single commit.
  • From master, tag got merged: git merge tag.
  • The branch search is irrelevant and not merged in any way.

enter image description here

How to convert minutes to Hours and minutes (hh:mm) in java

Use java.text.SimpleDateFormat to convert minute into hours and minute

SimpleDateFormat sdf = new SimpleDateFormat("mm");

try {
    Date dt = sdf.parse("90");
    sdf = new SimpleDateFormat("HH:mm");
    System.out.println(sdf.format(dt));
} catch (ParseException e) {
    e.printStackTrace();
}

How to get all Errors from ASP.Net MVC modelState?

I was able to do this using a little LINQ,

public static List<string> GetErrorListFromModelState
                                              (ModelStateDictionary modelState)
{
      var query = from state in modelState.Values
                  from error in state.Errors
                  select error.ErrorMessage;

      var errorList = query.ToList();
      return errorList;
}

The above method returns a list of validation errors.

Further Reading :

How to read all errors from ModelState in ASP.NET MVC

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

error running apache after xampp install

I think killing the process which is uses that port is more easy to handle than changing the ports in config files. Here is how to do it in Windows. You can follow same procedure to Linux but different commands. Run command prompt as Administrator. Then type below command to find out all of processes using the port.

netstat -ano

There will be plenty of processes using various ports. So to get only port we need use findstr like below (here I use port 80)

netstat -ano | findstr 80

this will gave you result like this

TCP    0.0.0.0:80             0.0.0.0:0              LISTENING       7964

Last number is the process ID of the process. so what we have to do is kill the process using PID we can use taskkill command for that.

taskkill /PID 7964 /F

Run your server again. This time it will be able to run. This can uses for Mysql server too.

how do I get eclipse to use a different compiler version for Java?

From the menu bar: Project -> Properties -> Java Compiler

Enable project specific settings (checked) Uncheck "use Compliance from execution environment '.... Select the desired "compiler compliance level"

That will allow you to compile "1.5" code using a "1.6" JDK.

If you want to acutally use a 1.5 JDK to produce "1.5" compliant code, then install a suitable 1.5 JDK and tell eclipse where it is installed via:

Window -> preferences -> Installed JREs

And then go back to your project

Project -> properties -> Java Build Path -> libraries

remove the 1.6 system libaries, and: add library... -> JRE System LIbrary -> Alternate JRE -> The JRE you want.

Verify that the correct JRE is on the project's build path, save everything, and enjoy!

Android Facebook style slide

After a search for several hours, I found Paul Grime's solution probably is the best one. But it has too much functionality in it. So it may be hard to study for beginners. So I would like to provide my implementation which is came from Paul's idea but it is simpler and should be easy to read.

implementation of side menu bar by using java code without XML

Custom method names in ASP.NET Web API

See this article for a longer discussion of named actions. It also shows that you can use the [HttpGet] attribute instead of prefixing the action name with "get".

http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

Zero an array in C code

int arr[20] = {0} would be easiest if it only needs to be done once.

Center an element in Bootstrap 4 Navbar

Try this.

.nav-tabs > li{
    float:none !important;
    display:inline-block !important;
}

.nav-tabs {
    text-align:center !important;
}

How to set locale in DatePipe in Angular 2?

You do something like this:

{{ dateObj | date:'shortDate' }}

or

{{ dateObj | date:'ddmmy' }}

See: https://angular.io/docs/ts/latest/api/common/index/DatePipe-pipe.html

How to get $HOME directory of different user in bash script?

The output of getent passwd username can be parsed with a Bash regular expression

OTHER_HOME="$(
  [[ "$(
    getent \
    passwd \
    "${OTHER_USER}"
  )" =~ ([^:]*:){5}([^:]+) ]] \
  && echo "${BASH_REMATCH[2]}"
)"

How to setup Main class in manifest file in jar produced by NetBeans project

In 7.3 just enable Properties/Build/Package/Copy Dependent Libraries and main class will be added to manifest when building depending on selected target.

Removing cordova plugins from the project

v2.0.0 of cordova-check-plugins enables you to remove all plugins in a project:

$ npm install -g cordova-check-plugins
$ cordova-check-plugins --remove-all

It will attempt to use the Cordova CLI to remove each plugin, but if this fails it will force removal of the plugin from platforms/ and plugins/.

If you also want to remove from config.xml, use:

$ cordova-check-plugins --remove-all --save

Disclaimer: I am the author of cordova-check-plugins

Convert MySQL to SQlite

Not every DB schema can be converted. MySQL is more complex and feature-rich than SQLite. However, if your schema is simple enough, you could dump it into an SQL file and try to import it / load it into an SQLite DB.

Apache VirtualHost and localhost

For someone doing everything described here and still can't access:

XAMPP with Apache HTTP Server 2.4:

In file httpd-vhost.conf:

<VirtualHost *>
    DocumentRoot "D:/xampp/htdocs/dir"
    ServerName something.dev
   <Directory "D:/xampp/htdocs/dir">
    Require all granted #apache v 2.4.4 uses just this
   </Directory>
</VirtualHost>

There isn't any need for a port, or an IP address here. Apache configures it on its own files. There isn't any need for NameVirtualHost *:80; it's deprecated. You can use it, but it doesn't make any difference.

Then to edit hosts, you must run Notepad as administrator (described bellow). If you were editing the file without doing this, you are editing a pseudo file, not the original (yes, it saves, etc., but it's not the real file)

In Windows:

Find the Notepad icon, right click, run as administrator, open file, go to C:/WINDOWS/system32/driver/etc/hosts, check "See all files", and open hosts.

If you where editing it before, probably you will see it's not the file you were previously editing when not running as administrator.

Then to check if Apache is reading your httpd-vhost.conf, go to folder xampFolder/apache/bin, Shift + right click, open a terminal command here, open XAMPP (as you usually do), start Apache, and then on the command line, type httpd -S. You will see a list of the virtual hosts. Just check if your something.dev is there.

Get string between two strings in a string

I think this works:

   static void Main(string[] args)
    {
        String text = "One=1,Two=2,ThreeFour=34";

        Console.WriteLine(betweenStrings(text, "One=", ",")); // 1
        Console.WriteLine(betweenStrings(text, "Two=", ",")); // 2
        Console.WriteLine(betweenStrings(text, "ThreeFour=", "")); // 34

        Console.ReadKey();

    }

    public static String betweenStrings(String text, String start, String end)
    {
        int p1 = text.IndexOf(start) + start.Length;
        int p2 = text.IndexOf(end, p1);

        if (end == "") return (text.Substring(p1));
        else return text.Substring(p1, p2 - p1);                      
    }

Reading specific XML elements from XML file

This is how I would do it (the code below has been tested, full source provided below), begin by creating a class with common properties

    class Word
    {
        public string Base { get; set; }
        public string Category { get; set; }
        public string Id { get; set; }
    }

load using XDocument with INPUT_DATA for demonstration purposes and find element name with lexicon . . .

    XDocument doc = XDocument.Parse(INPUT_DATA);
    XElement lex = doc.Element("lexicon");

make sure there is a value and use linq to extract the word elements from it . . .

    Word[] catWords = null;
    if (lex != null)
    {
        IEnumerable<XElement> words = lex.Elements("word");
        catWords = (from itm in words
                    where itm.Element("category") != null
                        && itm.Element("category").Value == "verb"
                        && itm.Element("id") != null
                        && itm.Element("base") != null
                    select new Word() 
                    {
                        Base = itm.Element("base").Value,
                        Category = itm.Element("category").Value,
                        Id = itm.Element("id").Value,
                    }).ToArray<Word>();
    }

The where statement checks if the category element exists and that the category value is not null and then check it again that it is a verb. Then check that the other nodes also exists . . .

The linq query will return an IEnumerable< Typename > object, so we can call ToArray< Typename >() to cast the entire collection into the type we want.

Then print it to get . . .

[Found]
 Id: E0006429
 Base: abandon
 Category: verb

[Found]
 Id: E0006524
 Base: abolish
 Category: verb

Full Source:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace test
{
    class Program
    {

        class Word
        {
            public string Base { get; set; }
            public string Category { get; set; }
            public string Id { get; set; }
        }

        static void Main(string[] args)
        {
            XDocument doc = XDocument.Parse(INPUT_DATA);
            XElement lex = doc.Element("lexicon");
            Word[] catWords = null;
            if (lex != null)
            {
                IEnumerable<XElement> words = lex.Elements("word");
                catWords = (from itm in words
                            where itm.Element("category") != null
                                && itm.Element("category").Value == "verb"
                                && itm.Element("id") != null
                                && itm.Element("base") != null
                            select new Word() 
                            {
                                Base = itm.Element("base").Value,
                                Category = itm.Element("category").Value,
                                Id = itm.Element("id").Value,
                            }).ToArray<Word>();
            }

            //print it
            if (catWords != null)
            {
                Console.WriteLine("Words with <category> and value verb:\n");
                foreach (Word itm in catWords)
                    Console.WriteLine("[Found]\n Id: {0}\n Base: {1}\n Category: {2}\n", 
                        itm.Id, itm.Base, itm.Category);
            }
        }

        const string INPUT_DATA =
        @"<?xml version=""1.0""?>
        <lexicon>
        <word>
          <base>a</base>
          <category>determiner</category>
          <id>E0006419</id>
        </word>
        <word>
          <base>abandon</base>
          <category>verb</category>
          <id>E0006429</id>
          <ditransitive/>
          <transitive/>
        </word>
        <word>
          <base>abbey</base>
          <category>noun</category>
          <id>E0203496</id>
        </word>
        <word>
          <base>ability</base>
          <category>noun</category>
          <id>E0006490</id>
        </word>
        <word>
          <base>able</base>
          <category>adjective</category>
          <id>E0006510</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abnormal</base>
          <category>adjective</category>
          <id>E0006517</id>
          <predicative/>
          <qualitative/>
        </word>
        <word>
          <base>abolish</base>
          <category>verb</category>
          <id>E0006524</id>
          <transitive/>
        </word>
        </lexicon>";

    }
}

Sql Server : How to use an aggregate function like MAX in a WHERE clause

yes you need to use a having clause after the Group by clause , as the where is just to filter the data on simple parameters , but group by followed by a Having statement is the idea to group the data and filter it on basis of some aggregate function......

Python Pandas: Get index of rows which column matches certain value

I extended this question that is how to gets the row, columnand value of all matches value?

here is solution:

import pandas as pd
import numpy as np


def search_coordinate(df_data: pd.DataFrame, search_set: set) -> list:
    nda_values = df_data.values
    tuple_index = np.where(np.isin(nda_values, [e for e in search_set]))
    return [(row, col, nda_values[row][col]) for row, col in zip(tuple_index[0], tuple_index[1])]


if __name__ == '__main__':
    test_datas = [['cat', 'dog', ''],
                  ['goldfish', '', 'kitten'],
                  ['Puppy', 'hamster', 'mouse']
                  ]
    df_data = pd.DataFrame(test_datas)
    print(df_data)
    result_list = search_coordinate(df_data, {'dog', 'Puppy'})
    print(f"\n\n{'row':<4} {'col':<4} {'name':>10}")
    [print(f"{row:<4} {col:<4} {name:>10}") for row, col, name in result_list]

Output:

          0        1       2
0       cat      dog        
1  goldfish           kitten
2     Puppy  hamster   mouse


row  col        name
0    1           dog
2    0         Puppy

Redirecting Output from within Batch file

@echo OFF
[your command] >> [Your log file name].txt

I used the command above in my batch file and it works. In the log file, it shows the results of my command.

Limiting floats to two decimal points

I feel that the simplest approach is to use the format() function.

For example:

a = 13.949999999999999
format(a, '.2f')

13.95

This produces a float number as a string rounded to two decimal points.

PHP how to get value from array if key is in a variable

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

Array
(
    [0] => 4
)

Now:

$key = 4;
$value = $array[$key];
print $value;

Output:

Hello There

error: pathspec 'test-branch' did not match any file(s) known to git

I got this error because the instruction on the Web was

git checkout https://github.com/veripool/verilog-mode

which I did in a directory where (on my own initiative) i had run git init. The correct Web instruction (for newbies like me) should have been

git clone https://github.com/veripool/verilog-mode

Bootstrap 4 Change Hamburger Toggler Color

One simplest way to encounter this is to use font awesome for example

 <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation">
       <span><i class="fas fa-bars"></i></span>
</button>

Then u can change the i element like you change any other ielement.

How do I convert a org.w3c.dom.Document object to a String?

If you are ok to do transformation, you may try this.

DocumentBuilderFactory domFact = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFact.newDocumentBuilder();
Document doc = builder.parse(st);
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
System.out.println("XML IN String format is: \n" + writer.toString());

iOS 7 status bar overlapping UI

Here is my approach using CSS and Javascript:

1) Define the following in your CSS:

#ios7-statusbar-fix {
    width:100%;
    height:20px;
    background-color:white;
    position:fixed;
    z-index:10000;
    margin-top:-20px;
    display:none;
}

2) Add div-container with this id as very first element after your <body>-tag:

<body>
    <div id="ios7-statusbar-fix"></div>
…

3) Filter iOS 7 devices and apply changes via Javascript:

if (navigator.userAgent.match(/(iPad.*|iPhone.*|iPod.*);.*CPU.*OS 7_\d/i)) {
        document.body.style.marginTop = '20px';
        document.getElementById('ios7-statusbar-fix').style.display = 'block';
}

Forbidden: You don't have permission to access / on this server, WAMP Error

I find the best (and least frustrating) path is to start with Allow from All, then, when you know it will work that way, scale it back to the more secure Allow from 127.0.0.1 or Allow from ::1 (localhost).

As long as your firewall is configured properly, Allow from all shouldn't cause any problems, but it is better to only allow from localhost if you don't need other computers to be able to access your site.

Don't forget to restart Apache whenever you make changes to httpd.conf. They will not take effect until the next start.

Hopefully this is enough to get you started, there is lots of documentation available online.

Property '...' has no initializer and is not definitely assigned in the constructor

You can also do the following if you really don't want to initialise it.

makes?: any[];

How to check if directory exists in %PATH%?

This version works fairly well. It simply checks whether vim71 is in the path, and prepends it if not.

@echo off
echo %PATH% | find /c /i "vim71" > nul
if not errorlevel 1 goto jump
PATH = C:\Program Files\Vim\vim71\;%PATH%
:jump

This demo is to illustrate the errorlevel logic:

@echo on
echo %PATH% | find /c /i "Windows"
if "%errorlevel%"=="0" echo Found Windows
echo %PATH% | find /c /i "Nonesuch"
if "%errorlevel%"=="0" echo Found Nonesuch

The logic is reversed in the vim71 code since errorlevel 1 is equivalent to errorlevel >= 1. It follows that errorlevel 0 would always evaluate true, so "not errorlevel 1" is used.

Postscript Checking may not be necessary if you use setlocal and endlocal to localise your environment settings, e.g.

@echo off
setlocal
PATH = C:\Program Files\Vim\vim71\;%PATH%
rem your code here
endlocal

After endlocal you are back with your original path.

Oracle JDBC ojdbc6 Jar as a Maven Dependency

The correct answer was supplied by Raghuram in the comments section to my original question.

For whatever reason, pointing "mvn install" to a full path of the physical ojdbc6.jar file didn't work for me. (Or I consistently repeatedly flubbed it up when running the command, but no errors were issued.)

cd-ing into the directory where I keep ojdb6.jar and running the command from there worked the first time.

If Raghuram would like to answer this question, I'll accept his answer instead. Thanks everyone!

Bi-directional Map in Java?

Creating a Guava BiMap and getting its inverted value is not so trivial.

A simple example:

import com.google.common.collect.BiMap;
import com.google.common.collect.HashBiMap;

public class BiMapTest {

  public static void main(String[] args) {

    BiMap<String, String> biMap = HashBiMap.create();

    biMap.put("k1", "v1");
    biMap.put("k2", "v2");

    System.out.println("k1 = " + biMap.get("k1"));
    System.out.println("v2 = " + biMap.inverse().get("v2"));
  }
}

IndexError: tuple index out of range ----- Python

This is because your row variable/tuple does not contain any value for that index. You can try printing the whole list like print(row) and check how many indexes there exists.

Add User to Role ASP.NET Identity

Are you looking for something like this:

RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new MyDbContext()));
var str = RoleManager.Create(new IdentityRole(roleName));

Also check User Identity

How to prevent form from submitting multiple times from client side?

To do this using javascript is bit easy. Following is the code which will give desired functionality :

_x000D_
_x000D_
$('#disable').on('click', function(){_x000D_
    $('#disable').attr("disabled", true);_x000D_
  });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id="disable">Disable Me!</button>
_x000D_
_x000D_
_x000D_

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

An implementation of the fast Fourier transform (FFT) in C#

http://www.exocortex.org/dsp/ is an open-source C# mathematics library with FFT algorithms.

jQuery replace one class with another

Create a class in your CSS file:

.active {
  z-index: 20;
  background: rgb(23,55,94)
  color: #fff;
}

Then in your jQuery

$(this).addClass("active");

How to pass argument to Makefile from command line?

Here is a generic working solution based on @Beta's

I'm using GNU Make 4.1 with SHELL=/bin/bash atop my Makefile, so YMMV!

This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).

%:
    @:

And this is a macro which gets the args for us:

args = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`

Here is a job which might call this one:

test:
    @echo $(call args,defaultstring)

The result would be:

$ make test
defaultstring
$ make test hi
hi

Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile

Div height 100% and expands to fit content

If you just leave the height: 100% and use display:block; the div will take as much space as the content inside the div. This way all the text will stay in the black background.

How to make an installer for my C# application?

There are several methods, two of which are as follows. Provide a custom installer or a setup project.

Here is how to create a custom installer

[RunInstaller(true)]
public class MyInstaller : Installer
{
    public HelloInstaller()
        : base()
    {
    }

    public override void Commit(IDictionary mySavedState)
    {
        base.Commit(mySavedState);
        System.IO.File.CreateText("Commit.txt");
    }

    public override void Install(IDictionary stateSaver)
    {
        base.Install(stateSaver);
        System.IO.File.CreateText("Install.txt");
    }

    public override void Uninstall(IDictionary savedState)
    {
        base.Uninstall(savedState);
        File.Delete("Commit.txt");
        File.Delete("Install.txt");
    }

    public override void Rollback(IDictionary savedState)
    {
        base.Rollback(savedState);
        File.Delete("Install.txt");
    }
}

To add a setup project

  • Menu file -> New -> Project --> Other Projects Types --> Setup and Deployment

  • Set properties of the project, using the properties window

The article How to create a Setup package by using Visual Studio .NET provides the details.

How to make a programme continue to run after log out from ssh?

You should try using nohup and running it in the background:

nohup sleep 3600 &

How do I load external fonts into an HTML document?

I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:

http://raphaeljs.com/

It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)

Hide strange unwanted Xcode logs

Building on the original tweet from @rustyshelf, and illustrated answer from iDevzilla, here's a solution that silences the noise from the simulator without disabling NSLog output from the device.

  1. Under Product > Scheme > Edit Scheme... > Run (Debug), set the OS_ACTIVITY_MODE environment variable to ${DEBUG_ACTIVITY_MODE} so it looks like this:

enter image description here

  1. Go to your project build settings, and click + to add a User-Defined Setting named DEBUG_ACTIVITY_MODE. Expand this setting and Click the + next to Debug to add a platform-specific value. Select the dropdown and change it to "Any iOS Simulator". Then set its value to "disable" so it looks like this:

enter image description here

How can I convert a DateTime to an int?

string date = DateTime.Now.ToString();

date = date.Replace("/", "");
date = date.Replace(":", "");
date = date.Replace(" ", "");
date = date.Replace("AM", "");
date = date.Replace("PM", "");            
return date;

Tomcat 8 is not able to handle get request with '|' in query parameters?

The URI is encoded as UTF-8, but Tomcat is decoding them as ISO-8859-1. You need to edit the connector settings in the server.xml and add the URIEncoding="UTF-8" attribute.

or edit this parameter on your application.properties

server.tomcat.uri-encoding=utf-8

What is the best collation to use for MySQL with PHP?

Collations affect how data is sorted and how strings are compared to each other. That means you should use the collation that most of your users expect.

Example from the documentation for charset unicode:

utf8_general_ci also is satisfactory for both German and French, except that ‘ß’ is equal to ‘s’, and not to ‘ss’. If this is acceptable for your application, then you should use utf8_general_ci because it is faster. Otherwise, use utf8_unicode_ci because it is more accurate.

So - it depends on your expected user base and on how much you need correct sorting. For an English user base, utf8_general_ci should suffice, for other languages, like Swedish, special collations have been created.

jquery 3.0 url.indexOf error

I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load") instead of .load().

This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:

    .load();

to

    .trigger("load");

I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024

What is the purpose of the var keyword and when should I use it (or omit it)?

@Chris S gave a nice example showcasing the practical difference (and danger) between var and no var. Here's another one, I find this one particularly dangerous because the difference is only visible in an asynchronous environment so it can easily slip by during testing.

As you'd expect the following snippet outputs ["text"]:

_x000D_
_x000D_
function var_fun() {_x000D_
  let array = []_x000D_
  array.push('text')_x000D_
  return array_x000D_
}_x000D_
_x000D_
console.log(var_fun())
_x000D_
_x000D_
_x000D_

So does the following snippet (note the missing let before array):

_x000D_
_x000D_
function var_fun() {_x000D_
  array = []_x000D_
  array.push('text')_x000D_
  return array_x000D_
}_x000D_
_x000D_
console.log(var_fun())
_x000D_
_x000D_
_x000D_

Executing the data manipulation asynchronously still produces the same result with a single executor:

_x000D_
_x000D_
function var_fun() {_x000D_
  array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
var_fun().then(result => {console.log(result)})
_x000D_
_x000D_
_x000D_

But behaves differently with multiple ones:

_x000D_
_x000D_
function var_fun() {_x000D_
  array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
[1,2,3].forEach(i => {_x000D_
  var_fun().then(result => {console.log(result)})_x000D_
})
_x000D_
_x000D_
_x000D_

Using let however:

_x000D_
_x000D_
function var_fun() {_x000D_
  let array = [];_x000D_
  return new Promise(resolve => resolve()).then(() => {_x000D_
    array.push('text')_x000D_
    return array_x000D_
  })_x000D_
}_x000D_
_x000D_
[1,2,3].forEach(i => {_x000D_
  var_fun().then(result => {console.log(result)})_x000D_
})
_x000D_
_x000D_
_x000D_

Print content of JavaScript object?

Javascript for all!

String.prototype.repeat = function(num) {
    if (num < 0) {
        return '';
    } else {
        return new Array(num + 1).join(this);
    }
};

function is_defined(x) {
    return typeof x !== 'undefined';
}

function is_object(x) {
    return Object.prototype.toString.call(x) === "[object Object]";
}

function is_array(x) {
    return Object.prototype.toString.call(x) === "[object Array]";
}

/**
 * Main.
 */
function xlog(v, label) {
    var tab = 0;

    var rt = function() {
        return '    '.repeat(tab);
    };

    // Log Fn
    var lg = function(x) {
        // Limit
        if (tab > 10) return '[...]';
        var r = '';
        if (!is_defined(x)) {
            r = '[VAR: UNDEFINED]';
        } else if (x === '') {
            r = '[VAR: EMPTY STRING]';
        } else if (is_array(x)) {
            r = '[\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + ']';
        } else if (is_object(x)) {
            r = '{\n';
            tab++;
            for (var k in x) {
                r += rt() + k + ' : ' + lg(x[k]) + ',\n';
            }
            tab--;
            r += rt() + '}';
        } else {
            r = x;
        }
        return r;
    };

    // Space
    document.write('\n\n');

    // Log
    document.write('< ' + (is_defined(label) ? (label + ' ') : '') + Object.prototype.toString.call(v) + ' >\n' + lg(v));
};



// Demo //

var o = {
    'aaa' : 123,
    'bbb' : 'zzzz',
    'o' : {
        'obj1' : 'val1',
        'obj2' : 'val2',
        'obj3' : [1, 3, 5, 6],
        'obj4' : {
            'a' : 'aaaa',
            'b' : null
        }
    },
    'a' : [ 'asd', 123, false, true ],
    'func' : function() {
        alert('test');
    },
    'fff' : false,
    't' : true,
    'nnn' : null
};

xlog(o, 'Object'); // With label
xlog(o); // Without label

xlog(['asd', 'bbb', 123, true], 'ARRAY Title!');

var no_definido;
xlog(no_definido, 'Undefined!');

xlog(true);

xlog('', 'Empty String');

How to verify if a file exists in a batch file?

Here is a good example on how to do a command if a file does or does not exist:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

Use the XCOPY command:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

I will explain what the /c /d /h /e /i /y means:

  /C           Continues copying even if errors occur.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /H           Copies hidden and system files also.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.

`To see all the commands type`xcopy /? in cmd

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

Path/sync.bat
Path/myprogram.ini

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

How to name Dockerfiles

dev.Dockerfile, test.Dockerfile, build.Dockerfile etc.

On VS Code I use <purpose>.Dockerfile and it gets recognized correctly.

A regex for version number parsing

I found this, and it works for me:

/(\^|\~?)(\d|x|\*)+\.(\d|x|\*)+\.(\d|x|\*)+

Resize image in PHP

You can give a try to TinyPNG PHP library. Using this library your image gets optimized automatically during resizing process. All you need to install the library and get an API key from https://tinypng.com/developers. To install a library, run the below command.

composer require tinify/tinify

After that, your code is as follows.

require_once("vendor/autoload.php");

\Tinify\setKey("YOUR_API_KEY");

$source = \Tinify\fromFile("large.jpg"); //image to be resize
$resized = $source->resize(array(
    "method" => "fit",
    "width" => 150,
    "height" => 100
));
$resized->toFile("thumbnail.jpg"); //resized image

I have a written a blog on the same topic http://artisansweb.net/resize-image-php-using-tinypng

How to append multiple values to a list in Python

If you take a look at the official docs, you'll see right below append, extend. That's what your looking for.

There's also itertools.chain if you are more interested in efficient iteration than ending up with a fully populated data structure.

How do you add PostgreSQL Driver as a dependency in Maven?

PostgreSQL drivers jars are included in Central Repository of Maven:

For PostgreSQL up to 9.1, use:

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>VERSION</version>
</dependency>

or for 9.2+

<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>VERSION</version>
</dependency>

(Thanks to @Caspar for the correction)

Playing .mp3 and .wav in Java?

To add MP3 reading support to Java Sound, add the mp3plugin.jar of the JMF to the run-time class path of the application.

Note that the Clip class has memory limitations that make it unsuitable for more than a few seconds of high quality sound.

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

How to import a CSS file in a React Component

The following imports an external CSS file in a React component and outputs the CSS rules in the <head /> of the website.

  1. Install Style Loader and CSS Loader:
npm install --save-dev style-loader
npm install --save-dev css-loader
  1. In webpack.config.js:
module.exports = {
    module: {
        rules: [
            {
                test: /\.css$/,
                use: [ 'style-loader', 'css-loader' ]
            }
        ]
    }
}
  1. In a component file:
import './path/to/file.css';

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

link_to image tag. how to add class to a tag

<%= link_to root_path do %><%= image_tag("Search.png",:alt=>'Vivek',:title=>'Vivek',:class=>'dock-item')%><%= content_tag(:span, "Search").html_safe%><% end %>

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

The excellent library Type::Tiny provides an framework with which to build type-checking into your Perl code. What I show here is only the thinnest tip of the iceberg and is using Type::Tiny in the most simplistic and manual way.

Be sure to check out the Type::Tiny::Manual for more information.

use Types::Common::String qw< NonEmptyStr >;

if ( NonEmptyStr->check($name) ) {
    # Do something here.
}

NonEmptyStr->($name);  # Throw an exception if validation fails

Using comma as list separator with AngularJS

You could do it this way:

<b ng-repeat="email in friend.email">{{email}}{{$last ? '' : ', '}}</b>

..But I like Philipp's answer :-)

jQuery - how to write 'if not equal to' (opposite of ==)

!=

For example,

if ("apple" != "orange")
  // true, the string "apple" is not equal to the string "orange"

Means not. See also the logical operators list. Also, when you see triple characters, it's a type sensitive comparison. (e.g. if (1 === '1') [not equal])

JavaScript unit test tools for TDD

YUI has a testing framework as well. This video from Yahoo! Theater is a nice introduction, although there are a lot of basics about TDD up front.

This framework is generic and can be run against any JavaScript or JS library.

Height of status bar in Android

The reason why the top answer does not work for some people is because you cannot get the dimensions of a view until it is ready to render. Use an OnGlobalLayoutListener to get said dimensions when you actually can:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final ViewGroup decorView = (ViewGroup) this.getWindow().getDecorView();
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT >= 16) {
                decorView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            } else {
                // Nice one, Google
                decorView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            }
            Rect rect = new Rect();
            decorView.getWindowVisibleDisplayFrame(rect);
            rect.top; // This is the height of the status bar
        }
    }
}

This is the most reliable method.

PHP: check if any posted vars are empty - form: all fields required

foreach($_POST as $key=>$value)
{

   if(empty(trim($value))
        echo "$key input required of value ";

}

How do I find where JDK is installed on my windows machine?

Java installer puts several files into %WinDir%\System32 folder (java.exe, javaws.exe and some others). When you type java.exe in command line or create process without full path, Windows runs these as last resort if they are missing in %PATH% folders.

You can lookup all versions of Java installed in registry. Take a look at HKLM\SOFTWARE\JavaSoft\Java Runtime Environment and HKLM\SOFTWARE\Wow6432Node\JavaSoft\Java Runtime Environment for 32-bit java on 64 bit Windows.

This is how java itself finds out different versions installed. And this is why both 32-bit and 64-bit version can co-exist and works fine without interfering.

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

Installing PIL (Python Imaging Library) in Win7 64 bits, Python 2.6.4

Pillow is new version

PIL-1.1.7.win-amd64-py2.x installers are available at

http://www.lfd.uci.edu/~gohlke/pythonlibs/#pil

How to give credentials in a batch script that copies files to a network location?

You can also map the share to a local drive as follows:

net use X: "\\servername\share" /user:morgan password

Twitter Bootstrap Modal Form Submit

This answer is late, but I'm posting anyway hoping it will help someone. Like you, I also had difficulty submitting a form that was outside my bootstrap modal, and I didn't want to use ajax because I wanted a whole new page to load, not just part of the current page. After much trial and error here's the jQuery that worked for me:

$(function () {
    $('body').on('click', '.odom-submit', function (e) {
        $(this.form).submit();
        $('#myModal').modal('hide');
    });
});

To make this work I did this in the modal footer

<div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary odom-submit">Save changes</button>
</div>

Notice the addition to class of odom-submit. You can, of course, name it whatever suits your particular situation.

Correlation between two vectors?

Try xcorr, it's a built-in function in MATLAB for cross-correlation:

c = xcorr(A_1, A_2);

However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef command instead.

Equivalent of Oracle's RowID in SQL Server

Several of the answers above will work around the lack of a direct reference to a specific row, but will not work if changes occur to the other rows in a table. That is my criteria for which answers fall technically short.

A common use of Oracle's ROWID is to provide a (somewhat) stable method of selecting rows and later returning to the row to process it (e.g., to UPDATE it). The method of finding a row (complex joins, full-text searching, or browsing row-by-row and applying procedural tests against the data) may not be easily or safely re-used to qualify the UPDATE statement.

The SQL Server RID seems to provide the same functionality, but does not provide the same performance. That is the only issue I see, and unfortunately the purpose of retaining a ROWID is to avoid repeating an expensive operation to find the row in, say, a very large table. Nonetheless, performance for many cases is acceptable. If Microsoft adjusts the optimizer in a future release, the performance issue could be addressed.

It is also possible to simply use FOR UPDATE and keep the CURSOR open in a procedural program. However, this could prove expensive in large or complex batch processing.

Caveat: Even Oracle's ROWID would not be stable if the DBA, between the SELECT and the UPDATE, for example, were to rebuild the database, because it is the physical row identifier. So the ROWID device should only be used within a well-scoped task.

Chrome doesn't delete session cookies

I just had this problem of Chrome storing a Session ID but I do not like the idea of disabling the option to continue where I left off. I looked at the cookies for the website and found a Session ID cookie for the login page. Deleting that did not correct my problem. I search for the domain and found there was another Session ID cookie on the domain. Deleting both Session ID cookies manually fixed the problem and I did not close and reopen the browser which could have restored the cookies.

How to allow access outside localhost

No package.json is necessery to change.

For me it works using:

ng serve --host=0.0.0.0 --port=5999 --disable-host-check

Host: http://localhost:5999/

How to Cast Objects in PHP

I think that the best approach is to just create a new instance of a class and than assign the object. Here's what I would do:

public function ($someVO) {

     $someCastVO = new SomeVO();
     $someCastVO = $someVO;
     $someCastVO->SomePropertyInVO = "123";

}

Doing this will give you code hinting in most IDEs and help ensure you are using the correct properties.

How to convert "0" and "1" to false and true

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function

Entity Framework - Code First - Can't Store List<String>

Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.

Convert Enumeration to a Set/List

I needed same thing and this solution work fine, hope it can help someone also

Enumeration[] array = Enumeration.values();
List<Enumeration> list = Arrays.asList(array);

then you can get the .name() of your enumeration.

How do I wait for an asynchronously dispatched block to finish?

Very primitive solution to the problem:

void (^nextOperationAfterLongOperationBlock)(void) = ^{

};

[object runSomeLongOperationAndDo:^{
    STAssert…
    nextOperationAfterLongOperationBlock();
}];

iterrows pandas get next rows value

This can be solved also by izipping the dataframe (iterator) with an offset version of itself.

Of course the indexing error cannot be reproduced this way.

Check this out

import pandas as pd
from itertools import izip

df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])   

for id1, id2 in izip(df.iterrows(),df.ix[1:].iterrows()):
    print id1[1]['value']
    print id2[1]['value']

which gives

AA
BB
BB
CC

How to save RecyclerView's scroll position using RecyclerView.State?

All layout managers bundled in the support library already know how to save and restore scroll position.

Scroll position is restored on the first layout pass which happens when the following conditions are met:

  • a layout manager is attached to the RecyclerView
  • an adapter is attached to the RecyclerView

Typically you set the layout manager in XML so all you have to do now is

  1. Load the adapter with data
  2. Then attach the adapter to the RecyclerView

You can do this at any time, it's not constrained to Fragment.onCreateView or Activity.onCreate.

Example: Ensure the adapter is attached every time the data is updated.

viewModel.liveData.observe(this) {
    // Load adapter.
    adapter.data = it

    if (list.adapter != adapter) {
        // Only set the adapter if we didn't do it already.
        list.adapter = adapter
    }
}

The saved scroll position is calculated from the following data:

  • Adapter position of the first item on the screen
  • Pixel offset of the top of the item from the top of the list (for vertical layout)

Therefore you can expect a slight mismatch e.g. if your items have different dimensions in portrait and landscape orientation.


The RecyclerView/ScrollView/whatever needs to have an android:id for its state to be saved.

CodeIgniter - how to catch DB errors?

Put this code in a file called MY_Exceptions.php in application/core folder:

<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 * Class dealing with errors as exceptions
 */
class MY_Exceptions extends CI_Exceptions
{

    /**
     * Force exception throwing on erros
     */
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500)
    {
        set_status_header($status_code);

        $message = implode(" / ", (!is_array($message)) ? array($message) : $message);

        throw new CiError($message);
    }

}

/**
 * Captured error from Code Igniter
 */
class CiError extends Exception
{

}

It will make all the Code Igniter errors to be treated as Exception (CiError). Then, turn all your database debug on:

$db['default']['db_debug'] = true;

How to get cell value from DataGridView in VB.Net?

The line would be as shown below:

Dim x As Integer    
x = dgvName.Rows(yourRowIndex).Cells(yourColumnIndex).Value

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I found that this works really well in Chrome.

Right click on the element that you'd like to inspect, then click Force Element State > Hover. Screenshot attached.

Force element state

Npm Please try using this command again as root/administrator

This is the flow often happens in this case. You run a command with no admin rights, you get message npm ERR! Please try running this command again as root/Administrator.. Then you open one more CLI(cmd, powershell, bash or whatever) and don't close the previous CLI. It appears you have 2 prompts opened in the same directory. And until you close CLI which runs with no admin rights you will be continuously getting npm ERR! Please try running this command again as root/Administrator. So close CLI which runs with no admins rights before running a new one.

NOTE: a lot of IDE has embedded CLI(Visual Studio, VS Code etc) so please close the instance of IDE as well

mongoError: Topology was destroyed

Here what I did, It works fine. Issue was gone after adding below options.

const dbUrl = "mongodb://localhost:27017/sampledb";
const options =  { useMongoClient: true, keepAlive: 1, connectTimeoutMS: 30000, reconnectTries: 30, reconnectInterval: 5000, useNewUrlParser: true }
mongoose.connect(dbUrl,options, function(
  error
) {
  if (error) {
    console.log("mongoerror", error);
  } else {
    console.log("connected");
  }

});

Select rows where column is null

for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :

**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **

No connection could be made because the target machine actively refused it (PHP / WAMP)

You might need:

  • In wamp\bin\mysql\mysqlX.X.XX\my.ini find these lines:

    [client] ... port = 3308 ... [wampmysqld64] ... port = 3308

As you see, the port number is 3308. You should :

  • use that port in applications, like WordPress: define('DB_HOST', 'localhost:3308')

or

  • change it globally in wamp\bin\apache\apache2.X.XXX\bin\php.ini change mysqli.default_port = ... to 3308

How can I query a value in SQL Server XML column

You could do the following

declare @role varchar(100) = 'Alpha'
select * from xmltable where convert(varchar(max),xmlfield) like '%<role>'+@role+'</role>%'

Obviously this is a bit of a hack and I wouldn't recommend it for any formal solutions. However I find this technique very useful when doing adhoc queries on XML columns in SQL Server Management Studio for SQL Server 2012.

How to execute two mysql queries as one in PHP/MYSQL?

Like this:

$result1 = mysql_query($query1);
$result2 = mysql_query($query2);

// do something with the 2 result sets...

if ($result1)
    mysql_free_result($result1);

if ($result2)
    mysql_free_result($result2);

CheckBox in RecyclerView keeps on checking different items

As stated above, the checked state of the object should be included within object properties. In some cases you may need also to change the object selection state by clicking on the object itself and let the CheckBox inform about the actual state (either selected or unselected). The checkbox will then use the state of the object at the actual position of the given adapter which is (by default/in most cases) the position of the element in the list.

Check the snippet below, it may be useful.

_x000D_
_x000D_
import android.content.Context;_x000D_
import android.graphics.Bitmap;_x000D_
import android.net.Uri;_x000D_
import android.provider.MediaStore;_x000D_
import android.support.v7.widget.RecyclerView;_x000D_
import android.view.LayoutInflater;_x000D_
import android.view.View;_x000D_
import android.view.ViewGroup;_x000D_
import android.widget.CheckBox;_x000D_
import android.widget.CompoundButton;_x000D_
import android.widget.ImageView;_x000D_
_x000D_
import java.io.File;_x000D_
import java.io.IOException;_x000D_
import java.util.List;_x000D_
_x000D_
public class TakePicImageAdapter extends RecyclerView.Adapter<TakePicImageAdapter.ViewHolder>{_x000D_
    private Context context;_x000D_
    private List<Image> imageList;_x000D_
_x000D_
    public TakePicImageAdapter(Context context, List<Image> imageList) {_x000D_
        this.context = context;_x000D_
        this.imageList = imageList;_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public TakePicImageAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
        View view= LayoutInflater.from(context).inflate(R.layout.image_item,parent,false);_x000D_
        return new ViewHolder(view);_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public void onBindViewHolder(final TakePicImageAdapter.ViewHolder holder, final int position) {_x000D_
        File file=new File(imageList.get(position).getPath());_x000D_
        try {_x000D_
            Bitmap bitmap= MediaStore.Images.Media.getBitmap(context.getContentResolver(), Uri.fromFile(file));_x000D_
            holder.image.setImageBitmap(bitmap_x000D_
            );_x000D_
        } catch (IOException e) {_x000D_
            e.printStackTrace();_x000D_
        }_x000D_
        holder.selectImage.setOnCheckedChangeListener(null);_x000D_
        holder.selectImage.setChecked(imageList.get(position).isSelected());_x000D_
        holder.selectImage.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {_x000D_
            @Override_x000D_
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {_x000D_
                holder.selectImage.setChecked(isChecked);_x000D_
                imageList.get(position).setSelected(isChecked);_x000D_
            }_x000D_
        });_x000D_
        holder.image.setOnClickListener(new View.OnClickListener() {_x000D_
            @Override_x000D_
            public void onClick(View v) {_x000D_
                if (imageList.get(position).isSelected())_x000D_
                {_x000D_
                    imageList.get(position).setSelected(false);_x000D_
                    holder.selectImage.setChecked(false);_x000D_
                }else_x000D_
                {_x000D_
                    imageList.get(position).setSelected(true);_x000D_
                    holder.selectImage.setChecked(true);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
_x000D_
    }_x000D_
_x000D_
    @Override_x000D_
    public int getItemCount() {_x000D_
        return imageList.size();_x000D_
    }_x000D_
_x000D_
    public class ViewHolder extends RecyclerView.ViewHolder {_x000D_
        public ImageView image;public CheckBox selectImage;_x000D_
        public ViewHolder(View itemView) {_x000D_
            super(itemView);_x000D_
            image=(ImageView)itemView.findViewById(R.id.image);_x000D_
            selectImage=(CheckBox) itemView.findViewById(R.id.ch);_x000D_
_x000D_
        }_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How to convert a currency string to a double with jQuery or Javascript?

Remove all non dot / digits:

var currency = "-$4,400.50";
var number = Number(currency.replace(/[^0-9.-]+/g,""));

Pythonic way to create a long multi-line string

This approach uses:

  • almost no internal punctuation by using a triple quoted string
  • strips away local indentation using the inspect module
  • uses Python 3.6 formatted string interpolation ('f') for the account_id and def_id variables.

This way looks the most Pythonic to me.

import inspect

query = inspect.cleandoc(f'''
    SELECT action.descr as "action",
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id={account_id} AND
    def_id={def_id}'''
)

background: fixed no repeat not working on mobile

I have been busy using different posts and methods for two days trying to figure it out. I urge anyone to START by looking at the post by Eggs, and mess around with the codepen he and others have built.

This has been the only solution to work properly for me that I have found. I recommend his answer as a solution/ a good starting point at minimum for those of us still figuring out this problem in our own web applications.

I haven't gotten enough reputation yet to comment on his post, otherwise I would. I can't even vote on it yet or I would do that too.

This is the actual code I used:

html::before {
    content: ' ';
    display: block;
    background-image: url('path-to-your-image');
    background-position: bottom left; 
    /*For my instance this is how I have built my bg image. Indexes off the 
bottom left for consistency*/
    background-size: cover;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    position: fixed;
    z-index: -10; 
    /*I haven't tested my full app functionality after changing the z-index, but everything appears to work flawlessly right now.*/
}

I tried everything with his original code. When I had

background-position: center; 

chrome (on latest android update as of 1/8/18) would lag with updating the image's position, so when scrolling through the website there would be a patch of color where my navbar/URL bar of the browser was. Then it would disappear after the browser recalculated the image center(is what I assume was happening).

So, I recommend making an image around your footer or header like I did, and setting either top left/right or bottom left/right for your position.

In summary, THIS WORKS for me. So try it out if you're reading down this far and nothing has worked yet. Though you should've already hit the original post by now.

Thank you Eggs, and the other fellows you collaborated with on your Codepen.

How to decompile a whole Jar file?

You extract it and then use jad against the dir.

Generate signed apk android studio

Read this my answer here

How do I export a project in the Android studio?

This will guide you step by step to generate signed APK and how to create keystore file from Android Studio.

From the link you can do it easily as I added the screenshot of it step by step.

Short answer

If you have Key-store file then you can do same simply.

Go to Build then click on Generate Signed APK

Convert integer to string Jinja

I found the answer.

Cast integer to string:

myOldIntValue|string

Cast string to integer:

myOldStrValue|int

How to get a web page's source code from Java

URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in = new BufferedReader(
            new InputStreamReader(
            yahoo.openStream()));

String inputLine;

while ((inputLine = in.readLine()) != null)
    System.out.println(inputLine);

in.close();

How to handle the `onKeyPress` event in ReactJS?

You need to call event.persist(); this method on your keyPress event. Example:

const MyComponent = (props) => {
   const keyboardEvents = (event) =>{
       event.persist();
       console.log(event.key); // this will return string of key name like 'Enter'
   }
   return(
         <div onKeyPress={keyboardEvents}></div>
   )
}

If you now type console.log(event) in keyboardEvents function you will get other attributes like:

keyCode // number
charCode // number
shiftKey // boolean
ctrlKey // boolean
altKey // boolean

And many other attributes

Thanks & Regards

P.S: React Version : 16.13.1

How to find the type of an object in Go?

Best way is using reflection concept in Google.
reflect.TypeOf gives type along with the package name
reflect.TypeOf().Kind() gives underlining type

How can I make grep print the lines below and above each matching line?

grep's -A 1 option will give you one line after; -B 1 will give you one line before; and -C 1 combines both to give you one line both before and after, -1 does the same.

Bootstrap radio button "checked" flag

Assuming you want a default button checked.

<div class="row">
    <h1>Radio Group #2</h1>
    <label for="year" class="control-label input-group">Year</label>
    <div class="btn-group" data-toggle="buttons">
        <label class="btn btn-default">
            <input type="radio" name="year" value="2011">2011
        </label>
        <label class="btn btn-default">
            <input type="radio" name="year" value="2012">2012
        </label>
        <label class="btn btn-default active">
            <input type="radio" name="year" value="2013" checked="">2013
        </label>
    </div>
  </div>

Add the active class to the button (label tag) you want defaulted and checked="" to its input tag so it gets submitted in the form by default.

REST HTTP status codes for failed validation or invalid duplicate

Status Code 304 Not Modified would also make an acceptable response to a duplicate request. This is similar to processing a header of If-None-Match using an entity tag.

In my opinion, @Piskvor's answer is the more obvious choice to what I perceive is the intent of the original question, but I have an alternative that is also relevant.

If you want to treat a duplicate request as a warning or notification rather than as an error, a response status code of 304 Not Modified and Content-Location header identifying the existing resource would be just as valid. When the intent is merely to ensure that a resource exists, a duplicate request would not be an error but a confirmation. The request is not wrong, but is simply redundant, and the client can refer to the existing resource.

In other words, the request is good, but since the resource already exists, the server does not need to perform any further processing.

Adding a default value in dropdownlist after binding with database

design

<asp:DropDownList ID="ddlArea" DataSourceID="ldsArea" runat="server" ondatabound="ddlArea_DataBound" />

codebehind

protected void ddlArea_DataBound(object sender, EventArgs e)
{
    ddlArea.Items.Insert(0, new ListItem("--Select--", "0"));
}

Javascript Regex: How to put a variable inside a regular expression?

accepted answer doesn't work for me and doesn't follow MDN examples

see the 'Description' section in above link

I'd go with the following it's working for me:

let stringThatIsGoingToChange = 'findMe';
let flagsYouWant = 'gi' //simple string with flags
let dynamicRegExp = new RegExp(`${stringThatIsGoingToChange}`, flagsYouWant)

// that makes dynamicRegExp = /findMe/gi

Java - How to convert type collection into ArrayList?

Try this code

Convert ArrayList to Collection

  ArrayList<User> usersArrayList = new ArrayList<User>();

  Collection<User> userCollection = new HashSet<User>(usersArrayList);

Convert Collection to ArrayList

  Collection<User> userCollection = new HashSet<User>(usersArrayList);

  List<User> userList = new ArrayList<User>(userCollection );

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

If you get this error when you are running it, then probably its because you have not included mysql-connector JAR file to your webserver's lib folder.

Now it is important to add mysql-connector-java-5.1.25-bin.jar to your classpath and also to your webserver's lib directory. Tomcat lib path is given as an example Tomcat 6.0\lib

Can't access 127.0.0.1

Just one command did the work

netsh http add iplisten 127.0.0.1

How to select rows from a DataFrame based on column values

Faster results can be achieved using numpy.where.

For example, with unubtu's setup -

In [76]: df.iloc[np.where(df.A.values=='foo')]
Out[76]: 
     A      B  C   D
0  foo    one  0   0
2  foo    two  2   4
4  foo    two  4   8
6  foo    one  6  12
7  foo  three  7  14

Timing comparisons:

In [68]: %timeit df.iloc[np.where(df.A.values=='foo')]  # fastest
1000 loops, best of 3: 380 µs per loop

In [69]: %timeit df.loc[df['A'] == 'foo']
1000 loops, best of 3: 745 µs per loop

In [71]: %timeit df.loc[df['A'].isin(['foo'])]
1000 loops, best of 3: 562 µs per loop

In [72]: %timeit df[df.A=='foo']
1000 loops, best of 3: 796 µs per loop

In [74]: %timeit df.query('(A=="foo")')  # slowest
1000 loops, best of 3: 1.71 ms per loop

Local variable referenced before assignment?

As the Python interpreter reads the definition of a function (or, I think, even a block of indented code), all variables that are assigned to inside the function are added to the locals for that function. If a local does not have a definition before an assignment, the Python interpreter does not know what to do, so it throws this error.

The solution here is to add

global feed

to your function (usually near the top) to indicate to the interpreter that the feed variable is not local to this function.

Find all files with name containing string

Use grep as follows:

grep -R "touch" .

-R means recurse. If you would rather not go into the subdirectories, then skip it.

-i means "ignore case". You might find this worth a try as well.

How to pass a URI to an intent?

you can store the uri as string

intent.putExtra("imageUri", imageUri.toString());

and then just convert the string back to uri like this

Uri myUri = Uri.parse(extras.getString("imageUri"));

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

Using CSS to affect div style inside iframe

Apparently it can be done via jQuery:

$('iframe').load( function() {
    $('iframe').contents().find("head")
      .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
});

https://stackoverflow.com/a/13959836/1625795

How do you delete all text above a certain line

Providing you know these vim commands:

1G -> go to first line in file
G -> go to last line in file

then, the following make more sense, are more unitary and easier to remember IMHO:

d1G -> delete starting from the line you are on, to the first line of file
dG -> delete starting from the line you are on, to the last line of file

Cheers.

WPF: Setting the Width (and Height) as a Percentage Value

IValueConverter implementation can be used. Converter class which takes inheritance from IValueConverter takes some parameters like value (percentage) and parameter (parent's width) and returns desired width value. In XAML file, component's width is set with the desired value:

public class SizePercentageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter == null)
            return 0.7 * value.ToDouble();

        string[] split = parameter.ToString().Split('.');
        double parameterDouble = split[0].ToDouble() + split[1].ToDouble() / (Math.Pow(10, split[1].Length));
        return value.ToDouble() * parameterDouble;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // Don't need to implement this
        return null;
    }
}

XAML:

<UserControl.Resources>
    <m:SizePercentageConverter x:Key="PercentageConverter" />
</UserControl.Resources>

<ScrollViewer VerticalScrollBarVisibility="Auto"
          HorizontalScrollBarVisibility="Disabled"
          Width="{Binding Converter={StaticResource PercentageConverter}, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualWidth}"
          Height="{Binding Converter={StaticResource PercentageConverter}, ConverterParameter=0.6, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type Border}},Path=ActualHeight}">
....
</ScrollViewer>

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

For me after extensive debugging the fix was a simple missing throw; statement in the catch after the rollback. Without it this ugly error message is what you end up with.

begin catch
    if @@trancount > 0 rollback transaction;
    throw; --allows capture of useful info when an exception happens within the transaction
end catch

How does the stack work in assembly language?

stack is part of memory. it use for input and output of functions. also it use for remembering function's return.

esp register is remember the stack address.

stack and esp are implemented by hardware. also you can implement it yourself. it will make your program very slow.

example:

nop // esp = 0012ffc4

push 0 //esp = 0012ffc0 ,Dword[0012ffc0]=00000000

call proc01 // esp = 0012ffbc ,Dword[0012ffbc] = eip , eip = adrr[proc01]

pop eax // eax = Dword[esp], esp = esp + 4

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

Display a decimal in scientific notation

I prefer Python 3.x way.

cal = 123.4567
print(f"result {cal:.4E}")

4 indicates how many digits are shown shown in the floating part.

cal = 123.4567
totalDigitInFloatingPArt = 4
print(f"result {cal:.{totalDigitInFloatingPArt}E} ")

Is there a command to refresh environment variables from the command prompt in Windows?

By design there isn't a built in mechanism for Windows to propagate an environment variable add/change/remove to an already running cmd.exe, either from another cmd.exe or from "My Computer -> Properties ->Advanced Settings -> Environment Variables".

If you modify or add a new environment variable outside of the scope of an existing open command prompt you either need to restart the command prompt, or, manually add using SET in the existing command prompt.

The latest accepted answer shows a partial work-around by manually refreshing all the environment variables in a script. The script handles the use case of changing environment variables globally in "My Computer...Environment Variables", but if an environment variable is changed in one cmd.exe the script will not propagate it to another running cmd.exe.

How to round up the result of integer division?

A generic method, whose result you can iterate over may be of interest:

public static Object[][] chunk(Object[] src, int chunkSize) {

    int overflow = src.length%chunkSize;
    int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
    Object[][] dest = new Object[numChunks][];      
    for (int i=0; i<numChunks; i++) {
        dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
        System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length); 
    }
    return dest;
}

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

This is the normal behavior, and it's caused by the default <select> style under Firefox : you can't set line-height, then you need to play on padding when you want to have a customized <select>.

Example, with results under Firefox 25 / Chrome 31 / IE 10 :

<select>
  <option>Default</option>
  <option>Default</option>
  <option>Default</option>
</select>

<select class="form-control">
  <option>Bootstrap</option>
  <option>Bootstrap</option>
  <option>Bootstrap</option>
</select>

<select class="form-control custom">
  <option>Custom</option>
  <option>Custom</option>
  <option>Custom</option>
</select>
select.custom {
  padding: 0px;
}

Bootply

enter image description here

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Your syntax is wrong.

You need to call attr with two parameters, like this:

$('.salesperson', newOption).attr('defaultSelected', "selected");

Your current code assigns the value "selected" to the variable defaultSelected, then passes that value to the attr function, which will then return the value of the selected attribute.

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

How to clear the text of all textBoxes in the form?

private void CleanForm(Control ctrl)
{
    foreach (var c in ctrl.Controls)
    {
        if (c is TextBox)
        {
            ((TextBox)c).Text = String.Empty;
        }

        if( c.Controls.Count > 0)
        {
           CleanForm(c);
        }
    }
}

When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).

pthread_join() and pthread_exit()

It because every time

void pthread_exit(void *ret);

will be called from thread function so which ever you want to return simply its pointer pass with pthread_exit().

Now at

int pthread_join(pthread_t tid, void **ret);

will be always called from where thread is created so here to accept that returned pointer you need double pointer ..

i think this code will help you to understand this

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

void* thread_function(void *ignoredInThisExample)
{
    char *a = malloc(10);
    strcpy(a,"hello world");
    pthread_exit((void*)a);
}
int main()
{
    pthread_t thread_id;
    char *b;

    pthread_create (&thread_id, NULL,&thread_function, NULL);

    pthread_join(thread_id,(void**)&b); //here we are reciving one pointer 
                                        value so to use that we need double pointer 
    printf("b is %s\n",b); 
    free(b); // lets free the memory

}

Are Git forks actually Git clones?

Yes, fork is a clone. It emerged because, you cannot push to others' copies without their permission. They make a copy of it for you (fork), where you will have write permission as well.

In the future if the actual owner or others users with a fork like your changes they can pull it back to their own repository. Alternatively you can send them a "pull-request".

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

http://msdn.microsoft.com/en-us/library/ms157328.aspx

How to get the current time in Python

import datetime

todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12

# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38

Algorithm to generate all possible permutations of a list?

this is a java version for permutation

public class Permutation {

    static void permute(String str) {
        permute(str.toCharArray(), 0, str.length());
    }

    static void permute(char [] str, int low, int high) {
        if (low == high) {
            System.out.println(str);
            return;
        }

        for (int i=low; i<high; i++) {
            swap(str, i, low);
            permute(str, low+1, high);
            swap(str, low, i);
        }

    }

    static void swap(char [] array, int i, int j) {
        char t = array[i];
        array[i] = array[j];
        array[j] = t;
    }
}

Batch: Remove file extension

You can use %%~nf to get the filename only as described in the reference for for:

@echo off
    for /R "C:\Users\Admin\Ordner" %%f in (*.flv) do (
    echo %%~nf
)
pause

The following options are available:

Variable with modifier  Description

%~I                     Expands %I which removes any surrounding 
                        quotation marks ("").
%~fI                    Expands %I to a fully qualified path name.
%~dI                    Expands %I to a drive letter only.
%~pI                    Expands %I to a path only.
%~nI                    Expands %I to a file name only.
%~xI                    Expands %I to a file extension only.
%~sI                    Expands path to contain short names only.
%~aI                    Expands %I to the file attributes of file.
%~tI                    Expands %I to the date and time of file.
%~zI                    Expands %I to the size of file.
%~$PATH:I               Searches the directories listed in the PATH environment 
                        variable and expands %I to the fully qualified name of 
                        the first one found. If the environment variable name is 
                        not defined or the file is not found by the search,
                        this modifier expands to the empty string.    

WPF What is the correct way of using SVG files as icons in WPF

Your technique will depend on what XAML object your SVG to XAML converter produces. Does it produce a Drawing? An Image? A Grid? A Canvas? A Path? A Geometry? In each case your technique will be different.

In the examples below I will assume you are using your icon on a button, which is the most common scenario, but note that the same techniques will work for any ContentControl.

Using a Drawing as an icon

To use a Drawing, paint an approriately-sized rectangle with a DrawingBrush:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush>
        <DrawingBrush.Drawing>

          <Drawing ... /> <!-- Converted from SVG -->

        </DrawingBrush.Drawing>
      </DrawingBrush>
    </Rectangle.Fill>
  </Rectangle>
</Button>

Using an Image as an icon

An image can be used directly:

<Button>
  <Image ... />  <!-- Converted from SVG -->
</Button>

Using a Grid as an icon

A grid can be used directly:

<Button>
  <Grid ... />  <!-- Converted from SVG -->
</Button>

Or you can include it in a Viewbox if you need to control the size:

<Button>
  <Viewbox ...>
    <Grid ... />  <!-- Converted from SVG -->
  </Viewbox>
</Button>

Using a Canvas as an icon

This is like using an image or grid, but since a canvas has no fixed size you need to specify the height and width (unless these are already set by the SVG converter):

<Button>
  <Canvas Height="100" Width="100">  <!-- Converted from SVG, with additions -->
  </Canvas>
</Button>

Using a Path as an icon

You can use a Path, but you must set the stroke or fill explicitly:

<Button>
  <Path Stroke="Red" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

or

<Button>
  <Path Fill="Blue" Data="..." /> <!-- Converted from SVG, with additions -->
</Button>

Using a Geometry as an icon

You can use a Path to draw your geometry. If it should be stroked, set the Stroke:

<Button>
  <Path Stroke="Red" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

or if it should be filled, set the Fill:

<Button>
  <Path Fill="Blue" Width="100" Height="100">
    <Path.Data>
      <Geometry ... /> <!-- Converted from SVG -->
    </Path.Data>
  </Path>
</Button>

How to data bind

If you're doing the SVG -> XAML conversion in code and want the resulting XAML to appear using data binding, use one of the following:

Binding a Drawing:

<Button>
  <Rectangle Width="100" Height="100">
    <Rectangle.Fill>
      <DrawingBrush Drawing="{Binding Drawing, Source={StaticResource ...}}" />
    </Rectangle.Fill>
  </Rectangle>
</Button>

Binding an Image:

<Button Content="{Binding Image}" />

Binding a Grid:

<Button Content="{Binding Grid}" />

Binding a Grid in a Viewbox:

<Button>
  <Viewbox ...>
    <ContentPresenter Content="{Binding Grid}" />
  </Viewbox>
</Button>

Binding a Canvas:

<Button>
  <ContentPresenter Height="100" Width="100" Content="{Binding Canvas}" />
</Button>

Binding a Path:

<Button Content="{Binding Path}" />  <!-- Fill or stroke must be set in code unless set by the SVG converter -->

Binding a Geometry:

<Button>
  <Path Width="100" Height="100" Data="{Binding Geometry}" />
</Button>

Scroll to bottom of div with Vue.js

As I understood, the desired effect you want is to scroll to the end of a list (or scrollable div) when something happens (e.g.: a item is added to the list). If so, you can scroll to the end of a container element (or even the page it self) using only pure Javascript and the VueJS selectors.

var container = this.$el.querySelector("#container");
container.scrollTop = container.scrollHeight;

I've provided a working example in this fiddle: https://jsfiddle.net/my54bhwn

Every time a item is added to the list, the list is scrolled to the end to show the new item.

Hope this help you.

Material UI and Grid system

The way I do is go to http://getbootstrap.com/customize/ and only check "grid system" to download. There are bootstrap-theme.css and bootstrap.css in downloaded files, and I only need the latter.

In this way, I can use the grid system of Bootstrap, with everything else from Material UI.

keycloak Invalid parameter: redirect_uri

If you're trying to redirect to the keycloak login page after logout (as I was), that is not allowed by default but also needs to be configured in the "Valid Redirect URIs" setting in the admin console of your client.

Check if a string has a certain piece of text

Here you go: ES5

var test = 'Hello World';
if( test.indexOf('World') >= 0){
  // Found world
}

With ES6 best way would be to use includes function to test if the string contains the looking work.

const test = 'Hello World';
if (test.includes('World')) { 
  // Found world
}

HTML5 validation when the input type is not "submit"

I may be late, but the way I did it was to create a hidden submit input, and calling it's click handler upon submit. Something like (using jquery for simplicity):

<input type="text" id="example" name="example" value="" required>
<button type="button"  onclick="submitform()" id="save">Save</button>
<input id="submit_handle" type="submit" style="display: none">

<script>
function submitform() {
    $('#submit_handle').click();
}
</script>

How do you switch pages in Xamarin.Forms?

If your project has been set up as a PCL forms project (and very likely as Shared Forms as well but I haven't tried that) there is a class App.cs that looks like this:

public class App
{
    public static Page GetMainPage ()
    {     
        AuditorDB.Model.Extensions.AutoTimestamp = true;
        return new NavigationPage (new LoginPage ());
    }
}

you can modify the GetMainPage method to return a new TabbedPaged or some other page you have defined in the project

From there on you can add commands or event handlers to execute code and do

// to show OtherPage and be able to go back
Navigation.PushAsync(new OtherPage());

// to show AnotherPage and not have a Back button
Navigation.PushModalAsync(new AnotherPage()); 

// to go back one step on the navigation stack
Navigation.PopAsync();

CSS: how do I create a gap between rows in a table?

If none of the other answers are satisfactory, you could always just create an empty row and style it with CSS appropriately to be transparent.

Write applications in C or C++ for Android?

Looking at this it seems it is possible:

"the fact is only Java language is supported doesn’t mean that you cannot develop applications in other languages. This have been proved by many developers, hackers and experts in application development for mobile. The guys at Elements Interactive B.V., the company behind Edgelib library, succeeded to run native C++ applications on the Android platform, even that at this time there is still many issues on display and sound … etc. This include the S-Tris2 game and a 3D animation demo of Edgelib."

Call to undefined function App\Http\Controllers\ [ function name ]

If they are in the same controller class, it would be:

foreach ( $characters as $character) {
    $num += $this->getFactorial($index) * $index;
    $index ++;
}

Otherwise you need to create a new instance of the class, and call the method, ie:

$controller = new MyController();
foreach ( $characters as $character) {
    $num += $controller->getFactorial($index) * $index;
    $index ++;
}

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

Responding because this answer came up first for search when I was having the same issue:

[08S01][unixODBC][FreeTDS][SQL Server]Unable to connect: Adaptive Server is unavailable or does not exist

MSSQL named instances have to be configured properly without setting the port. (documentation on the freetds config says set instance or port NOT BOTH)

freetds.conf

[Name]
host = Server.com
instance = instance_name
#port = port is found automatically, don't define explicitly
tds version = 8.0
client charset = UTF-8

And in odbc.ini just because you can set Port, DON'T when you are using a named instance.

Difference between String replace() and replaceAll()

From Java 9 there is some optimizations in replace method.

In Java 8 it uses a regex.

public String replace(CharSequence target, CharSequence replacement) {
    return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
            this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}

From Java 9 and on.

enter image description here

And Stringlatin implementation.

enter image description here

Which perform way better.

https://medium.com/madhash/composite-pattern-in-a-nutshell-ad1bf78479cc?source=post_internal_links---------2------------------

Negate if condition in bash script

You can use unequal comparison -ne instead of -eq:

wget -q --tries=10 --timeout=20 --spider http://google.com
if [[ $? -ne 0 ]]; then
    echo "Sorry you are Offline"
    exit 1
fi

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

Split string with PowerShell and do something with each token

Another way to accomplish this is a combination of Justus Thane's and mklement0's answers. It doesn't make sense to do it this way when you look at a one liner example, but when you're trying to mass-edit a file or a bunch of filenames it comes in pretty handy:

$test = '   One      for the money   '
$option = [System.StringSplitOptions]::RemoveEmptyEntries
$($test.split(' ',$option)).foreach{$_}

This will come out as:

One
for
the
money

Detect if range is empty

If you find yourself in a situation where you can’t use CountA then it's much faster to first store your range as an array and loop on the array data than it is to loop on range/cell data.

Function IsRangeEmpty(ByVal rng As Range) As Boolean
    'Converts a range to an array and returns true if a value is found in said array
    
    Dim area As Range
    For Each area In rng.Areas
        
        If area.Cells.Count > 1 Then
        
            'save range as array
            Dim arr As Variant
            arr = area.value
            
            'loop through array
            Dim cel As Variant
            For Each cel In arr
            
                'if cell is not empty then
                If Len(Trim(cel)) > 0 Then
                    IsRangeEmpty = False
                    Exit Function
                End If

            Next cel
            
        Else    'cannot loop on array with one value
            
            'if cell is not empty then
            If Len(Trim(area.Value2)) > 0 Then
                IsRangeEmpty = False
                Exit Function
            End If
            
        End If

    Next area

    IsRangeEmpty = True

End Function

Example of how to use it:

Sub Test()
    Debug.Print IsRangeEmpty(Range("A38:P38"))
End Sub

If Range("A38:P38") is empty, it would print True in the Immediate Window; otherwise it'd print False.

What is the difference between a schema and a table and a database?

This particular posting has been shown to relate to Oracle only and the definition of Schema changes when in the context of another DB.

Probably the kinda thing to just google up but FYI terms do seem to vary in their definitions which is the most annoying thing :)

In Oracle a database is a database. In your head think of this as the data files and the redo logs and the actual physical presence on the disk of the database itself (i.e. not the instance)

A Schema is effectively a user. More specifically it's a set of tables/procs/indexes etc owned by a user. Another user has a different schema (tables he/she owns) however user can also see any schemas they have select priviliedges on. So a database can consist of hundreds of schemas, and each schema hundreds of tables. You can have tables with the same name in different schemas, which are in the same database.

A Table is a table, a set of rows and columns containing data and is contained in schemas.

Definitions may be different in SQL Server for instance. I'm not aware of this.

Retrieve last 100 lines logs

len=`cat filename | wc -l`
len=$(( $len + 1 ))
l=$(( $len - 99 ))
sed -n "${l},${len}p" filename

first line takes the length (Total lines) of file then +1 in the total lines after that we have to fatch 100 records so, -99 from total length then just put the variables in the sed command to fetch the last 100 lines from file

I hope this will help you.

How to avoid 'undefined index' errors?

In my case, I get it worked by defining the default value if the submitted data is empty. Here is what I finally did (using PHP7.3.5):

if(empty($_POST['auto'])){ $_POST['auto'] = ""; }

How to Clone Objects

I use AutoMapper for this. It works like this:

Mapper.CreateMap(typeof(Person), typeof(Person));
Mapper.Map(a, b);

Now person a has all the properties of person b.

As an aside, AutoMapper works for differing objects as well. For more information, check it out at http://automapper.org

Update: I use this syntax now (simplistically - really the CreateMaps are in AutoMapper profiles):

Mapper.CreateMap<Person, Person>;
Mapper.Map(a, b);

Note that you don't have to do a CreateMap to map one object of the same type to another, but if you don't, AutoMapper will create a shallow copy, meaning to the lay man that if you change one object, the other changes also.

"Cannot GET /" with Connect on Node.js

You might be needed to restart the process if app.get not working. Press ctl+c and then restart node app.

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

Append text to textarea with javascript

Use event delegation by assigning the onclick to the <ol>. Then pass the event object as the argument, and using that, grab the text from the clicked element.

_x000D_
_x000D_
function addText(event) {_x000D_
    var targ = event.target || event.srcElement;_x000D_
    document.getElementById("alltext").value += targ.textContent || targ.innerText;_x000D_
}
_x000D_
<textarea id="alltext"></textarea>_x000D_
_x000D_
<ol onclick="addText(event)">_x000D_
  <li>Hello</li>_x000D_
  <li>World</li>_x000D_
  <li>Earthlings</li>_x000D_
</ol>
_x000D_
_x000D_
_x000D_

Note that this method of passing the event object works in older IE as well as W3 compliant systems.

jquery change style of a div on click

$(document).ready(function() {
  $('#div_one').bind('click', function() {
    $('#div_two').addClass('large');
  });
});

If I understood your question.

Or you can modify css directly:

var $speech = $('div.speech');
var currentSize = $speech.css('fontSize');
$speech.css('fontSize', '10px');

jQuery UI themes and HTML tables

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

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

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

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

Getting list of tables, and fields in each, in a database

For MYSQL:

Select *
From INFORMATION_SCHEMA.COLUMNS
where TABLE_SCHEMA = "<DatabaseName>"

Error: "an object reference is required for the non-static field, method or property..."

Create a class and put all your code in there and call an instance of this class from the Main :

static void Main(string[] args)
{

    MyClass cls  = new MyClass();
    Console.Write("Write a number: ");
    long a= Convert.ToInt64(Console.ReadLine()); // a is the number given by the user
    long av = cls.volteado(a);
    bool isTrue = cls.siprimo(a);
    ......etc

}

How to show particular image as thumbnail while implementing share on Facebook?

I was having the same problems and believe I have solved it. I used the link meta tag as mentioned here to point to the image I wanted, but the key is that if you do that FB won't pull any other images as choices. Also if your image is too big, you won't have any choices at all.

Here's how I fixed my site http://gnorml.com/blog/facebook-link-thumbnails/

CSS: On hover show and hide different div's at the same time?

http://jsfiddle.net/MBLZx/

Here is the code

_x000D_
_x000D_
 .showme{ _x000D_
   display: none;_x000D_
 }_x000D_
 .showhim:hover .showme{_x000D_
   display : block;_x000D_
 }_x000D_
 .showhim:hover .ok{_x000D_
   display : none;_x000D_
 }
_x000D_
 <div class="showhim">_x000D_
     HOVER ME_x000D_
     <div class="showme">hai</div>_x000D_
     <div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
   
_x000D_
_x000D_
_x000D_

Where to declare variable in react js

Using ES6 syntax in React does not bind this to user-defined functions however it will bind this to the component lifecycle methods.

So the function that you declared will not have the same context as the class and trying to access this will not give you what you are expecting.

For getting the context of class you have to bind the context of class to the function or use arrow functions.

Method 1 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.onMove = this.onMove.bind(this);
        this.testVarible= "this is a test";
    }

    onMove() {
        console.log(this.testVarible);
    }
}

Method 2 to bind the context:

class MyContainer extends Component {

    constructor(props) {
        super(props);
        this.testVarible= "this is a test";
    }

    onMove = () => {
        console.log(this.testVarible);
    }
}

Method 2 is my preferred way but you are free to choose your own.

Update: You can also create the properties on class without constructor:

class MyContainer extends Component {

    testVarible= "this is a test";

    onMove = () => {
        console.log(this.testVarible);
    }
}

Note If you want to update the view as well, you should use state and setState method when you set or change the value.

Example:

class MyContainer extends Component {

    state = { testVarible: "this is a test" };

    onMove = () => {
        console.log(this.state.testVarible);
        this.setState({ testVarible: "new value" });
    }
}

How to change the Content of a <textarea> with JavaScript

Put the textarea to a form, naming them, and just use the DOM objects easily, like this:

<body onload="form1.box.value = 'Welcome!'">
  <form name="form1">
    <textarea name="box"></textarea>
  </form>
</body>

What is an ORM, how does it work, and how should I use one?

Can anyone give me a brief explanation...

Sure.

ORM stands for "Object to Relational Mapping" where

  • The Object part is the one you use with your programming language ( python in this case )

  • The Relational part is a Relational Database Manager System ( A database that is ) there are other types of databases but the most popular is relational ( you know tables, columns, pk fk etc eg Oracle MySQL, MS-SQL )

  • And finally the Mapping part is where you do a bridge between your objects and your tables.

In applications where you don't use a ORM framework you do this by hand. Using an ORM framework would allow you do reduce the boilerplate needed to create the solution.

So let's say you have this object.

 class Employee:
      def __init__( self, name ): 
          self.__name = name

       def getName( self ):
           return self.__name

       #etc.

and the table

   create table employee(
          name varcar(10),
          -- etc  
    )

Using an ORM framework would allow you to map that object with a db record automagically and write something like:

   emp = Employee("Ryan")

   orm.save( emp )

And have the employee inserted into the DB.

Oops it was not that brief but I hope it is simple enough to catch other articles you read.

Flutter Countdown Timer

Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class

TweenAnimationBuilder<Duration>(
              duration: Duration(minutes: 3),
              tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
              onEnd: () {
                print('Timer ended');
              },
              builder: (BuildContext context, Duration value, Widget child) {
              final minutes = value.inMinutes;
              final seconds = value.inSeconds % 60;
              return Padding(
                     padding: const EdgeInsets.symmetric(vertical: 5),
                     child: Text('$minutes:$seconds',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 30)));
              }),

and You also get onEnd call back which notifies you when the animation completes;

here's the output

How to switch activity without animation in Android?

create your own style overriding android:Theme

<style name="noAnimationStyle" parent="android:Theme">
    <item name="android:windowAnimationStyle">@null</item>
</style>

Then use it in manifest like this:

<activity android:name=".MainActivity"
    android:theme="@style/noAnimationStyle">
</activity>

Check if a value is in an array (C#)

    public static bool Contains(Array a, object val)
    {
        return Array.IndexOf(a, val) != -1;
    }

Git push: "fatal 'origin' does not appear to be a git repository - fatal Could not read from remote repository."

I had the same issue. When I checked my config file I noticed that 'fetch = +refs/heads/:refs/remotes/origin/' was on the same line as 'url = Z:/GIT/REPOS/SEL.git' as shown:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git     fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

At first I did not think that this would have mattered but after seeing the post by Magere I moved the line and that fixed the problem:

[core]
    repositoryformatversion = 0
    filemode = false
    bare = false
    logallrefupdates = true
    symlinks = false
    ignorecase = true
[remote "origin"]
    url = Z:/GIT/REPOS/SEL.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[gui]
    wmstate = normal
    geometry = 1109x563+32+32 216 255

What is FCM token in Firebase?

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}

How to detect when an @Input() value changes in Angular?

You can use a BehaviorSubject within a facade service then subscribe to that subject in any component and when an event happens to trigger a change in data call .next() on it. Make sure to close out those subscriptions within the on destroy lifecycle hook.

data-api.facade.ts

@Injectable({
  providedIn: 'root'
})
export class DataApiFacade {

currentTabIndex: BehaviorSubject<number> = new BehaviorSubject(0);

}

some.component.ts

constructor(private dataApiFacade: DataApiFacade){}

ngOnInit(): void {
  this.dataApiFacade.currentTabIndex
    .pipe(takeUntil(this.destroy$))
       .subscribe(value => {
          if (value) {
             this.currentTabIndex = value;
          }
    });
}

setTabView(event: MatTabChangeEvent) {
  this.dataApiFacade.currentTabIndex.next(event.index);
}

ngOnDestroy() {
  this.destroy$.next(true);
  this.destroy$.complete();
}

How to find out which JavaScript events fired?

Just thought I'd add that you can do this in Chrome as well:

Ctrl + Shift + I (Developer Tools) > Sources> Event Listener Breakpoints (on the right).

You can also view all events that have already been attached by simply right clicking on the element and then browsing its properties (the panel on the right).

For example:

  • Right click on the upvote button to the left
  • Select inspect element
  • Collapse the styles section (section on the far right - double chevron)
  • Expand the event listeners option
  • Now you can see the events bound to the upvote
  • Not sure if it's quite as powerful as the firebug option, but has been enough for most of my stuff.

    Another option that is a bit different but surprisingly awesome is Visual Event: http://www.sprymedia.co.uk/article/Visual+Event+2

    It highlights all of the elements on a page that have been bound and has popovers showing the functions that are called. Pretty nifty for a bookmark! There's a Chrome plugin as well if that's more your thing - not sure about other browsers.

    AnonymousAndrew has also pointed out monitorEvents(window); here

    How to replace part of string by position?

    Like other have mentioned the Substring() function is there for a reason:

    static void Main(string[] args)
    {
        string input = "ABCDEFGHIJ";
    
        string output = input.Overwrite(3, "ZX"); // 4th position has index 3
        // ABCZXFGHIJ
    }
    
    public static string Overwrite(this string text, int position, string new_text)
    {
        return text.Substring(0, position) + new_text + text.Substring(position + new_text.Length);
    }
    

    Also I timed this against the StringBuilder solution and got 900 tics vs. 875. So it is slightly slower.

    How to read data from java properties file using Spring Boot

    I have created following class

    ConfigUtility.java

    @Configuration
    public class ConfigUtility {
    
        @Autowired
        private Environment env;
    
        public String getProperty(String pPropertyKey) {
            return env.getProperty(pPropertyKey);
        }
    } 
    

    and called as follow to get application.properties value

    myclass.java

    @Autowired
    private ConfigUtility configUtil;
    
    public AppResponse getDetails() {
    
      AppResponse response = new AppResponse();
        String email = configUtil.getProperty("emailid");
        return response;        
    }
    

    application.properties

    [email protected]

    unit tested, working as expected...

    Apache Spark: The number of cores vs. the number of executors

    There is a small issue in the First two configurations i think. The concepts of threads and cores like follows. The concept of threading is if the cores are ideal then use that core to process the data. So the memory is not fully utilized in first two cases. If you want to bench mark this example choose the machines which has more than 10 cores on each machine. Then do the bench mark.

    But dont give more than 5 cores per executor there will be bottle neck on i/o performance.

    So the best machines to do this bench marking might be data nodes which have 10 cores.

    Data node machine spec: CPU: Core i7-4790 (# of cores: 10, # of threads: 20) RAM: 32GB (8GB x 4) HDD: 8TB (2TB x 4)

    Support for "border-radius" in IE

    A workaround and a handy tool:

    CSS3Pie uses .htc files and the behavior property to implement CSS3 into IE 6 - 8.

    Modernizr is a bit of javascript that will put classes on your html element, allowing you to serve different style definitions to different browsers based on their capabilities.

    Obviously, these both add more overhead, but with IE9 due to only run on Vista/7 we might be stuck for quite awhile. As of August 2010 Windows XP still accounts for 48% of web client OSes.

    Java "user.dir" property - what exactly does it mean?

    It's the directory where java was run from, where you started the JVM. Does not have to be within the user's home directory. It can be anywhere where the user has permission to run java.

    So if you cd into /somedir, then run your program, user.dir will be /somedir.

    A different property, user.home, refers to the user directory. As in /Users/myuser or /home/myuser or C:\Users\myuser.

    See here for a list of system properties and their descriptions.