Programs & Examples On #Openstv

How to download excel (.xls) file from API in postman?

If the endpoint really is a direct link to the .xls file, you can try the following code to handle downloading:

public static boolean download(final File output, final String source) {
    try {
        if (!output.createNewFile()) {
            throw new RuntimeException("Could not create new file!");
        }
        URL url = new URL(source);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // Comment in the code in the following line in case the endpoint redirects instead of it being a direct link
        // connection.setInstanceFollowRedirects(true);
        connection.setRequestProperty("AUTH-KEY-PROPERTY-NAME", "yourAuthKey");
        final ReadableByteChannel rbc = Channels.newChannel(connection.getInputStream());
        final FileOutputStream fos = new FileOutputStream(output);
        fos.getChannel().transferFrom(rbc, 0, 1 << 24);
        fos.close();
        return true;
    } catch (final Exception e) {
        e.printStackTrace();
    }
    return false;
}

All you should need to do is set the proper name for the auth token and fill it in.

Example usage:

download(new File("C:\\output.xls"), "http://www.website.com/endpoint");

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

Zabbix server is not running: the information displayed may not be current

In my case, this occurred because the password in the server config file was commented out.

Open the server config file: # sudo vim /etc/zabbix/zabbix-server.conf

Scroll down to db user and below there will be the password with a # commenting out. Remove the hash and insert your DB password.

PHP upload image

<?php

$filename=$_FILES['file']['name'];
$filetype=$_FILES['file']['type'];
if($filetype=='image/jpeg' or $filetype=='image/png' or $filetype=='image/gif')
{
move_uploaded_file($_FILES['file']['tmp_name'],'dir_name/'.$filename);
$filepath="dir_name`enter code here`/".$filename;
}

?> 

Perl - If string contains text?

For case-insensitive string search, use index (or rindex) in combination with fc. This example expands on the answer by Eugene Yarmash:

use feature qw( fc ); 
my $str = "Abc"; 
my $substr = "aB"; 

print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found

$str = "Abc";
$substr = "bA";

print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing

print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing

Both index and rindex return -1 if the substring is not found.
And fc returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc or lc. Remember to enable this function, for example with use feature qw( fc );.

Remove scroll bar track from ScrollView in Android

By using below, solved the problem

android:scrollbarThumbVertical="@null"

Microsoft Web API: How do you do a Server.MapPath?

As an aside to those that stumble along across this, one nice way to run test level on using the HostingEnvironment call, is if accessing say a UNC share: \example\ that is mapped to ~/example/ you could execute this to get around IIS-Express issues:

#if DEBUG
    var fs = new FileStream(@"\\example\file",FileMode.Open, FileAccess.Read);
#else
    var fs = new FileStream(HostingEnvironment.MapPath("~/example/file"), FileMode.Open, FileAccess.Read);
#endif

I find that helpful in case you have rights to locally test on a file, but need the env mapping once in production.

How to install a plugin in Jenkins manually

To install plugin "git" with all its dependencies:

curl -XPOST http://localhost:8080/pluginManager/installNecessaryPlugins -d '<install plugin="git@current" />'

Here, the plugin installed is git ; the version, specified as @current is ignored by Jenkins. Jenkins is running on localhost port 8080, change this as needed. As far as I know, this is the simplest way to install a plugin with all its dependencies 'by hand'. Tested on Jenkins v1.644

What's the difference between a proxy server and a reverse proxy server?

Let's consider the purpose of the service.

In forward proxy:

Proxy helps user to access server.

In reverse proxy:

Proxy helps server to be accessed by user.

In the latter case, the one who is helped by the proxy is no longer a user, but a server, that's the reason why we call it a reverse proxy.

Fit image to table cell [Pure HTML]

Use your developer's tool of choice and check if the tr, td or img has any padding or margins.

Add an incremental number in a field in INSERT INTO SELECT query in SQL Server

You can use the row_number() function for this.

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
            row_number() over (order by (select NULL))
    FROM PM_Ingrediants 
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

If you want to start with the maximum already in the table then do:

INSERT INTO PM_Ingrediants_Arrangements_Temp(AdminID, ArrangementID, IngrediantID, Sequence)
    SELECT @AdminID, @ArrangementID, PM_Ingrediants.ID,
           coalesce(const.maxs, 0) + row_number() over (order by (select NULL))
    FROM PM_Ingrediants cross join
         (select max(sequence) as maxs from PM_Ingrediants_Arrangement_Temp) const
    WHERE PM_Ingrediants.ID IN (SELECT ID FROM GetIDsTableFromIDsList(@IngrediantsIDs)
                             )

Finally, you can just make the sequence column an auto-incrementing identity column. This saves the need to increment it each time:

create table PM_Ingrediants_Arrangement_Temp ( . . .
    sequence int identity(1, 1) -- and might consider making this a primary key too
    . . .
)

How can I save a screenshot directly to a file in Windows?

You may want something like this: http://addons.mozilla.org/en-US/firefox/addon/5648

I think there is a version for IE and also with Explorer Integration. Pretty good software.

jQuery UI Color Picker

Had the same problem (is not a method) with jQuery when working on autocomplete. It appeared the code was executed before the autocomplete.js was loaded. So make sure the ui.colorpicker.js is loaded before calling colorpicker.

What does "where T : class, new()" mean?

where (C# Reference)

The new() Constraint lets the compiler know that any type argument supplied must have an accessible parameterless--or default-- constructor

So it should be, T must be a class, and have an accessible parameterless--or default constructor.

How do I change selected value of select2 dropdown with JqGrid?

My Expected code :

$('#my-select').val('').change();

working perfectly thank to @PanPipes for the usefull one.

How to get current language code with Swift?

Swift 3 & 4 & 4.2 & 5

Locale.current.languageCode does not compile regularly. Because you did not implemented localization for your project.

You have two possible solutions

1) String(Locale.preferredLanguages[0].prefix(2)) It returns phone lang properly.

If you want to get the type en-En, you can use Locale.preferredLanguages[0]

2) Select Project(MyApp)->Project (not Target)-> press + button into Localizations, then add language which you want.

How to run single test method with phpunit?

Here's the more generic answer:

If you are sure the method name is unique you can only filter by method name (this works for me)

phpunit --filter {TestMethodName}

However it is safer to specify the file path/reference as well

phpunit --filter {TestMethodName} {FilePath}

Example:

phpunit --filter testSaveAndDrop reference/to/escalation/EscalationGroupTest.php

Quick note: I've noticed that if I have a function named testSave and another function named testSaveAndDrop using command phpunit --filter testSave will also run testSaveAndDrop and any other function that starts with testSave*, it's weird!!

java calling a method from another class

You have to initialise the object (create the object itself) in order to be able to call its methods otherwise you would get a NullPointerException.

WordList words = new WordList();

How do I get a value of a <span> using jQuery?

$('#item1').text(); or $('#item1').html(); works fine for id="item1"

Debugging JavaScript in IE7

IE8 Developer Tools are able to switch to IE7 modeenter image description here

How can I give eclipse more memory than 512M?

Here is how i increased the memory allocation of eclipse Juno:

enter image description here

I have a total of 4GB on my system and when im working on eclipse, i dont run any other heavy softwares along side it. So I allocated 2Gb.

The thing i noticed is that the difference between min and max values should be of 512. The next value should be let say 2048 min + 512 = 2560max

Here is the heap value inside eclipse after setting -Xms2048m -Xmx2560m:

enter image description here

How to update multiple columns in single update statement in DB2

If the values came from another table, you might want to use

 UPDATE table1 t1 
 SET (col1, col2) = (
      SELECT col3, col4 
      FROM  table2 t2 
      WHERE t1.col8=t2.col9
 )

Example:

UPDATE table1
SET (col1, col2, col3) =(
   (SELECT MIN (ship_charge), MAX (ship_charge) FROM orders), 
   '07/01/2007'
)
WHERE col4 = 1001;

How to check if an array value exists?

Just use the PHP function array_key_exists()

<?php
$search_array = array('first' => 1, 'second' => 4);
if (array_key_exists('first', $search_array)) {
    echo "The 'first' element is in the array";
}
?>

For homebrew mysql installs, where's my.cnf?

On your shell type my_print_defaults --help

At the bottom of the result, you should be able to see the file from which the server reads the configurations. It prints something like this:

Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

How do I use System.getProperty("line.separator").toString()?

I think your problem is that String.split() treats its argument as a regex, and regexes treat newlines specially. You may need to explicitly create a regex object to pass to split() (there is another overload of it) and configure that regex to allow newlines by passing MULTILINE in the flags param of Pattern.compile(). Docs

How do I output text without a newline in PowerShell?

$host.UI.Write('Enabling feature XYZ.......')
Enable-SPFeature...
$host.UI.WriteLine('Done')

Select multiple rows with the same value(s)

You need to understand that when you include GROUP BY in your query you are telling SQL to combine rows. you will get one row per unique Locus value. The Having then filters those groups. Usually you specify an aggergate function in the select list like:

--show how many of each Locus there is
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus

--only show the groups that have more than one row in them
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus HAVING COUNT(*)>1

--to just display all the rows for your condition, don't use GROUP BY or HAVING
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10'

The transaction manager has disabled its support for remote/network transactions

If you could not find Local DTC in the component services try to run this PowerShell script first:

$DTCSettings = @(
"NetworkDtcAccess",               # Network DTC Access
"NetworkDtcAccessClients",        # Allow Remote Clients        ( Client and Administration)
"NetworkDtcAccessAdmin",          # Allow Remote Administration ( Client and Administration)
"NetworkDtcAccessTransactions",   #                (Transaction Manager Communication )
"NetworkDtcAccessInbound",        # Allow Inbound  (Transaction Manager Communication )
"NetworkDtcAccessOutbound" ,      # Allow Outbound (Transaction Manager Communication )
"XaTransactions",                 # Enable XA Transactions
"LuTransactions"                  # Enable SNA LU 6.2 Transactions
)
foreach($setting in $DTCSettings)
{
Set-ItemProperty -Path HKLM:\Software\Microsoft\MSDTC\Security -Name $setting -Value 1
} 
Restart-Service msdtc

And it appears!

Source: The partner transaction manager has disabled its support for remote/network transactions

Placing border inside of div and not on its edge

Best cross browser solution (mostly for IE support) like @Steve said is to make a div 98px in width and height than add a border 1px around it, or you could make a background image for div 100x100 px and draw a border on it.

How to access property of anonymous type in C#?

The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.

But I came across a different scenario, which also covers the question asked. What if you have to use an existing object list, like ViewData["htmlAttributes"] in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... })?

For this slightly different scenario I want to share with you what I found out. In the solutions below, I am assuming the following declaration for nodes:

List<object> nodes = new List<object>();

nodes.Add(
new
{
    Checked = false,
    depth = 1,
    id = "div_1" 
});

1. Solution with dynamic

In C# 4.0 and higher versions, you can simply cast to dynamic and write:

if (nodes.Any(n => ((dynamic)n).Checked == false))
    Console.WriteLine("found a  not checked  element!");

Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked property and throws a RuntimeBinderException in this case - so if you try to use a non-existing Checked2 property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'".

2. Solution with reflection

The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.

Background

As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]).

Inspired by the code in the link above, I created an extension class providing GetProp, UnanonymizeProperties and UnanonymizeListItems as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:

if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
    Console.WriteLine("found a  not checked  element!");
}

or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any() as if condition, which filters implicitly and then checks if there are any elements returned.

To get the first object containing "Checked" property and return its property "depth", you can use:

var depth = nodes.UnanonymizeListItems()
             ?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");

or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];

Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:

if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true)); 
                                      return y.HasValue && y.Value == false;}).Any())
{
    Console.WriteLine("found a  not checked   element!");
}

This prevents, that a KeyNotFoundException occurs if the "Checked" property does not exist.


The class below contains the following extension methods:

  • UnanonymizeProperties: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.
  • UnanonymizeListItems: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.
  • GetProp: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)

For the examples above, all that is required is that you add the extension class below:

public static class AnonymousTypeExtensions
{
    // makes properties of object accessible 
    public static IDictionary UnanonymizeProperties(this object obj)
    {
        Type type = obj?.GetType();
        var properties = type?.GetProperties()
               ?.Select(n => n.Name)
               ?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
        return properties;
    }
    
    // converts object list into list of properties that meet the filterCriteria
    public static List<IDictionary> UnanonymizeListItems(this List<object> objectList, 
                    Func<IDictionary<string, object>, bool> filterCriteria=default)
    {
        var accessibleList = new List<IDictionary>();
        foreach (object obj in objectList)
        {
            var props = obj.UnanonymizeProperties();
            if (filterCriteria == default
               || filterCriteria((IDictionary<string, object>)props) == true)
            { accessibleList.Add(props); }
        }
        return accessibleList;
    }

    // returns specific property, i.e. obj.GetProp(propertyName)
    // requires prior usage of AccessListItems and selection of one element, because
    // object needs to be a IDictionary<string, object>
    public static object GetProp(this object obj, string propertyName, 
                                 bool treatNotFoundAsNull = false)
    {
        try 
        {
            return ((System.Collections.Generic.IDictionary<string, object>)obj)
                   ?[propertyName];
        }
        catch (KeyNotFoundException)
        {
            if (treatNotFoundAsNull) return default(object); else throw;
        }
    }
}

Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?. by . and ?[ by [ everywhere (and do the null-handling traditionally by using if statements or catch NullReferenceExceptions), e.g.

var depth = nodes.UnanonymizeListItems()
            .FirstOrDefault(n => n.Contains("Checked"))["depth"];

As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.

If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.

Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.

What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.

What is the difference between syntax and semantics in programming languages?

Understanding how the compiler sees the code

Usually, syntax and semantics analysis of the code is done in the 'frontend' part of the compiler.

  • Syntax: Compiler generates tokens for each keyword and symbols: the token contains the information- type of keyword and its location in the code. Using these tokens, an AST(short for Abstract Syntax Tree) is created and analysed. What compiler actually checks here is whether the code is lexically meaningful i.e. does the 'sequence of keywords' comply with the language rules? As suggested in previous answers, you can see it as the grammar of the language(not the sense/meaning of the code). Side note: Syntax errors are reported in this phase.(returns tokens with the error type to the system)

  • Semantics: Now, the compiler will check whether your code operations 'makes sense'. e.g. If the language supports Type Inference, sematic error will be reported if you're trying to assign a string to a float. OR declaring the same variable twice. These are errors that are 'grammatically'/ syntaxially correct, but makes no sense during the operation. Side note: For checking whether the same variable is declared twice, compiler manages a symbol table

So, the output of these 2 frontend phases is an annotated AST(with data types) and symbol table.

Understanding it in a less technical way

Considering the normal language we use; here, English:

e.g. He go to the school. - Incorrect grammar/syntax, though he wanted to convey a correct sense/semantic.

e.g. He goes to the cold. - cold is an adjective. In English, we might say this doesn't comply with grammar, but it actually is the closest example to incorrect semantic with correct syntax I could think of.

How to concatenate two layers in keras?

Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0


import tensorflow as tf

# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)

# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)

# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])

# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])

# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)

Result:

------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

I don't know what that would look like with your python setup but that should be easy to translate.

Get connection string from App.config

Also check that you've included the System.Configuration dll under your references. Without it, you won't have access to the ConfigurationManager class in the System.Configuration namespace.

How can I change a button's color on hover?

a.button:hover{
    background: #383;  }

works for me but in my case

#buttonClick:hover {
background-color:green;  }

How to print time in format: 2009-08-10 18:17:54.811

You could use strftime, but struct tm doesn't have resolution for parts of seconds. I'm not sure if that's absolutely required for your purposes.

struct tm tm;
/* Set tm to the correct time */
char s[20]; /* strlen("2009-08-10 18:17:54") + 1 */
strftime(s, 20, "%F %H:%M:%S", &tm);

ERROR Error: StaticInjectorError(AppModule)[UserformService -> HttpClient]:

Simply i have import in appmodule.ts

import { HttpClientModule } from '@angular/common/http';
  imports: [
     BrowserModule,
     FormsModule,
     HttpClientModule  <<<this 
  ],

My problem resolved

How to search in a List of Java object

If you always search based on value3, you could store the objects in a Map:

Map<String, List<Sample>> map = new HashMap <>();

You can then populate the map with key = value3 and value = list of Sample objects with that same value3 property.

You can then query the map:

List<Sample> allSamplesWhereValue3IsDog = map.get("Dog");

Note: if no 2 Sample instances can have the same value3, you can simply use a Map<String, Sample>.

How to enable mod_rewrite for Apache 2.2

What worked for me (in ubuntu):

sudo su
cd /etc/apache2/mods-enabled
ln ../mods-available/rewrite.load rewrite.load

Also, as already mentioned, make sure AllowOverride all is set in the relevant section of /etc/apache2/sites-available/default

Difference between final and effectively final

Effective final topic is described in JLS 4.12.4 and the last paragraph consists a clear explanation:

If a variable is effectively final, adding the final modifier to its declaration will not introduce any compile-time errors. Conversely, a local variable or parameter that is declared final in a valid program becomes effectively final if the final modifier is removed.

Best way to detect Mac OS X or Windows computers with JavaScript or jQuery

Is this what you are looking for? Otherwise, let me know and I will remove this post.

Try this jQuery plugin: http://archive.plugins.jquery.com/project/client-detect

Demo: http://www.stoimen.com/jquery.client.plugin/

This is based on quirksmode BrowserDetect a wrap for jQuery browser/os detection plugin.

For keen readers:
http://www.stoimen.com/blog/2009/07/16/jquery-browser-and-os-detection-plugin/
http://www.quirksmode.org/js/support.html

And more code around the plugin resides here: http://www.stoimen.com/jquery.client.plugin/jquery.client.js

How to get the innerHTML of selectable jquery element?

The parameter ui has a property called selected which is a reference to the selected dom element, you can call innerHTML on that element.

Your code $('.ui-selected').innerHTML tries to return the innerHTML property of a jQuery wrapper element for a dom element with class ui-selected

$(function () {
    $("#select-image").selectable({
        selected: function (event, ui) {
            var $variable = ui.selected.innerHTML; // or $(ui.selected).html()
            console.log($variable);
        }
    });
});

Demo: Fiddle

Convert timestamp to date in MySQL query

I did it with the 'date' function as described in here :

(SELECT count(*) as the-counts,(date(timestamp)) as the-timestamps FROM `user_data` WHERE 1 group BY the-timestamps)

How do I make a JSON object with multiple arrays?

Enclosed in {} represents an object; enclosed in [] represents an array, there can be multiple objects in the array
example object :

{
    "brand": "bwm", 
    "price": 30000
}


{
    "brand": "benz", 
    "price": 50000
}

example array:

[
    {
        "brand": "bwm", 
        "price": 30000
    }, 
    {
        "brand": "benz", 
        "price": 50000
    }
]

In order to use JSON more beautifully, you can go here JSON Viewer do format

Javascript to display the current date and time

Get the data you need and combine it in the String;

getDate(): Returns the date
getMonth(): Returns the month
getFullYear(): Returns the year
getHours();
getMinutes();

Check out : Working With Dates

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

is there something like isset of php in javascript/jQuery?

Try this expression:

typeof(variable) != "undefined" && variable !== null

This will be true if the variable is defined and not null, which is the equivalent of how PHP's isset works.

You can use it like this:

if(typeof(variable) != "undefined" && variable !== null) {
    bla();
}

How to make the main content div fill height of screen with css

No Javascript, no absolute positioning and no fixed heights are required for this one.

Here's an all CSS / CSS only method which doesn't require fixed heights or absolute positioning:

CSS

.container { 
  display: table;
}
.content { 
  display: table-row; 
  height: 100%; 
}
.content-body { 
  display: table-cell;
}

HTML

<div class="container">
  <header class="header">
    <p>This is the header</p>
  </header>
  <section class="content">
    <div class="content-body">
      <p>This is the content.</p>
    </div>
  </section>
  <footer class="footer">
    <p>This is the footer.</p>
  </footer>
</div>

See it in action here: http://jsfiddle.net/AzLQY/

The benefit of this method is that the footer and header can grow to match their content and the body will automatically adjust itself. You can also choose to limit their height with css.

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

As it is a multi-class problem, you have to use the categorical_crossentropy, the binary cross entropy will produce bogus results, most likely will only evaluate the first two classes only.

50% for a multi-class problem can be quite good, depending on the number of classes. If you have n classes, then 100/n is the minimum performance you can get by outputting a random class.

How can I create a unique constraint on my column (SQL Server 2008 R2)?

Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.

  1. Right click on "Indexes" and click "New Index..." (note: this is disabled if you have the table open in design view)

enter image description here

  1. Give new index a name ("U_Name"), check "Unique", and click "Add..."

enter image description here

  1. Select "Name" column in the next windown

enter image description here

  1. Click OK in both windows

How to tell if UIViewController's view is visible

The view's window property is non-nil if a view is currently visible, so check the main view in the view controller:

Invoking the view method causes the view to load (if it is not loaded) which is unnecessary and may be undesirable. It would be better to check first to see if it is already loaded. I've added the call to isViewLoaded to avoid this problem.

if (viewController.isViewLoaded && viewController.view.window) {
    // viewController is visible
}

Since iOS9 it has became easier:

if viewController.viewIfLoaded?.window != nil {
    // viewController is visible
}

Or if you have a UINavigationController managing the view controllers, you could check its visibleViewController property instead.

What is the difference between json.dumps and json.load?

dumps takes an object and produces a string:

>>> a = {'foo': 3}
>>> json.dumps(a)
'{"foo": 3}'

load would take a file-like object, read the data from that object, and use that string to create an object:

with open('file.json') as fh:
    a = json.load(fh)

Note that dump and load convert between files and objects, while dumps and loads convert between strings and objects. You can think of the s-less functions as wrappers around the s functions:

def dump(obj, fh):
    fh.write(dumps(obj))

def load(fh):
    return loads(fh.read())

Converting HTML element to string in JavaScript / JQuery

What you want is the outer HTML, not the inner HTML :

$('<some element/>')[0].outerHTML;

Why do I need an IoC container as opposed to straightforward DI code?

Personally, I use IoC as some sort of structure map of my application (Yeah, I also prefer StructureMap ;) ). It makes it easy to substitute my ussual interface implementations with Moq implementations during tests. Creating a test setup can be as easy as making a new init-call to my IoC-framework, substituting whichever class is my test-boundary with a mock.

This is probably not what IoC is there for, but it's what I find myself using it for the most..

Confused by python file mode "w+"

r for read

w for write

r+ for read/write without deleting the original content if file exists, otherwise raise exception

w+ for delete the original content then read/write if file exists, otherwise create the file

For example,

>>> with open("file1.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file1.txt", "w+") as f:
...   f.write("c")
... 

$ cat file1.txt 
c$
>>> with open("file2.txt", "r+") as f:
...   f.write("ab\n")
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IOError: [Errno 2] No such file or directory: 'file2.txt'

>>> with open("file2.txt", "w") as f:
...   f.write("ab\n")
... 
>>> with open("file2.txt", "r+") as f:
...   f.write("c")
... 

$ cat file2.txt 
cb
$

Inner text shadow with CSS

You should be able to do it using the text-shadow, erm somethink like this:

.inner_text_shadow
{
    text-shadow: 1px 1px white, -1px -1px #444;
}

here's an example: http://jsfiddle.net/ekDNq/

How to view an HTML file in the browser with Visual Studio Code

probably most will be able to find a solution from the above answers but seeing as how none worked for me (vscode v1.34) i thought i'd share my experience. if at least one person finds it helpful then, cool not a wasted post, amiirte?


anyway, my solution (windows) is built a-top of @noontz's. his configuration may have been sufficient for older versions of vscode but not with 1.34 (at least, i couldn't get it working ..).

our configs are nearly identical save a single property -- that property being, the group property. i'm not sure why but without this, my task would not even appear in the command palette.

so. a working tasks.json for windows users running vscode 1.34:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Chrome",
            "type": "process",
            "command": "chrome.exe",
            "windows": {
                "command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
            },
            "args": [
                "${file}"
            ],
            "group": "build",
            "problemMatcher": []
        }
    ]
}

note that the problemMatcher property is not required for this to work but without it an extra manual step is imposed on you. tried to read the docs on this property but i'm too thick to understand. hopefully someone will come about and school me but yeah, thanks in advance for that. all i know is -- include this property and ctrl+shift+b opens the current html file in a new chrome tab, hassle free.


easy.

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

Adding the why this occurs and more possible cause. A lot of interfaces still do not understand ES6 Javascript syntax/features, hence there is need for Es6 to be compiled to ES5 whenever it is used in any file or project. The possible reasons for the SyntaxError: Cannot use import statement outside a module error is you are trying to run the file independently, you are yet to install and set up an Es6 compiler such as Babel or the path of the file in your runscript is wrong/not the compiled file. If you will want to continue without a compiler the best possible solution is to use ES5 syntax which in your case would be var ms = require(./ms.js); this can later be updated as appropriate or better still setup your compiler and ensure your file/project is compiled before running and also ensure your run script is running the compiled file usually named dist, build or whatever you named it and the path to the compiled file in your runscript is correct.

How to hide status bar in Android

 if (Build.VERSION.SDK_INT < 16) {
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 } else {
     View decorView = getWindow().getDecorView();
      int uiOptions = View.SYSTEM_UI_FLAG_FULLSCREEN;
      decorView.setSystemUiVisibility(uiOptions);
      ActionBar actionBar = getActionBar();
      actionBar.hide();
 }

iOS 7 status bar overlapping UI

Place this code snippet in your MainViewController.m file in the phonegap project.

- (void)viewDidLayoutSubviews{

    if ([self respondsToSelector:@selector(topLayoutGuide)]) // iOS 7 or above
    {
        CGFloat top = self.topLayoutGuide.length;
        if(self.webView.frame.origin.y == 0){
            // We only want to do this once, or 
            // if the view has somehow been "restored" by other    code.
            self.webView.frame = CGRectMake(self.webView.frame.origin.x,
                                           self.webView.frame.origin.y + top,
                                           self.webView.frame.size.width,
                                           self.webView.frame.size.height-top);
        } 
    } 
}

org.hibernate.PersistentObjectException: detached entity passed to persist

This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

Solution:

@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

Convert Python ElementTree to string

Element objects have no .getroot() method. Drop that call, and the .tostring() call works:

xmlstr = ElementTree.tostring(et, encoding='utf8', method='xml')

You only need to use .getroot() if you have an ElementTree instance.

Other notes:

  • This produces a bytestring, which in Python 3 is the bytes type.
    If you must have a str object, you have two options:

    1. Decode the resulting bytes value, from UTF-8: xmlstr.decode("utf8")

    2. Use encoding='unicode'; this avoids an encode / decode cycle:

      xmlstr = ElementTree.tostring(et, encoding='unicode', method='xml')
      
  • If you wanted the UTF-8 encoded bytestring value or are using Python 2, take into account that ElementTree doesn't properly detect utf8 as the standard XML encoding, so it'll add a <?xml version='1.0' encoding='utf8'?> declaration. Use utf-8 or UTF-8 (with a dash) if you want to prevent this. When using encoding="unicode" no declaration header is added.

How to prevent a dialog from closing when a button is clicked

An alternate solution

I would like to present an alternate answer from a UX perspective.

Why would you want to prevent a dialog from closing when a button is clicked? Presumably it is because you have a custom dialog in which the user hasn't made a choice or hasn't completely filled everything out yet. And if they are not finished, then you shouldn't allow them to click the positive button at all. Just disable it until everything is ready.

The other answers here give lots of tricks for overriding the positive button click. If that were important to do, wouldn't Android have made a convenient method to do it? They didn't.

Instead, the Dialogs design guide shows an example of such a situation. The OK button is disabled until the user makes a choice. No overriding tricks are necessary at all. It is obvious to the user that something still needs to be done before going on.

enter image description here

How to disable the positive button

See the Android documentation for creating a custom dialog layout. It recommends that you place your AlertDialog inside a DialogFragment. Then all you need to do is set listeners on the layout elements to know when to enable or disable the positive button.

The positive button can be disabled like this:

AlertDialog dialog = (AlertDialog) getDialog();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);

Here is an entire working DialogFragment with a disabled positive button such as might be used in the image above.

import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;

public class MyDialogFragment extends DialogFragment {

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // inflate the custom dialog layout
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.my_dialog_layout, null);

        // add a listener to the radio buttons
        RadioGroup radioGroup = (RadioGroup) view.findViewById(R.id.radio_group);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                // enable the positive button after a choice has been made
                AlertDialog dialog = (AlertDialog) getDialog();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(true);
            }
        });

        // build the alert dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setView(view)
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        // TODO: use an interface to pass the user choice back to the activity
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        MyDialogFragment.this.getDialog().cancel();
                    }
                });
        return builder.create();
    }

    @Override
    public void onResume() {
        super.onResume();

        // disable positive button by default
        AlertDialog dialog = (AlertDialog) getDialog();
        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
    }
}

The custom dialog can be run from an activity like this:

MyDialogFragment dialog = new MyDialogFragment();
dialog.show(getFragmentManager(), "MyTag");

Notes

  • For the sake of brevity, I omitted the communication interface to pass the user choice info back to the activity. The documentation shows how this is done, though.
  • The button is still null in onCreateDialog so I disabled it in onResume. This has the undesireable effect of disabling the it again if the user switches to another app and then comes back without dismissing the dialog. This could be solved by also unselecting any user choices or by calling a Runnable from onCreateDialog to disable the button on the next run loop.

    view.post(new Runnable() {
        @Override
        public void run() {
            AlertDialog dialog = (AlertDialog) getDialog();
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
        }
    });
    

Related

How to use external ".js" files

I hope this helps someone here: I encountered an issue where I needed to use JavaScript to manipulate some dynamically generated elements. After including the code to my external .js file which I had referenced to between the <script> </script> tags at the head section and it was working perfectly, nothing worked again from the script.Tried using developer tool on FF and it returned null value for the variable holding the new element. I decided to move my script tag to the bottom of the html file just before the </body> tag and bingo every part of the script started to respond fine again.

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

MySQL COUNT DISTINCT

You need to use a group by clause.

SELECT  site_id, MAX(ts) as TIME, count(*) group by site_id

Google Maps API v3: How do I dynamically change the marker icon?

You can try this code

    <script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>

<script>

    function initialize()
    {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP    
                         };
        map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
        var markers = [
            ['title-1', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.120850, '<p> Hello - 1 </p>'],
            ['title-2', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.420850, '<p> Hello - 2 </p>'],
            ['title-3', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.720850, '<p> Hello - 3 </p>'],
            ['title-4', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.020850, '<p> Hello - 4 </p>'],
            ['title-5', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.320850, '<p> Hello - 5 </p>']
        ];

        var infoWindow = new google.maps.InfoWindow(), marker, i;
        var testMarker = [];
        var status = [];
        for( i = 0; i < markers.length; i++ ) 
        {
            var title = markers[i][0];
            var loan = markers[i][1];
            var lat = markers[i][2];
            var long = markers[i][3];
            var add = markers[i][4];


            var iconGreen = 'img/greenMarker.png'; //green marker
            var iconRed = 'img/redMarker.png';     //red marker

            var infoWindowContent = loan + "\n" + placeId + add;

            var position = new google.maps.LatLng(lat, long);
            bounds.extend(position);

            marker = new google.maps.Marker({
                map: map,
                title: title,
                position: position,
                icon: iconGreen
            });
            testMarker[i] = marker;
            status[i] = 1;
            google.maps.event.addListener(marker, 'click', ( function toggleBounce( i,status,testMarker) 
            {
                return function() 
                {
                    infoWindow.setContent(markers[i][1]+markers[i][4]);
                    if( status[i] === 1 )
                    {
                        testMarker[i].setIcon(iconRed);
                        status[i] = 0;

                    }
                    for( var k = 0; k <  markers.length ; k++ )
                    {
                        if(k != i)
                        {
                            testMarker[k].setIcon(iconGreen);
                            status[i] = 1;

                        }
                    }
                    infoWindow.open(map, testMarker[i]);
                }
            })( i,status,testMarker));
            map.fitBounds(bounds);
        }
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event)
        {
            this.setZoom(8);
            google.maps.event.removeListener(boundsListener);
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div id="mapDiv" style="width:820px; height:300px"></div>

Zoom to fit: PDF Embedded in HTML

Bit of a late response but I noticed that this information can be hard to find and haven't found the answer on SO, so here it is.

Try a differnt parameter #view=FitH to force it to fit in the horzontal space and also you need to start the querystring off with a # rather than an & making it:

filename.pdf#view=FitH

What I've noticed it is that this will work if adobe reader is embedded in the browser but chrome will use it's own version of the reader and won't respond in the same way. In my own case, the chrome browser zoomed to fit width by default, so no problem , but Internet Explorer needed the above parameters to ensure the link always opened the pdf page with the correct view setting.

For a full list of available parameters see this doc

EDIT: (lazy mode on)

enter image description here enter image description here enter image description here enter image description here enter image description here

How set maximum date in datepicker dialog in android?

Try This

I have tried too many solutions but neither them was working,After wasting my half day finally i made a solution.

This code simply show you a DatePickerDialog with Minimum and Maximum date,month and year,whatever you want just modify it.

final Calendar calendar = Calendar.getInstance();
                DatePickerDialog dialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker arg0, int year, int month, int day_of_month) {
                        calendar.set(Calendar.YEAR, year);
                        calendar.set(Calendar.MONTH, (month+1));
                        calendar.set(Calendar.DAY_OF_MONTH, day_of_month);
                        String myFormat = "dd/MM/yyyy";
                        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.getDefault());
                        your_edittext.setText(sdf.format(calendar.getTime()));
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                dialog.getDatePicker().setMinDate(calendar.getTimeInMillis());// TODO: used to hide previous date,month and year
                calendar.add(Calendar.YEAR, 0);
                dialog.getDatePicker().setMaxDate(calendar.getTimeInMillis());// TODO: used to hide future date,month and year
                dialog.show();

Output:- Disable previous and future calendar

enter image description here

What do pty and tty mean?

"tty" originally meant "teletype" and "pty" means "pseudo-teletype".

In UNIX, /dev/tty* is any device that acts like a "teletype", ie, a terminal. (Called teletype because that's what we had for terminals in those benighted days.)

A pty is a pseudotty, a device entry that acts like a terminal to the process reading and writing there, but is managed by something else. They first appeared (as I recall) for X Window and screen and the like, where you needed something that acted like a terminal but could be used from another program.

Set a button group's width to 100% and make buttons equal width?

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="btn-group btn-block">_x000D_
  <button type="button" data-toggle="dropdown" class="btn btn-default btn-xs  btn-block  dropdown-toggle">Actions <span class="caret"></span>_x000D_
<span class="sr-only">Toggle Dropdown</span></button><ul role="menu" class="dropdown-menu"><li><a href="#">Action one</a></li><li class="divider"></li><li><a href="#" >Action Two</a></li></ul></div>
_x000D_
_x000D_
_x000D_

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

How do I POST a x-www-form-urlencoded request using Fetch?

var details = {
    'userName': '[email protected]',
    'password': 'Password!',
    'grant_type': 'password'
};

var formBody = [];
for (var property in details) {
  var encodedKey = encodeURIComponent(property);
  var encodedValue = encodeURIComponent(details[property]);
  formBody.push(encodedKey + "=" + encodedValue);
}
formBody = formBody.join("&");

fetch('http://identity.azurewebsites.net' + '/token', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  body: formBody
})

it is so helpful for me and works without any error

refrence : https://gist.github.com/milon87/f391e54e64e32e1626235d4dc4d16dc8

How do I separate an integer into separate digits in an array in JavaScript?

Update with string interpolation in ES2015.

const num = 07734;
let numStringArr = `${num}`.split('').map(el => parseInt(el)); // [0, 7, 7, 3, 4]

Jenkins - how to build a specific branch

This is extension of answer provided by Ranjith

I would suggest, you to choose a choice-parameter build, and specify the branches that you would like to build. Active Choice Parameter

And after that, you can specify branches to build. Branch to Build

Now, when you would build your project, you would be provided with "Build with Parameters, where you can choose the branch to build"

You can also write a groovy script to fetch all your branches to in active choice parameter.

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

No 'Access-Control-Allow-Origin' header is present on the requested resource error

Chrome doesn't allow you to integrate two different localhost,that's why we are getting this error. You just have to include Microsoft Visual Studio Web Api Core package from nuget manager.And add the two lines of code in WebApi project's in your WebApiConfig.cs file.

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Then all done.

How to check if a value exists in a dictionary (python)

Python dictionary has get(key) function

>>> d.get(key)

For Example,

>>> d = {'1': 'one', '3': 'three', '2': 'two', '5': 'five', '4': 'four'}
>>> d.get('3')
'three'
>>> d.get('10')
None

If your key does'nt exist, will return None value.

foo = d[key] # raise error if key doesn't exist
foo = d.get(key) # return None if key doesn't exist

Content relevant to versions less than 3.0 and greater than 5.0.

.

What should main() return in C and C++?

If you really have issues related to efficiency of returning an integer from a process, you should probably avoid to call that process so many times that this return value becomes an issue.

If you are doing this (call a process so many times), you should find a way to put your logic directly inside the caller, or in a DLL file, without allocate a specific process for each call; the multiple process allocations bring you the relevant efficiency problem in this case.

In detail, if you only want to know if returning 0 is more or less efficient than returning 1, it could depend from the compiler in some cases, but generically, assuming they are read from the same source (local, field, constant, embedded in the code, function result, etc.) it requires exactly the same number of clock cycles.

Rollback to last git commit

Caveat Emptor - Destructive commands ahead.

Mitigation - git reflog can save you if you need it.


1) UNDO local file changes and KEEP your last commit

git reset --hard

2) UNDO local file changes and REMOVE your last commit

git reset --hard HEAD^

3) KEEP local file changes and REMOVE your last commit

git reset --soft HEAD^

What would be the Unicode character for big bullet in the middle of the character?

You can use a span with 50% border radius.

_x000D_
_x000D_
 .mydot{_x000D_
     background: rgb(66, 183, 42);_x000D_
     border-radius: 50%;_x000D_
     display: inline-block;_x000D_
     height: 20px;_x000D_
     margin-left: 4px;_x000D_
     margin-right: 4px;_x000D_
     width: 20px;_x000D_
}    
_x000D_
<span class="mydot"></span>
_x000D_
_x000D_
_x000D_

Eclipse: How do I add the javax.servlet package to a project?

When you define a server in server view, then it will create you a server runtime library with server libs (including servlet api), that can be assigned to your project. However, then everybody that uses your project, need to create the same type of runtime in his/her eclipse workspace even for compiling.

If you directly download the servlet api jar, than it could lead to problems, since it will be included into the artifacts of your projects, but will be also present in servlet container.

In Maven it is much nicer, since you can define the servlet api interfaces as a "provided" dependency, that means it is present in the "to be production" environment.

XML Schema minOccurs / maxOccurs default values

Short answer:

As written in xsd:

<xs:attribute name="minOccurs" type="xs:nonNegativeInteger" use="optional" default="1"/>
<xs:attribute name="maxOccurs" type="xs:allNNI" use="optional" default="1"/>

If you provide an attribute with number, then the number is boundary. Otherwise attribute should appear exactly once.

Easy way to turn JavaScript array into comma-separated list?

Taking the initial code:

var arr = new Array(3);
arr[0] = "Zero";
arr[1] = "One";
arr[2] = "Two";

The initial answer of using the join function is ideal. One thing to consider would be the ultimate use of the string.

For using in some end textual display:

arr.join(",")
=> "Zero,One,Two"

For using in a URL for passing multiple values through in a (somewhat) RESTful manner:

arr.join("|")
=> "Zero|One|Two"

var url = 'http://www.yoursitehere.com/do/something/to/' + arr.join("|");
=> "http://www.yoursitehere.com/do/something/to/Zero|One|Two"

Of course, it all depends on the final use. Just keep the data source and use in mind and all will be right with the world.

How to show form input fields based on select value?

You have a few issues with your code:

  1. you are missing an open quote on the id of the select element, so: <select name="dbType" id=dbType">

should be <select name="dbType" id="dbType">

  1. $('this') should be $(this): there is no need for the quotes inside the paranthesis.

  2. use .val() instead of .value() when you want to retrieve the value of an option

  3. when u initialize "selection" do it with a var in front of it, unless you already have done it at the beggining of the function

try this:

   $('#dbType').on('change',function(){
        if( $(this).val()==="other"){
        $("#otherType").show()
        }
        else{
        $("#otherType").hide()
        }
    });

http://jsfiddle.net/ks6cv/

UPDATE for use with switch:

$('#dbType').on('change',function(){
     var selection = $(this).val();
    switch(selection){
    case "other":
    $("#otherType").show()
   break;
    default:
    $("#otherType").hide()
    }
});

UPDATE with links for jQuery and jQuery-UI:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>??

sizing div based on window width

A good trick is to use inner box-shadow, and let it do all the fading for you rather than applying it to the image.

How to get Url Hash (#) from server side

RFC 2396 section 4.1:

When a URI reference is used to perform a retrieval action on the identified resource, the optional fragment identifier, separated from the URI by a crosshatch ("#") character, consists of additional reference information to be interpreted by the user agent after the retrieval action has been successfully completed. As such, it is not part of a URI, but is often used in conjunction with a URI.

(emphasis added)

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

How to convert a Hibernate proxy to a real entity object

Since Hibernate ORM 5.2.10, you can do it likee this:

Object unproxiedEntity = Hibernate.unproxy(proxy);

Before Hibernate 5.2.10. the simplest way to do that was to use the unproxy method offered by Hibernate internal PersistenceContext implementation:

Object unproxiedEntity = ((SessionImplementor) session)
                         .getPersistenceContext()
                         .unproxy(proxy);

How do I convert a String object into a Hash object?

Quick and dirty method would be

eval("{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }") 

But it has severe security implications.
It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.

Spring Bean Scopes

Just want to update, that in Spring 5, as mentioned in Spring docs, Spring supports 6 scopes, four of which are available only if you use a web-aware ApplicationContext.

singleton (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype Scopes a single bean definition to any number of object instances.

request Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

application Scopes a single bean definition to the lifecycle of a ServletContext. Only valid in the context of a web-aware Spring ApplicationContext.

websocket Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Factorial in numpy and scipy

    from numpy import prod

    def factorial(n):
        print prod(range(1,n+1))

or with mul from operator:

    from operator import mul

    def factorial(n):
        print reduce(mul,range(1,n+1))

or completely without help:

    def factorial(n):
        print reduce((lambda x,y: x*y),range(1,n+1))

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

Setting font on NSAttributedString on UITextView disregards line spacing

//For proper line spacing

NSString *text1 = @"Hello";
NSString *text2 = @"\nWorld";
UIFont *text1Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:10];
NSMutableAttributedString *attributedString1 =
[[NSMutableAttributedString alloc] initWithString:text1 attributes:@{ NSFontAttributeName : text1Font }];
NSMutableParagraphStyle *paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle1 setAlignment:NSTextAlignmentCenter];
[paragraphStyle1 setLineSpacing:4];
[attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [attributedString1 length])];

UIFont *text2Font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:16];
NSMutableAttributedString *attributedString2 =
[[NSMutableAttributedString alloc] initWithString:text2 attributes:@{NSFontAttributeName : text2Font }];
NSMutableParagraphStyle *paragraphStyle2 = [[NSMutableParagraphStyle alloc] init];
[paragraphStyle2 setLineSpacing:4];
[paragraphStyle2 setAlignment:NSTextAlignmentCenter];
[attributedString2 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle2 range:NSMakeRange(0, [attributedString2 length])];

[attributedString1 appendAttributedString:attributedString2];

How to put text in the upper right, or lower right corner of a "box" using css

<style>
  #content { width: 300px; height: 300px; border: 1px solid black; position: relative; }
  .topright { position: absolute; top: 5px; right: 5px; text-align: right; }
  .bottomright { position: absolute; bottom: 5px; right: 5px; text-align: right; }
</style>
<div id="content">
  <div class="topright">here</div>
  <div class="bottomright">and here</div>
  Lorem ipsum etc................
</div>

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

setBackground vs setBackgroundDrawable (Android)

You can use setBackgroundResource() instead which is in API level 1.

How can I get my webapp's base URL in ASP.NET MVC?

For MVC 4:

String.Format("{0}://{1}{2}", Url.Request.RequestUri.Scheme, Url.Request.RequestUri.Authority, ControllerContext.Configuration.VirtualPathRoot);

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

How to export plots from matplotlib with transparent background?

Png files can handle transparency. So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png file.

And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?

If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.

Google drive limit number of download

Sorry, you can't view or download this file at this time is an error message that you may get when you try to download files on Google Drive.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB

The explanation for the error message is simple: while users are free to share files publicly, or with a large number of users, quotas are in effect that limit availability.

If too many users view or download a file, it may be locked for a 24 hour period before the quota is reset. The period that a file is locked may be shorter according to Google.

If a file is particularly popular, it may take days or even longer before you manage to download it to your computer or place it on your Drive storage.

It could be a solution:

  1. Locate the "uc" part of the address, and replace it with "open", so that the beginning of the URL reads * https:// drive.google.com/open?*

  2. Load the address again once you have replaced uc with open in the address.

  3. This loads a new screen with controls at the top.

  4. Click on the "add to my drive" icon at the top right.

  5. Click on "add to my drive" again to open your Google Drive storage in a new tab in the browser.

  6. You should see the locked file on your drive now.

  7. Select it with a right-click, and then the "make a copy" option from the menu.

    8.Select the copy of the file with a right-click, and there download to download the file to your local system.

Basically, what this does is create a copy of the file on your own Drive account. Since you are the owner of the copied file, you may download it to your local system this way.

Please note that this works only if you are signed in to a Google Account. Also note that you are the owner of the copied file and will be held responsible for policy violations or other issues linked to the file.

Another option is: Any public folder in Drive can host files and provide direct links to the files.

How to create the hosting URL: https:// googledrive.com/host/FolderID (your id file)

This will provide a folder that will give direct links to files inside the folder. Note: hosting view will not display files created in Google Docs.

My solution:

I had the same problem, so I made a JSON file in Google Drive but the URL file (.mp3) is in Dropbox. It is working fantastic even though I have 40,000 active user. I used this solution because I did not have time to search too much! I wrote you the Dropbox Limits anyway but I did not get problems with it

Traffic limits DROPBOX

Links and file requests are automatically banned if they generate unusually large amounts of traffic.

Dropbox Basic (free) accounts:

20 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned 100,000 downloads per day: The total number of downloads that all of your links combined can generate

Dropbox Plus and Business accounts: About 200 GB per day: The total amount of traffic that all of your links and file requests combined can generate without getting banned There's no daily limit to the number of downloads that your links can generate If your account hits our limit, we'll send a message to the email address registered to your account. Your links will be temporarily disabled, and anyone who tries to access them will see an error page instead of your files.

P.S. If you need more information about my files and how did it and How to make the URL File from Dropbox, I hope help to the people is reading this! (I posted it before but Someone deleted my last post)!

How to get Map data using JDBCTemplate.queryForMap

queryForMap is appropriate if you want to get a single row. You are selecting without a where clause, so you probably want to queryForList. The error is probably indicative of the fact that queryForMap wants one row, but you query is retrieving many rows.

Check out the docs. There is a queryForList that takes just sql; the return type is a

List<Map<String,Object>>.

So once you have the results, you can do what you are doing. I would do something like

List results = template.queryForList(sql);

for (Map m : results){
   m.get('userid');
   m.get('username');
} 

I'll let you fill in the details, but I would not iterate over keys in this case. I like to explicit about what I am expecting.

If you have a User object, and you actually want to load User instances, you can use the queryForList that takes sql and a class type

queryForList(String sql, Class<T> elementType)

(wow Spring has changed a lot since I left Javaland.)

open link of google play store in mobile version android

You can check if the Google Play Store app is installed and, if this is the case, you can use the "market://" protocol.

final String my_package_name = "........."  // <- HERE YOUR PACKAGE NAME!!
String url = "";

try {
    //Check whether Google Play store is installed or not:
    this.getPackageManager().getPackageInfo("com.android.vending", 0);

    url = "market://details?id=" + my_package_name;
} catch ( final Exception e ) {
    url = "https://play.google.com/store/apps/details?id=" + my_package_name;
}


//Open the app page in Google Play store:
final Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
startActivity(intent);

How can I limit possible inputs in a HTML5 "number" element?

And you can add a max attribute that will specify the highest possible number that you may insert

<input type="number" max="999" />

if you add both a max and a min value you can specify the range of allowed values:

<input type="number" min="1" max="999" />

The above will still not stop a user from manually entering a value outside of the specified range. Instead he will be displayed a popup telling him to enter a value within this range upon submitting the form as shown in this screenshot:

enter image description here

How do I add PHP code/file to HTML(.html) files?

Add this line

AddHandler application/x-httpd-php .html

to httpd.conf file for what you want to do. But remember, if you do this then your web server will be very slow, because it will be parsing even static code which will not contain php code. So the better way will be to make the file extension .phtml instead of just .html.

HTML img align="middle" doesn't align an image

You don't need align="center" and float:left. Remove both of these. margin: 0 auto is sufficient.

Python not working in command prompt?

Rather than the command "python", consider launching Python via the py launcher, as described in sg7's answer, which by runs your latest version of Python (or lets you select a specific version). The py launcher is enabled via a check box during installation (default: "on").

Nevertheless, you can still put the "python" command in your PATH, either at "first installation" or by "modifying" an existing installation.


First Installation:

Checking the "[x] Add Python x.y to PATH" box on the very first dialog. Here's how it looks in version 3.8: enter image description here

This has the effect of adding the following to the PATH variable:

C:\Users\...\AppData\Local\Programs\Python\Python38-32\Scripts\
C:\Users\...\AppData\Local\Programs\Python\Python38-32\

Modifying an Existing Installation:

Re-run your installer (e.g. in Downloads, python-3.8.4.exe) and Select "Modify". Check all the optional features you want (likely no changes), then click [Next]. Check [x] "Add Python to environment variables", and [Install]. enter image description here

Good PHP ORM Library?

You can check out Repose if you are feeling adventurous. Like Outlet, it is modeled after Hibernate.

It is still very early in its development, but so far the only restrictions on the domain model are that the classes are not marked final and properties are not marked private. Once I get into the land of PHP >= 5.3, I'll try to implement support for private properties as well.

JSON.net: how to deserialize without using the default constructor?

Solution:

public Response Get(string jsonData) {
    var json = JsonConvert.DeserializeObject<modelname>(jsonData);
    var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
    return data;
}

Model:

public class modelname {
    public long parameter{ get; set; }
    public int parameter{ get; set; }
    public int parameter{ get; set; }
    public string parameter{ get; set; }
}

MySQLi count(*) always returns 1

Always try to do an associative fetch, that way you can easy get what you want in multiple case result

Here's an example

$result = $mysqli->query("SELECT COUNT(*) AS cityCount FROM myCity")
$row = $result->fetch_assoc();
echo $row['cityCount']." rows in table myCity.";

How to disable Google Chrome auto update?

I have tried all of these options and none seem to work. Sometimes I actually got a message "GoogleUpdate is disabled" when I checked the "About" page, but somehow a week later it was still updated.

Now I just add GoogleUpdate to the firewall and block internet access. If I check the "About" page I get a message it is updating and after a few seconds that it can't update and I should check my firewall.

How do I run Redis on Windows?

The MSOpenTech-Redis project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way. More details in https://github.com/microsoftarchive/redis

To install & setup Redis Server on Windows 10 https://redislabs.com/blog/redis-on-windows-10

To install & setup Redis Server on macOS & Linux https://redis.io/download

Also, you may install & setup Redis Server on Linux via the package manager

For quick Redis Server Installation & Setup Guide for macOS https://github.com/rahamath18/Redis-on-MacOS

Save image from url with curl PHP

This is easiest implement.

function downloadFile($url, $path)
{
    $newfname = $path;
    $file = fopen($url, 'rb');
    if ($file) {
        $newf = fopen($newfname, 'wb');
        if ($newf) {
            while (!feof($file)) {
                fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
            }
        }
    }
    if ($file) {
        fclose($file);
    }
    if ($newf) {
        fclose($newf);
    }
}

NodeJS accessing file with relative path

Simple! The folder named .. is the parent folder, so you can make the path to the file you need as such

var foobar = require('../config/dev/foobar.json');

If you needed to go up two levels, you would write ../../ etc

Some more details about this in this SO answer and it's comments

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

How can I get my Twitter Bootstrap buttons to right align?

for bootstrap 4 documentation

  <div class="row justify-content-end">
    <div class="col-4">
      Start of the row
    </div>
    <div class="col-4">
      End of the row
    </div>
  </div>

Bootstrap close responsive menu "on click"

Just to spell out user1040259's solution, add this code to your $(document).ready(function() {});

    $('.nav').click( function() {
        $('.btn-navbar').addClass('collapsed');
        $('.nav-collapse').removeClass('in').css('height', '0');
    });

As they mention, this doesn't animate the move... but it does close the nav bar on item selection

Command-line Unix ASCII-based charting / plotting tool

Another simpler/lighter alternative to gnuplot is ervy, a NodeJS based terminal charts tool.

Supported types: scatter (XY points), bar, pie, bullet, donut and gauge.

Usage examples with various options can be found on the projects GitHub repo

enter image description here

enter image description here

How to download the latest artifact from Artifactory repository?

In case you need to download an artifact in a Dockerfile, instead of using wget or curl or the likes you can simply use the 'ADD' directive:

ADD ${ARTIFACT_URL} /opt/app/app.jar

Of course, the tricky part is determining the ARTIFACT_URL, but there's enough about that in all the other answers.

However, Docker best practises strongly discourage using ADD for this purpose and recommend using wget or curl.

WCF Error - Could not find default endpoint element that references contract 'UserService.UserService'

Do you have an Interface that your "UserService" class implements.

Your endpoints should specify an interface for the contract attribute:

contract="UserService.IUserService"

How do you get the list of targets in a makefile?

Yet another additional answer to above.

tested on MacOSX using only cat and awk on terminal

cat Makefile | awk '!/SHELL/ && /^[A-z]/ {print $1}' | awk '{print substr($0, 1, length($0)-1)}'

will output of the make file like below:

target1

target2

target3

in the Makefile, it should be the same statement, ensure that you escape the variables using $$variable rather than $variable.

Explanation

cat - spits out the contents

| - pipe parses output to next awk

awk - runs regex excluding "shell" and accepting only "A-z" lines then prints out the $1 first column

awk - yet again removes the last character ":" from the list

this is a rough output and you can do more funky stuff with just AWK. Try to avoid sed as its not as consistent in BSDs variants i.e. some works on *nix but fails on BSDs like MacOSX.

More

You should be able add this (with modifications) to a file for make, to the default bash-completion folder /usr/local/etc/bash-completion.d/ meaning when you "make tab tab" .. it will complete the targets based on the one liner script.

Find if a String is present in an array

This can be done in java 8 using Stream.

import java.util.stream.Stream;

String[] stringList = {"Red", "Orange", "Yellow", "Green", "Blue", "Violet", "Orange", "Blue"};

boolean contains = Stream.of(stringList).anyMatch(x -> x.equals(say.getText());

VB.NET Inputbox - How to identify when the Cancel Button is pressed?

Although this question is being asked for 5 years ago. I just want to share my answer. Below is how I detect whether someone is clicked cancel and OK button in input box:

Public sName As String

Sub FillName()
    sName = InputBox("Who is your name?")
    ' User is clicked cancel button
    If StrPtr(sName) = False Then
        MsgBox ("Please fill your name!")
        Exit Sub
    End If

   ' User is clicked OK button whether entering any data or without entering any datas
    If sName = "" Then
        ' If sName string is empty 
        MsgBox ("Please fill your name!")
    Else
        ' When sName string is filled
        MsgBox ("Welcome " & sName & " and nice see you!")
    End If
End Sub

Checking if a string can be converted to float in Python

str(strval).isdigit()

seems to be simple.

Handles values stored in as a string or int or float

Chrome hangs after certain amount of data transfered - waiting for available socket

Chrome is a Chromium-based browser and Chromium-based browsers only allow maximum 6 open socket connections at a time, when the 7th connection starts up it will just sit idle and wait for one of the 6 which are running to stop and then it will start running. Hence the error code ‘waiting for available sockets’, the 7th one will wait for one of those 6 sockets to become available and then it will start running.

You can either

Change Input to Upper Case

onBlur="javascript:{this.value = this.value.toUpperCase(); }

will change uppercase easily.

Demo Here

How to load data from a text file in a PostgreSQL database?

Let consider that your data are in the file values.txt and that you want to import them in the database table myTable then the following query does the job

COPY myTable FROM 'value.txt' (DELIMITER('|'));

https://www.postgresql.org/docs/current/static/sql-copy.html

Disable firefox same origin policy

In about:config add content.cors.disable (empty string).

500 internal server error at GetResponse()

Have you tried to specify UserAgent for your request? For example:

request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

Check, if you are not accidentally requesting HTTPS protocol instead of HTTP.

I have overlooked that I was requesting https://localhost:... instead of http://localhost:... and it resulted to this weird message..

VBA check if object is set

The (un)safe way to do this - if you are ok with not using option explicit - is...

Not TypeName(myObj) = "Empty"

This also handles the case if the object has not been declared. This is useful if you want to just comment out a declaration to switch off some behaviour...

Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ true, the object exists - TypeName is Object

'Dim myObj as Object
Not TypeName(myObj) = "Empty"  '/ false, the object has not been declared

This works because VBA will auto-instantiate an undeclared variable as an Empty Variant type. It eliminates the need for an auxiliary Boolean to manage the behaviour.

JavaScript blob filename without link

saveFileOnUserDevice = function(file){ // content: blob, name: string
        if(navigator.msSaveBlob){ // For ie and Edge
            return navigator.msSaveBlob(file.content, file.name);
        }
        else{
            let link = document.createElement('a');
            link.href = window.URL.createObjectURL(file.content);
            link.download = file.name;
            document.body.appendChild(link);
            link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
            link.remove();
            window.URL.revokeObjectURL(link.href);
        }
    }

angularjs directive call function specified in attribute and pass an argument to it

Not knowing exactly what you want to do... but still here's a possible solution.

Create a scope with a '&'-property in the local scope. It "provides a way to execute an expression in the context of the parent scope" (see the directive documentation for details).

I also noticed that you used a shorthand linking function and shoved in object attributes in there. You can't do that. It is more clear (imho) to just return the directive-definition object. See my code below.

Here's a code sample and a fiddle.

<div ng-app="myApp">
<div ng-controller="myController">
    <div my-method='theMethodToBeCalled'>Click me</div>
</div>
</div>

<script>

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

   app.directive("myMethod",function($parse) {
       var directiveDefinitionObject = {
         restrict: 'A',
         scope: { method:'&myMethod' },
         link: function(scope,element,attrs) {
            var expressionHandler = scope.method();
            var id = "123";

            $(element).click(function( e, rowid ) {
               expressionHandler(id);
            });
         }
       };
       return directiveDefinitionObject;
   });

   app.controller("myController",function($scope) {
      $scope.theMethodToBeCalled = function(id) { 
          alert(id); 
      };
   });

</script>

Array Index Out of Bounds Exception (Java)

This is Very Good Example of minus Length of an array in java, i am giving here both examples

 public static int linearSearchArray(){

   int[] arrayOFInt = {1,7,5,55,89,1,214,78,2,0,8,2,3,4,7};
   int key = 7;
   int i = 0;
   int count = 0;
   for ( i = 0; i< arrayOFInt.length; i++){
        if ( arrayOFInt[i]  == key ){
         System.out.println("Key Found in arrayOFInt = " + arrayOFInt[i] );
         count ++;
        }
   }

   System.out.println("this Element found the ("+ count +") number of Times");
return i;  
}

this above i < arrayOFInt.length; not need to minus one by length of array; but if you i <= arrayOFInt.length -1; is necessary other wise arrayOutOfIndexException Occur, hope this will help you.

Jinja2 template variable if None Object set a default value

As addition to other answers, one can write something else if variable is None like this:

{{ variable or '' }}

What is the difference between <p> and <div>?

The previous code was

<p class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></p>

So I have to changed it to

<div class='item'><span class='name'>*Scrambled eggs on crusty Italian ciabatta and bruschetta tomato</span><span class='price'>$12.50</span></div>

It was the easy fix. And the CSS for the above code is

.item {
    position: relative;
    border: 1px solid green;
    height: 30px;
}

.item .name {
    position: absolute;
    top: 0px;
    left: 0px;
}

.item .price {
    position: absolute;
    right: 0px;
    bottom: 0px;
}

So div tag can contain other elements. P should not be forced to do that.

Asp.net 4.0 has not been registered

The aspnet_regiis approach described above doesn't appear to work on Windows 8.1:

C:\Windows\system32>aspnet_regiis -i

Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440
Administration utility to install and uninstall ASP.NET on the local machine.
Copyright (C) Microsoft Corporation. All rights reserved.
Start installing ASP.NET (4.0.30319.33440).
This option is not supported on this version of the operating system. Administrators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Windows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlink/?LinkID=216771.
Finished installing ASP.NET (4.0.30319.33440).

As indicated in the message, I went to:

  1. Start
  2. Turn Windows features on or off
  3. .NET Framework 4.5 Advanced Services

and checked ASP.NET 4.5.

This seems to have resolved the problem.

How to catch and print the full exception traceback without halting/exiting the program?

python 3 solution

stacktrace_helper.py:

from linecache import getline
import sys
import traceback


def get_stack_trace():
    exc_type, exc_value, exc_tb = sys.exc_info()
    trace = traceback.format_stack()
    trace = list(filter(lambda x: ("\\lib\\" not in x and "/lib/" not in x and "stacktrace_helper.py" not in x), trace))
    ex_type = exc_type.__name__
    ex_line = exc_tb.tb_lineno
    ex_file = exc_tb.tb_frame.f_code.co_filename
    ex_message = str(exc_value)
    line_code = ""
    try:
        line_code = getline(ex_file, ex_line).strip()
    except:
        pass

    trace.insert(
        0, f'File "{ex_file}", line {ex_line}, line_code: {line_code} , ex: {ex_type} {ex_message}',
    )
    return trace


def get_stack_trace_str(msg: str = ""):
    trace = list(get_stack_trace())
    trace_str = "\n".join(list(map(str, trace)))
    trace_str = msg + "\n" + trace_str
    return trace_str

Change directory in PowerShell

Unlike the CMD.EXE CHDIR or CD command, the PowerShell Set-Location cmdlet will change drive and directory, both. Get-Help Set-Location -Full will get you more detailed information on Set-Location, but the basic usage would be

PS C:\> Set-Location -Path Q:\MyDir

PS Q:\MyDir> 

By default in PowerShell, CD and CHDIR are alias for Set-Location.

(Asad reminded me in the comments that if the path contains spaces, it must be enclosed in quotes.)

How to permanently remove few commits from remote branch

This might be too little too late but what helped me is the cool sounding 'nuclear' option. Basically using the command filter-branch you can remove files or change something over a large number of files throughout your entire git history.

It is best explained here.

How can I get a list of Git branches, ordered by most recent commit?

List of Git branch names, ordered by most recent commit…

Expanding on Jakub’s answer and Joe’s tip, the following will strip out the "refs/heads/" so the output only displays the branch names:


Command:

git for-each-ref --count=30 --sort=-committerdate refs/heads/ --format='%(refname:short)'

Result:

Recent Git branches

How to select specified node within Xpath node sets by index with Selenium?

There is no i in xpath is not entirely true. You can still use the count() to find the index.

Consider the following page

_x000D_
_x000D_
<html>_x000D_
_x000D_
 <head>_x000D_
  <title>HTML Sample table</title>_x000D_
 </head>_x000D_
_x000D_
 <style>_x000D_
 table, td, th {_x000D_
  border: 1px solid black;_x000D_
  font-size: 15px;_x000D_
  font-family: Trebuchet MS, sans-serif;_x000D_
 }_x000D_
 table {_x000D_
  border-collapse: collapse;_x000D_
  width: 100%;_x000D_
 }_x000D_
_x000D_
 th, td {_x000D_
  text-align: left;_x000D_
  padding: 8px;_x000D_
 }_x000D_
_x000D_
 tr:nth-child(even){background-color: #f2f2f2}_x000D_
_x000D_
 th {_x000D_
  background-color: #4CAF50;_x000D_
  color: white;_x000D_
 }_x000D_
 </style>_x000D_
_x000D_
 <body>_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 1</th>_x000D_
    <th>Heading 2</th>_x000D_
    <th>Heading 3</th>_x000D_
    <th>Heading 4</th>_x000D_
    <th>Heading 5</th>_x000D_
    <th>Heading 6</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </br>_x000D_
_x000D_
 <table>_x000D_
  <thead>_x000D_
   <tr>_x000D_
    <th>Heading 7</th>_x000D_
    <th>Heading 8</th>_x000D_
    <th>Heading 9</th>_x000D_
    <th>Heading 10</th>_x000D_
    <th>Heading 11</th>_x000D_
    <th>Heading 12</th>_x000D_
   </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
   <tr>_x000D_
    <td>Data row 1 col 1</td>_x000D_
    <td>Data row 1 col 2</td>_x000D_
    <td>Data row 1 col 3</td>_x000D_
    <td>Data row 1 col 4</td>_x000D_
    <td>Data row 1 col 5</td>_x000D_
    <td>Data row 1 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 2 col 1</td>_x000D_
    <td>Data row 2 col 2</td>_x000D_
    <td>Data row 2 col 3</td>_x000D_
    <td>Data row 2 col 4</td>_x000D_
    <td>Data row 2 col 5</td>_x000D_
    <td>Data row 2 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 3 col 1</td>_x000D_
    <td>Data row 3 col 2</td>_x000D_
    <td>Data row 3 col 3</td>_x000D_
    <td>Data row 3 col 4</td>_x000D_
    <td>Data row 3 col 5</td>_x000D_
    <td>Data row 3 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 4 col 1</td>_x000D_
    <td>Data row 4 col 2</td>_x000D_
    <td>Data row 4 col 3</td>_x000D_
    <td>Data row 4 col 4</td>_x000D_
    <td>Data row 4 col 5</td>_x000D_
    <td>Data row 4 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td>Data row 5 col 1</td>_x000D_
    <td>Data row 5 col 2</td>_x000D_
    <td>Data row 5 col 3</td>_x000D_
    <td>Data row 5 col 4</td>_x000D_
    <td>Data row 5 col 5</td>_x000D_
    <td>Data row 5 col 6</td>_x000D_
   </tr>_x000D_
   <tr>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
    <td><button>Modify</button></td>_x000D_
   </tr>_x000D_
  </tbody>_x000D_
 </table>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

The page has 2 tables and has 6 columns each with unique column names and 6 rows with variable data. The last row has the Modify button in both the tables.

Assuming that the user has to select the 4th Modify button from the first table based on the heading

Use the xpath //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

The count() operator comes in handy in situations like these.

Logic:

  1. Find the header for the Modify button using //th[.='Heading 4']
  2. Find the index of the header column using count(//tr/th[.='Heading 4']/preceding-sibling::th)+1

Note: Index starts at 0

  1. Get the rows for the corresponding header using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]

  2. Get the Modify button from the extracted node list using //th[.='Heading 4']/ancestor::thead/following-sibling::tbody/tr/td[count(//tr/th[.='Heading 4']/preceding-sibling::th)+1]/button

How to perform a real time search and filter on a HTML table

I created these examples.

Simple indexOf search

var $rows = $('#table tr');
$('#search').keyup(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();

    $rows.show().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        return !~text.indexOf(val);
    }).hide();
});

Demo: http://jsfiddle.net/7BUmG/2/

Regular expression search

More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green or green apple:

var $rows = $('#table tr');
$('#search').keyup(function() {

    var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
        reg = RegExp(val, 'i'),
        text;

    $rows.show().filter(function() {
        text = $(this).text().replace(/\s+/g, ' ');
        return !reg.test(text);
    }).hide();
});

Demo: http://jsfiddle.net/dfsq/7BUmG/1133/

Debounce

When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:

$('#search').keyup(debounce(function() {
    var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
    // etc...
}, 300));

You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.

Android and setting alpha for (image) view alpha

It's easier than the other response. There is an xml value alpha that takes double values.

android:alpha="0.0" thats invisible

android:alpha="0.5" see-through

android:alpha="1.0" full visible

That's how it works.

How to split strings into text and number?

without using regex, using isdigit() built-in function, only works if starting part is text and latter part is number

def text_num_split(item):
    for index, letter in enumerate(item, 0):
        if letter.isdigit():
            return [item[:index],item[index:]]

print(text_num_split("foobar12345"))

OUTPUT :

['foobar', '12345']

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

Saving to CSV in Excel loses regional date format

Place an apostrophe in front of the date and it should export in the correct format. Just found it out for myself, I found this thread searching for an answer.

How to take column-slices of dataframe in pandas

Also, Given a DataFrame

data

as in your example, if you would like to extract column a and d only (e.i. the 1st and the 4th column), iloc mothod from the pandas dataframe is what you need and could be used very effectively. All you need to know is the index of the columns you would like to extract. For example:

>>> data.iloc[:,[0,3]]

will give you

          a         d
0  0.883283  0.100975
1  0.614313  0.221731
2  0.438963  0.224361
3  0.466078  0.703347
4  0.955285  0.114033
5  0.268443  0.416996
6  0.613241  0.327548
7  0.370784  0.359159
8  0.692708  0.659410
9  0.806624  0.875476

call a static method inside a class?

In the later PHP version self::staticMethod(); also will not work. It will throw the strict standard error.

In this case, we can create object of same class and call by object

here is the example

class Foo {

    public function fun1() {
        echo 'non-static';   
    }

    public static function fun2() {
        echo (new self)->fun1();
    }
}

Github: error cloning my private repository

On a side note, this issue can happen in Windows if the user who is trying to use git is different than the user who installed it. The error may indicate that git cannot access the certificate files. Installing git as the administrator and using @rogertoday's answer resolved my issue.

Create a basic matrix in C (input by user !)

#include<stdio.h>
int main(void)
{  
int mat[10][10],i,j;

printf("Enter your matrix\n");  
for(i=0;i<2;i++)
  for(j=0;j<2;j++)
  {  
    scanf("%d",&mat[i][j]);  
  }  
printf("\nHere is your matrix:\n");   
for(i=0;i<2;i++)    
{  
    for(j=0;j<2;j++)  
    {  
      printf("%d ",mat[i][j]);  
    }  
    printf("\n");  
  }  

}

How to align absolutely positioned element to center?

position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;

Why is “while ( !feof (file) )” always wrong?

I'd like to provide an abstract, high-level perspective.

Concurrency and simultaneity

I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.

Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)

So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)

EOF

Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.

Examples

In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.

  • C stdio, read from a file:

      for (;;) {
          size_t n = fread(buf, 1, bufsize, infile);
          consume(buf, n);
          if (n == 0) { break; }
      }
    

The result we must use is n, the number of elements that were read (which may be as little as zero).

  • C stdio, scanf:

      for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
          consume(a, b, c);
      }
    

The result we must use is the return value of scanf, the number of elements converted.

  • C++, iostreams formatted extraction:

      for (int n; std::cin >> n; ) {
          consume(n);
      }
    

The result we must use is std::cin itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good() state.

  • C++, iostreams getline:

      for (std::string line; std::getline(std::cin, line); ) {
          consume(line);
      }
    

The result we must use is again std::cin, just as before.

  • POSIX, write(2) to flush a buffer:

      char const * p = buf;
      ssize_t n = bufsize;
      for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
      if (n != 0) { /* error, failed to write complete buffer */ }
    

The result we use here is k, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.

  • POSIX getline()

      char *buffer = NULL;
      size_t bufsiz = 0;
      ssize_t nbytes;
      while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
      {
          /* Use nbytes of data in buffer */
      }
      free(buffer);
    

    The result we must use is nbytes, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).

    Note that the function explicitly returns -1 (and not EOF!) when an error occurs or it reaches EOF.

You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.

  • A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:

      std::string input = "   123   ";   // example
    
      std::istringstream iss(input);
      int value;
      if (iss >> value >> std::ws && iss.get() == EOF) {
          consume(value);
      } else {
          // error, "input" is not parsable as an integer
      }
    

We use two results here. The first is iss, the stream object itself, to check that the formatted extraction to value succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get(), and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.

In the C standard library you can achieve something similar with the strto*l functions by checking that the end pointer has reached the end of the input string.

The answer

while(!feof) is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.

Initializing a dictionary in python with a key value and no corresponding values

Use the fromkeys function to initialize a dictionary with any default value. In your case, you will initialize with None since you don't have a default value in mind.

empty_dict = dict.fromkeys(['apple','ball'])

this will initialize empty_dict as:

empty_dict = {'apple': None, 'ball': None}

As an alternative, if you wanted to initialize the dictionary with some default value other than None, you can do:

default_value = 'xyz'
nonempty_dict = dict.fromkeys(['apple','ball'],default_value)

angular-cli where is webpack.config.js file - new angular6 does not support ng eject

According to this issue, it was a design decision to not allow users to modify the Webpack configuration to reduce the learning curve.

Considering the number of useful configuration on Webpack, this is a great drawback.

I would not recommend using angular-cli for production applications, as it is highly opinionated.

Check if string contains only digits

If you want to even support for float values (Dot separated values) then you can use this expression :

var isNumber = /^\d+\.\d+$/.test(value);

How to export/import PuTTy sessions list?

Example:
How to transfer putty configuration and session configuration from one user account to another e.g. when created a new account and want to use the putty sessions/configurations from the old account

Process:
- Export registry key from old account into a file
- Import registry key from file into new account

Export reg key: (from OLD account)

  1. Login into the OLD account e.g. tomold
  2. Open normal 'command prompt' (NOT admin !)
  3. Type 'regedit'
  4. Navigate to registry section where the configuration is being stored e.g. [HKEY_CURRENT_USER\SOFTWARE\SimonTatham] and click on it
  5. Select 'Export' from the file menu or right mouse click (radio ctrl 'selected branch')
  6. Save into file and name it e.g. 'puttyconfig.reg'
  7. Logout again

Import reg key: (into NEW account)

  1. Login into NEW account e.g. tom

  2. Open normal 'command prompt' (NOT admin !)

  3. Type 'regedit'

  4. Select 'Import' from the menu

  5. Select the registry file to import e.g. 'puttyconfig.reg'

  6. Done

Note:
Do not use an 'admin command prompt' as settings are located under '[HKEY_CURRENT_USER...] 'and regedit would run as admin and show that section for the admin-user rather then for the user to transfer from and/or to.

How to clone git repository with specific revision/changeset?

Its simple. You just have to set the upstream for the current branch

$ git clone repo
$ git checkout -b newbranch
$ git branch --set-upstream-to=origin/branch newbranch
$ git pull

That's all

How to get function parameter names/values dynamically?

function getArgs(args) {
    var argsObj = {};

    var argList = /\(([^)]*)/.exec(args.callee)[1];
    var argCnt = 0;
    var tokens;

    while (tokens = /\s*([^,]+)/g.exec(argList)) {
        argsObj[tokens[1]] = args[argCnt++];
    }

    return argsObj;
}

Spring can you autowire inside an abstract class?

I have that kind of spring setup working

an abstract class with an autowired field

public abstract class AbstractJobRoute extends RouteBuilder {

    @Autowired
    private GlobalSettingsService settingsService;

and several children defined with @Component annotation.

Convert string to Time

"16:23:01" doesn't match the pattern of "hh:mm:ss tt" - it doesn't have an am/pm designator, and 16 clearly isn't in a 12-hour clock. You're specifying that format in the parsing part, so you need to match the format of the existing data. You want:

DateTime dateTime = DateTime.ParseExact(time, "HH:mm:ss",
                                        CultureInfo.InvariantCulture);

(Note the invariant culture, not the current culture - assuming your input genuinely always uses colons.)

If you want to format it to hh:mm:ss tt, then you need to put that part in the ToString call:

lblClock.Text = date.ToString("hh:mm:ss tt", CultureInfo.CurrentCulture);

Or better yet (IMO) use "whatever the long time pattern is for the culture":

lblClock.Text = date.ToString("T", CultureInfo.CurrentCulture);

Also note that hh is unusual; typically you don't want to 0-left-pad the number for numbers less than 10.

(Also consider using my Noda Time API, which has a LocalTime type - a more appropriate match for just a "time of day".)

SQLException : String or binary data would be truncated

BEGIN TRY
    INSERT INTO YourTable (col1, col2) VALUES (@val1, @val2)
END TRY
BEGIN CATCH
    --print or insert into error log or return param or etc...
    PRINT '@val1='+ISNULL(CONVERT(varchar,@val1),'')
    PRINT '@val2='+ISNULL(CONVERT(varchar,@val2),'')
END CATCH

how to find array size in angularjs

Just use the length property of a JavaScript array like so:

$scope.names.length

Also, I don't see a starting <script> tag in your code.

If you want the length inside your view, do it like so:

{{ names.length }}

Pythonic way to create a long multi-line string

"À la" Scala way (but I think is the most Pythonic way as the OP demands):

description = """
            | The intention of this module is to provide a method to
            | pass meta information in markdown_ header files for
            | using it in jinja_ templates.
            |
            | Also, to provide a method to use markdown files as jinja
            | templates. Maybe you prefer to see the code than
            | to install it.""".replace('\n            | \n','\n').replace('            | ',' ')

If you want final str without jump lines, just put \n at the start of the first argument of the second replace:

.replace('\n            | ',' ')`.

Note: the white line between "...templates." and "Also, ..." requires a white space after the |.

How to remove the default link color of the html hyperlink 'a' tag?

<style>
a {
color:      ;
}
</style>

This code changes the color from the default to what is specified in the style. Using a:hover, you can change the color of the text from the default on hover.

Get date from input form within PHP

Validate the INPUT.

$time = strtotime($_POST['dateFrom']);
if ($time) {
  $new_date = date('Y-m-d', $time);
  echo $new_date;
} else {
   echo 'Invalid Date: ' . $_POST['dateFrom'];
  // fix it.
}

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

How to drop a database with Mongoose?

The best way to drop your database in Mongoose depends on which version of Mongoose you are using. If you are using a version of Mongoose that 4.6.4 or newer, then this method added in that release is likely going to work fine for you:

mongoose.connection.dropDatabase();

In older releases this method did not exist. Instead, you were to use a direct MongoDB call:

mongoose.connection.db.dropDatabase();

However, if this was run just after the database connection was created, it could possibly fail silently. This is related to the connection actually be asynchronous and not being set up yet when the command happens. This is not normally a problem for other Mongoose calls like .find(), which queue until the connection is open and then run.

If you look at the source code for the dropDatabase() shortcut that was added, you can see it was designed to solve this exact problem. It checks to see if the connection is open and ready. If so, it fires the command immediately. If not, it registers the command to run when the database connection has opened.

Some of the suggestions above recommend always putting your dropDatabase command in the open handler. But that only works in the case when the connection is not open yet.

Connection.prototype.dropDatabase = function(callback) {
  var Promise = PromiseProvider.get();
  var _this = this;
  var promise = new Promise.ES6(function(resolve, reject) {
    if (_this.readyState !== STATES.connected) {
      _this.on('open', function() {
        _this.db.dropDatabase(function(error) {
          if (error) {
            reject(error);
          } else {
            resolve();
          }
        });
      });
    } else {
      _this.db.dropDatabase(function(error) {
        if (error) {
          reject(error);
        } else {
          resolve();
        }
      });
    }
  });
  if (callback) {
    promise.then(function() { callback(); }, callback);
  }
  return promise;
};

Here's a simple version of the above logic that can be used with earlier Mongoose versions:

// This shim is backported from Mongoose 4.6.4 to reliably drop a database
// http://stackoverflow.com/a/42860208/254318
// The first arg should be "mongoose.connection"
function dropDatabase (connection, callback) {
    // readyState 1 === 'connected'
    if (connection.readyState !== 1) {
      connection.on('open', function() {
        connection.db.dropDatabase(callback);
      });
    } else {
      connection.db.dropDatabase(callback);
    }
}  

What characters are valid in a URL?

All the gory details can be found in the current RFC on the topic: RFC 3986 (Uniform Resource Identifier (URI): Generic Syntax)

Based on this related answer, you are looking at a list that looks like: A-Z, a-z, 0-9, -, ., _, ~, :, /, ?, #, [, ], @, !, $, &, ', (, ), *, +, ,, ;, %, and =. Everything else must be url-encoded. Also, some of these characters can only exist in very specific spots in a URI and outside of those spots must be url-encoded (e.g. % can only be used in conjunction with url encoding as in %20), the RFC has all of these specifics.

Rails Object to hash

Swanand's answer is great.

if you are using FactoryGirl, you can use its build method to generate the attribute hash without the key id. e.g.

build(:post).attributes

"NOT IN" clause in LINQ to Entities

Try:

from p in db.Products
where !theBadCategories.Contains(p.Category)
select p;

What's the SQL query you want to translate into a Linq query?

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

JavaScript string with new line - but not using \n

I think they using \n anyway even couse it not visible, or maybe they using \r. So just replace \n or \r with <br/>

Function to convert timestamp to human date in javascript

This is what I did for the instagram API. converted timestamp with date method by multiplying by 1000. and then added all entity individually like (year, months, etc)

created the custom month list name and mapped with getMonth() method which returns the index of the month.

convertStampDate(unixtimestamp){

// Unixtimestamp

// Months array
var months_arr = ['January','February','March','April','May','June','July','August','September','October','November','December'];

// Convert timestamp to milliseconds
var date = new Date(unixtimestamp*1000);

// Year
var year = date.getFullYear();

// Month
var month = months_arr[date.getMonth()];

// Day
var day = date.getDate();

// Hours
var hours = date.getHours();

// Minutes
var minutes = "0" + date.getMinutes();

// Seconds
var seconds = "0" + date.getSeconds();

// Display date time in MM-dd-yyyy h:m:s format
var fulldate = month+' '+day+'-'+year+' '+hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);

// filtered fate
var convdataTime = month+' '+day;
return convdataTime;
}

Call with stamp argument convertStampDate('1382086394000')

and thats it.

Get the (last part of) current directory name in C#

You're looking for Path.GetFileName.
Note that this won't work if the path ends in a \.

Best way to store a key=>value array in JavaScript?

I know its late but it might be helpful for those that want other ways. Another way array key=>values can be stored is by using an array method called map(); (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) you can use arrow function too

 
    var countries = ['Canada','Us','France','Italy'];  
// Arrow Function
countries.map((value, key) => key+ ' : ' + value );
// Anonomous Function
countries.map(function(value, key){
return key + " : " + value;
});

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

from unix timestamp to datetime

Without moment.js:

_x000D_
_x000D_
var time_to_show = 1509968436; // unix timestamp in seconds_x000D_
_x000D_
var t = new Date(time_to_show * 1000);_x000D_
var formatted = ('0' + t.getHours()).slice(-2) + ':' + ('0' + t.getMinutes()).slice(-2);_x000D_
_x000D_
document.write(formatted);
_x000D_
_x000D_
_x000D_

Format numbers to strings in Python

I've tried this in Python 3.6.9

>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)

<class 'str'>

How to get second-highest salary employees in a table

Another intuitive way is :- Suppose we want to find Nth highest salary then

1) Sort Employee as per descending order of salary

2) Take first N records using rownum. So in this step Nth record here is Nth highest salary

3) Now sort this temporary result in ascending order. Thus Nth highest salary is now first record

4) Get first record from this temporary result.

It will be Nth highest salary.

select * from 
 (select * from 
   (select * from  
       (select * from emp order by sal desc)  
   where rownum<=:N )  
 order by sal )
where rownum=1;

In case there are repeating salaries then in innermost query distinct can be used.

select * from 
 (select * from 
   (select * from  
       (select distinct(sal) from emp order by 1 desc)  
   where rownum<=:N )  
 order by sal )
where rownum=1;

RegEx: How can I match all numbers greater than 49?

Next matches all greater or equal to 11100:

^([1-9][1-9][1-9]\d{2}\d*|[1-9][2-9]\d{3}\d*|[2-9]\d{4}\d*|\d{6}\d*)$

For greater or equal 50:

^([5-9]\d{1}\d*|\d{3}\d*)$

See pattern and modify to any number. Also it would be great to find some recursive forward/backward operators for large numbers.

Easy way to export multiple data.frame to multiple Excel worksheets

Many good answers here, but some of them are a little dated. If you want to add further worksheets to a single file then this is the approach I find works for me. For clarity, here is the workflow for openxlsx version 4.0

# Create a blank workbook
OUT <- createWorkbook()

# Add some sheets to the workbook
addWorksheet(OUT, "Sheet 1 Name")
addWorksheet(OUT, "Sheet 2 Name")

# Write the data to the sheets
writeData(OUT, sheet = "Sheet 1 Name", x = dataframe1)
writeData(OUT, sheet = "Sheet 2 Name", x = dataframe2)

# Export the file
saveWorkbook(OUT, "My output file.xlsx")

EDIT

I've now trialled a few other answers, and I actually really like @Syed's. It doesn't exploit all the functionality of openxlsx but if you want a quick-and-easy export method then that's probably the most straightforward.

Getting the WordPress Post ID of current post

Try using this:

$id = get_the_ID();

How to specify line breaks in a multi-line flexbox layout?

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
_x000D_
.item {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: gold;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div>_x000D_
    <div class="item">1</div>_x000D_
    <div class="item">2</div>_x000D_
    <div class="item">3</div>_x000D_
  </div>_x000D_
  <div>_x000D_
    <div class="item">4</div>_x000D_
    <div class="item">5</div>_x000D_
    <div class="item">6</div>_x000D_
  </div>_x000D_
  <div>_x000D_
    <div class="item">7</div>_x000D_
    <div class="item">8</div>_x000D_
    <div class="item">9</div>_x000D_
  </div>_x000D_
  <div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.

Android ListView not refreshing after notifyDataSetChanged

If the adapter is already set, setting it again will not refresh the listview. Instead first check if the listview has a adapter and then call the appropriate method.

I think its not a very good idea to create a new instance of the adapter while setting the list view. Instead, create an object.

BuildingAdapter adapter = new BuildingAdapter(context);

    if(getListView().getAdapter() == null){ //Adapter not set yet.
     setListAdapter(adapter);
    }
    else{ //Already has an adapter
    adapter.notifyDataSetChanged();
    }

Also you might try to run the refresh list on UI Thread:

activity.runOnUiThread(new Runnable() {         
        public void run() {
              //do your modifications here

              // for example    
              adapter.add(new Object());
              adapter.notifyDataSetChanged()  
        }
});

Is there a "null coalescing" operator in JavaScript?

After reading your clarification, @Ates Goral's answer provides how to perform the same operation you're doing in C# in JavaScript.

@Gumbo's answer provides the best way to check for null; however, it's important to note the difference in == versus === in JavaScript especially when it comes to issues of checking for undefined and/or null.

There's a really good article about the difference in two terms here. Basically, understand that if you use == instead of ===, JavaScript will try to coalesce the values you're comparing and return what the result of the comparison after this coalescence.

MongoDB query multiple collections at once

One solution: add isAdmin: 0/1 flag to your post collection document.

Other solution: use DBrefs

Meaning of ${project.basedir} in pom.xml

There are a set of available properties to all Maven projects.

From Introduction to the POM:

project.basedir: The directory that the current project resides in.

This means this points to where your Maven projects resides on your system. It corresponds to the location of the pom.xml file. If your POM is located inside /path/to/project/pom.xml then this property will evaluate to /path/to/project.

Some properties are also inherited from the Super POM, which is the case for project.build.directory. It is the value inside the <project><build><directory> element of the POM. You can get a description of all those values by looking at the Maven model. For project.build.directory, it is:

The directory where all files generated by the build are placed. The default value is target.

This is the directory that will hold every generated file by the build.

Ellipsis for overflow text in dropdown boxes

You can use this jQuery function instead of plus Bootstrap tooltip

function DDLSToolTipping(ddlsArray) {
    $(ddlsArray).each(function (index, ddl) {
        DDLToolTipping(ddl)
    });
}

function DDLToolTipping(ddlID, maxLength, allowDots) {
    if (maxLength == null) { maxLength = 12 }
    if (allowDots == null) { allowDots = true }

    var selectedOption = $(ddlID).find('option:selected').text();

    if (selectedOption.length > maxLength) {
        $(ddlID).attr('data-toggle', "tooltip")
                .attr('title', selectedOption);

        if (allowDots) {
            $(ddlID).prev('sup').remove();
            $(ddlID).before(
            "<sup style='font-size: 9.5pt;position: relative;top: -1px;left: -17px;z-index: 1000;background-color: #f7f7f7;border-radius: 229px;font-weight: bold;color: #666;'>...</sup>"
               )
        }
    }

    else if ($(ddlID).attr('title') != null) {
        $(ddlID).removeAttr('data-toggle')
                .removeAttr('title');
    }
}

Find a line in a file and remove it

Try this:

public static void main(String[] args) throws IOException {

    File file = new File("file.csv");

    CSVReader csvFileReader = new CSVReader(new FileReader(file));

    List<String[]> list = csvFileReader.readAll();

    for (int i = 0; i < list.size(); i++) {
        String[] filter = list.get(i);
        if (filter[0].equalsIgnoreCase("bbb")) {
            list.remove(i);
        }
    }
    csvFileReader.close();
    CSVWriter csvOutput = new CSVWriter(new FileWriter(file));

    csvOutput.writeAll(list);
    csvOutput.flush();

    csvOutput.close();
}

Clear text area

Rather simpler method would be by using JavaScript method of innerHTML.

document.getElementById("#id_goes_here").innerHTML = "";

Rather simpler and more effective way.

   

What does #defining WIN32_LEAN_AND_MEAN exclude exactly?

According the to Windows Dev Center WIN32_LEAN_AND_MEAN excludes APIs such as Cryptography, DDE, RPC, Shell, and Windows Sockets.

Is there a splice method for strings?

It is faster to slice the string twice, like this:

function spliceSlice(str, index, count, add) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

than using a split followed by a join (Kumar Harsh's method), like this:

function spliceSplit(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)

Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.