Programs & Examples On #Jsonserializer

Ruby objects and JSON serialization (without Rails)

require 'json'
{"foo" => "bar"}.to_json
# => "{\"foo\":\"bar\"}"

Jackson enum Serializing and DeSerializer

You can customize the deserialization for any attribute.

Declare your deserialize class using the annotationJsonDeserialize (import com.fasterxml.jackson.databind.annotation.JsonDeserialize) for the attribute that will be processed. If this is an Enum:

@JsonDeserialize(using = MyEnumDeserialize.class)
private MyEnum myEnum;

This way your class will be used to deserialize the attribute. This is a full example:

public class MyEnumDeserialize extends JsonDeserializer<MyEnum> {

    @Override
    public MyEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        JsonNode node = jsonParser.getCodec().readTree(jsonParser);
        MyEnum type = null;
        try{
            if(node.get("attr") != null){
                type = MyEnum.get(Long.parseLong(node.get("attr").asText()));
                if (type != null) {
                    return type;
                }
            }
        }catch(Exception e){
            type = null;
        }
        return type;
    }
}

Cannot find JavaScriptSerializer in .Net 4.0

I'm using Visual Studio 2015 and finally ran across this post.

Yes in order to use

JavaScriptSerializer json = new JavaScriptSerializer();

You must right click on references and under Assemblies --> Framework choose

System.Web.Extensions

Then add in your reference

using System.Web.Script.Serialization;

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I found this MSDN forum post which suggests two solutions to your problem.

First solution (not recommended):

Find the .Net Framework 3.5 and 2.0 folder

Copy System.Web.Extensions.dll from 3.5 and System.Web.dll from 2.0 to the application folder

Add the reference to these two assemblies

Change the referenced assemblies property, setting "Copy Local" to true And build to test your application to ensure all code can work

Second solution (Use a different class / library):

The user who had posted the question claimed that Uri.EscapeUriString and How to: Serialize and Deserialize JSON Data helped him replicate the behavior of JavaScriptSerializer.

You could also try to use Json.Net. It's a third party library and pretty powerful.

jQuery ajax post file field

This should help. How can I upload files asynchronously?

As the post suggest I recommend a plugin located here http://malsup.com/jquery/form/#code-samples

How to add a custom HTTP header to every WCF call?

A bit late to the party but Juval Lowy addresses this exact scenario in his book and the associated ServiceModelEx library.

Basically he defines ClientBase and ChannelFactory specialisations that allow specifying type-safe header values. I suggesst downloading the source and looking at the HeaderClientBase and HeaderChannelFactory classes.

John

Owl Carousel Won't Autoplay

If you using v1.3.3 then use following property

autoPlay : 5000

Or using latest version then use following property

autoPlay : true

What's the main difference between int.Parse() and Convert.ToInt32

Convert.ToInt32

has 19 overloads or 19 different ways that you can call it. Maybe more in 2010 versions.

It will attempt to convert from the following TYPES;

Object, Boolean, Char, SByte, Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Single, Double, Decimal, String, Date

and it also has a number of other methods; one to do with a number base and 2 methods involve a System.IFormatProvider

Parse on the other hand only has 4 overloads or 4 different ways you can call the method.

Integer.Parse( s As String)

Integer.Parse( s As String,  style As System.Globalization.NumberStyles )

Integer.Parse( s As String, provider As System.IFormatProvider )

Integer.Parse( s As String,  style As System.Globalization.NumberStyles, provider As System.IFormatProvider )

How to count lines in a document?

cat file.log | wc -l | grep -oE '\d+'
  • grep -oE '\d+': In order to return the digit numbers ONLY.

Shell Script: Execute a python program from within a shell script

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv

Html helper for <input type="file" />

I had this same question a while back and came across one of Scott Hanselman's posts:

Implementing HTTP File Upload with ASP.NET MVC including Tests and Mocks

Hope this helps.

How to convert Seconds to HH:MM:SS using T-SQL

DECLARE @Seconds INT = 86200;
SELECT 
CONVERT(VARCHAR(15), 
CAST(CONVERT(VARCHAR(12), @Seconds / 60 / 60 % 24)
+':'+ CONVERT(VARCHAR(2), @Seconds / 60 % 60)
+':'+ CONVERT(VARCHAR(2), @Seconds % 60) AS TIME), 100) AS [HH:MM:SS (AM/PM)]

enter image description here

How to read connection string in .NET Core?

i have a data access library which works with both .net core and .net framework.

the trick was in .net core projects to keep the connection strings in a xml file named "app.config" (also for web projects), and mark it as 'copy to output directory',

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="conn1" connectionString="...." providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

ConfigurationManager.ConnectionStrings - will read the connection string.

    var conn1 = ConfigurationManager.ConnectionStrings["conn1"].ConnectionString;

What is the meaning of polyfills in HTML5?

A polyfill is a shim which replaces the original call with the call to a shim.

For example, say you want to use the navigator.mediaDevices object, but not all browsers support this. You could imagine a library that provided a shim which you might use like this:

<script src="js/MediaShim.js"></script>
<script>
    MediaShim.mediaDevices.getUserMedia(...);
</script>

In this case, you are explicitly calling a shim instead of using the original object or method. The polyfill, on the other hand, replaces the objects and methods on the original objects.

For example:

<script src="js/adapter.js"></script>
<script>
    navigator.mediaDevices.getUserMedia(...);
</script>

In your code, it looks as though you are using the standard navigator.mediaDevices object. But really, the polyfill (adapter.js in the example) has replaced this object with its own one.

The one it has replaced it with is a shim. This will detect if the feature is natively supported and use it if it is, or it will work around it using other APIs if it is not.

So a polyfill is a sort of "transparent" shim. And this is what Remy Sharp (who coined the term) meant when saying "if you removed the polyfill script, your code would continue to work, without any changes required in spite of the polyfill being removed".

Check if element is visible in DOM

Here's the code I wrote to find the only visible among a few similar elements, and return the value of its "class" attribute without jQuery:

  // Build a NodeList:
  var nl = document.querySelectorAll('.myCssSelector');

  // convert it to array:
  var myArray = [];for(var i = nl.length; i--; myArray.unshift(nl[i]));

  // now find the visible (= with offsetWidth more than 0) item:
  for (i =0; i < myArray.length; i++){
    var curEl = myArray[i];
    if (curEl.offsetWidth !== 0){
      return curEl.getAttribute("class");
    }
  }

How do I access command line arguments in Python?

You can use sys.argv to get the arguments as a list.

If you need to access individual elements, you can use

sys.argv[i]  

where i is index, 0 will give you the python filename being executed. Any index after that are the arguments passed.

Export a list into a CSV or TXT file in R

I export lists into YAML format with CPAN YAML package.

l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")

Bonus of YAML that it's a human readable text format so it's easy to read/share/import/etc

$ cat list.yaml
a: '1'
b: 1.0
c:
  a: '1'
  b: 1.0

How to make a machine trust a self-signed Java application

SERIOUS DISCLAIMER

This solution has a serious security flaw. Please use at your own risk.
Have a look at the comments on this post, and look at all the answers to this question.


OK, I had to go to the customer premises and found a solution. I:

  • Exported the keystore that holds the signing keys in PKCS #12 format
  • Opened control panel Java -> Security tab
  • Clicked Manage certificates
  • Imported this new keystore as a secure site CA

Then I opened the JAWS application without any warning. This is a little bit cumbersome, but much cheaper than buying a signed certificate!

Send multipart/form-data files with angular using $http

Take a look at the FormData object: https://developer.mozilla.org/en/docs/Web/API/FormData

this.uploadFileToUrl = function(file, uploadUrl){
        var fd = new FormData();
        fd.append('file', file);
        $http.post(uploadUrl, fd, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
        .success(function(){
        })
        .error(function(){
        });
    }

What is the .idea folder?

When you use the IntelliJ IDE, all the project-specific settings for the project are stored under the .idea folder.

Project settings are stored with each specific project as a set of xml files under the .idea folder. If you specify the default project settings, these settings will be automatically used for each newly created project.

Check this documentation for the IDE settings and here is their recommendation on Source Control and an example .gitignore file.

Note: If you are using git or some version control system, you might want to set this folder "ignore". Example - for git, add this directory to .gitignore. This way, the application is not IDE-specific.

configuring project ':app' failed to find Build Tools revision

I had c++ codes in my project but i didn't have NDK installed, installing it solved the problem

Linux command-line call not returning what it should from os.system?

If you're only interested in the output from the process, it's easiest to use subprocess' check_output function:


output = subprocess.check_output(["command", "arg1", "arg2"]);

Then output holds the program output to stdout. Check the link above for more info.

What does $1 mean in Perl?

$1, $2, etc will contain the value of captures from the last successful match - it's important to check whether the match succeeded before accessing them, i.e.

 if ( $var =~ m/( )/ ) { # use $1 etc... }

An example of the problem - $1 contains 'Quick' in both print statements below:

#!/usr/bin/perl

'Quick brown fox' =~ m{ ( quick ) }ix;
print "Found: $1\n";

'Lazy dog' =~ m{ ( quick ) }ix;
print "Found: $1\n";

Shell script to get the process ID on Linux

option -v is very important. It can exclude a grep expression itself

e.g.

ps -w | grep sshd | grep -v grep | awk '{print $1}' to get sshd id

VBA Go to last empty row

try this:

Sub test()

With Application.WorksheetFunction
    Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With

End Sub

Hope this works for you.

How to solve "The specified service has been marked for deletion" error

Deleting registry keys as suggested above got my service stuck in the stopping state. The following procedure worked for me:

open task manager > select services tab > select the service > right click and select "go to process" > right click on the process and select End process

Service should be gone after that

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

Permission denied error while writing to a file in Python

Please close the file if its still open on your computer, then try running the python code. I hope it works

Gradle failed to resolve library in Android Studio

For me follwing steps helped.

It seems to be bug of Android Studio 3.4/3.5 and it was "fixed" by disabling:

File ? Settings ? Experimental ? Gradle ? Only sync the active variant

Removing viewcontrollers from navigation stack

// removing the viewcontrollers by class names from stack and then dismissing the current view.

 self.navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
      if vc.isKind(of: ViewController.self) || vc.isKind(of: ViewController2.self) 
       {
        return true
        } 
     else 
        {
         return false
         }
        })
self.navigationController?.popViewController(animated: false)
self.dismiss(animated: true, completion: nil)

Await operator can only be used within an Async method

You can only use await in an async method, and Main cannot be async.

You'll have to use your own async-compatible context, call Wait on the returned Task in the Main method, or just ignore the returned Task and just block on the call to Read. Note that Wait will wrap any exceptions in an AggregateException.

If you want a good intro, see my async/await intro post.

jQuery attr() change img src

You remove the original image here:

newImg.animate(css, SPEED, function() {
    img.remove();
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And all that's left behind is newImg. Then you reset link references the image using #rocket:

$("#rocket").attr('src', ...

But your newImg doesn't have an id attribute let alone an id of rocket.

To fix this, you need to remove img and then set the id attribute of newImg to rocket:

newImg.animate(css, SPEED, function() {
    var old_id = img.attr('id');
    img.remove();
    newImg.attr('id', old_id);
    newImg.removeClass('morpher');
    (callback || function() {})();
});

And then you'll get the shiny black rocket back again: http://jsfiddle.net/ambiguous/W2K9D/

UPDATE: A better approach (as noted by mellamokb) would be to hide the original image and then show it again when you hit the reset button. First, change the reset action to something like this:

$("#resetlink").click(function(){
    clearInterval(timerRocket);
    $("#wrapper").css('top', '250px');
    $('.throbber, .morpher').remove(); // Clear out the new stuff.
    $("#rocket").show();               // Bring the original back.
});

And in the newImg.load function, grab the images original size:

var orig = {
    width: img.width(),
    height: img.height()
};

And finally, the callback for finishing the morphing animation becomes this:

newImg.animate(css, SPEED, function() {
    img.css(orig).hide();
    (callback || function() {})();
});

New and improved: http://jsfiddle.net/ambiguous/W2K9D/1/

The leaking of $('.throbber, .morpher') outside the plugin isn't the best thing ever but it isn't a big deal as long as it is documented.

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

How to modify WooCommerce cart, checkout pages (main theme portion)

You can use function: wc_get_page_id( 'cart' ) to get the ID of the page. This function will use the page setup as 'cart' page and not the slug. Meaning it will keep working also when you setup a different url for your 'cart' on the settings page. This works for all kind of Woocommerce special page, like 'checkout', 'shop' etc.

example:

if (wc_get_page_id( 'cart' ) == get_the_ID()) {
  // Do something.
}

Java - Check if input is a positive integer, negative integer, natural number and so on.

What about using the following:

int number = input.nextInt();
if (number < 0) {
    // negative
} else {
   // it's a positive
}

file_put_contents - failed to open stream: Permission denied

The other option

is that you can make Apache (www-data), the owner of the folder

sudo chown -R www-data:www-data /var/www

that should make file_put_contents work now. But for more security you better also set the permissions like below

find /var/www -type d -print0 | xargs -0 chmod 0755 # folder
find /var/www -type f -print0 | xargs -0 chmod 0644 # files
  • change /var/www to the root folder of your php files

Delete with "Join" in Oracle sql Query

Recently I learned of the following syntax:

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

I think it looks much cleaner then other proposed code.

How to disable input conditionally in vue.js

Can use this add condition.

  <el-form-item :label="Amount ($)" style="width:100%"  >
            <template slot-scope="scoped">
            <el-input-number v-model="listQuery.refAmount" :disabled="(rowData.status !== 1 ) === true" ></el-input-number>
            </template>
          </el-form-item>

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

I had the same issue and found out that my code was using the injection before it was initialized.

services.AddControllers(); // Will cause a problem if you use your IBloggerRepository in there since it's defined after this line.
services.AddScoped<IBloggerRepository, BloggerRepository>();

I know it has nothing to do with the question, but since I was sent to this page, I figure out it my be useful to someone else.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

Mockito - difference between doReturn() and when()

Continuing this answer, There is another difference that if you want your method to return different values for example when it is first time called, second time called etc then you can pass values so for example...

PowerMockito.doReturn(false, false, true).when(SomeClass.class, "SomeMethod", Matchers.any(SomeClass.class));

So it will return false when the method is called in same test case and then it will return false again and lastly true.

Grid of responsive squares

The accepted answer is great, however this can be done with flexbox.

Here's a grid system written with BEM syntax that allows for 1-10 columns to be displayed per row.

If there the last row is incomplete (for example you choose to show 5 cells per row and there are 7 items), the trailing items will be centered horizontally. To control the horizontal alignment of the trailing items, simply change the justify-content property under the .square-grid class.

.square-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.square-grid__cell {
  background-color: rgba(0, 0, 0, 0.03);
  box-shadow: 0 0 0 1px black;
  overflow: hidden;
  position: relative;
}

.square-grid__content {
  left: 0;
  position: absolute;
  top: 0;
}

.square-grid__cell:after {
  content: '';
  display: block;
  padding-bottom: 100%;
}

// Sizes – Number of cells per row

.square-grid__cell--10 {
  flex-basis: 10%;
}

.square-grid__cell--9 {
  flex-basis: 11.1111111%;
}

.square-grid__cell--8 {
  flex-basis: 12.5%;
}

.square-grid__cell--7 {
  flex-basis: 14.2857143%;
}

.square-grid__cell--6 {
  flex-basis: 16.6666667%;
}

.square-grid__cell--5 {
  flex-basis: 20%;
}

.square-grid__cell--4 {
  flex-basis: 25%;
}

.square-grid__cell--3 {
  flex-basis: 33.333%;
}

.square-grid__cell--2 {
  flex-basis: 50%;
}

.square-grid__cell--1 {
  flex-basis: 100%;
}

_x000D_
_x000D_
.square-grid {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap;_x000D_
  justify-content: center;_x000D_
}_x000D_
_x000D_
.square-grid__cell {_x000D_
  background-color: rgba(0, 0, 0, 0.03);_x000D_
  box-shadow: 0 0 0 1px black;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.square-grid__content {_x000D_
  left: 0;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
.square-grid__cell:after {_x000D_
  content: '';_x000D_
  display: block;_x000D_
  padding-bottom: 100%;_x000D_
}_x000D_
_x000D_
// Sizes – Number of cells per row_x000D_
_x000D_
.square-grid__cell--10 {_x000D_
  flex-basis: 10%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--9 {_x000D_
  flex-basis: 11.1111111%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--8 {_x000D_
  flex-basis: 12.5%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--7 {_x000D_
  flex-basis: 14.2857143%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--6 {_x000D_
  flex-basis: 16.6666667%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--5 {_x000D_
  flex-basis: 20%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--4 {_x000D_
  flex-basis: 25%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--3 {_x000D_
  flex-basis: 33.333%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--2 {_x000D_
  flex-basis: 50%;_x000D_
}_x000D_
_x000D_
.square-grid__cell--1 {_x000D_
  flex-basis: 100%;_x000D_
}
_x000D_
<div class='square-grid'>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class='square-grid__cell square-grid__cell--7'>_x000D_
    <div class='square-grid__content'>_x000D_
      Some content_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fiddle: https://jsfiddle.net/patrickberkeley/noLm1r45/3/

This is tested in FF and Chrome.

How to convert unix timestamp to calendar date moment.js

Using moment.js as you asked, there is a unix method that accepts unix timestamps in seconds:

var dateString = moment.unix(value).format("MM/DD/YYYY");

sql like operator to get the numbers only

Try something like this - it works for the cases you have mentioned.

select * from tbl
where answer like '%[0-9]%'
and answer not like '%[:]%'
and answer not like '%[A-Z]%'

How to get IntPtr from byte[] in C#

This should work but must be used within an unsafe context:

byte[] buffer = new byte[255];
fixed (byte* p = buffer)
{
    IntPtr ptr = (IntPtr)p;
    // do you stuff here
}

beware, you have to use the pointer in the fixed block! The gc can move the object once you are not anymore in the fixed block.

How to load an external webpage into a div of a html page

Using simple html,

 <div> 
    <object type="text/html" data="http://validator.w3.org/" width="800px" height="600px" style="overflow:auto;border:5px ridge blue">
    </object>
 </div>

Or jquery,

<script>
        $("#mydiv")
            .html('<object data="http://your-website-domain"/>');
</script>

JSFIDDLE DEMO

How to read .pem file to get private and public key

To get the public key you can simply do:

public static PublicKey getPublicKeyFromCertFile(final String certfile){

     return new X509CertImpl(new FileInputStream(new File(certfile))).getPublicKey();

To get the private key is trickier, you can:

public static PrivateKey getPrivateKeyFromKeyFile(final String keyfile){
    try {
        Process p;
        p = Runtime.getRuntime().exec("openssl pkcs8 -nocrypt -topk8 -inform PEM " +
                "-in " + keyfile + " -outform DER -out " + keyfile + ".der");

        p.waitFor();
        System.out.println("Command executed" + (p.exitValue() == 0 ? " successfully" : " with error" ));
    } catch ( IOException | InterruptedException e) {
        e.printStackTrace();
        System.exit(1);
    }

    PrivateKey myPrivKey = null;
    try {
        byte[] keyArray = Files.readAllBytes(Paths.get(keyfile + ".der"));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyArray);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        myPrivKey = keyFactory.generatePrivate(keySpec);
    } catch (IOException | NoSuchAlgorithmException | InvalidKeySpecException e){
        e.printStackTrace();
        System.exit(1);
    }

    return myPrivKey;
}

What's the point of the X-Requested-With header?

A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.

Only the following headers are allowed cross domain:

  • Accept
  • Accept-Language
  • Content-Language
  • Last-Event-ID
  • Content-Type

any others cause a "pre-flight" request to be issued in CORS supported browsers.

Without CORS it is not possible to add X-Requested-With to a cross domain XHR request.

If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin header could be an option in supported browsers, although you will leave old browsers vulnerable.)

New Flash bypass discovered

You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.

OWASP Recommend combining this with an Origin and Referer check:

This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)

However, for the reasons already discussed checking Origin can be tricky.

Update

Written a more in depth blog post on CORS, CSRF and X-Requested-With here.

Android fade in and fade out with ImageView

I used used fadeIn animation to replace new image for old one

ObjectAnimator.ofFloat(imageView, View.ALPHA, 0.2f, 1.0f).setDuration(1000).start();

Center a position:fixed element

Just add:

left: calc(-50vw + 50%);
right: calc(-50vw + 50%);
margin-left: auto;
margin-right: auto;

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

How to merge a specific commit in Git

If you have committed changes to master branch. Now you want to move that same commit to release-branch. Check the commit id(Eg:xyzabc123) for the commit.

Now try following commands

git checkout release-branch
git cherry-pick xyzabc123
git push origin release-branch

Setting java locale settings

On linux, create file in /etc/default/locale with the following contents

LANG=en.utf8

and then use the source command to export this variable by running

source /etc/default/locale

The source command sets the variable permanently.

All inclusive Charset to avoid "java.nio.charset.MalformedInputException: Input length = 1"?

You probably want to have a list of supported encodings. For each file, try each encoding in turn, maybe starting with UTF-8. Every time you catch the MalformedInputException, try the next encoding.

How can I set the request header for curl?

Just use the -H parameter several times:

curl -H "Accept-Charset: utf-8" -H "Content-Type: application/x-www-form-urlencoded" http://www.some-domain.com

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

I got this same error when installing to an actual device. More information and a solution to loading the missing libraries to the device can be found at the following site:

Fixing the INSTALL_FAILED_MISSING_SHARED_LIBRARY Error

To set this up correctly, there are 2 key files that need to be copied to the system:

com.google.android.maps.xml

com.google.android.maps.jar

These files are located in the any of these google app packs:

http://android.d3xt3...0120-signed.zip

http://goo-inside.me...0120-signed.zip

http://android.local...0120-signed.zip

These links no longer work, but you can find the files in the android sdk if you have Google Maps API v1

After unzipping any of these files, you want to copy the files to your system, like-ah-so:

adb remount

adb push system/etc/permissions/com.google.android.maps.xml /system/etc/permissions

adb push system/framework/com.google.android.maps.jar /system/framework

adb reboot

"Could not find acceptable representation" using spring-boot-starter-web

For me, the problem was trying to pass a filename in a url, with a dot. For example

"http://localhost:8080/something/asdf.jpg" //causes error because of '.jpg'

It could be solved by not passing the .jpg extension, or sending it all in a request body.

Error: "setFile(null,false) call failed" when using log4j

Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'

It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.

Jersey client: How to add a list as query parameter

One could use the queryParam method, passing it parameter name and an array of values:

    public WebTarget queryParam(String name, Object... values);

Example (jersey-client 2.23.2):

    WebTarget target = ClientBuilder.newClient().target(URI.create("http://localhost"));
    target.path("path")
            .queryParam("param_name", Arrays.asList("paramVal1", "paramVal2").toArray())
            .request().get();

This will issue request to following URL:

    http://localhost/path?param_name=paramVal1&param_name=paramVal2

add image to uitableview cell

cell.imageView.image = [UIImage imageNamed:@"image.png"];

UPDATE: Like Steven Fisher said, this should only work for cells with style UITableViewCellStyleDefault which is the default style. For other styles, you'd need to add a UIImageView to the cell's contentView.

SVN check out linux

There should be svn utility on you box, if installed:

$ svn checkout http://example.com/svn/somerepo somerepo

This will check out a working copy from a specified repository to a directory somerepo on our file system.

You may want to print commands, supported by this utility:

$ svn help

uname -a output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm or the following command:

$ sudo yum install subversion

Exact time measurement for performance testing

Stopwatch is fine, but loop the work 10^6 times, then divide by 10^6. You'll get a lot more precision.

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

What we didn't do right was to not apply with the accurate code when signing in the Build Settings. We fixed the issue up this way: Enter into Build Settings >> Code Signing >> Code Sign Identity. Then, apply with your iOS Developer ID for 'Debug', but be sure to apply with your iOS Distribution Profile for 'Release' We didn't apply correctly, so we couldn't have permission to ask for the App from the server, actually. Anyway this post forced us to revise all the parameters and requirements, so we pretty appreciate all your answers. Regards, T.

JPA: how do I persist a String into a database field, type MYSQL Text

for mysql 'text':

@Column(columnDefinition = "TEXT")
private String description;

for mysql 'longtext':

@Lob
private String description;

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

Negative weights using Dijkstra's Algorithm

you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.

this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]

in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.

How to make the corners of a button round?

drawable folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="#FFFFFF"/>
    <corners android:radius="30dp"/>
    <stroke android:width="2dp" android:color="#999999"/>
</shape>

layout folder

<Button
    android:id="@+id/button2"
    <!-- add style to avoid square background -->
    style="@style/Widget.AppCompat.Button.Borderless"
    android:background="@drawable/corner_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    />

make sure add style to avoid square background

Simplest way to display current month and year like "Aug 2016" in PHP?

Full version:

<? echo date('F Y'); ?>

Short version:

<? echo date('M Y'); ?>

Here is a good reference for the different date options.

update

To show the previous month we would have to introduce the mktime() function and make use of the optional timestamp parameter for the date() function. Like this:

echo date('F Y', mktime(0, 0, 0, date('m')-1, 1, date('Y')));

This will also work (it's typically used to get the last day of the previous month):

echo date('F Y', mktime(0, 0, 0, date('m'), 0, date('Y')));

Hope that helps.

How to modify values of JsonObject / JsonArray directly?

Since 2.3 version of Gson library the JsonArray class have a 'set' method.

Here's an simple example:

JsonArray array = new JsonArray();
array.add(new JsonPrimitive("Red"));
array.add(new JsonPrimitive("Green"));
array.add(new JsonPrimitive("Blue"));

array.remove(2);
array.set(0, new JsonPrimitive("Yelow"));

Install Application programmatically on Android

Try this - Write on Manifest:

uses-permission android:name="android.permission.INSTALL_PACKAGES"
        tools:ignore="ProtectedPermissions"

Write the Code:

File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
                        "application/vnd.android.package-archive");

startActivity(promptInstall);

Differences between MySQL and SQL Server

Frankly, I can't find a single reason to use MySQL rather than MSSQL. The issue before used to be cost but SQL Server 2005 Express is free and there are lots of web hosting companies which offer full hosting with sql server for less than $5.00 a month.

MSSQL is easier to use and has many features which do not exist in MySQL.

Assigning the return value of new by reference is deprecated

& is used in PHP to pass an object to a method / assign a new object to a variable by reference. It is deprecated in PHP 5 because PHP 5 passes all objects by reference by default.

Can I send a ctrl-C (SIGINT) to an application on Windows?

SIGINT can be send to program using windows-kill, by syntax windows-kill -SIGINT PID, where PID can be obtained by Microsoft's pslist.

Regarding catching SIGINTs, if your program is in Python then you can implement SIGINT processing/catching like in this solution.

What is the difference between jQuery: text() and html() ?

.text() will give you the actual text in between HTML tags. For example, the paragraph text in between p tags. What is interesting to note is that it will give you all the text in the element you are targeting with with your $ selector plus all the text in the children elements of that selected element. So If you have multiple p tags with text inside the body element and you do a $(body).text(), you will get all the text from all the paragraphs. (Text only, not the p tags themselves.)

.html() will give you the text and the tags. So $(body).html() will basically give you your entire page HTML page

.val() works for elements that have a value attribute, such as input. An input does not have contained text or HTML and thus .text() and .html() will both be null for input elements.

If condition inside of map() React

You're mixing if statement with a ternary expression, that's why you're having a syntax error. It might be easier for you to understand what's going on if you extract mapping function outside of your render method:

renderItem = (id) => {
    // just standard if statement
    if (this.props.schema.collectionName.length < 0) {
        return (
            <Expandable>
                <ObjectDisplay
                    key={id}
                    parentDocumentId={id}
                    schema={schema[this.props.schema.collectionName]}
                    value={this.props.collection.documents[id]}
                />
            </Expandable>
        );
    }
    return (
        <h1>hejsan</h1>
    );
}

Then just call it when mapping:

render() {
    return (
        <div>
            <div className="box">
                { 
                    this.props.collection.ids
                        .filter(
                            id =>
                            // note: this is only passed when in top level of document
                            this.props.collection.documents[id][
                                this.props.schema.foreignKey
                            ] === this.props.parentDocumentId
                        )
                        .map(this.renderItem)
                }
            </div>
        </div>
    )
}

Of course, you could have used the ternary expression as well, it's a matter of preference. What you use, however, affects the readability, so make sure to check different ways and tips to properly do conditional rendering in react and react native.

Check whether an array is empty

I can't replicate that (php 5.3.6):

php > $error = array();
php > $error['something'] = false;
php > $error['somethingelse'] = false;
php > var_dump(empty($error));
bool(false)

php > $error = array();
php > var_dump(empty($error));
bool(true)
php >

exactly where are you doing the empty() call that returns true?

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

Is true == 1 and false == 0 in JavaScript?

Use === to equate the variables instead of ==.

== checks if the value of the variables is similar

=== checks if the value of the variables and the type of the variables are similar

Notice how

if(0===false) {
    document.write("oh!!! that's true");
}?

and

if(0==false) {
    document.write("oh!!! that's true");
}?

give different results

How can I get a Dialog style activity window to fill the screen?

I found the solution:

In your activity which has the Theme.Dialog style set, do this:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.your_layout);

    getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}

It's important that you call Window.setLayout() after you call setContentView(), otherwise it won't work.

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

Usage of MySQL's "IF EXISTS"

You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.

Turn the EXISTS clause into a subquery instead within an IF function

SELECT IF( EXISTS(
             SELECT *
             FROM gdata_calendars
             WHERE `group` =  ? AND id = ?), 1, 0)

In fact, booleans are returned as 1 or 0

SELECT EXISTS(
         SELECT *
         FROM gdata_calendars
         WHERE `group` =  ? AND id = ?)

How can I reduce the waiting (ttfb) time

If you are using PHP, try using <?php flush(); ?> after </head> and before </body> or whatever section you want to output quickly (like the header or content). It will output the actually code without waiting for php to end. Don't use this function all the time, or the speed increase won't be noticable.

More info

MySQL LIMIT on DELETE statement

simply use

DELETE FROM test WHERE 1= 1 LIMIT 10 

How can I pass parameters to a partial view in mvc 4

One of The Shortest method i found for single value while i was searching for myself, is just passing single string and setting string as model in view like this.

In your Partial calling side

@Html.Partial("ParitalAction", "String data to pass to partial")

And then binding the model with Partial View like this

@model string

and the using its value in Partial View like this

@Model

You can also play with other datatypes like array, int or more complex data types like IDictionary or something else.

Hope it helps,

How to make the Facebook Like Box responsive?

None of the css trick worked for me (in my case the fb-like box was pulled right with "float:right"). However, what worked without any additional tricks is an IFRAME version of the button code. I.e.:

<iframe src="//www.facebook.com/plugins/like.php?href=..." 
        scrolling="no" frameborder="0" 
        style="border:none; overflow:hidden; width:71px; height:21px;" 
        allowTransparency="true">
</iframe>

(Note custom width in style, and no need to include additional javascript.)

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Peters' python 2 workaround fails on an edge case:

d = {u'keyword': u'bad credit  \xe7redit cards'}
with io.open('filename', 'w', encoding='utf8') as json_file:
    data = json.dumps(d, ensure_ascii=False).decode('utf8')
    try:
        json_file.write(data)
    except TypeError:
        # Decode data to Unicode first
        json_file.write(data.decode('utf8'))

UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 25: ordinal not in range(128)

It was crashing on the .decode('utf8') part of line 3. I fixed the problem by making the program much simpler by avoiding that step as well as the special casing of ascii:

with io.open('filename', 'w', encoding='utf8') as json_file:
  data = json.dumps(d, ensure_ascii=False, encoding='utf8')
  json_file.write(unicode(data))

cat filename
{"keyword": "bad credit  çredit cards"}

Python Accessing Nested JSON Data

In your code j is Already json data and j['places'] is list not dict.

 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = r.json()

 print j['state']
 for each in j['places']:
    print each['latitude']

Directly export a query to CSV using SQL Developer

You can use the spool command (SQL*Plus documentation, but one of many such commands SQL Developer also supports) to write results straight to disk. Each spool can change the file that's being written to, so you can have several queries writing to different files just by putting spool commands between them:

spool "\path\to\spool1.txt"

select /*csv*/ * from employees;

spool "\path\to\spool2.txt"

select /*csv*/ * from locations;

spool off;

You'd need to run this as a script (F5, or the second button on the command bar above the SQL Worksheet). You might also want to explore some of the formatting options and the set command, though some of those do not translate to SQL Developer.

Since you mentioned CSV in the title I've included a SQL Developer-specific hint that does that formatting for you.

A downside though is that SQL Developer includes the query in the spool file, which you can avoid by having the commands and queries in a script file that you then run as a script.

Mock functions in Go

I would do something like,

Main

var getPage = get_page
func get_page (...

func downloader() {
    dl_slots = make(chan bool, DL_SLOT_AMOUNT) // Init the download slot semaphore
    content := getPage(BASE_URL)
    links_regexp := regexp.MustCompile(LIST_LINK_REGEXP)
    matches := links_regexp.FindAllStringSubmatch(content, -1)
    for _, match := range matches{
        go serie_dl(match[1], match[2])
    }
}

Test

func TestDownloader (t *testing.T) {
    origGetPage := getPage
    getPage = mock_get_page
    defer func() {getPage = origGatePage}()
    // The rest to be written
}

// define mock_get_page and rest of the codes
func mock_get_page (....

And I would avoid _ in golang. Better use camelCase

Insert a line break in mailto body

As per RFC2368 which defines mailto:, further reinforced by an example in RFC1738, it is explicitly stated that the only valid way to generate a line break is with %0D%0A.

This also applies to all url schemes such as gopher, smtp, sdp, imap, ldap, etc..

How do you select the entire excel sheet with Range using VBA?

Maybe this might work:

Sh.Range("A1", Sh.Range("A" & Rows.Count).End(xlUp))

REST API error code 500 handling

It is a server error, not a client error. If server errors weren't to be returned to the client, there wouldn't have been created an entire status code class for them (i.e. 5xx).

You can't hide the fact that you either made a programming error or some service you rely on is unavailable, and that certainly isn't the client's fault. Returning any other range of code in those cases than the 5xx series would make no sense.

RFC 7231 mentions in section 6.6. Server Error 5xx:

The 5xx (Server Error) class of status code indicates that the server is aware that it has erred or is incapable of performing the requested method.

This is exactly the case. There's nothing "internal" about the code "500 Internal Server Error" in the sense that it shouldn't be exposed to the client.

How to edit default dark theme for Visual Studio Code?

As far as the themes, VS Code is every bit as editable as Sublime. You can edit any of the default themes that come with VS code. You just have to know where to find the theme files.

Side note: I love the Monokai theme. However, all I wanted to change about it was the background. I don't like the dark grayish background. Instead, I think the contrast is WAY better with a solid black background. The code pops out much more.

Anyways, I hunted for the theme file and found it (in windows) at:

c:\Program Files (x86)\Microsoft VS Code\resources\app\extensions\theme-monokai\themes\

In that folder I found the Monokai.tmTheme file and modified the first background key as follows:

<key>background</key>
<string>#000000</string>

There are a few 'background' key in the theme file, make sure you edit the correct one. The one I edited was at the very top. Line 12 I think.

How to play .wav files with java

The snippet here works fine, tested with windows sound:

public static void main(String[] args) {
        AePlayWave aw = new AePlayWave( "C:\\WINDOWS\\Media\\tada.wav" );
        aw.start();     
}

What is the opposite of :hover (on mouse leave)?

The opposite of :hover appears to be :link.

(edit: not technically an opposite because there are 4 selectors :link, :visited, :hover and :active. Five if you include :focus.)

For example when defining a rule .button:hover{ text-decoration:none } to remove the underline on a button, the underline shows up when you roll off the button in some browsers. I've fixed this with .button:hover, .button:link{ text-decoration:none }

This of course only works for elements that are actually links (have href attribute)

List of Timezone IDs for use with FindTimeZoneById() in C#?

And if you'd like a HTML select with the Windows time zones in:

<select>
<option value="Morocco Standard Time">(GMT) Casablanca</option>
<option value="GMT Standard Time">(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London</option>
<option value="Greenwich Standard Time">(GMT) Monrovia, Reykjavik</option>
<option value="W. Europe Standard Time">(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna</option>
<option value="Central Europe Standard Time">(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague</option>
<option value="Romance Standard Time">(GMT+01:00) Brussels, Copenhagen, Madrid, Paris</option>
<option value="Central European Standard Time">(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb</option>
<option value="W. Central Africa Standard Time">(GMT+01:00) West Central Africa</option>
<option value="Jordan Standard Time">(GMT+02:00) Amman</option>
<option value="GTB Standard Time">(GMT+02:00) Athens, Bucharest, Istanbul</option>
<option value="Middle East Standard Time">(GMT+02:00) Beirut</option>
<option value="Egypt Standard Time">(GMT+02:00) Cairo</option>
<option value="South Africa Standard Time">(GMT+02:00) Harare, Pretoria</option>
<option value="FLE Standard Time">(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius</option>
<option value="Israel Standard Time">(GMT+02:00) Jerusalem</option>
<option value="E. Europe Standard Time">(GMT+02:00) Minsk</option>
<option value="Namibia Standard Time">(GMT+02:00) Windhoek</option>
<option value="Arabic Standard Time">(GMT+03:00) Baghdad</option>
<option value="Arab Standard Time">(GMT+03:00) Kuwait, Riyadh</option>
<option value="Russian Standard Time">(GMT+03:00) Moscow, St. Petersburg, Volgograd</option>
<option value="E. Africa Standard Time">(GMT+03:00) Nairobi</option>
<option value="Georgian Standard Time">(GMT+03:00) Tbilisi</option>
<option value="Iran Standard Time">(GMT+03:30) Tehran</option>
<option value="Arabian Standard Time">(GMT+04:00) Abu Dhabi, Muscat</option>
<option value="Azerbaijan Standard Time">(GMT+04:00) Baku</option>
<option value="Mauritius Standard Time">(GMT+04:00) Port Louis</option>
<option value="Caucasus Standard Time">(GMT+04:00) Yerevan</option>
<option value="Afghanistan Standard Time">(GMT+04:30) Kabul</option>
<option value="Ekaterinburg Standard Time">(GMT+05:00) Ekaterinburg</option>
<option value="Pakistan Standard Time">(GMT+05:00) Islamabad, Karachi</option>
<option value="West Asia Standard Time">(GMT+05:00) Tashkent</option>
<option value="India Standard Time">(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi</option>
<option value="Sri Lanka Standard Time">(GMT+05:30) Sri Jayawardenepura</option>
<option value="Nepal Standard Time">(GMT+05:45) Kathmandu</option>
<option value="N. Central Asia Standard Time">(GMT+06:00) Almaty, Novosibirsk</option>
<option value="Central Asia Standard Time">(GMT+06:00) Astana, Dhaka</option>
<option value="Myanmar Standard Time">(GMT+06:30) Yangon (Rangoon)</option>
<option value="SE Asia Standard Time">(GMT+07:00) Bangkok, Hanoi, Jakarta</option>
<option value="North Asia Standard Time">(GMT+07:00) Krasnoyarsk</option>
<option value="China Standard Time">(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi</option>
<option value="North Asia East Standard Time">(GMT+08:00) Irkutsk, Ulaan Bataar</option>
<option value="Singapore Standard Time">(GMT+08:00) Kuala Lumpur, Singapore</option>
<option value="W. Australia Standard Time">(GMT+08:00) Perth</option>
<option value="Taipei Standard Time">(GMT+08:00) Taipei</option>
<option value="Tokyo Standard Time">(GMT+09:00) Osaka, Sapporo, Tokyo</option>
<option value="Korea Standard Time">(GMT+09:00) Seoul</option>
<option value="Yakutsk Standard Time">(GMT+09:00) Yakutsk</option>
<option value="Cen. Australia Standard Time">(GMT+09:30) Adelaide</option>
<option value="AUS Central Standard Time">(GMT+09:30) Darwin</option>
<option value="E. Australia Standard Time">(GMT+10:00) Brisbane</option>
<option value="AUS Eastern Standard Time">(GMT+10:00) Canberra, Melbourne, Sydney</option>
<option value="West Pacific Standard Time">(GMT+10:00) Guam, Port Moresby</option>
<option value="Tasmania Standard Time">(GMT+10:00) Hobart</option>
<option value="Vladivostok Standard Time">(GMT+10:00) Vladivostok</option>
<option value="Central Pacific Standard Time">(GMT+11:00) Magadan, Solomon Is., New Caledonia</option>
<option value="New Zealand Standard Time">(GMT+12:00) Auckland, Wellington</option>
<option value="Fiji Standard Time">(GMT+12:00) Fiji, Kamchatka, Marshall Is.</option>
<option value="Tonga Standard Time">(GMT+13:00) Nuku'alofa</option>
<option value="Azores Standard Time">(GMT-01:00) Azores</option>
<option value="Cape Verde Standard Time">(GMT-01:00) Cape Verde Is.</option>
<option value="Mid-Atlantic Standard Time">(GMT-02:00) Mid-Atlantic</option>
<option value="E. South America Standard Time">(GMT-03:00) Brasilia</option>
<option value="Argentina Standard Time">(GMT-03:00) Buenos Aires</option>
<option value="SA Eastern Standard Time">(GMT-03:00) Georgetown</option>
<option value="Greenland Standard Time">(GMT-03:00) Greenland</option>
<option value="Montevideo Standard Time">(GMT-03:00) Montevideo</option>
<option value="Newfoundland Standard Time">(GMT-03:30) Newfoundland</option>
<option value="Atlantic Standard Time">(GMT-04:00) Atlantic Time (Canada)</option>
<option value="SA Western Standard Time">(GMT-04:00) La Paz</option>
<option value="Central Brazilian Standard Time">(GMT-04:00) Manaus</option>
<option value="Pacific SA Standard Time">(GMT-04:00) Santiago</option>
<option value="Venezuela Standard Time">(GMT-04:30) Caracas</option>
<option value="SA Pacific Standard Time">(GMT-05:00) Bogota, Lima, Quito, Rio Branco</option>
<option value="Eastern Standard Time">(GMT-05:00) Eastern Time (US & Canada)</option>
<option value="US Eastern Standard Time">(GMT-05:00) Indiana (East)</option>
<option value="Central America Standard Time">(GMT-06:00) Central America</option>
<option value="Central Standard Time">(GMT-06:00) Central Time (US & Canada)</option>
<option value="Central Standard Time (Mexico)">(GMT-06:00) Guadalajara, Mexico City, Monterrey</option>
<option value="Canada Central Standard Time">(GMT-06:00) Saskatchewan</option>
<option value="US Mountain Standard Time">(GMT-07:00) Arizona</option>
<option value="Mountain Standard Time (Mexico)">(GMT-07:00) Chihuahua, La Paz, Mazatlan</option>
<option value="Mountain Standard Time">(GMT-07:00) Mountain Time (US & Canada)</option>
<option value="Pacific Standard Time">(GMT-08:00) Pacific Time (US & Canada)</option>
<option value="Pacific Standard Time (Mexico)">(GMT-08:00) Tijuana, Baja California</option>
<option value="Alaskan Standard Time">(GMT-09:00) Alaska</option>
<option value="Hawaiian Standard Time">(GMT-10:00) Hawaii</option>
<option value="Samoa Standard Time">(GMT-11:00) Midway Island, Samoa</option>
<option value="Dateline Standard Time">(GMT-12:00) International Date Line West</option>
</select>

And if you'd like to use it in C#.NET MVC in a Razor view:

var timezones = new List<SelectListItem> { 
new SelectListItem() { Value="", Text="Select timezone...", Selected = false },
new SelectListItem() { Value="Morocco Standard Time", Text="(GMT) Casablanca", Selected = false },
new SelectListItem() { Value="GMT Standard Time", Text="(GMT) Greenwich Mean Time : Dublin, Edinburgh, Lisbon, London", Selected = false },
new SelectListItem() { Value="Greenwich Standard Time", Text="(GMT) Monrovia, Reykjavik", Selected = false },
new SelectListItem() { Value="W. Europe Standard Time", Text="(GMT+01:00) Amsterdam, Berlin, Bern, Rome, Stockholm, Vienna", Selected = false },
new SelectListItem() { Value="Central Europe Standard Time", Text="(GMT+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague", Selected = false },
new SelectListItem() { Value="Romance Standard Time", Text="(GMT+01:00) Brussels, Copenhagen, Madrid, Paris", Selected = false },
new SelectListItem() { Value="Central European Standard Time", Text="(GMT+01:00) Sarajevo, Skopje, Warsaw, Zagreb", Selected = false },
new SelectListItem() { Value="W. Central Africa Standard Time", Text="(GMT+01:00) West Central Africa", Selected = false },
new SelectListItem() { Value="Jordan Standard Time", Text="(GMT+02:00) Amman", Selected = false },
new SelectListItem() { Value="GTB Standard Time", Text="(GMT+02:00) Athens, Bucharest, Istanbul", Selected = false },
new SelectListItem() { Value="Middle East Standard Time", Text="(GMT+02:00) Beirut", Selected = false },
new SelectListItem() { Value="Egypt Standard Time", Text="(GMT+02:00) Cairo", Selected = false },
new SelectListItem() { Value="South Africa Standard Time", Text="(GMT+02:00) Harare, Pretoria", Selected = false },
new SelectListItem() { Value="FLE Standard Time", Text="(GMT+02:00) Helsinki, Kyiv, Riga, Sofia, Tallinn, Vilnius", Selected = false },
new SelectListItem() { Value="Israel Standard Time", Text="(GMT+02:00) Jerusalem", Selected = false },
new SelectListItem() { Value="E. Europe Standard Time", Text="(GMT+02:00) Minsk", Selected = false },
new SelectListItem() { Value="Namibia Standard Time", Text="(GMT+02:00) Windhoek", Selected = false },
new SelectListItem() { Value="Arabic Standard Time", Text="(GMT+03:00) Baghdad", Selected = false },
new SelectListItem() { Value="Arab Standard Time", Text="(GMT+03:00) Kuwait, Riyadh", Selected = false },
new SelectListItem() { Value="Russian Standard Time", Text="(GMT+03:00) Moscow, St. Petersburg, Volgograd", Selected = false },
new SelectListItem() { Value="E. Africa Standard Time", Text="(GMT+03:00) Nairobi", Selected = false },
new SelectListItem() { Value="Georgian Standard Time", Text="(GMT+03:00) Tbilisi", Selected = false },
new SelectListItem() { Value="Iran Standard Time", Text="(GMT+03:30) Tehran", Selected = false },
new SelectListItem() { Value="Arabian Standard Time", Text="(GMT+04:00) Abu Dhabi, Muscat", Selected = false },
new SelectListItem() { Value="Azerbaijan Standard Time", Text="(GMT+04:00) Baku", Selected = false },
new SelectListItem() { Value="Mauritius Standard Time", Text="(GMT+04:00) Port Louis", Selected = false },
new SelectListItem() { Value="Caucasus Standard Time", Text="(GMT+04:00) Yerevan", Selected = false },
new SelectListItem() { Value="Afghanistan Standard Time", Text="(GMT+04:30) Kabul", Selected = false },
new SelectListItem() { Value="Ekaterinburg Standard Time", Text="(GMT+05:00) Ekaterinburg", Selected = false },
new SelectListItem() { Value="Pakistan Standard Time", Text="(GMT+05:00) Islamabad, Karachi", Selected = false },
new SelectListItem() { Value="West Asia Standard Time", Text="(GMT+05:00) Tashkent", Selected = false },
new SelectListItem() { Value="India Standard Time", Text="(GMT+05:30) Chennai, Kolkata, Mumbai, New Delhi", Selected = false },
new SelectListItem() { Value="Sri Lanka Standard Time", Text="(GMT+05:30) Sri Jayawardenepura", Selected = false },
new SelectListItem() { Value="Nepal Standard Time", Text="(GMT+05:45) Kathmandu", Selected = false },
new SelectListItem() { Value="N. Central Asia Standard Time", Text="(GMT+06:00) Almaty, Novosibirsk", Selected = false },
new SelectListItem() { Value="Central Asia Standard Time", Text="(GMT+06:00) Astana, Dhaka", Selected = false },
new SelectListItem() { Value="Myanmar Standard Time", Text="(GMT+06:30) Yangon (Rangoon)", Selected = false },
new SelectListItem() { Value="SE Asia Standard Time", Text="(GMT+07:00) Bangkok, Hanoi, Jakarta", Selected = false },
new SelectListItem() { Value="North Asia Standard Time", Text="(GMT+07:00) Krasnoyarsk", Selected = false },
new SelectListItem() { Value="China Standard Time", Text="(GMT+08:00) Beijing, Chongqing, Hong Kong, Urumqi", Selected = false },
new SelectListItem() { Value="North Asia East Standard Time", Text="(GMT+08:00) Irkutsk, Ulaan Bataar", Selected = false },
new SelectListItem() { Value="Singapore Standard Time", Text="(GMT+08:00) Kuala Lumpur, Singapore", Selected = false },
new SelectListItem() { Value="W. Australia Standard Time", Text="(GMT+08:00) Perth", Selected = false },
new SelectListItem() { Value="Taipei Standard Time", Text="(GMT+08:00) Taipei", Selected = false },
new SelectListItem() { Value="Tokyo Standard Time", Text="(GMT+09:00) Osaka, Sapporo, Tokyo", Selected = false },
new SelectListItem() { Value="Korea Standard Time", Text="(GMT+09:00) Seoul", Selected = false },
new SelectListItem() { Value="Yakutsk Standard Time", Text="(GMT+09:00) Yakutsk", Selected = false },
new SelectListItem() { Value="Cen. Australia Standard Time", Text="(GMT+09:30) Adelaide", Selected = false },
new SelectListItem() { Value="AUS Central Standard Time", Text="(GMT+09:30) Darwin", Selected = false },
new SelectListItem() { Value="E. Australia Standard Time", Text="(GMT+10:00) Brisbane", Selected = false },
new SelectListItem() { Value="AUS Eastern Standard Time", Text="(GMT+10:00) Canberra, Melbourne, Sydney", Selected = false },
new SelectListItem() { Value="West Pacific Standard Time", Text="(GMT+10:00) Guam, Port Moresby", Selected = false },
new SelectListItem() { Value="Tasmania Standard Time", Text="(GMT+10:00) Hobart", Selected = false },
new SelectListItem() { Value="Vladivostok Standard Time", Text="(GMT+10:00) Vladivostok", Selected = false },
new SelectListItem() { Value="Central Pacific Standard Time", Text="(GMT+11:00) Magadan, Solomon Is., New Caledonia", Selected = false },
new SelectListItem() { Value="New Zealand Standard Time", Text="(GMT+12:00) Auckland, Wellington", Selected = false },
new SelectListItem() { Value="Fiji Standard Time", Text="(GMT+12:00) Fiji, Kamchatka, Marshall Is.", Selected = false },
new SelectListItem() { Value="Tonga Standard Time", Text="(GMT+13:00) Nuku'alofa", Selected = false },
new SelectListItem() { Value="Azores Standard Time", Text="(GMT-01:00) Azores", Selected = false },
new SelectListItem() { Value="Cape Verde Standard Time", Text="(GMT-01:00) Cape Verde Is.", Selected = false },
new SelectListItem() { Value="Mid-Atlantic Standard Time", Text="(GMT-02:00) Mid-Atlantic", Selected = false },
new SelectListItem() { Value="E. South America Standard Time", Text="(GMT-03:00) Brasilia", Selected = false },
new SelectListItem() { Value="Argentina Standard Time", Text="(GMT-03:00) Buenos Aires", Selected = false },
new SelectListItem() { Value="SA Eastern Standard Time", Text="(GMT-03:00) Georgetown", Selected = false },
new SelectListItem() { Value="Greenland Standard Time", Text="(GMT-03:00) Greenland", Selected = false },
new SelectListItem() { Value="Montevideo Standard Time", Text="(GMT-03:00) Montevideo", Selected = false },
new SelectListItem() { Value="Newfoundland Standard Time", Text="(GMT-03:30) Newfoundland", Selected = false },
new SelectListItem() { Value="Atlantic Standard Time", Text="(GMT-04:00) Atlantic Time (Canada)", Selected = false },
new SelectListItem() { Value="SA Western Standard Time", Text="(GMT-04:00) La Paz", Selected = false },
new SelectListItem() { Value="Central Brazilian Standard Time", Text="(GMT-04:00) Manaus", Selected = false },
new SelectListItem() { Value="Pacific SA Standard Time", Text="(GMT-04:00) Santiago", Selected = false },
new SelectListItem() { Value="Venezuela Standard Time", Text="(GMT-04:30) Caracas", Selected = false },
new SelectListItem() { Value="SA Pacific Standard Time", Text="(GMT-05:00) Bogota, Lima, Quito, Rio Branco", Selected = false },
new SelectListItem() { Value="Eastern Standard Time", Text="(GMT-05:00) Eastern Time (US & Canada)", Selected = false },
new SelectListItem() { Value="US Eastern Standard Time", Text="(GMT-05:00) Indiana (East)", Selected = false },
new SelectListItem() { Value="Central America Standard Time", Text="(GMT-06:00) Central America", Selected = false },
new SelectListItem() { Value="Central Standard Time", Text="(GMT-06:00) Central Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Central Standard Time (Mexico)", Text="(GMT-06:00) Guadalajara, Mexico City, Monterrey", Selected = false },
new SelectListItem() { Value="Canada Central Standard Time", Text="(GMT-06:00) Saskatchewan", Selected = false },
new SelectListItem() { Value="US Mountain Standard Time", Text="(GMT-07:00) Arizona", Selected = false },
new SelectListItem() { Value="Mountain Standard Time (Mexico)", Text="(GMT-07:00) Chihuahua, La Paz, Mazatlan", Selected = false },
new SelectListItem() { Value="Mountain Standard Time", Text="(GMT-07:00) Mountain Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time", Text="(GMT-08:00) Pacific Time (US & Canada)", Selected = false },
new SelectListItem() { Value="Pacific Standard Time (Mexico)", Text="(GMT-08:00) Tijuana, Baja California", Selected = false },
new SelectListItem() { Value="Alaskan Standard Time", Text="(GMT-09:00) Alaska", Selected = false },
new SelectListItem() { Value="Hawaiian Standard Time", Text="(GMT-10:00) Hawaii", Selected = false },
new SelectListItem() { Value="Samoa Standard Time", Text="(GMT-11:00) Midway Island, Samoa", Selected = false },
new SelectListItem() { Value="Dateline Standard Time", Text="(GMT-12:00) International Date Line West", Selected = false }
}

Although for Razor you can of course just generate the options by looping through TimeZoneInfo.GetSystemTimeZones()

How do I add files and folders into GitHub repos?

Simple solution:

git init
git add =A
git commit -m "your commit"
git push -u origin master

if you want add folder to existing repo ..then add folder to local project code

git rm --cached ./folderName
 git add ./folderName

after that

git status
git commit -m "your commit"
git push -u origin master

Looping over arrays, printing both index and value

users=("kamal" "jamal" "rahim" "karim" "sadia")
index=()
t=-1

for i in ${users[@]}; do
  t=$(( t + 1 ))
  if [ $t -eq 0 ]; then
    for j in ${!users[@]}; do
      index[$j]=$j
    done
  fi
  echo "${index[$t]} is $i"
done

How to hide/show div tags using JavaScript?

try yo write document.getElementById('id').style.visibility="hidden";

How to add a tooltip to an svg graphic?

I came up with something using HTML + CSS only. Hope it works for you

_x000D_
_x000D_
.mzhrttltp {
  position: relative;
  display: inline-block;
}
.mzhrttltp .hrttltptxt {
  visibility: hidden;
  width: 120px;
  background-color: #040505;
  font-size:13px;color:#fff;font-family:IranYekanWeb;
  text-align: center;
  border-radius: 3px;
  padding: 4px 0;
  position: absolute;
  z-index: 1;
  top: 105%;
  left: 50%;
  margin-left: -60px;
}

.mzhrttltp .hrttltptxt::after {
  content: "";
  position: absolute;
  bottom: 100%;
  left: 50%;
  margin-left: -5px;
  border-width: 5px;
  border-style: solid;
  border-color: transparent transparent #040505 transparent;
}

.mzhrttltp:hover .hrttltptxt {
  visibility: visible;
}
_x000D_
<div class="mzhrttltp"><svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24" fill="none" stroke="#e2062c" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" class="feather feather-heart"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"></path></svg><div class="hrttltptxt">?????&zwnj;????&zwnj;??</div></div>
_x000D_
_x000D_
_x000D_

Combining node.js and Python

I'd recommend using some work queue using, for example, the excellent Gearman, which will provide you with a great way to dispatch background jobs, and asynchronously get their result once they're processed.

The advantage of this, used heavily at Digg (among many others) is that it provides a strong, scalable and robust way to make workers in any language to speak with clients in any language.

Upgrading PHP in XAMPP for Windows?

You can go through the following link as it helped me, should work for you as well. http://hype-free.blogspot.com/2007/07/updating-php-in-xampp-for-windows.html

Realizing that my answer helped couple of users, here is the edit from original link:

Edit:

First of all Always backup your data.

  1. Download the latest binary version of PHP (make sure to get the .zip package not the installer)
  2. De-archive it to a directory
  3. Overwrite the contents of directory in the php subfolder of your XAMPP installation directory.
  4. Overwrite the contents of the directory apache\bin with the newer versions.
  5. Now the trick: take the files which have a '_2' in their names (for example php5apache2_2.dll or php5apache2_2_filter.dll), copy them in the apache\bin subdirectory and remove the '_2' part, overwriting the existing files. This is necessary because by XAMPP uses Apache version 2.2 and the files with the 2 prefix are built for Apache 2.0, so you must take the files build for the newer version (which has a different plugin interface) and rename them in the filenames XAMPP expects.

NOTE: there are two directories to be updated with new version of files, namely php sub-directory and apache/bin sub-directory, inside XAMPP installation.

Convert Int to String in Swift

I prefer using String Interpolation

let x = 45
let string = "\(x)"

Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

css transform, jagged edges in chrome

Adding a 1px transparent border will trigger anti-aliasing

outline: 1px solid transparent;

Alternatively, add a 1px transparent box-shadow.

box-shadow: 0 0 1px rgba(255,255,255,0);

jQuery Scroll to Div

It is often required to move both body and html objects together.

$('html,body').animate({
   scrollTop: $("#divToBeScrolledTo").offset().top
});

ShiftyThomas is right:

$("#divToBeScrolledTo").offset().top + 10 // +10 (pixels) reduces the margin.

So to increase the margin use:

$("#divToBeScrolledTo").offset().top - 10 // -10 (pixels) would increase the margin between the top of your window and your element.

how to save and read array of array in NSUserdefaults in swift?

Here is:

var array : [String] = ["One", "Two", "Three"]
let userDefault = UserDefaults.standard
// set
userDefault.set(array, forKey: "array")
// retrieve 
if let fetchArray = userDefault.array(forKey: "array") as? [String] {
    // code 
}

When to use window.opener / window.parent / window.top

when you are dealing with popups window.opener plays an important role, because we have to deal with fields of parent page as well as child page, when we have to use values on parent page we can use window.opener or we want some data on the child window or popup window at the time of loading then again we can set the values using window.opener

submitting a form when a checkbox is checked

You can submit form by just clicking on checkbox by simple method in JavaScript. Inside form tag or Input attribute add following attribute:

    onchange="this.form.submit()"

Example:

<form>
      <div>
           <input type="checkbox">
      </div>
</form>

How to install XNA game studio on Visual Studio 2012?

There seems to be some confusion over how to get this set up for the Express version specifically. Using the Windows Desktop (WD) version of VS Express 2012, I followed the instructions in Steve B's and Rick Martin's answers with the modifications below.

  • In step 2 rather than copying to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0", copy to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WDExpressExtensions\Microsoft\XNA Game Studio 4.0"
  • In step 4, after making the changes also add the line <Edition>WDExpress</Edition> (you should be able to see where it makes sense)
  • In step 5, replace devenv.exe with WDExpress.exe
  • In Rick Martin's step, replace "%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions" with "%LocalAppData%\Microsoft\WDExpress\11.0\Extensions"

I haven't done a lot of work since then, but I did manage to create a new game project and it seems fine so far.

Python convert object to float

I eventually used:

weather["Temp"] = weather["Temp"].convert_objects(convert_numeric=True)

It worked just fine, except that I got the following message.

C:\ProgramData\Anaconda3\lib\site-packages\ipykernel_launcher.py:3: FutureWarning:
convert_objects is deprecated.  Use the data-type specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.

How to create jar file with package structure?

You want

$ jar cvf asd.jar .

to specify the directory (e.g. .) to jar from. That will maintain your folder structure within the jar file.

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

what does this mean ? image/png;base64?

That is, you are referencing an image, but instead of providing an external url, the png image data is in the url itself, embedded in the style sheet. data:image/png;base64 tells the browser that the data is inline, is a png image and is in this case base64 encoded. The encoding is needed because png images can contain bytes that are invalid inside a HTML document (or within the HTTP protocol even).

MySQL LIKE IN()?

Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (
'val1',
'val2',
'val3'
)

In REGEXP this won't work

REGEXP '
val1$|
val2$|
val3$
'

It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

Matching special characters and letters in regex

Well, why not just add them to your existing character class?

var pattern = /[a-zA-Z0-9&._-]/

If you need to check whether a string consists of nothing but those characters you have to anchor the expression as well:

var pattern = /^[a-zA-Z0-9&._-]+$/

The added ^ and $ match the beginning and end of the string respectively.

Testing for letters, numbers or underscore can be done with \w which shortens your expression:

var pattern = /^[\w&.-]+$/

As mentioned in the comment from Nathan, if you're not using the results from .match() (it returns an array with what has been matched), it's better to use RegExp.test() which returns a simple boolean:

if (pattern.test(qry)) {
    // qry is non-empty and only contains letters, numbers or special characters.
}

Update 2

In case I have misread the question, the below will check if all three separate conditions are met.

if (/[a-zA-Z]/.test(qry) && /[0-9]/.test(qry) && /[&._-]/.test(qry)) {
   // qry contains at least one letter, one number and one special character
}

How do I use hexadecimal color strings in Flutter?

How to use Hex Color Code #b74093 in Flutter

Simply remove the # sign from hex color code and ad 0xff with color code inside Color class

#b74093 will become Color(0xffb74093) in Flutter

#B74093 will become Color(0xFFB74093) in Flutter

the ff or FF in Color(0xFFB74093) defines the opacity

Hexa Colors Example with all opacity types on Dartpad

enter image description here

iPhone: How to get current milliseconds?

If you're looking at using this for relative timing (for example for games or animation) I'd rather use CACurrentMediaTime()

double CurrentTime = CACurrentMediaTime();

Which is the recommended way; NSDate draws from the networked synch-clock and will occasionally hiccup when re-synching it against the network.

It returns the current absolute time, in seconds.


If you want only the decimal part (often used when syncing animations),

let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)

ASP.NET Web API application gives 404 when deployed at IIS 7

I you are using Visual Studio 2012, download and install Update 2 that Microsoft released recently (as of 4/2013).

Visual Studio 2012 Update 2

There are some bug fixes in that update related to the issue.

SQL: capitalize first letter only

Please check the query without using a function:

declare @T table(Insurance varchar(max))

insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')

select (
       select upper(T.N.value('.', 'char(1)'))+
                lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
       from X.InsXML.nodes('/N') as T(N)
       for xml path(''), type
       ).value('.', 'varchar(max)') as Insurance
from 
  (
  select cast('<N>'+replace(
            replace(
                Insurance, 
                ' ', '</N><N>'),
            '-', '-</N><N>')+'</N>' as xml) as InsXML
  from @T
  ) as X

C - Convert an uppercase letter to lowercase

You messed up the second part of your if condition. That should be a <= 90.

Also, FYI, there is a C library function tolower that does this already:

#include <ctype.h>
#include <stdio.h>

int main() {
    putchar(tolower('A'));
}

Convert XLS to CSV on command line

:: For UTF-8 works for Microsoft Office 2016 and higher!

Try this code:

if WScript.Arguments.Count < 2 Then
    WScript.Echo "Please specify the source and the destination files. Usage: ExcelToCsv <xls/xlsx source file> <csv destination file>"
    Wscript.Quit
End If

csv_format = 62

Set objFSO = CreateObject("Scripting.FileSystemObject")

src_file = objFSO.GetAbsolutePathName(Wscript.Arguments.Item(0))
dest_file = objFSO.GetAbsolutePathName(WScript.Arguments.Item(1))


Dim oExcel
Set oExcel = CreateObject("Excel.Application")

Dim oBook
Set oBook = oExcel.Workbooks.Open(src_file)

oBook.SaveAs dest_file, csv_format

oBook.Close False
oExcel.Quit

iPhone SDK on Windows (alternative solutions)

There is another solution if you want to develop in C/C++. http://www.DragonFireSDK.com will allow you to build iPhone applications in Visual Studio on Windows. It's worth a look-see for sure.

Duplicate keys in .NET dictionaries?

U can define a method to building a Compound string key every where u want to using dictionary u must using this method to build your key for example:

private string keyBuilder(int key1, int key2)
{
    return string.Format("{0}/{1}", key1, key2);
}

for using:

myDict.ContainsKey(keyBuilder(key1, key2))

Setting different color for each series in scatter plot on matplotlib

I don't know what you mean by 'manually'. You can choose a colourmap and make a colour array easily enough:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

x = np.arange(10)
ys = [i+x+(i*x)**2 for i in range(10)]

colors = cm.rainbow(np.linspace(0, 1, len(ys)))
for y, c in zip(ys, colors):
    plt.scatter(x, y, color=c)

Matplotlib graph with different colors

Or you can make your own colour cycler using itertools.cycle and specifying the colours you want to loop over, using next to get the one you want. For example, with 3 colours:

import itertools

colors = itertools.cycle(["r", "b", "g"])
for y in ys:
    plt.scatter(x, y, color=next(colors))

Matplotlib graph with only 3 colors

Come to think of it, maybe it's cleaner not to use zip with the first one neither:

colors = iter(cm.rainbow(np.linspace(0, 1, len(ys))))
for y in ys:
    plt.scatter(x, y, color=next(colors))

img src SVG changing the styles with CSS

Why not just using CSS's filter property to manipulate the color on :hover or whatever other state? I found it works over SVG images into img tags. At least, it's almost fully supported in 2020. It seams to me the simpliest solution. The only caveat is having to tweak the filter properties in order to find the target color. But you have also this very useful tool.

Where does System.Diagnostics.Debug.Write output appear?

You need to add a TraceListener to see them appear on the Console.

TextWriterTraceListener writer = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(writer);

They also appear in the Visual Studio Output window when in Debug mode.

jQuery: more than one handler for same event

You should be able to use chaining to execute the events in sequence, e.g.:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

I guess the below code is doing the same

$('#target')
      .click(function(event) {
        alert('Hello!');
      })
      .click(function(event) {
        alert('Hello again!');
      })
      .click(function(event) {
        alert('Hello yet again!');
      });

Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3

TFM also says:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

How to display multiple images in one figure correctly?

You could try the following:

import matplotlib.pyplot as plt
import numpy as np

def plot_figures(figures, nrows = 1, ncols=1):
    """Plot a dictionary of figures.

    Parameters
    ----------
    figures : <title, figure> dictionary
    ncols : number of columns of subplots wanted in the display
    nrows : number of rows of subplots wanted in the figure
    """

    fig, axeslist = plt.subplots(ncols=ncols, nrows=nrows)
    for ind,title in zip(range(len(figures)), figures):
        axeslist.ravel()[ind].imshow(figures[title], cmap=plt.jet())
        axeslist.ravel()[ind].set_title(title)
        axeslist.ravel()[ind].set_axis_off()
    plt.tight_layout() # optional



# generation of a dictionary of (title, images)
number_of_im = 20
w=10
h=10
figures = {'im'+str(i): np.random.randint(10, size=(h,w)) for i in range(number_of_im)}

# plot of the images in a figure, with 5 rows and 4 columns
plot_figures(figures, 5, 4)

plt.show()

However, this is basically just copy and paste from here: Multiple figures in a single window for which reason this post should be considered to be a duplicate.

I hope this helps.

Rotate label text in seaborn factorplot

I had a problem with the answer by @mwaskorn, namely that

g.set_xticklabels(rotation=30)

fails, because this also requires the labels. A bit easier than the answer by @Aman is to just add

plt.xticks(rotation=45)

How can I stage and commit all files, including newly added files, using a single command?

I have in my config two aliases:

alias.foo=commit -a -m 'none'
alias.coa=commit -a -m

if I am too lazy I just commit all changes with

git foo

and just to do a quick commit

git coa "my changes are..."

coa stands for "commit all"

How do you read CSS rule values with JavaScript?

I've found none of the suggestions to really work. Here's a more robust one that normalizes spacing when finding classes.

//Inside closure so that the inner functions don't need regeneration on every call.
const getCssClasses = (function () {
    function normalize(str) {
        if (!str)  return '';
        str = String(str).replace(/\s*([>~+])\s*/g, ' $1 ');  //Normalize symbol spacing.
        return str.replace(/(\s+)/g, ' ').trim();           //Normalize whitespace
    }
    function split(str, on) {               //Split, Trim, and remove empty elements
        return str.split(on).map(x => x.trim()).filter(x => x);
    }
    function containsAny(selText, ors) {
        return selText ? ors.some(x => selText.indexOf(x) >= 0) : false;
    }
    return function (selector) {
        const logicalORs = split(normalize(selector), ',');
        const sheets = Array.from(window.document.styleSheets);
        const ruleArrays = sheets.map((x) => Array.from(x.rules || x.cssRules || []));
        const allRules = ruleArrays.reduce((all, x) => all.concat(x), []);
        return allRules.filter((x) => containsAny(normalize(x.selectorText), logicalORs));
    };
})();

Here's it in action from the Chrome console.

enter image description here

Changing Vim indentation behavior by file type

Today, you could try editorconfig, there is also a vim plugin for it. With this, you are able not only change indentation size in vim, but in many other editors, keep consistent coding styles.

Below is a simple editorconfig, as you can see, the python files will have 4 spaces for indentation, and pug template files will only have 2.

# 4 space indentation for python files
[*.py]
indent_style = space
indent_size = 4

# 2 space indentation for pug templates
[*.pug]
indent_size = 2

How to correctly use "section" tag in HTML5?

that’s just wrong: is not a wrapper. The element denotes a semantic section of your content to help construct a document outline. It should contain a heading. If you’re looking for a page wrapper element (for any flavour of HTML or XHTML), consider applying styles directly to the element as described by Kroc Camen. If you still need an additional element for styling, use a . As Dr Mike explains, div isn’t dead, and if there’s nothing else more appropriate, it’s probably where you really want to apply your CSS.

you can check this : http://html5doctor.com/avoiding-common-html5-mistakes/

Showing the same file in both columns of a Sublime Text window

View -> Layout -> Choose one option or use shortcut

Layout        Shortcut

Single        Alt + Shift + 1
Columns: 2    Alt + Shift + 2
Columns: 3    Alt + Shift + 3
Columns: 4    Alt + Shift + 4
Rows: 2       Alt + Shift + 8
Rows: 3       Alt + Shift + 9
Grid: 4       Alt + Shift + 5

enter image description here

Why do I get java.lang.AbstractMethodError when trying to load a blob in the db?

Just put ojdbc6.jar in class path, so that we can fix CallbaleStatement exception:

oracle.jdbc.driver.T4CPreparedStatement.setBinaryStream(ILjava/io/InputStream;J)V)

in Oracle.

SQL ON DELETE CASCADE, Which Way Does the Deletion Occur?

Cascade will work when you delete something on table Courses. Any record on table BookCourses that has reference to table Courses will be deleted automatically.

But when you try to delete on table BookCourses only the table itself is affected and not on the Courses

follow-up question: why do you have CourseID on table Category?

Maybe you should restructure your schema into this,

CREATE TABLE Categories 
(
  Code CHAR(4) NOT NULL PRIMARY KEY,
  CategoryName VARCHAR(63) NOT NULL UNIQUE
);

CREATE TABLE Courses 
(
  CourseID INT NOT NULL PRIMARY KEY,
  BookID INT NOT NULL,
  CatCode CHAR(4) NOT NULL,
  CourseNum CHAR(3) NOT NULL,
  CourseSec CHAR(1) NOT NULL,
);

ALTER TABLE Courses
ADD FOREIGN KEY (CatCode)
REFERENCES Categories(Code)
ON DELETE CASCADE;

How to pass in password to pg_dump?

$ PGPASSWORD="mypass" pg_dump -i -h localhost -p 5432 -U username -F c -b -v -f dumpfilename.dump databasename

Launch Failed. Binary not found. CDT on Eclipse Helios

I had this problem for a long while and I couldn't figure out the answer. I had added all the paths, built everything and pretty much followed what everyone on here had suggested, but no luck.

Finally I read the comments and saw that there were some compilation errors that were aborting the procedure before the binaries and exe file was generated.

Bottom line: Do a code review and make sure that there are no errors in your code because sometimes eclipse will not always catch everything.

If you can run a basic hello world but not your code then obviously something is wrong with your code. I learned the hard way.

Remove Null Value from String array in java

Those are zero-length strings, not null. But if you want to remove them:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

How to count items in JSON data

import json

json_data = json.dumps({
  "result":[
    {
      "run":[
        {
          "action":"stop"
        },
        {
          "action":"start"
        },
        {
          "action":"start"
        }
      ],
      "find": "true"
    }
  ]
})

item_dict = json.loads(json_data)
print len(item_dict['result'][0]['run'])

Convert it in dict.

How to always show the vertical scrollbar in a browser?

Add the class to the div you want to be scrollable.

overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.

<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
    width: 500px;
    height: 300px;
    overflow-x: hidden; 
    overflow-y: scroll;
}


</style>
</head>
<body>

<div class="scroll"><h1> DATA </h1></div>

Is there a limit to the length of a GET request?

setFixedLengthStreamingMode(int) with contentLength parameters could set the fixed length of a HTTP request body.

How to create a directory if it doesn't exist using Node.js?

fs.exist() is deprecated. So I have used fs.stat() to check the directory status. If the directory does not exist fs.stat() throw an error with message like 'no such file or directory'. Then I have created a directory.

const fs = require('fs').promises;
    
const dir = './dir';
fs.stat(dir).catch(async (err) => {
  if (err.message.includes('no such file or directory')) {
    await fs.mkdir(dir);
  }
});

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

If you want the old directive back, you can add this to your app:

Directive:

directives.directive('ngBindHtmlUnsafe', ['$sce', function($sce){
    return {
        scope: {
            ngBindHtmlUnsafe: '=',
        },
        template: "<div ng-bind-html='trustedHtml'></div>",
        link: function($scope, iElm, iAttrs, controller) {
            $scope.updateView = function() {
                $scope.trustedHtml = $sce.trustAsHtml($scope.ngBindHtmlUnsafe);
            }

            $scope.$watch('ngBindHtmlUnsafe', function(newVal, oldVal) {
                $scope.updateView(newVal);
            });
        }
    };
}]);

Usage

<div ng-bind-html-unsafe="group.description"></div>

Source - https://github.com/angular-ui/bootstrap/issues/813

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

Find indices of elements equal to zero in a NumPy array

If you are working with a one-dimensional array there is a syntactic sugar:

>>> x = numpy.array([1,0,2,0,3,0,4,5,6,7,8])
>>> numpy.flatnonzero(x == 0)
array([1, 3, 5])

"Correct" way to specifiy optional arguments in R functions

To be honest I like the OP's first way of actually starting it with a NULL value and then checking it with is.null (primarily because it is very simply and easy to understand). It maybe depends on the way people are used to coding but the Hadley seems to support the is.null way too:

From Hadley's book "Advanced-R" Chapter 6, Functions, p.84 (for the online version check here):

You can determine if an argument was supplied or not with the missing() function.

i <- function(a, b) {
  c(missing(a), missing(b))
}
i()
#> [1] TRUE TRUE
i(a = 1)
#> [1] FALSE  TRUE
i(b = 2)
#> [1]  TRUE FALSE
i(1, 2)
#> [1] FALSE FALSE

Sometimes you want to add a non-trivial default value, which might take several lines of code to compute. Instead of inserting that code in the function definition, you could use missing() to conditionally compute it if needed. However, this makes it hard to know which arguments are required and which are optional without carefully reading the documentation. Instead, I usually set the default value to NULL and use is.null() to check if the argument was supplied.

How to access the local Django webserver from outside world

For AWS users.

I had to use the following steps to get there.

1) Ensure that pip and django are installed at the sudo level

  • sudo apt-get install python-pip
  • sudo pip install django

2) Ensure that security group in-bound rules includ http on port 80 for 0.0.0.0/0

  • configured through AWS console

3) Add Public IP and DNS to ALLOWED_HOSTS

  • ALLOWED_HOSTS is a list object that you can find in settings.py
  • ALLOWED_HOSTS = ["75.254.65.19","ec2-54-528-27-21.compute-1.amazonaws.com"]

4) Launch development server with sudo on port 80

  • sudo python manage.py runserver 0:80

Site now available at either of the following (no need for :80 as that is default for http):

  • [Public DNS] i.e. ec2-54-528-27-21.compute-1.amazonaws.com
  • [Public IP] i.e 75.254.65.19

Getting a POST variable

In addition to using Request.Form and Request.QueryString and depending on your specific scenario, it may also be useful to check the Page's IsPostBack property.

if (Page.IsPostBack)
{
  // HTTP Post
}
else
{
  // HTTP Get
}

How do I make a transparent border with CSS?

You can use "transparent" as a colour. In some versions of IE, that comes up as black, but I've not tested it out since the IE6 days.

http://www.researchkitchen.de/blog/archives/css-bordercolor-transparent.php

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

Where does PHP's error log reside in XAMPP?

By default xampp php log file path is in /xampp_installation_folder/php/logs/php_error_log, but I noticed that sometimes it would not be generated automatically. Maybe it could be a Windows account write permission problem? I am not sure, but I created the logs folder and php_error_log file manually and then php logs were logged in it finally.

Another git process seems to be running in this repository

It may be happening your branch is corrupted create new branch git branch #check branch. I have created a new branch and working .

branch -b "main"
git checkout -b "main"  #main is new branch
git add .
git commit -m "all files"
git remote add origin #**YOUR REPO**  https://github.com/tarun-techmarbles/wp-dump-sql-git-push.git
git push origin main  #push with new branch 

Plotting multiple lines, in different colors, with pandas dataframe

If you have seaborn installed, an easier method that does not require you to perform pivot:

import seaborn as sns

sns.lineplot(data=df, x='x', y='y', hue='color')

Creating a byte array from a stream

The one above is ok...but you will encounter data corruption when you send stuff over SMTP (if you need to). I've altered to something else that will help to correctly send byte for byte: '

using System;
using System.IO;

        private static byte[] ReadFully(string input)
        {
            FileStream sourceFile = new FileStream(input, FileMode.Open); //Open streamer
            BinaryReader binReader = new BinaryReader(sourceFile);
            byte[] output = new byte[sourceFile.Length]; //create byte array of size file
            for (long i = 0; i < sourceFile.Length; i++)
                output[i] = binReader.ReadByte(); //read until done
            sourceFile.Close(); //dispose streamer
            binReader.Close(); //dispose reader
            return output;
        }'

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

How to read values from the querystring with ASP.NET Core?

Here is a code sample I've used (with a .NET Core view):

@{
    Microsoft.Extensions.Primitives.StringValues queryVal;

    if (Context.Request.Query.TryGetValue("yourKey", out queryVal) &&
        queryVal.FirstOrDefault() == "yourValue")
    {
    }
}

jQuery Form Validation before Ajax submit

You can try doing:

if($("#form").validate()) {
 return true;
} else {
 return false;
}

"Prevent saving changes that require the table to be re-created" negative effects

Reference - Turning off this option can help you avoid re-creating a table, it can also lead to changes being lost. For example, suppose that you enable the Change Tracking feature in SQL Server 2008 to track changes to the table. When you perform an operation that causes the table to be re-created, you receive the error message that is mentioned in the "Symptoms" section. However, if you turn off this option, the existing change tracking information is deleted when the table is re-created. Therefore,Microsoft recommend that you do not work around this problem by turning off the option.

Copy text from nano editor to shell

For whoever still looking for a copy + paste solution in nano editor

To select text

  • ctrl+6
  • Use arrow to move the cursor to where you want the mark to end

Note: If you want to copy the whole line, no need to mark just move the cursor to the line

To copy:

  • Press alt + 6

To paste:

  • Press ctrl + U

Reference

How can I implement a tree in Python?

There aren't trees built in, but you can easily construct one by subclassing a Node type from List and writing the traversal methods. If you do this, I've found bisect useful.

There are also many implementations on PyPi that you can browse.

If I remember correctly, the Python standard lib doesn't include tree data structures for the same reason that the .NET base class library doesn't: locality of memory is reduced, resulting in more cache misses. On modern processors it's usually faster to just bring a large chunk of memory into the cache, and "pointer rich" data structures negate the benefit.

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Finding median of list in Python

You can use the list.sort to avoid creating new lists with sorted and sort the lists in place.

Also you should not use list as a variable name as it shadows python's own list.

def median(l):
    half = len(l) // 2
    l.sort()
    if not len(l) % 2:
        return (l[half - 1] + l[half]) / 2.0
    return l[half]

Fatal error: Maximum execution time of 30 seconds exceeded in C:\xampp\htdocs\wordpress\wp-includes\class-http.php on line 1610

Please

  1. locate the file [XAMPP Installation Directory]\php\php.ini (e.g. C:\xampp\php\php.ini)
  2. open php.ini in Notepad or any Text editor
  3. locate the line containing max_execution_time and
  4. increase the value from 30 to some larger number (e.g. set: max_execution_time = 90)
  5. then restart Apache web server from the XAMPP control panel

If there will still be the same error after that, try to increase the value for the max_execution_time further more.

What is the Swift equivalent of isEqualToString in Objective-C?

In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Difference between spring @Controller and @RestController annotation

Actually, be careful - they are not exactly the same.

If you define any interceptors within your application, they will not apply to Controllers annotated as @RestController, however they do work with @Controller annotated controllers.

ie. configuration for the interceptor:

@Configuration
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {


    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new TemplateMappingInterceptor()).addPathPatterns("/**", "/admin-functions**").excludePathPatterns("/login**");
    }

}

and in the declaration of a Spring controller:

@Controller
public class AdminServiceController {...

Will work, however

@RestController
public class AdminServiceController {...

does not end up having the interceptor being associated with it.

Spring jUnit Testing properties file

Firstly, application.properties in the @PropertySource should read application-test.properties if that's what the file is named (matching these things up matters):

@PropertySource("classpath:application-test.properties ")

That file should be under your /src/test/resources classpath (at the root).

I don't understand why you'd specify a dependency hard coded to a file called application-test.properties. Is that component only to be used in the test environment?

The normal thing to do is to have property files with the same name on different classpaths. You load one or the other depending on whether you are running your tests or not.

In a typically laid out application, you'd have:

src/test/resources/application.properties

and

src/main/resources/application.properties

And then inject it like this:

@PropertySource("classpath:application.properties")

The even better thing to do would be to expose that property file as a bean in your spring context and then inject that bean into any component that needs it. This way your code is not littered with references to application.properties and you can use anything you want as a source of properties. Here's an example: how to read properties file in spring project?

Intersect Two Lists in C#

From performance point of view if two lists contain number of elements that differ significantly, you can try such approach (using conditional operator ?:):

1.First you need to declare a converter:

Converter<string, int> del = delegate(string s) { return Int32.Parse(s); };

2.Then you use a conditional operator:

var r = data1.Count > data2.Count ?
 data2.ConvertAll<int>(del).Intersect(data1) :
 data1.Select(v => v.ToString()).Intersect(data2).ToList<string>().ConvertAll<int>(del);

You convert elements of shorter list to match the type of longer list. Imagine an execution speed if your first set contains 1000 elements and second only 10 (or opposite as it doesn't matter) ;-)

As you want to have a result as List, in a last line you convert the result (only result) back to int.

Can you delete data from influxdb?

The accepted answer (DROP SERIES) will work for many cases, but will not work if the records you need to delete are distributed among many time ranges and tag sets.

A more general purpose approach (albeit a slower one) is to issue the delete queries one-by-one, with the use of another programming language.

  1. Query for all the records you need to delete (or use some filtering logic in your script)
  2. For each of the records you want to delete:

    1. Extract the time and the tag set (ignore the fields)
    2. Format this into a query, e.g.

      DELETE FROM "things" WHERE time=123123123 AND tag1='val' AND tag2='val'
      

      Send each of the queries one at a time

How to build x86 and/or x64 on Windows from command line with CMAKE?

This cannot be done with CMake. You have to generate two separate build folders. One for the x86 NMake build and one for the x64 NMake build. You cannot generate a single Visual Studio project covering both architectures with CMake, either.

To build Visual Studio projects from the command line for both 32-bit and 64-bit without starting a Visual Studio command prompt, use the regular Visual Studio generators.

For CMake 3.13 or newer, run the following commands:

cmake -G "Visual Studio 16 2019" -A Win32 -S \path_to_source\ -B "build32"
cmake -G "Visual Studio 16 2019" -A x64 -S \path_to_source\ -B "build64"
cmake --build build32 --config Release
cmake --build build64 --config Release

For earlier versions of CMake, run the following commands:

mkdir build32 & pushd build32
cmake -G "Visual Studio 15 2017" \path_to_source\
popd
mkdir build64 & pushd build64
cmake -G "Visual Studio 15 2017 Win64" \path_to_source\
popd
cmake --build build32 --config Release
cmake --build build64 --config Release

CMake generated projects that use one of the Visual Studio generators can be built from the command line with using the option --build followed by the build directory. The --config option specifies the build configuration.

API pagination best practices

I think currently your api's actually responding the way it should. The first 100 records on the page in the overall order of objects you are maintaining. Your explanation tells that you are using some kind of ordering ids to define the order of your objects for pagination.

Now, in case you want that page 2 should always start from 101 and end at 200, then you must make the number of entries on the page as variable, since they are subject to deletion.

You should do something like the below pseudocode:

page_max = 100
def get_page_results(page_no) :

    start = (page_no - 1) * page_max + 1
    end = page_no * page_max

    return fetch_results_by_id_between(start, end)

jQuery ui datepicker with Angularjs

I have almost exactly the same code as you and mine works.

Do you have jQueryUI.js included in the page?

There's a fiddle here

<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}


var datePicker = angular.module('app', []);

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

You'll also need the ng-app="app" somewhere in your HTML

Create a Maven project in Eclipse complains "Could not resolve archetype"

click windows-> preferences->Maven. uncheck "Offline" check box. This was not able to download archetype which I was using. When I uncheck it, Everything worked smooth.

Excel VBA Open workbook, perform actions, save as, close

After discussion posting updated answer:

Option Explicit
Sub test()

    Dim wk As String, yr As String
    Dim fname As String, fpath As String
    Dim owb As Workbook

    With Application
        .DisplayAlerts = False
        .ScreenUpdating = False
        .EnableEvents = False
    End With

    wk = ComboBox1.Value
    yr = ComboBox2.Value
    fname = yr & "W" & wk
    fpath = "C:\Documents and Settings\jammil\Desktop\AutoFinance\ProjectControl\Data"

    On Error GoTo ErrorHandler
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)

    'Do Some Stuff

    With owb
        .SaveAs fpath & Format(Date, "yyyymm") & "DB" & ".xlsx", 51
        .Close
    End With

    With Application
        .DisplayAlerts = True
        .ScreenUpdating = True
        .EnableEvents = True
    End With

Exit Sub
ErrorHandler: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

Else: Call Clear

End Sub

Error Handling:

You could try something like this to catch a specific error:

    On Error Resume Next
    Set owb = Application.Workbooks.Open(fpath & "\" & fname)
    If Err.Number = 1004 Then
    GoTo FileNotFound
    Else
    End If

    ...
    Exit Sub
    FileNotFound: If MsgBox("This File Does Not Exist!", vbRetryCancel) = vbCancel Then

    Else: Call Clear

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

Getting the filenames of all files in a folder

Create a File object, passing the directory path to the constructor. Use the listFiles() to retrieve an array of File objects for each file in the directory, and then call the getName() method to get the filename.

List<String> results = new ArrayList<String>();


File[] files = new File("/path/to/the/directory").listFiles();
//If this pathname does not denote a directory, then listFiles() returns null. 

for (File file : files) {
    if (file.isFile()) {
        results.add(file.getName());
    }
}

Undo git pull, how to bring repos to old state

it works first use: git reflog

find your SHA of your previus state and make (HEAD@{1} is an example)

git reset --hard HEAD@{1}

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

Numpy: find index of the elements within range

a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.argwhere((a>=6) & (a<=10))

How to rename a directory/folder on GitHub website?

Go into your directory and click on 'Settings' next to the little cog. There is a field to rename your directory.

How can I get onclick event on webview in android?

WebViewClient.shouldOverrideUrlLoading might be helpful. We are having a similar requirement in one of our app. Not tried yet.

call javascript function onchange event of dropdown list

Your code is working just fine, you have to declare javscript method before DOM ready.

your working example

How to get the sign, mantissa and exponent of a floating point number

You're &ing the wrong bits. I think you want:

s = *ptr >> 31;
e = *ptr & 0x7f800000;
e >>= 23;
m = *ptr & 0x007fffff;

Remember, when you &, you are zeroing out bits that you don't set. So in this case, you want to zero out the sign bit when you get the exponent, and you want to zero out the sign bit and the exponent when you get the mantissa.

Note that the masks come directly from your picture. So, the exponent mask will look like:

0 11111111 00000000000000000000000

and the mantissa mask will look like:

0 00000000 11111111111111111111111

Function return value in PowerShell

PowerShell has really wacky return semantics - at least when viewed from a more traditional programming perspective. There are two main ideas to wrap your head around:

  • All output is captured, and returned
  • The return keyword really just indicates a logical exit point

Thus, the following two script blocks will do effectively the exact same thing:

$a = "Hello, World"
return $a

 

$a = "Hello, World"
$a
return

The $a variable in the second example is left as output on the pipeline and, as mentioned, all output is returned. In fact, in the second example you could omit the return entirely and you would get the same behavior (the return would be implied as the function naturally completes and exits).

Without more of your function definition I can't say why you are getting a PSMethod object. My guess is that you probably have something a few lines up that is not being captured and is being placed on the output pipeline.

It is also worth noting that you probably don't need those semicolons - unless you are nesting multiple expressions on a single line.

You can read more about the return semantics on the about_Return page on TechNet, or by invoking the help return command from PowerShell itself.

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

How to get the last row of an Oracle a table

SELECT * FROM (
    SELECT * FROM table_name ORDER BY sortable_column DESC
) WHERE ROWNUM = 1;

How do I make a branch point at a specific commit?

You can make master point at 1258f0d0aae this way:

git checkout master
git reset --hard 1258f0d0aae

But you have to be careful about doing this. It may well rewrite the history of that branch. That would create problems if you have published it and other people are working on the branch.

Also, the git reset --hard command will throw away any uncommitted changes (i.e. those just in your working tree or the index).

You can also force an update to a branch with:

git branch -f master 1258f0d0aae

... but git won't let you do that if you're on master at the time.

How to get row count in sqlite using Android?

Use android.database.DatabaseUtils to get number of count.

public long getTaskCount(long tasklist_Id) {
        return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}

It is easy utility that has multiple wrapper methods to achieve database operations.

Can typescript export a function?

To answer the title of your question directly because this comes up in Google first:

YES, TypeScript can export a function!

Here is a direct quote from the TS Documentation:

"Any declaration (such as a variable, function, class, type alias, or interface) can be exported by adding the export keyword."

Reference Link

Scroll RecyclerView to show selected item on top

If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom LinearSmoothScroller:

import android.content.Context;
import android.graphics.PointF;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;

public class SnappingLinearLayoutManager extends LinearLayoutManager {

    public SnappingLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {
        RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private class TopSnappedSmoothScroller extends LinearSmoothScroller {
        public TopSnappedSmoothScroller(Context context) {
            super(context);

        }

        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return SnappingLinearLayoutManager.this
                    .computeScrollVectorForPosition(targetPosition);
        }

        @Override
        protected int getVerticalSnapPreference() {
            return SNAP_TO_START;
        }
    }
}

use an instance of the layoutmanager in recycle view and then calling recyclerView.smoothScrollToPosition(pos); will smooth scroll to selected position to top of the recycler view

Capturing multiple line output into a Bash variable

After trying most of the solutions here, the easiest thing I found was the obvious - using a temp file. I'm not sure what you want to do with your multiple line output, but you can then deal with it line by line using read. About the only thing you can't really do is easily stick it all in the same variable, but for most practical purposes this is way easier to deal with.

./myscript.sh > /tmp/foo
while read line ; do 
    echo 'whatever you want to do with $line'
done < /tmp/foo

Quick hack to make it do the requested action:

result=""
./myscript.sh > /tmp/foo
while read line ; do
  result="$result$line\n"
done < /tmp/foo
echo -e $result

Note this adds an extra line. If you work on it you can code around it, I'm just too lazy.


EDIT: While this case works perfectly well, people reading this should be aware that you can easily squash your stdin inside the while loop, thus giving you a script that will run one line, clear stdin, and exit. Like ssh will do that I think? I just saw it recently, other code examples here: https://unix.stackexchange.com/questions/24260/reading-lines-from-a-file-with-bash-for-vs-while

One more time! This time with a different filehandle (stdin, stdout, stderr are 0-2, so we can use &3 or higher in bash).

result=""
./test>/tmp/foo
while read line  <&3; do
    result="$result$line\n"
done 3</tmp/foo
echo -e $result

you can also use mktemp, but this is just a quick code example. Usage for mktemp looks like:

filenamevar=`mktemp /tmp/tempXXXXXX`
./test > $filenamevar

Then use $filenamevar like you would the actual name of a file. Probably doesn't need to be explained here but someone complained in the comments.

Sequel Pro Alternative for Windows

I use SQLYog at home and work. It turns out they DO have a free open-source version, though sadly they've been trying to hide that fact for the last few years.

You can download the open-source version from https://github.com/webyog/sqlyog-community - just click the "Download SQLyog Community Version" link.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

Any way to return PHP `json_encode` with encode UTF-8 and not Unicode?

Use JSON_UNESCAPED_UNICODE inside json_encode() if your php version >=5.4.