Programs & Examples On #Weekend

How do I exclude Weekend days in a SQL Server query?

Calculate Leave working days in a table column as a default value--updated

If you are using SQL here is the query which can help you: http://gallery.technet.microsoft.com/Calculate...

filename and line number of Python script

Here's what works for me to get the line number in Python 3.7.3 in VSCode 1.39.2 (dmsg is my mnemonic for debug message):

import inspect

def dmsg(text_s):
    print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)

To call showing a variable name_s and its value:

name_s = put_code_here
dmsg('name_s: ' + name_s)

Output looks like this:

37| name_s: value_of_variable_at_line_37

How to work with string fields in a C struct?

I think this solution uses less code and is easy to understand even for newbie.

For string field in struct, you can use pointer and reassigning the string to that pointer will be straightforward and simpler.

Define definition of struct:

typedef struct {
  int number;
  char *name;
  char *address;
  char *birthdate;
  char gender;
} Patient;

Initialize variable with type of that struct:

Patient patient;
patient.number = 12345;
patient.address = "123/123 some road Rd.";
patient.birthdate = "2020/12/12";
patient.gender = "M";

It is that simple. Hope this answer helps many developers.

CSS horizontal centering of a fixed div?

If using inline-blocks is an option I would recommend this approach:

.container { 
    /* fixed position a zero-height full width container */
    position: fixed;
    top: 0; /* or whatever position is desired */
    left: 0;
    right: 0;
    height: 0;
    /* center all inline content */
    text-align: center;
}

.container > div {
    /* make the block inline */
    display: inline-block;
    /* reset container's center alignment */
    text-align: left;
} 

I wrote a short post on this here: http://salomvary.github.com/position-fixed-horizontally-centered.html

Set default value of javascript object attributes

This is actually possible to do with Object.create. It will not work for "non defined" properties. But for the ones that has been given a default value.

var defaults = {
    a: 'test1',
    b: 'test2'
};

Then when you create your properties object you do it with Object.create

properties = Object.create(defaults);

Now you will have two object where the first object is empty, but the prototype points to the defaults object. To test:

console.log('Unchanged', properties);
properties.a = 'updated';
console.log('Updated', properties);
console.log('Defaults', Object.getPrototypeOf(properties));

Remove a marker from a GoogleMap

If you use Kotlin language you just add this code:

Create global variables of GoogleMap and Marker types.

I use variable marker to make variable marker value can change directly

private lateinit var map: GoogleMap
private lateinit var marker: Marker

And I use this function/method to add the marker on my map:

private fun placeMarkerOnMap(location: LatLng) {
    val markerOptions = MarkerOptions().position(location)
    val titleStr = getAddress(location)
    markerOptions.title(titleStr)
    marker = map.addMarker(markerOptions)
}

After I create the function I place this code on the onMapReady() to remove the marker and create a new one:

map.setOnMapClickListener { location ->
        map.clear()
        marker.remove()
        placeMarkerOnMap(location)
    }

It's bonus if you want to display the address location when you click the marker add this code to hide and show the marker address but you need a method to get the address location. I got the code from this post: How to get complete address from latitude and longitude?

map.setOnMarkerClickListener {marker ->
        if (marker.isInfoWindowShown){
            marker.hideInfoWindow()
        }else{
            marker.showInfoWindow()
        }
        true
    }

CodeIgniter: How to get Controller, Action, URL information

controller class is not working any functions.

so I recommend to you use the following scripts

global $argv;

if(is_array($argv)){
    $action = $argv[1];
    $method = $argv[2];
}else{
    $request_uri = $_SERVER['REQUEST_URI'];
    $pattern = "/.*?\/index\.php\/(.*?)\/(.*?)$/";
    preg_match($pattern, $request_uri, $params);
    $action = $params[1];
    $method = $params[2];
}

Visual Studio Code - is there a Compare feature like that plugin for Notepad ++?

If you want to compare file in your project/directory with an external file (which is by the way the most common way I used to compare files) you can easily drag and drop the external file into the editor's tab and just use the command: "Compare Active File With..." on one of them selecting the other one in the newly popped up choice window. That seems to be the fastest way.

Swift Open Link in Safari

UPDATED for Swift 4: (credit to Marco Weber)

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.shared.openURL(requestUrl as URL) 
}

OR go with more of swift style using guard:

guard let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") else {
    return
}

UIApplication.shared.openURL(requestUrl as URL) 

Swift 3:

You can check NSURL as optional implicitly by:

if let requestUrl = NSURL(string: "http://www.iSecurityPlus.com") {
     UIApplication.sharedApplication().openURL(requestUrl)
}

How to error handle 1004 Error with WorksheetFunction.VLookup?

There is a way to skip the errors inside the code and go on with the loop anyway, hope it helps:

Sub new1()

Dim wsFunc As WorksheetFunction: Set wsFunc = Application.WorksheetFunction
Dim ws As Worksheet: Set ws = Sheets(1)
Dim rngLook As Range: Set rngLook = ws.Range("A:M")

currName = "Example"
On Error Resume Next ''if error, the code will go on anyway
cellNum = wsFunc.VLookup(currName, rngLook, 13, 0)

If Err.Number <> 0 Then
''error appeared
    MsgBox "currName not found" ''optional, no need to do anything
End If

On Error GoTo 0 ''no error, coming back to default conditions

End Sub

How to install a specific version of a ruby gem?

As others have noted, in general use the -v flag for the gem install command.

If you're developing a gem locally, after cutting a gem from your gemspec:

$ gem install gemname-version.gem

Assuming version 0.8, it would look like this:

$ gem install gemname-0.8.gem

What does enumerate() mean?

I am assuming that you know how to iterate over elements in some list:

for el in my_list:
    # do something

Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:

i = 0
for el in my_list:
    # do somethings, and use value of "i" somehow
    i += 1

However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list: So if you have

arr = ['a', 'b', 'c']

Then the command enumerate(arr) returns something like:

[(0,'a'), (1,'b'), (2,'c')]

Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for loop like below:

for index, value in enumerate(arr):
    print(index,value)

which would print out the sub-elements of the output of enumerate.

And in general you can basically "unpack" multiple items from list into multiple variables like below:

idx,value = (2,'c')
print(idx)
print(value)

which would print

2
c

This is the kind of assignment happening in each iteration of that loop with enumerate(arr) as iterable.

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

How to put a div in center of browser using CSS?

For Older browsers, you need to add this line on top of HTML doc

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

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

!=

For example,

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

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

Java: Replace all ' in a string with \'

Let's take a tour of String#repalceAll(String regex, String replacement)

You will see that:

An invocation of this method of the form str.replaceAll(regex, repl) yields exactly the same result as the expression

Pattern.compile(regex).matcher(str).replaceAll(repl)

So lets take a look at Matcher.html#replaceAll(java.lang.String) documentation

Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

You can see that in replacement we have special character $ which can be used as reference to captured group like

System.out.println("aHellob,aWorldb".replaceAll("a(\\w+?)b", "$1"));
// result Hello,World

But sometimes we don't want $ to be such special because we want to use it as simple dollar character, so we need a way to escape it.
And here comes \, because since it is used to escape metacharacters in regex, Strings and probably in other places it is good convention to use it here to escape $.

So now \ is also metacharacter in replacing part, so if you want to make it simple \ literal in replacement you need to escape it somehow. And guess what? You escape it the same way as you escape it in regex or String. You just need to place another \ before one you escaping.

So if you want to create \ in replacement part you need to add another \ before it. But remember that to write \ literal in String you need to write it as "\\" so to create two \\ in replacement you need to write it as "\\\\".


So try

s = s.replaceAll("'", "\\\\'");

Or even better

to reduce explicit escaping in replacement part (and also in regex part - forgot to mentioned that earlier) just use replace instead replaceAll which adds regex escaping for us

s = s.replace("'", "\\'");

What does "select 1 from" do?

The construction is usually used in "existence" checks

if exists(select 1 from customer_table where customer = 'xxx')

or

if exists(select * from customer_table where customer = 'xxx')

Both constructions are equivalent. In the past people said the select * was better because the query governor would then use the best indexed column. This has been proven not true.

Running multiple async tasks and waiting for them all to complete

Do you want to chain the Tasks, or can they be invoked in a parallel manner?

For chaining
Just do something like

Task.Run(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);
Task.Factory.StartNew(...).ContinueWith(...).ContinueWith(...).ContinueWith(...);

and don't forget to check the previous Task instance in each ContinueWith as it might be faulted.

For the parallel manner
The most simple method I came across: Parallel.Invoke Otherwise there's Task.WaitAll or you can even use WaitHandles for doing a countdown to zero actions left (wait, there's a new class: CountdownEvent), or ...

JavaScript OOP in NodeJS: how?

This is an example that works out of the box. If you want less "hacky", you should use inheritance library or such.

Well in a file animal.js you would write:

var method = Animal.prototype;

function Animal(age) {
    this._age = age;
}

method.getAge = function() {
    return this._age;
};

module.exports = Animal;

To use it in other file:

var Animal = require("./animal.js");

var john = new Animal(3);

If you want a "sub class" then inside mouse.js:

var _super = require("./animal.js").prototype,
    method = Mouse.prototype = Object.create( _super );

method.constructor = Mouse;

function Mouse() {
    _super.constructor.apply( this, arguments );
}
//Pointless override to show super calls
//note that for performance (e.g. inlining the below is impossible)
//you should do
//method.$getAge = _super.getAge;
//and then use this.$getAge() instead of super()
method.getAge = function() {
    return _super.getAge.call(this);
};

module.exports = Mouse;

Also you can consider "Method borrowing" instead of vertical inheritance. You don't need to inherit from a "class" to use its method on your class. For instance:

 var method = List.prototype;
 function List() {

 }

 method.add = Array.prototype.push;

 ...

 var a = new List();
 a.add(3);
 console.log(a[0]) //3;

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

How to get last N records with activerecord?

For Rails 4 and above version:

You can try something like this If you want first oldest entry

YourModel.order(id: :asc).limit(5).each do |d|

You can try something like this if you want last latest entries..

YourModel.order(id: :desc).limit(5).each do |d|

Why is Spring's ApplicationContext.getBean considered bad?

Using @Autowired or ApplicationContext.getBean() is really the same thing. In both ways you get the bean that is configured in your context and in both ways your code depends on spring. The only thing you should avoid is instantiating your ApplicationContext. Do this only once! In other words, a line like

ApplicationContext context = new ClassPathXmlApplicationContext("AppContext.xml");

should only be used once in your application.

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

And yes, you have to replace document.write with return as others suggested

QUERY syntax using cell reference

Copied from Web Applications:

=QUERY(Responses!B1:I, "Select B where G contains '"&$B1&"'")

Message 'src refspec master does not match any' when pushing commits in Git

I think it's because you pushed an invalid branch.

Generally, because the repository does not have a common master branch (maybe development branch). You can use

git branch

to see branches.

Get the key corresponding to the minimum value within a dictionary

For multiple keys which have equal lowest value, you can use a list comprehension:

d = {320:1, 321:0, 322:3, 323:0}

minval = min(d.values())
res = [k for k, v in d.items() if v==minval]

[321, 323]

An equivalent functional version:

res = list(filter(lambda x: d[x]==minval, d))

REST API - why use PUT DELETE POST GET?

In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.

Npm Error - No matching version found for

first, in C:\users\your PC write npm uninstall -g create-react-app then, create your project folder with npx create-react-app folder-name.

Call a stored procedure with another in Oracle

Your stored procedures work as coded. The problem is with the last line, it is unable to invoke either of your stored procedures.

Three choices in SQL*Plus are: call, exec, and an anoymous PL/SQL block.

call appears to be a SQL keyword, and is documented in the SQL Reference. http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/statements_4008.htm#BABDEHHG The syntax diagram indicates that parentesis are required, even when no arguments are passed to the call routine.

CALL test_sp_1();

An anonymous PL/SQL block is PL/SQL that is not inside a named procedure, function, trigger, etc. It can be used to call your procedure.

BEGIN
    test_sp_1;
END;
/

Exec is a SQL*Plus command that is a shortcut for the above anonymous block. EXEC <procedure_name> will be passed to the DB server as BEGIN <procedure_name>; END;

Full example:

SQL> SET SERVEROUTPUT ON
SQL> CREATE OR REPLACE PROCEDURE test_sp 
  2  AS 
  3  BEGIN 
  4      DBMS_OUTPUT.PUT_LINE('Test works'); 
  5  END;
  6  /

Procedure created.

SQL> CREATE OR REPLACE PROCEDURE test_sp_1 
  2  AS
  3  BEGIN
  4      DBMS_OUTPUT.PUT_LINE('Testing'); 
  5      test_sp; 
  6  END;
  7  /

Procedure created.

SQL> CALL test_sp_1();
Testing
Test works

Call completed.

SQL> exec test_sp_1
Testing
Test works

PL/SQL procedure successfully completed.

SQL> begin
  2      test_sp_1;
  3  end;
  4  /
Testing
Test works

PL/SQL procedure successfully completed.

SQL> 

usr/bin/ld: cannot find -l<nameOfTheLibrary>

Apart from the answers already given, it may also be the case that the *.so file exists but is not named properly. Or it may be the case that *.so file exists but it is owned by another user / root.

Issue 1: Improper name

If you are linking the file as -l<nameOfLibrary> then library file name MUST be of the form lib<nameOfLibrary> If you only have <nameOfLibrary>.so file, rename it!

Issue 2: Wrong owner

To verify that this is not the problem - do

ls -l /path/to/.so/file

If the file is owned by root or another user, you need to do

sudo chown yourUserName:yourUserName /path/to/.so/file

Could not load file or assembly ... The parameter is incorrect

In my case i wanted to compile a COM visible DLL. The problem was that an older version of this DLL was located here:

C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE

Thus Visual Studio loaded this version instead of the newly compiled one, as it tried to register it.

What does '&' do in a C++ declaration?

The "&" denotes a reference instead of a pointer to an object (In your case a constant reference).

The advantage of having a function such as

foo(string const& myname) 

over

foo(string const* myname)

is that in the former case you are guaranteed that myname is non-null, since C++ does not allow NULL references. Since you are passing by reference, the object is not copied, just like if you were passing a pointer.

Your second example:

const string &GetMethodName() { ... }

Would allow you to return a constant reference to, for example, a member variable. This is useful if you do not wish a copy to be returned, and again be guaranteed that the value returned is non-null. As an example, the following allows you direct, read-only access:

class A
{
  public:
  int bar() const {return someValue;}
  //Big, expensive to copy class
}

class B
{
public:
 A const& getA() { return mA;}
private:
 A mA;
}
void someFunction()
{
 B b = B();
 //Access A, ability to call const functions on A
 //No need to check for null, since reference is guaranteed to be valid.
 int value = b.getA().bar(); 
}

You have to of course be careful to not return invalid references. Compilers will happily compile the following (depending on your warning level and how you treat warnings)

int const& foo() 
{
 int a;

 //This is very bad, returning reference to something on the stack. This will
 //crash at runtime.
 return a; 
}

Basically, it is your responsibility to ensure that whatever you are returning a reference to is actually valid.

What is the ultimate postal code and zip regex?

There is none.

Postal/zip codes around the world don't follow a common pattern. In some countries they are made up by numbers, in others they can be combinations of numbers an letters, some can contain spaces, others dots, the number of characters can vary from two to at least six...

What you could do (theoretically) is create a seperate regex for every country in the world, not recommendable IMO. But you would still be missing on the validation part: Zip code 12345 may exist, but 12346 not, maybe 12344 doesn't exist either. How do you check for that with a regex?

You can't.

How to convert XML to JSON in Python?

One possibility would be to use Objectify or ElementTree from the lxml module. An older version ElementTree is also available in the python xml.etree module as well. Either of these will get your xml converted to Python objects which you can then use simplejson to serialize the object to JSON.

While this may seem like a painful intermediate step, it starts making more sense when you're dealing with both XML and normal Python objects.

Project has no default.properties file! Edit the project properties to set one

First Close your project.

Open a Text File then Add target=android-your_Api_Level.

Such as: target=android-7 And then Save that file as project.properties Then manually place project.properties file into your Project's Folder and then Reopen you project.

The file generally looks like:

# This file is automatically generated by Android Tools.
# Do not modify this file -- YOUR CHANGES WILL BE ERASED!
#
# This file must be checked in Version Control Systems.
#
# To customize properties used by the Ant build system use,
# "ant.properties", and override values to adapt the script to your
# project structure.

# Project target.
target=android-7

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

How to detect if javascript files are loaded?

Like T.J. wrote: the order is defined (at least it's sequential when your browser is about to execute any JavaScript, even if it may download the scripts in parallel somehow). However, as apparently you're having trouble, maybe you're using third-party JavaScript libraries that yield some 404 Not Found or timeout? If so, then read Best way to use Google’s hosted jQuery, but fall back to my hosted library on Google fail.

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

simple and correct solution is put off preload your audio and video file from setting and recheck your page your problem of waiting for available socket will resolved ...

if you use jplayer then replace preload:"metadata" to preload:"none" from jplayer JS file ...

preload:"metadata" is the default value which play your audio/video file on page load thats why google chrome showing "waiting for available socket" error

How does the vim "write with sudo" trick work?

The only problem with cnoremap w!! is that it replaces w with ! (and hangs until you type the next char) whenever you type w! at the : command prompt. Like when you want to actually force-save with w!. Also, even if it's not the first thing after :.

Therefore I would suggest mapping it to something like <Fn>w. I personally have mapleader = F1, so I'm using <Leader>w.

Data-frame Object has no Attribute

Check your DataFrame with data.columns

It should print something like this

Index([u'regiment', u'company',  u'name',u'postTestScore'], dtype='object')

Check for hidden white spaces..Then you can rename with

data = data.rename(columns={'Number ': 'Number'})

How to get scrollbar position with Javascript?

I did this for a <div> on Chrome.

element.scrollTop - is the pixels hidden in top due to the scroll. With no scroll its value is 0.

element.scrollHeight - is the pixels of the whole div.

element.clientHeight - is the pixels that you see in your browser.

var a = element.scrollTop;

will be the position.

var b = element.scrollHeight - element.clientHeight;

will be the maximum value for scrollTop.

var c = a / b;

will be the percent of scroll [from 0 to 1].

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

I recently ran into this problem because of my company's web content filter that uses its own Certificate Authority so that it can filter SSL traffic. PIP doesn't seem to be using the system's CA certificates in my case, producing the error you mention. Downgrading PIP to version 1.2.1 presented its own set of problems later on, so I went back to the original version that came with Python 3.4.

My workaround is quite simple: use easy_install. Either it doesn't check the certs (like the old PIP version), or it knows to use the system certs because it works every time for me and I can still use PIP to uninstall packages installed with easy_install.

If that doesn't work and you can get access to a network or computer that doesn't have the issue, you could always setup your own personal PyPI server: how to create local own pypi repository index without mirror?

I almost did that until I tried using easy_install as a last ditch effort.

HQL Hibernate INNER JOIN

Joins can only be used when there is an association between entities. Your Employee entity should not have a field named id_team, of type int, mapped to a column. It should have a ManyToOne association with the Team entity, mapped as a JoinColumn:

@ManyToOne
@JoinColumn(name="ID_TEAM")
private Team team;

Then, the following query will work flawlessly:

select e from Employee e inner join e.team

Which will load all the employees, except those that aren't associated to any team.

The same goes for all the other fields which are a foreign key to some other table mapped as an entity, of course (id_boss, id_profession).

It's time for you to read the Hibernate documentation, because you missed an extremely important part of what it is and how it works.

How to read a file in reverse order?

I had to do this some time ago and used the below code. It pipes to the shell. I am afraid i do not have the complete script anymore. If you are on a unixish operating system, you can use "tac", however on e.g. Mac OSX tac command does not work, use tail -r. The below code snippet tests for which platform you're on, and adjusts the command accordingly

# We need a command to reverse the line order of the file. On Linux this
# is 'tac', on OSX it is 'tail -r'
# 'tac' is not supported on osx, 'tail -r' is not supported on linux.

if sys.platform == "darwin":
    command += "|tail -r"
elif sys.platform == "linux2":
    command += "|tac"
else:
    raise EnvironmentError('Platform %s not supported' % sys.platform)

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

Is there a way to get the source code from an APK file?

Simple way: use online tool https://www.decompiler.com/, upload apk and get source code.


Procedure for decoding .apk files, step-by-step method:

Step 1:

  1. Make a new folder and copy over the .apk file that you want to decode.

  2. Now rename the extension of this .apk file to .zip (e.g. rename from filename.apk to filename.zip) and save it. Now you can access the classes.dex files, etc. At this stage you are able to see drawables but not xml and java files, so continue.

Step 2:

  1. Now extract this .zip file in the same folder (or NEW FOLDER).

  2. Download dex2jar and extract it to the same folder (or NEW FOLDER).

  3. Move the classes.dex file into the dex2jar folder.

  4. Now open command prompt and change directory to that folder (or NEW FOLDER). Then write d2j-dex2jar classes.dex (for mac terminal or ubuntu write ./d2j-dex2jar.sh classes.dex) and press enter. You now have the classes.dex.dex2jar file in the same folder.

  5. Download java decompiler, double click on jd-gui, click on open file, and open classes.dex.dex2jar file from that folder: now you get class files.

  6. Save all of these class files (In jd-gui, click File -> Save All Sources) by src name. At this stage you get the java source but the .xml files are still unreadable, so continue.

Step 3:

Now open another new folder

  1. Put in the .apk file which you want to decode

  2. Download the latest version of apktool AND apktool install window (both can be downloaded from the same link) and place them in the same folder

  3. Open a command window

  4. Now run command like apktool if framework-res.apk (if you don't have it get it here)and next

  5. apktool d myApp.apk (where myApp.apk denotes the filename that you want to decode)

now you get a file folder in that folder and can easily read the apk's xml files.

Step 4:

It's not any step, just copy contents of both folders(in this case, both new folders) to the single one

and enjoy the source code...

Replace a string in a file with nodejs

On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.

const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)

The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":

const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)

The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.

How to lowercase a pandas dataframe string column if it has missing values?

May be using List comprehension

import pandas as pd
import numpy as np
df=pd.DataFrame(['ONE','Two', np.nan],columns=['Name']})
df['Name'] = [str(i).lower() for i in df['Name']] 

print(df)

CodeIgniter Disallowed Key Characters

i saw this error when i was trying to send a form, and in one of the fields' names, i let the word "endereço".

echo form_input(array('class' => 'form-control', 'name' => 'endereco', 'placeholder' => 'Endereço', 'value' => set_value('endereco')));

When i changed 'ç' for 'c', the error was gone.

Negate if condition in bash script

Since you're comparing numbers, you can use an arithmetic expression, which allows for simpler handling of parameters and comparison:

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

Notice how instead of -ne, you can just use !=. In an arithmetic context, we don't even have to prepend $ to parameters, i.e.,

var_a=1
var_b=2
(( var_a < var_b )) && echo "a is smaller"

works perfectly fine. This doesn't appply to the $? special parameter, though.

Further, since (( ... )) evaluates non-zero values to true, i.e., has a return status of 0 for non-zero values and a return status of 1 otherwise, we could shorten to

if (( $? )); then

but this might confuse more people than the keystrokes saved are worth.

The (( ... )) construct is available in Bash, but not required by the POSIX shell specification (mentioned as possible extension, though).

This all being said, it's better to avoid $? altogether in my opinion, as in Cole's answer and Steven's answer.

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

UITableView - scroll to the top

Adding on to what's already been said, you can create a extension (Swift) or category (Objective C) to make this easier in the future:

Swift:

extension UITableView {
    func scrollToTop(animated: Bool) {
        setContentOffset(CGPointZero, animated: animated)
    }
}

Any time you want to scroll any given tableView to the top you can call the following code:

tableView.scrollToTop(animated: true)

Script not served by static file handler on IIS7.5

If you are using iis 7.5.

Just go to IIS Manager, open your website properties.

You will see 'Handler Mappings' section there, just go to that section and Search for 'staticFile'.

Most probably its a last file in the list.

Then Right Click on it and Select 'Revert To Parent'.

I have wasted so many hours while i have faced this first time, anyways this will solve your problem.

Presenting modal in iOS 13 fullscreen

Here is an easy solution without coding a single line.

  • Select View Controller in Storyboard
  • Select attribute Inspector
  • Set presentation "Automatic" to "FullScreen" as per below image

This change makes iPad app behavior as expected otherwise the new screen is displaying in the center of the screen as a popup.

enter image description here

How do you UDP multicast in Python?

Have a look at py-multicast. Network module can check if an interface supports multicast (on Linux at least).

import multicast
from multicast import network

receiver = multicast.MulticastUDPReceiver ("eth0", "238.0.0.1", 1234 )
data = receiver.read()
receiver.close()

config = network.ifconfig()
print config['eth0'].addresses
# ['10.0.0.1']
print config['eth0'].multicast
#True - eth0 supports multicast
print config['eth0'].up
#True - eth0 is up

Perhaps problems with not seeing IGMP, were caused by an interface not supporting multicast?

Java Mouse Event Right Click

I've seen

anEvent.isPopupTrigger() 

be used before. I'm fairly new to Java so I'm happy to hear thoughts about this approach :)

Table fixed header and scrollable body

You should try with "display:block;" to tbody, because now it's inline-block and in order to set height, the element should be "block"

How do MySQL indexes work?

Basically an index is a map of all your keys that is sorted in order. With a list in order, then instead of checking every key, it can do something like this:

1: Go to middle of list - is higher or lower than what I'm looking for?

2: If higher, go to halfway point between middle and bottom, if lower, middle and top

3: Is higher or lower? Jump to middle point again, etc.

Using that logic, you can find an element in a sorted list in about 7 steps, instead of checking every item.

Obviously there are complexities, but that gives you the basic idea.

IF - ELSE IF - ELSE Structure in Excel

=IF(CR<=10, "RED", if(CR<50, "YELLOW", if(CR<101, "GREEN")))

CR = ColRow (Cell) This is an example. In this example when value in Cell is less then or equal to 10 then RED word will appear on that cell. In the same manner other if conditions are true if first if is false.

What's the best UML diagramming tool?

Take a look at BOUML: multiplatform (QT), works pretty well and supports colaborative work.

BOUML is a free UML 2 tool box (under development) allowing you to specify and generate code in C++, Java, Idl, Php and Python.

BOUML runs under Unix/Linux/Solaris, MacOS X(Power PC and Intel) and Windows.

From Wikipedia:

The releases prior to version 4.23 are free software licensed under GPL. BOUML 5 and later is proprietary software.

Angular2 RC6: '<component> is not a known element'

When I had this problem, it was because I used 'templateUrl' instead of just 'template' in the decorator, since I use webpack and need to use require in it. Just be careful with the decorator name, in my case I generated the boilerplate code using a snippet, the decorator was created as:

@Component({
  selector: '',
  templateUrl: 'PATH_TO_TEMPLATE'
})

but for webpack the decorator should be just 'template' NOT 'templateUrl', like so:

@Component({
  selector: '',
  template: require('PATH_TO_TEMPLATE')
})

changing this solved the problem for me.

wanna know more about the two methods? read this medium post about template vs templateUrl

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

There were (at time of posting) one or two little typos in the accepted answer above, so here's the cleaned up version. In this example I'm stopping the CPU profiler when receiving Ctrl+C.

// capture ctrl+c and stop CPU profiler                            
c := make(chan os.Signal, 1)                                       
signal.Notify(c, os.Interrupt)                                     
go func() {                                                        
  for sig := range c {                                             
    log.Printf("captured %v, stopping profiler and exiting..", sig)
    pprof.StopCPUProfile()                                         
    os.Exit(1)                                                     
  }                                                                
}()    

Flexbox Not Centering Vertically in IE

Here is my working solution (SCSS):

.item{
  display: flex;
  justify-content: space-between;
  align-items: center;
  min-height: 120px;
  &:after{
    content:'';
    min-height:inherit;
    font-size:0;
  }
}

Waiting for background processes to finish before exiting script

You can use kill -0 for checking whether a particular pid is running or not.

Assuming, you have list of pid numbers in a file called pid in pwd

while true;
do 
    if [ -s pid ] ; then
        for pid in `cat pid`
        do  
            echo "Checking the $pid"
            kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
        done
    else
        echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
        break
    fi
done

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

I too had this error. But in my case, and I'm sure I'll be a one off here, I had accidentally deleted main.m when I hit the delete key after the app had crashed on the iPhone simulator.

After a crash, Xcode shows the main.m file and when I had hit delete, I had accidentally deleted the main.m file from my project, as it is easy to do when a file name is highlighted, not the code in the detail view.

Main.m normally resides in a group or folder named supporting files in the project file manager. I had not noticed this happened until it failed to build and run next time around and then I had to re-read the error message more closely and saw it said main.m is missing.

Thank you all for your input, but just in case there is someone in my position check for any file names in red showing missing files and restore them from a backup if you have it.

Java synchronized method lock on object, or method?

This might not work as the boxing and autoboxing from Integer to int and viceversa is dependant on JVM and there is high possibility that two different numbers might get hashed to same address if they are between -128 and 127.

Where do I find the Instagram media ID of a image

Right click on a photo and open in a new tab/window. Right click on inspect element. Search for:

instagram://media?id=

This will give you:

instagram://media?id=############# /// the ID

The full id construct from

photoID_userID

To get the user id, search for:

instapp:owner_user_id Will be in content=

Change Timezone in Lumen or Laravel 5

You just have to edit de app.php file in config directory Just find next lines

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

And.. chage it for:

'timezone' => 'Europe/Paris',

What is the proper way to display the full InnerException?

If you want information about all exceptions then use exception.ToString(). It will collect data from all inner exceptions.

If you want only the original exception then use exception.GetBaseException().ToString(). This will get you the first exception, e.g. the deepest inner exception or the current exception if there is no inner exception.

Example:

try {
    Exception ex1 = new Exception( "Original" );
    Exception ex2 = new Exception( "Second", ex1 );
    Exception ex3 = new Exception( "Third", ex2 );
    throw ex3;
} catch( Exception ex ) {
    // ex => ex3
    Exception baseEx = ex.GetBaseException(); // => ex1
}

Java - No enclosing instance of type Foo is accessible

You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

There are a few possible solutions. Which solution to use depends on what you want to achieve.

  • Move Thing out of the Hello class.

  • Change Thing to be a static nested class.

    static class Thing
    
  • Create an instance of Hello before creating an instance of Thing.

    public static void main(String[] args)
    {
        Hello h = new Hello();
        Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
    }
    

The last solution (a non-static nested class) would be mandatory if any instance of Thing depended on an instance of Hello to be meaningful. For example, if we had:

public class Hello {
    public int enormous;

    public Hello(int n) {
        enormous = n;
    }

    public class Thing {
        public int size;

        public Thing(int m) {
            if (m > enormous)
                size = enormous;
            else
                size = m;
        }
    }
    ...
}

any raw attempt to create an object of class Thing, as in:

Thing t = new Thing(31);

would be problematic, since there wouldn't be an obvious enormous value to test 31 against it. An instance h of the Hello outer class is necessary to provide this h.enormous value:

...
Hello h = new Hello(30);
...
Thing t = h.new Thing(31);
...

Because it doesn't mean a Thing if it doesn't have a Hello.

For more information on nested/inner classes: Nested Classes (The Java Tutorials)

Version vs build in Xcode

(Just leaving this here for my own reference.) This will show version and build for the "version" and "build" fields you see in an Xcode target:

- (NSString*) version {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

In Swift

func version() -> String {
    let dictionary = NSBundle.mainBundle().infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as? String
    let build = dictionary["CFBundleVersion"] as? String
    return "\(version) build \(build)"
}

Swift days between two NSDates

Here is my answer for Swift 3:

func daysBetweenDates(startDate: NSDate, endDate: NSDate, inTimeZone timeZone: TimeZone? = nil) -> Int {
    var calendar = Calendar.current
    if let timeZone = timeZone {
        calendar.timeZone = timeZone
    }
    let dateComponents = calendar.dateComponents([.day], from: startDate.startOfDay, to: endDate.startOfDay)
    return dateComponents.day!
}

Find and copy files

You need to use cp -t /home/shantanu/tosend in order to tell it that the argument is the target directory and not a source. You can then change it to -exec ... + in order to get cp to copy as many files as possible at once.

fill an array in C#

int[] arr = Enumerable.Repeat(42, 10000).ToArray();

I believe that this does the job :)

Node.js https pem error: routines:PEM_read_bio:no start line

I actually just had this same error message.

The problem was I had key and cert files swapped in the configuration object.

Add a dependency in Maven

You can also specify a dependency not in a maven repository. Could be usefull when no central maven repository for your team exist or if you have a CI server

    <dependency>
        <groupId>com.stackoverflow</groupId>
        <artifactId>commons-utils</artifactId>
        <version>1.3</version>
        <scope>system</scope>
        <systemPath>${basedir}/lib/commons-utils.jar</systemPath>
    </dependency>

font awesome icon in select option

I recommend for you to use Jquery plugin selectBoxIt selectBoxIt

It is nice and simple, and you can change the arrow of drop down menu.

Change a Git remote HEAD to point to something besides master

There was almost the same question on GitHub a year ago.

The idea was to rename the master branch:

git branch -m master development
git branch -m published master
git push -f origin master 

Making master have what you want people to use, and do all other work in branches.

(a "git-symbolic-ref HEAD refs/head/published" would not be propagated to the remote repo)

This is similar to "How do I delete origin/master in Git".


As said in this thread: (emphasis mine)

"git clone" creates only a single local branch.
To do that, it looks at the HEAD ref of the remote repo, and creates a local branch with the same name as the remote branch referenced by it.

So to wrap that up, you have repo A and clone it:

  • HEAD references refs/heads/master and that exists
    -> you get a local branch called master, starting from origin/master

  • HEAD references refs/heads/anotherBranch and that exists
    -> you get a local branch called anotherBranch, starting from origin/anotherBranch

  • HEAD references refs/heads/master and that doesn't exist
    -> "git clone" complains

Not sure if there's any way to directly modify the HEAD ref in a repo.

(which is the all point of your question, I know ;) )


Maybe the only way would be a "publication for the poor", where you:

 $ git-symbolic-ref HEAD refs/head/published
 $ git-update-server-info
 $ rsync -az .git/* server:/local_path_to/git/myRepo.git/

But that would involve write access to the server, which is not always possible.


As I explain in "Git: Correct way to change Active Branch in a bare repository?", git remote set-head wouldn't change anything on the remote repo.

It would only change the remote tracking branch stored locally in your local repo, in remotes/<name>/HEAD.


With Git 2.29 (Q4 2020), "git remote set-head(man)" that failed still said something that hints the operation went through, which was misleading.

See commit 5a07c6c (17 Sep 2020) by Christian Schlack (cschlack).
(Merged by Junio C Hamano -- gitster -- in commit 39149df, 22 Sep 2020)

remote: don't show success message when set-head fails

Signed-off-by: Christian Schlack

Suppress the message 'origin/HEAD set to master' in case of an error.

$ git remote set-head origin -a
error: Not a valid ref: refs/remotes/origin/master
origin/HEAD set to master

IN-clause in HQL or Java Persistence Query Language

Using pure JPA with Hibernate 5.0.2.Final as the actual provider the following seems to work with positional parameters as well:

Entity.java:

@Entity
@NamedQueries({
    @NamedQuery(name = "byAttributes", query = "select e from Entity e where e.attribute in (?1)") })
public class Entity {
    @Column(name = "attribute")
    private String attribute;
}

Dao.java:

public class Dao {
    public List<Entity> findByAttributes(Set<String> attributes) {
        Query query = em.createNamedQuery("byAttributes");
        query.setParameter(1, attributes);

        List<Entity> entities = query.getResultList();
        return entities;
    }
}

How to access to the parent object in c#

something like this:

  public int PowerRating
    {
       get { return base.PowerRating; } // if power inherits from meter...
    }

Input widths on Bootstrap 3

In Bootstrap 3

You can simply create a custom style:

.form-control-inline {
    min-width: 0;
    width: auto;
    display: inline;
}

Then add it to form controls like so:

<div class="controls">
    <select id="expirymonth" class="form-control form-control-inline">
        <option value="01">01 - January</option>
        <option value="02">02 - February</option>
        <option value="03">03 - March</option>
        <option value="12">12 - December</option>
    </select>
    <select id="expiryyear" class="form-control form-control-inline">
        <option value="2014">2014</option>
        <option value="2015">2015</option>
        <option value="2016">2016</option>
    </select>
</div>

This way you don't have to put extra markup for layout in your HTML.

Git submodule head 'reference is not a tree' error

Assuming the submodule's repository does contain a commit you want to use (unlike the commit that is referenced from current state of the super-project), there are two ways to do it.

The first requires you to already know the commit from the submodule that you want to use. It works from the “inside, out” by directly adjusting the submodule then updating the super-project. The second works from the “outside, in” by finding the super-project's commit that modified the submodule and then reseting the super-project's index to refer to a different submodule commit.

Inside, Out

If you already know which commit you want the submodule to use, cd to the submodule, check out the commit you want, then git add and git commit it back in the super-project.

Example:

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

Oops, someone made a super-project commit that refers to an unpublished commit in the submodule sub. Somehow, we already know that we want the submodule to be at commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c. Go there and check it out directly.

Checkout in the Submodule

$ cd sub
$ git checkout 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
Note: moving to '5d5a3ee314476701a20f2c6ec4a53f88d651df6c' which isn't a local branch
If you want to create a new branch from this checkout, you may do so
(now or later) by using -b with the checkout command again. Example:
  git checkout -b <new_branch_name>
HEAD is now at 5d5a3ee... quux
$ cd ..

Since we are checking out a commit, this produces a detached HEAD in the submodule. If you want to make sure that the submodule is using a branch, then use git checkout -b newbranch <commit> to create and checkout a branch at the commit or checkout the branch that you want (e.g. one with the desired commit at the tip).

Update the Super-project

A checkout in the submodule is reflected in the super-project as a change to the working tree. So we need to stage the change in the super-project's index and verify the results.

$ git add sub

Check the Results

$ git submodule update
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The submodule update was silent because the submodule is already at the specified commit. The first diff shows that the index and worktree are the same. The third diff shows that the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.


Outside, In

If you are not sure which commit you should use from the submodule, you can look at the history in the superproject to guide you. You can also manage the reset directly from the super-project.

$ git submodule update
fatal: reference is not a tree: e47c0a16d5909d8cb3db47c81896b8b885ae1556
Unable to checkout 'e47c0a16d5909d8cb3db47c81896b8b885ae1556' in submodule path 'sub'

This is the same situation as above. But this time we will focus on fixing it from the super-project instead of dipping into the submodule.

Find the Super-project's Errant Commit

$ git log --oneline -p -- sub
ce5d37c local change in sub
diff --git a/sub b/sub
index 5d5a3ee..e47c0a1 160000
--- a/sub
+++ b/sub
@@ -1 +1 @@
-Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c
+Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
bca4663 added sub
diff --git a/sub b/sub
new file mode 160000
index 0000000..5d5a3ee
--- /dev/null
+++ b/sub
@@ -0,0 +1 @@
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

OK, it looks like it went bad in ce5d37c, so we will restore the submodule from its parent (ce5d37c~).

Alternatively, you can take the submodule's commit from the patch text (5d5a3ee314476701a20f2c6ec4a53f88d651df6c) and use the above “inside, out” process instead.

Checkout in the Super-project

$ git checkout ce5d37c~ -- sub

This reset the submodule entry for sub to what it was at commit ce5d37c~ in the super-project.

Update the Submodule

$ git submodule update
Submodule path 'sub': checked out '5d5a3ee314476701a20f2c6ec4a53f88d651df6c'

The submodule update went OK (it indicates a detached HEAD).

Check the Results

$ git diff ce5d37c~ -- sub
$ git diff
$ git diff --cached
diff --git c/sub i/sub
index e47c0a1..5d5a3ee 160000
--- c/sub
+++ i/sub
@@ -1 +1 @@
-Subproject commit e47c0a16d5909d8cb3db47c81896b8b885ae1556
+Subproject commit 5d5a3ee314476701a20f2c6ec4a53f88d651df6c

The first diff shows that sub is now the same in ce5d37c~. The second diff shows that the index and worktree are the same. The third diff shows the only staged change is moving the sub submodule to a different commit.

Commit

git commit

This commits the fixed-up submodule entry.

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

How can I get an int from stdio in C?

The solution is quite simple ... you're reading getchar() which gives you the first character in the input buffer, and scanf just parsed it (really don't know why) to an integer, if you just forget the getchar for a second, it will read the full buffer until a newline char.

printf("> ");
int x;
scanf("%d", &x);
printf("got the number: %d", x);

Outputs

> [prompt expecting input, lets write:] 1234 [Enter]
got the number: 1234

Accessing MP3 metadata with Python

easiest method is songdetails..

for read data

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    print song.artist

similarly for edit

import songdetails
song = songdetails.scan("blah.mp3")
if song is not None:
    song.artist = u"The Great Blah"
    song.save()

Don't forget to add u before name until you know chinese language.

u can read and edit in bulk using python glob module

ex.

import glob
songs = glob.glob('*')   # script should be in directory of songs.
for song in songs:
    # do the above work.

Check if an HTML input element is empty or has no value entered by user

You want:

if (document.getElementById('customx').value === ""){
    //do something
}

The value property will give you a string value and you need to compare that against an empty string.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to serve static files in Flask

The simplest way is create a static folder inside the main project folder. Static folder containing .css files.

main folder

/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)

Image of main folder containing static and templates folders and flask script

flask

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def login():
    return render_template("login.html")

html (layout)

<!DOCTYPE html>
<html>
    <head>
        <title>Project(1)</title>
        <link rel="stylesheet" href="/static/styles.css">
     </head>
    <body>
        <header>
            <div class="container">
                <nav>
                    <a class="title" href="">Kamook</a>
                    <a class="text" href="">Sign Up</a>
                    <a class="text" href="">Log In</a>
                </nav>
            </div>
        </header>  
        {% block body %}
        {% endblock %}
    </body>
</html>

html

{% extends "layout.html" %}

{% block body %}
    <div class="col">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
    </div>
{% endblock %}

What resources are shared between threads?

Thread share the heap (there is a research about thread specific heap) but current implementation share the heap. (and of course the code)

How to convert from int to string in objective c: example code

Dot grammar maybe more swift!

@(intValueDemo).stringValue 

for example

int intValueDemo  = 1;
//or
NSInteger intValueDemo = 1;

//So you can use dot grammar 
NSLog(@"%@",@(intValueDemo).stringValue);

How to resize Twitter Bootstrap modal dynamically based on the content

I simply override the css:

.modal-dialog {
    max-width: 1000px;
}

SPA best practices for authentication and session management

I would go for the second, the token system.

Did you know about ember-auth or ember-simple-auth? They both use the token based system, like ember-simple-auth states:

A lightweight and unobtrusive library for implementing token based authentication in Ember.js applications. http://ember-simple-auth.simplabs.com

They have session management, and are easy to plug into existing projects too.

There is also an Ember App Kit example version of ember-simple-auth: Working example of ember-app-kit using ember-simple-auth for OAuth2 authentication.

How to scale a UIImageView proportionally?

I used following code.where imageCoverView is UIView holds UIImageView

if (image.size.height<self.imageCoverView.bounds.size.height && image.size.width<self.imageCoverView.bounds.size.width)
{
    [self.profileImageView sizeToFit];
    self.profileImageView.contentMode =UIViewContentModeCenter
}
else
{
    self.profileImageView.contentMode =UIViewContentModeScaleAspectFit;
}

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Please note that in upcoming version of C# which is 8, the answers are not true.

All the reference types are non-nullable by default and you can actually do the following:

public string? MyNullableString; 
this.MyNullableString = null; //Valid

However,

public string MyNonNullableString; 
this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 

The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

More info

Type Checking: typeof, GetType, or is?

Performance test typeof() vs GetType():

using System;
namespace ConsoleApplication1
    {
    class Program
    {
        enum TestEnum { E1, E2, E3 }
        static void Main(string[] args)
        {
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test1(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            {
                var start = DateTime.UtcNow;
                for (var i = 0; i < 1000000000; i++)
                    Test2(TestEnum.E2);
                Console.WriteLine(DateTime.UtcNow - start);
            }
            Console.ReadLine();
        }
        static Type Test1<T>(T value) => typeof(T);
        static Type Test2(object value) => value.GetType();
    }
}

Results in debug mode:

00:00:08.4096636
00:00:10.8570657

Results in release mode:

00:00:02.3799048
00:00:07.1797128

Convert a string to integer with decimal in Python

"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.

You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).

round(float('23.45678'))

Check if number is prime number

var number;

Console.WriteLine("Accept number:");
number = Convert.ToInt32(Console.ReadLine());

if (IsPrime(number))
{
    Console.WriteLine("It is prime");
}
else
{
    Console.WriteLine("It is not prime");
}       

public static bool IsPrime(int number)
{
    if (number <= 1) return false;
    if (number == 2) return true;
    if (number % 2 == 0) return false;

    var boundary = (int)Math.Floor(Math.Sqrt(number));
          
    for (int i = 3; i <= boundary; i += 2)
        if (number % i == 0)
            return false;
    
    return true;        
}

I changed number / 2 to Math.Sqrt(number) because from in wikipedia, they said:

This routine consists of dividing n by each integer m that is greater than 1 and less than or equal to the square root of n. If the result of any of these divisions is an integer, then n is not a prime, otherwise it is a prime. Indeed, if n = a*b is composite (with a and b ?

  1. then one of the factors a or b is necessarily at most square root of n

Why doesn't GCC optimize a*a*a*a*a*a to (a*a*a)*(a*a*a)?

There are already a few good answers to this question, but for the sake of completeness I wanted to point out that the applicable section of the C standard is 5.1.2.2.3/15 (which is the same as section 1.9/9 in the C++11 standard). This section states that operators can only be regrouped if they are really associative or commutative.

How do I open port 22 in OS X 10.6.7

I couldn't solve the problem; Then I did the following and the issue was resolved: Refer here:

sudo launchctl unload -w /System/Library/LaunchDaemons/ssh.plist  
    (Supply your password when it is requested)   
sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist  
ssh -v localhost  
sudo launchctl list | grep "sshd"  
    46427   -   com.openssh.sshd  

How to set thousands separator in Java?

public String formatStr(float val) {
 return String.format(Locale.CANADA, "%,.2f", val);
}

formatStr(2524.2) // 2,254.20



Why does multiplication repeats the number several times?

In [58]: price = 1 *9
In [59]: price
Out[59]: 9

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

Telling Python to save a .txt file to a certain directory on Windows and Mac

Just use an absolute path when opening the filehandle for writing.

import os.path

save_path = 'C:/example/'

name_of_file = raw_input("What is the name of the file: ")

completeName = os.path.join(save_path, name_of_file+".txt")         

file1 = open(completeName, "w")

toFile = raw_input("Write what you want into the field")

file1.write(toFile)

file1.close()

You could optionally combine this with os.path.abspath() as described in Bryan's answer to automatically get the path of a user's Documents folder. Cheers!

Is object empty?

Lets put this baby to bed; tested under Node, Chrome, Firefox and IE 9, it becomes evident that for most use cases:

  • (for...in...) is the fastest option to use!
  • Object.keys(obj).length is 10 times slower for empty objects
  • JSON.stringify(obj).length is always the slowest (not surprising)
  • Object.getOwnPropertyNames(obj).length takes longer than Object.keys(obj).length can be much longer on some systems.

Bottom line performance wise, use:

function isEmpty(obj) { 
   for (var x in obj) { return false; }
   return true;
}

or

function isEmpty(obj) {
   for (var x in obj) { if (obj.hasOwnProperty(x))  return false; }
   return true;
}

Results under Node:

  • first result: return (Object.keys(obj).length === 0)
  • second result: for (var x in obj) { return false; }...
  • third result: for (var x in obj) { if (obj.hasOwnProperty(x)) return false; }...
  • forth result: return ('{}' === JSON.stringify(obj))

Testing for Object with 0 keys 0.00018 0.000015 0.000015 0.000324

Testing for Object with 1 keys 0.000346 0.000458 0.000577 0.000657

Testing for Object with 2 keys 0.000375 0.00046 0.000565 0.000773

Testing for Object with 3 keys 0.000406 0.000476 0.000577 0.000904

Testing for Object with 4 keys 0.000435 0.000487 0.000589 0.001031

Testing for Object with 5 keys 0.000465 0.000501 0.000604 0.001148

Testing for Object with 6 keys 0.000492 0.000511 0.000618 0.001269

Testing for Object with 7 keys 0.000528 0.000527 0.000637 0.00138

Testing for Object with 8 keys 0.000565 0.000538 0.000647 0.00159

Testing for Object with 100 keys 0.003718 0.00243 0.002535 0.01381

Testing for Object with 1000 keys 0.0337 0.0193 0.0194 0.1337

Note that if your typical use case tests a non empty object with few keys, and rarely do you get to test empty objects or objects with 10 or more keys, consider the Object.keys(obj).length option. - otherwise go with the more generic (for... in...) implementation.

Note that Firefox seem to have a faster support for Object.keys(obj).length and Object.getOwnPropertyNames(obj).length, making it a better choice for any non empty Object, but still when it comes to empty objects, the (for...in...) is simply 10 times faster.

My 2 cents is that Object.keys(obj).length is a poor idea since it creates an object of keys just to count how many keys are inside, than destroys it! In order to create that object he needs to loop overt the keys... so why use it and not the (for... in...) option :)

_x000D_
_x000D_
var a = {};_x000D_
_x000D_
function timeit(func,count) {_x000D_
   if (!count) count = 100000;_x000D_
   var start = Date.now();_x000D_
   for (i=0;i<count;i++) func();_x000D_
   var end = Date.now();_x000D_
   var duration = end - start;_x000D_
   console.log(duration/count)_x000D_
}_x000D_
_x000D_
function isEmpty1() {_x000D_
    return (Object.keys(a).length === 0)_x000D_
}_x000D_
function isEmpty2() {_x000D_
    for (x in a) { return false; }_x000D_
    return true;_x000D_
}_x000D_
function isEmpty3() {_x000D_
    for (x in a) { if (a.hasOwnProperty(x))  return false; }_x000D_
    return true;_x000D_
}_x000D_
function isEmpty4() {_x000D_
    return ('{}' === JSON.stringify(a))_x000D_
}_x000D_
_x000D_
_x000D_
for (var j=0;j<10;j++) {_x000D_
   a = {}_x000D_
   for (var i=0;i<j;i++) a[i] = i;_x000D_
   console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
   timeit(isEmpty1);_x000D_
   timeit(isEmpty2);_x000D_
   timeit(isEmpty3);_x000D_
   timeit(isEmpty4);_x000D_
}_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<100;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1);_x000D_
timeit(isEmpty2);_x000D_
timeit(isEmpty3);_x000D_
timeit(isEmpty4, 10000);_x000D_
_x000D_
a = {}_x000D_
for (var i=0;i<1000;i++) a[i] = i;_x000D_
console.log('Testing for Object with '+Object.keys(a).length+' keys')_x000D_
timeit(isEmpty1,10000);_x000D_
timeit(isEmpty2,10000);_x000D_
timeit(isEmpty3,10000);_x000D_
timeit(isEmpty4,10000);
_x000D_
_x000D_
_x000D_

How to find sitemap.xml path on websites?

The location of the sitemap affects which URLs that it can include, but otherwise there is no standard. Here is a good link with more explaination: http://www.sitemaps.org/protocol.html#location

How to print a specific row of a pandas DataFrame?

Sounds like you're calling df.plot(). That error indicates that you're trying to plot a frame that has no numeric data. The data types shouldn't affect what you print().

Use print(df.iloc[159220])

'namespace' but is used like a 'type'

if the error is

Line 26:
Line 27: @foreach (Customers customer in Model) Line 28: { Line 29:

give the full name space
like @foreach (Start.Models.customer customer in Model)

AngularJS Multiple ng-app within a page

Only one app is automatically initialized. Others have to manually initialized as follows:

Syntax:

angular.bootstrap(element, [modules]);

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="https://code.angularjs.org/1.5.8/angular.js" data-semver="1.5.8" data-require="[email protected]"></script>_x000D_
  <script data-require="[email protected]" data-semver="0.2.18" src="//cdn.rawgit.com/angular-ui/ui-router/0.2.18/release/angular-ui-router.js"></script>_x000D_
  <link rel="stylesheet" href="style.css" />_x000D_
  <script>_x000D_
    var parentApp = angular.module('parentApp', [])_x000D_
  .controller('MainParentCtrl', function($scope) {_x000D_
    $scope.name = 'universe';_x000D_
  });_x000D_
_x000D_
_x000D_
_x000D_
var childApp = angular.module('childApp', ['parentApp'])_x000D_
  .controller('MainChildCtrl', function($scope) {_x000D_
    $scope.name = 'world';_x000D_
  });_x000D_
_x000D_
_x000D_
angular.element(document).ready(function() {_x000D_
  angular.bootstrap(document.getElementById('childApp'), ['childApp']);_x000D_
});_x000D_
    _x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="childApp">_x000D_
    <div ng-controller="MainParentCtrl">_x000D_
      Hello {{name}} !_x000D_
      <div>_x000D_
        <div ng-controller="MainChildCtrl">_x000D_
          Hello {{name}} !_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

AngularJS API

Sys is undefined

Dean L's answer, https://stackoverflow.com/a/1718513/292060 worked for me, since my call to Sys was also too early. Since I'm using jQuery, instead of moving it down, I put the script inside a document.ready call:

$(document).ready(function () {
  Sys. calls here
});

This seems to be late enough that Sys is available.

Read from file in eclipse

Did you try refreshing (right click -> refresh) the project folder after copying the file in there? That will SYNC your file system with Eclipse's internal file system.

When you run Eclipse projects, the CWD (current working directory) is project's root directory. Not bin's directory. Not src's directory, but the root dir.

Also, if you're in Linux, remember that its file systems are usually case sensitive.

How to measure time in milliseconds using ANSI C?

The accepted answer is good enough.But my solution is more simple.I just test in Linux, use gcc (Ubuntu 7.2.0-8ubuntu3.2) 7.2.0.

Alse use gettimeofday, the tv_sec is the part of second, and the tv_usec is microseconds, not milliseconds.

long currentTimeMillis() {
  struct timeval time;
  gettimeofday(&time, NULL);

  return time.tv_sec * 1000 + time.tv_usec / 1000;
}

int main() {
  printf("%ld\n", currentTimeMillis());
  // wait 1 second
  sleep(1);
  printf("%ld\n", currentTimeMillis());
  return 0;
 }

It print:

1522139691342
1522139692342, exactly a second.
^

Using Ansible set_fact to create a dictionary from register results

Thank you Phil for your solution; in case someone ever gets in the same situation as me, here is a (more complex) variant:

---
# this is just to avoid a call to |default on each iteration
- set_fact:
    postconf_d: {}

- name: 'get postfix default configuration'
  command: 'postconf -d'
  register: command

# the answer of the command give a list of lines such as:
# "key = value" or "key =" when the value is null
- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >
      {{
        postconf_d |
        combine(
          dict([ item.partition('=')[::2]|map('trim') ])
        )
  with_items: command.stdout_lines

This will give the following output (stripped for the example):

"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": "hash:/etc/aliases, nis:mail.aliases",
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

Going even further, parse the lists in the 'value':

- name: 'set postfix default configuration as fact'
  set_fact:
    postconf_d: >-
      {% set key, val = item.partition('=')[::2]|map('trim') -%}
      {% if ',' in val -%}
        {% set val = val.split(',')|map('trim')|list -%}
      {% endif -%}
      {{ postfix_default_main_cf | combine({key: val}) }}
  with_items: command.stdout_lines
...
"postconf_d": {
    "alias_database": "hash:/etc/aliases", 
    "alias_maps": [
        "hash:/etc/aliases", 
        "nis:mail.aliases"
    ], 
    "allow_min_user": "no", 
    "allow_percent_hack": "yes"
}

A few things to notice:

  • in this case it's needed to "trim" everything (using the >- in YAML and -%} in Jinja), otherwise you'll get an error like:

    FAILED! => {"failed": true, "msg": "|combine expects dictionaries, got u\"  {u'...
    
  • obviously the {% if .. is far from bullet-proof

  • in the postfix case, val.split(',')|map('trim')|list could have been simplified to val.split(', '), but I wanted to point out the fact you will need to |list otherwise you'll get an error like:

    "|combine expects dictionaries, got u\"{u'...': <generator object do_map at ...
    

Hope this can help.

Is it really impossible to make a div fit its size to its content?

you can also use

word-break: break-all;

when nothing seems working this works always ;)

How to tell if browser/tab is active

I would try to set a flag on the window.onfocus and window.onblur events.

The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:

var isTabActive;

window.onfocus = function () { 
  isTabActive = true; 
}; 

window.onblur = function () { 
  isTabActive = false; 
}; 

// test
setInterval(function () { 
  console.log(window.isTabActive ? 'active' : 'inactive'); 
}, 1000);

Try it out here.

Why does JS code "var a = document.querySelector('a[data-a=1]');" cause error?

Because you need parentheses around the value your looking for. So here : document.querySelector('a[data-a="1"]')

If you don't know in advance the value but is looking for it via variable you can use template literals :

Say we have divs with data-price

<div data-price="99">My okay price</div>
<div data-price="100">My too expensive price</div>

We want to find an element but with the number that someone chose (so we don't know it):

// User chose 99    
let chosenNumber = 99
document.querySelector(`[data-price="${chosenNumber}"`]

How do I make a list of data frames?

I consider myself a complete newbie, but I think I have an extremely simple answer to one of the original subquestions that has not been stated here: accessing the data frames, or parts of it.

Let's start by creating the list with data frames as was stated above:

d1 <- data.frame(y1 = c(1, 2, 3), y2 = c(4, 5, 6))

d2 <- data.frame(y1 = c(3, 2, 1), y2 = c(6, 5, 4))

my.list <- list(d1, d2)

Then, if you want to access a specific value in one of the data frames, you can do so by using the double brackets sequentially. The first set gets you into the data frame, and the second set gets you to the specific coordinates:

my.list[[1]][[3,2]]

[1] 6

Private Variables and Methods in Python

Please note that there is no such thing as "private method" in Python. Double underscore is just name mangling:

>>> class A(object):
...     def __foo(self):
...         pass
... 
>>> a = A()
>>> A.__dict__.keys()
['__dict__', '_A__foo', '__module__', '__weakref__', '__doc__']
>>> a._A__foo()

So therefore __ prefix is useful when you need the mangling to occur, for example to not clash with names up or below inheritance chain. For other uses, single underscore would be better, IMHO.

EDIT, regarding confusion on __, PEP-8 is quite clear on that:

If your class is intended to be subclassed, and you have attributes that you do not want subclasses to use, consider naming them with double leading underscores and no trailing underscores. This invokes Python's name mangling algorithm, where the name of the class is mangled into the attribute name. This helps avoid attribute name collisions should subclasses inadvertently contain attributes with the same name.

Note 3: Not everyone likes name mangling. Try to balance the need to avoid accidental name clashes with potential use by advanced callers.

So if you don't expect subclass to accidentally re-define own method with same name, don't use it.

what is the difference between json and xml

They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:

JSON:

{
  "persons": [
    {
      "name": "Ford Prefect",
      "gender": "male"
    },
    {
      "name": "Arthur Dent",
      "gender": "male"
    },
    {
      "name": "Tricia McMillan",
      "gender": "female"
    }
  ]
}

XML:

<persons>
  <person>
    <name>Ford Prefect</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Arthur Dent</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Tricia McMillan</name>
    <gender>female</gender>
  </person>
</persons>

The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.

The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.

While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).

++i or i++ in for loops ??

Personal preference.

Usually. Sometimes it matters but, not to seem like a jerk here, but if you have to ask, it probably doesn't.

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

I had a similar problem not being able to access phpmyadmin on a testing server after changing the root password. I tried everything mentioned above, including advice from other forums, using all kinds of variations to the config files. THEN I remembered that Google Chrome has some issues working with a testing server. The reason is that Chrome has a security feature to prevent local hard drive access from a remote website - unfortunately this can cause issues in a testing environment because the server is a local hard drive. When I tried to log in to phpmyadmin with Internet Explorer it worked fine. I tried several tests of Chrome v IE9, and Chrome would not work under any configuration with the root password set. I also tested Firefox it also worked fine, the issue is only with Chrome. My advice: if you're on a testing server make sure your config file has the correct settings as described above, but if the problem continues and you're using Chrome try a different browser.

How do I get an OAuth 2.0 authentication token in C#

You may use the following code to get the bearer token.

private string GetBearerToken()
{
    var client = new RestClient("https://service.endpoint.com");
    client.Authenticator = new HttpBasicAuthenticator("abc", "123");
    var request = new RestRequest("api/oauth2/token", Method.POST);
    request.AddHeader("content-type", "application/json");
    request.AddParameter("application/json", "{ \"grant_type\":\"client_credentials\" }", 
    ParameterType.RequestBody);
    var responseJson = _client.Execute(request).Content;
    var token = JsonConvert.DeserializeObject<Dictionary<string, object>>(responseJson)["access_token"].ToString();
    if(token.Length == 0)
    {
        throw new AuthenticationException("API authentication failed.");
    }
    return token;
}

How do I add 24 hours to a unix timestamp in php?

A Unix timestamp is simply the number of seconds since January the first 1970, so to add 24 hours to a Unix timestamp we just add the number of seconds in 24 hours. (24 * 60 *60)

time() + 24*60*60;

Select unique values with 'select' function in 'dplyr' library

Just to add to the other answers, if you would prefer to return a vector rather than a dataframe, you have the following options:

dplyr < 0.7.0

Enclose the dplyr functions in a parentheses and combine it with $ syntax:

(mtcars %>% distinct(cyl))$cyl

dplyr >= 0.7.0

Use the pull verb:

mtcars %>% distinct(cyl) %>% pull()

PHP - count specific array values

You can do this with array_keys and count.

$array = array("blue", "red", "green", "blue", "blue");
echo count(array_keys($array, "blue"));

Output:

3

Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

using Pure Js

function arr(){
  var a= [1,2,3,4,5,34,2,5,7,8,6,4,3,25,8,34,56,7,8,76,4,23,34,46,575,8564,53,5345657566];
  var b= [];
  b.push(a[0]);
  var z=0;

  for(var i=0; i< a.length; i++){
      for(var j=0; j< b.length; j++){
        if(b[j] == a[i]){
          z = 0;
          break;
        }
        else
          z = 1;
      }
      if(z)
        b.push(a[i]);
    }
  console.log(b);
}

Java: Difference between the setPreferredSize() and setSize() methods in components

Usage depends on whether the component's parent has a layout manager or not.

  • setSize() -- use when a parent layout manager does not exist;
  • setPreferredSize() (also its related setMinimumSize and setMaximumSize) -- use when a parent layout manager exists.

The setSize() method probably won't do anything if the component's parent is using a layout manager; the places this will typically have an effect would be on top-level components (JFrames and JWindows) and things that are inside of scrolled panes. You also must call setSize() if you've got components inside a parent without a layout manager.

Generally, setPreferredSize() will lay out the components as expected if a layout manager is present; most layout managers work by getting the preferred (as well as minimum and maximum) sizes of their components, then using setSize() and setLocation() to position those components according to the layout's rules.

For example, a BorderLayout tries to make the bounds of its "north" region equal to the preferred size of its north component---they may end up larger or smaller than that, depending on the size of the JFrame, the size of the other components in the layout, and so on.

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I faced the same error today, using React with Typescript and a back-end using Java Spring boot, if you have a hand on your back-end you can simply add a configuration file for the CORS.

For the below example I set allowed origin to * to allow all but you can be more specific and only set url like http://localhost:3000.

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
public class AppCorsConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    }
}

Keep SSH session alive

putty settings

FYI Putty Users can set the options here

SSL Proxy/Charles and Android trouble

Edit - this answer was for an earlier version of Charles. See @semicircle21 answer below for the proper steps for v3.10.x -- much easier than this approach too... :-)

For what it's worth here are the step by step instructions for this. They should apply equally well in iOS too:

  1. Open Charles
  2. Go to Proxy > Proxy Settings > SSL
  3. Check “Enable SSL Proxying”
  4. Select “Add location” and enter the host name and port (if needed)
  5. Click ok and make sure the option is checked
  6. Download the Charles cert from here: Charles cert >
  7. Send that file to yourself in an email.
  8. Open the email on your device and select the cert
  9. In “Name the certificate” enter whatever you want
  10. Click OK and you should get a message that the certificate was installed

You should then be able to see the SSL files in Charles. If you want to intercept and change the values you can use the "Map Local" tool which is really awesome:

  1. In Charles go to Tools > Map Local
  2. Select "Add entry"
  3. Enter the values for the file you want to replace
  4. In “Local path” select the file you want the app to load instead
  5. Click OK
  6. Make sure the entry is selected and click OK
  7. Run your app
  8. You should see in “Notes” that your file loads instead of the live one

Getting Spring Application Context

Note that by storing any state from the current ApplicationContext, or the ApplicationContext itself in a static variable - for example using the singleton pattern - you will make your tests unstable and unpredictable if you're using Spring-test. This is because Spring-test caches and reuses application contexts in the same JVM. For example:

  1. Test A run and it is annotated with @ContextConfiguration({"classpath:foo.xml"}).
  2. Test B run and it is annotated with @ContextConfiguration({"classpath:foo.xml", "classpath:bar.xml})
  3. Test C run and it is annotated with @ContextConfiguration({"classpath:foo.xml"})

When Test A runs, an ApplicationContext is created, and any beans implemeting ApplicationContextAware or autowiring ApplicationContext might write to the static variable.

When Test B runs the same thing happens, and the static variable now points to Test B's ApplicationContext

When Test C runs, no beans are created as the TestContext (and herein the ApplicationContext) from Test A is resused. Now you got a static variable pointing to another ApplicationContext than the one currently holding the beans for your test.

How to remove a class from elements in pure JavaScript?

This might help

let allElements = Array.from(document.querySelectorAll('.widget.hover'))
for (let element of allElements) {
  element.classList.remove('hover')
}

Copy and Paste a set range in the next empty row

You could also try this

Private Sub CommandButton1_Click()

Sheets("Sheet1").Range("A3:E3").Copy

Dim lastrow As Long
lastrow = Range("A65536").End(xlUp).Row

Sheets("Summary Info").Activate
Cells(lastrow + 1, 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

End Sub

Elegant way to check for missing packages and install them?

This is the purpose of the rbundler package: to provide a way to control the packages that are installed for a specific project. Right now the package works with the devtools functionality to install packages to your project's directory. The functionality is similar to Ruby's bundler.

If your project is a package (recommended) then all you have to do is load rbundler and bundle the packages. The bundle function will look at your package's DESCRIPTION file to determine which packages to bundle.

library(rbundler)
bundle('.', repos="http://cran.us.r-project.org")

Now the packages will be installed in the .Rbundle directory.

If your project isn't a package, then you can fake it by creating a DESCRIPTION file in your project's root directory with a Depends field that lists the packages that you want installed (with optional version information):

Depends: ggplot2 (>= 0.9.2), arm, glmnet

Here's the github repo for the project if you're interested in contributing: rbundler.

How to use glyphicons in bootstrap 3.0

This might help. It contains many examples which will be useful in understanding.

http://www.w3schools.com/bootstrap/bootstrap_ref_comp_glyphs.asp

Convert java.util.Date to String

It looks like you are looking for SimpleDateFormat.

Format: yyyy-MM-dd kk:mm:ss

React native ERROR Packager can't listen on port 8081

On a mac, run the following command to find id of the process which is using port 8081
sudo lsof -i :8081
Then run the following to terminate process:
kill -9 23583

Here is how it will look like enter image description here

Equation for testing if a point is inside a circle

Mathematically, Pythagoras is probably a simple method as many have already mentioned.

(x-center_x)^2 + (y - center_y)^2 < radius^2

Computationally, there are quicker ways. Define:

dx = abs(x-center_x)
dy = abs(y-center_y)
R = radius

If a point is more likely to be outside this circle then imagine a square drawn around it such that it's sides are tangents to this circle:

if dx>R then 
    return false.
if dy>R then 
    return false.

Now imagine a square diamond drawn inside this circle such that it's vertices touch this circle:

if dx + dy <= R then 
    return true.

Now we have covered most of our space and only a small area of this circle remains in between our square and diamond to be tested. Here we revert to Pythagoras as above.

if dx^2 + dy^2 <= R^2 then 
    return true
else 
    return false.

If a point is more likely to be inside this circle then reverse order of first 3 steps:

if dx + dy <= R then 
    return true.
if dx > R then 
    return false.
if dy > R 
    then return false.
if dx^2 + dy^2 <= R^2 then 
    return true
else
    return false.

Alternate methods imagine a square inside this circle instead of a diamond but this requires slightly more tests and calculations with no computational advantage (inner square and diamonds have identical areas):

k = R/sqrt(2)
if dx <= k and dy <= k then 
    return true.

Update:

For those interested in performance I implemented this method in c, and compiled with -O3.

I obtained execution times by time ./a.out

I implemented this method, a normal method and a dummy method to determine timing overhead.

Normal: 21.3s This: 19.1s Overhead: 16.5s

So, it seems this method is more efficient in this implementation.

// compile gcc -O3 <filename>.c
// run: time ./a.out

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

#define TRUE  (0==0)
#define FALSE (0==1)

#define ABS(x) (((x)<0)?(0-(x)):(x))

int xo, yo, R;

int inline inCircle( int x, int y ){  // 19.1, 19.1, 19.1
  int dx = ABS(x-xo);
  if (    dx >  R ) return FALSE;
  int dy = ABS(y-yo);
  if (    dy >  R ) return FALSE;
  if ( dx+dy <= R ) return TRUE;
  return ( dx*dx + dy*dy <= R*R );
}

int inline inCircleN( int x, int y ){  // 21.3, 21.1, 21.5
  int dx = ABS(x-xo);
  int dy = ABS(y-yo);
  return ( dx*dx + dy*dy <= R*R );
}

int inline dummy( int x, int y ){  // 16.6, 16.5, 16.4
  int dx = ABS(x-xo);
  int dy = ABS(y-yo);
  return FALSE;
}

#define N 1000000000

int main(){
  int x, y;
  xo = rand()%1000; yo = rand()%1000; R = 1;
  int n = 0;
  int c;
  for (c=0; c<N; c++){
    x = rand()%1000; y = rand()%1000;
//    if ( inCircle(x,y)  ){
    if ( inCircleN(x,y) ){
//    if ( dummy(x,y) ){
      n++;
    }
  }
  printf( "%d of %d inside circle\n", n, N);
}

Are lists thread-safe?

I recently had this case where I needed to append to a list continuously in one thread, loop through the items and check if the item was ready, it was an AsyncResult in my case and remove it from the list only if it was ready. I could not find any examples that demonstrated my problem clearly Here is an example demonstrating adding to list in one thread continuously and removing from the same list in another thread continuously The flawed version runs easily on smaller numbers but keep the numbers big enough and run a few times and you will see the error

The FLAWED version

import threading
import time

# Change this number as you please, bigger numbers will get the error quickly
count = 1000
l = []

def add():
    for i in range(count):
        l.append(i)
        time.sleep(0.0001)

def remove():
    for i in range(count):
        l.remove(i)
        time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output when ERROR

Exception in thread Thread-63:
Traceback (most recent call last):
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/Users/zup/.pyenv/versions/3.6.8/lib/python3.6/threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "<ipython-input-30-ecfbac1c776f>", line 13, in remove
    l.remove(i)
ValueError: list.remove(x): x not in list

Version that uses locks

import threading
import time
count = 1000
l = []
lock = threading.RLock()
def add():
    with lock:
        for i in range(count):
            l.append(i)
            time.sleep(0.0001)

def remove():
    with lock:
        for i in range(count):
            l.remove(i)
            time.sleep(0.0001)


t1 = threading.Thread(target=add)
t2 = threading.Thread(target=remove)
t1.start()
t2.start()
t1.join()
t2.join()

print(l)

Output

[] # Empty list

Conclusion

As mentioned in the earlier answers while the act of appending or popping elements from the list itself is thread safe, what is not thread safe is when you append in one thread and pop in another

Animate a custom Dialog

Try below code:

public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));// set transparent in window background

        View _v = inflater.inflate(R.layout.some_you_layout, container, false);

        //load animation
        //Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), android.R.anim.fade_in);// system animation appearance
        Animation transition_in_view = AnimationUtils.loadAnimation(getContext(), R.anim.customer_anim);//customer animation appearance

        _v.setAnimation( transition_in_view );
        _v.startAnimation( transition_in_view );
        //really beautiful
        return _v;

    }

Create the custom Anim.: res/anim/customer_anim.xml:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">

    <translate
        android:duration="500"
        android:fromYDelta="100%"
        android:toYDelta="-7%"/>
    <translate
        android:duration="300"
        android:startOffset="500"
        android:toYDelta="7%" />
    <translate
        android:duration="200"
        android:startOffset="800"
        android:toYDelta="0%" />

</set>

Use of document.getElementById in JavaScript

Consider

 var x = document.getElementById("age");

Here x is the element with id="age".

Now look at the following line

var age = document.getElementById("age").value;

this means you are getting the value of the element which has id="age"

Relay access denied on sending mail, Other domain outside of network

If it is giving you relay access denied when you are trying to send an email from outside your network to a domain that your server is not authoritative for then it means your receive connector does not grant you the permissions for sending/relaying. Most likely what you need to do is to authenticate to the server to be granted the permissions for relaying but that does depend upon the configuration of your receive connector. In Exchange 2007/2010/2013 you would need to enable ExchangeUsers permission group as well as an authentication mechanism such as Basic authentication.

Once you're sure your receive connector is configured make sure your email client is configured for authentication as well for the SMTP server. It depends upon your server setup but normally for Exchange you would configure the username by itself, no need for the domain to appended or prefixed to it.

To test things out with authentication via telnet you can go over my post here for directions: https://jefferyland.wordpress.com/2013/05/28/essential-exchange-troubleshooting-send-email-via-telnet/

Check if a variable is between two numbers with Java

public static boolean between(int i, int minValueInclusive, int maxValueInclusive) {
    if (i >= minValueInclusive && i <= maxValueInclusive)
        return true;
    else
        return false;
}

https://alvinalexander.com/java/java-method-integer-is-between-a-range

How to write log to file

I prefer the simplicity and flexibility of the 12 factor app recommendation for logging. To append to a log file you can use shell redirection. The default logger in Go writes to stderr (2).

./app 2>> logfile

See also: http://12factor.net/logs

How to swap two variables in JavaScript

Because I hear this method runs slower:

b = [a, a = b][0];

If you plan on storing your vars in an object (or array), this function should work:

function swapVars(obj, var1, var2){
    let temp = obj[var1];
    obj[var1] = obj[var2];
    obj[var2] = temp;
}

Usage:

let test = {a: 'test 1', b: 'test 2'};

console.log(test); //output: {a: 'test 1', b: 'test 2'}

swapVars(test, 'a', 'b');

console.log(test); //output: {a: 'test 2', b: 'test 1'}

HTTP Range header

As Wrikken suggested, it's a valid request. It's also quite common when the client is requesting media or resuming a download.

A client will often test to see if the server handles ranged requests other than just looking for an Accept-Ranges response. Chrome always sends a Range: bytes=0- with its first GET request for a video, so it's something you can't dismiss.

Whenever a client includes Range: in its request, even if it's malformed, it's expecting a partial content (206) response. When you seek forward during HTML5 video playback, the browser only requests the starting point. For example:

Range: bytes=3744-

So, in order for the client to play video properly, your server must be able to handle these incomplete range requests.

You can handle the type of 'range' you specified in your question in two ways:

First, You could reply with the requested starting point given in the response, then the total length of the file minus one (the requested byte range is zero-indexed). For example:

Request:

GET /BigBuckBunny_320x180.mp4 
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/64656927

Second, you could reply with the starting point given in the request and an open-ended file length (size). This is for webcasts or other media where the total length is unknown. For example:

Request:

GET /BigBuckBunny_320x180.mp4
Range: bytes=100-

Response:

206 Partial Content
Content-Type: video/mp4
Content-Length: 64656927
Accept-Ranges: bytes
Content-Range: bytes 100-64656926/*

Tips:

You must always respond with the content length included with the range. If the range is complete, with start to end, then the content length is simply the difference:

Request: Range: bytes=500-1000

Response: Content-Range: bytes 500-1000/123456

Remember that the range is zero-indexed, so Range: bytes=0-999 is actually requesting 1000 bytes, not 999, so respond with something like:

Content-Length: 1000
Content-Range: bytes 0-999/123456

Or:

Content-Length: 1000
Content-Range: bytes 0-999/*

But, avoid the latter method if possible because some media players try to figure out the duration from the file size. If your request is for media content, which is my hunch, then you should include its duration in the response. This is done with the following format:

X-Content-Duration: 63.23 

This must be a floating point. Unlike Content-Length, this value doesn't have to be accurate. It's used to help the player seek around the video. If you are streaming a webcast and only have a general idea of how long it will be, it's better to include your estimated duration rather than ignore it altogether. So, for a two-hour webcast, you could include something like:

X-Content-Duration: 7200.00 

With some media types, such as webm, you must also include the content-type, such as:

Content-Type: video/webm 

All of these are necessary for the media to play properly, especially in HTML5. If you don't give a duration, the player may try to figure out the duration (to allow for seeking) from its file size, but this won't be accurate. This is fine, and necessary for webcasts or live streaming, but not ideal for playback of video files. You can extract the duration using software like FFMPEG and save it in a database or even the filename.

X-Content-Duration is being phased out in favor of Content-Duration, so I'd include that too. A basic, response to a "0-" request would include at least the following:

HTTP/1.1 206 Partial Content
Date: Sun, 08 May 2013 06:37:54 GMT
Server: Apache/2.0.52 (Red Hat)
Accept-Ranges: bytes
Content-Length: 3980
Content-Range: bytes 0-3979/3980
Content-Type: video/webm
X-Content-Duration: 2054.53
Content-Duration: 2054.53

One more point: Chrome always starts its first video request with the following:

Range: bytes=0-

Some servers will send a regular 200 response as a reply, which it accepts (but with limited playback options), but try to send a 206 instead to show than your server handles ranges. RFC 2616 says it's acceptable to ignore range headers.

How do I fix a NoSuchMethodError?

If you are writing a webapp, ensure that you don't have conflicting versions of a jar in your container's global library directory and also in your app. You may not necessarily know which jar is being used by the classloader.

e.g.

  • tomcat/common/lib
  • mywebapp/WEB-INF/lib

Running CMake on Windows

There is a vcvars32.bat in your Visual Studio installation directory. You can add call cmd.exe at the end of that batch program and launch it. From that shell you can use CMake or cmake-gui and cl.exe would be known to CMake.

Calculating the area under a curve given a set of coordinates, without knowing the function

The numpy and scipy libraries include the composite trapezoidal (numpy.trapz) and Simpson's (scipy.integrate.simps) rules.

Here's a simple example. In both trapz and simps, the argument dx=5 indicates that the spacing of the data along the x axis is 5 units.

from __future__ import print_function

import numpy as np
from scipy.integrate import simps
from numpy import trapz


# The y values.  A numpy array is used here,
# but a python list could also be used.
y = np.array([5, 20, 4, 18, 19, 18, 7, 4])

# Compute the area using the composite trapezoidal rule.
area = trapz(y, dx=5)
print("area =", area)

# Compute the area using the composite Simpson's rule.
area = simps(y, dx=5)
print("area =", area)

Output:

area = 452.5
area = 460.0

Get filename in batch for loop

If you want to remain both filename (only) and extension, you may use %~nxF:

FOR /R C:\Directory %F in (*.*) do echo %~nxF

How do you get the length of a list in the JSF expression language?

You mean size() don't you?

#{MyBean.somelist.size()}

works for me (using JBoss Seam which has the Jboss EL extensions)

How to call a stored procedure from Java and JPA

For me, only the following worked with Oracle 11g and Glassfish 2.1 (Toplink):

Query query = entityManager.createNativeQuery("BEGIN PROCEDURE_NAME(); END;");
query.executeUpdate();

The variant with curly braces resulted in ORA-00900.

How to use Git Revert

The question is quite old but revert is still confusing people (like me)

As a beginner, after some trial and error (more errors than trials) I've got an important point:

  • git revert requires the id of the commit you want to remove keeping it into your history

  • git reset requires the commit you want to keep, and will consequentially remove anything after that from history.

That is, if you use revert with the first commit id, you'll find yourself into an empty directory and an additional commit in history, while with reset your directory will be.. reverted back to the initial commit and your history will get as if the last commit(s) never happened.

To be even more clear, with a log like this:

# git log --oneline

cb76ee4 wrong
01b56c6 test
2e407ce first commit

Using git revert cb76ee4 will by default bring your files back to 01b56c6 and will add a further commit to your history:

8d4406b Revert "wrong"
cb76ee4 wrong
01b56c6 test
2e407ce first commit

git reset 01b56c6 will instead bring your files back to 01b56c6 and will clean up any other commit after that from your history :

01b56c6 test
2e407ce first commit

I know these are "the basis" but it was quite confusing for me, by running revert on first id ('first commit') I was expecting to find my initial files, it taken a while to understand, that if you need your files back as 'first commit' you need to use the next id.

Convert from DateTime to INT

EDIT: Casting to a float/int no longer works in recent versions of SQL Server. Use the following instead:

select datediff(day, '1899-12-30T00:00:00', my_date_field)
from mytable

Note the string date should be in an unambiguous date format so that it isn't affected by your server's regional settings.


In older versions of SQL Server, you can convert from a DateTime to an Integer by casting to a float, then to an int:

select cast(cast(my_date_field as float) as int)
from mytable

(NB: You can't cast straight to an int, as MSSQL rounds the value up if you're past mid day!)

If there's an offset in your data, you can obviously add or subtract this from the result

You can convert in the other direction, by casting straight back:

select cast(my_integer_date as datetime)
from mytable

How to pass an array within a query string?

You can use http_build_query to generate a URL-encoded querystring from an array in PHP. Whilst the resulting querystring will be expanded, you can decide on a unique separator you want as a parameter to the http_build_query method, so when it comes to decoding, you can check what separator was used. If it was the unique one you chose, then that would be the array querystring otherwise it would be the normal querystrings.

How do I find the length (or dimensions, size) of a numpy matrix in python?

matrix.size according to the numpy docs returns the Number of elements in the array. Hope that helps.

How do I include a JavaScript script file in Angular and call a function from that script?

In order to include a global library, eg jquery.js file in the scripts array from angular-cli.json (angular.json when using angular 6+):

"scripts": [
  "../node_modules/jquery/dist/jquery.js"
]

After this, restart ng serve if it is already started.

phpmyadmin logs out after 1440 secs

I have found the solution and using it successfully for sometime now.

Just install this Addon to your FF browser.

How to catch exception output from Python subprocess.check_output()?

There are good answers here, but in these answers, there has not been an answer that comes up with the text from the stack-trace output, which is the default behavior of an exception.

If you wish to use that formatted traceback information, you might wish to:

import traceback

try:
    check_call( args )
except CalledProcessError:
    tb = traceback.format_exc()
    tb = tb.replace(passwd, "******")
    print(tb)
    exit(1)

As you might be able to tell, the above is useful in case you have a password in the check_call( args ) that you wish to prevent from displaying.

Marquee text in Android

Here is an example:

public class TextViewMarquee extends Activity {
    private TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        tv = (TextView) this.findViewById(R.id.mywidget);  
        tv.setSelected(true);  // Set focus to the textview
    }
}

The xml file with the textview:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <TextView
        android:id="@+id/mywidget"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:singleLine="true"
        android:ellipsize="marquee"
        android:fadingEdge="horizontal"
        android:marqueeRepeatLimit="marquee_forever"
        android:scrollHorizontally="true"
        android:textColor="#ff4500"
        android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

There are Following Steps to solve this issue.


1. Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists.
2. Delete all the files and folders from dists folder.
3. If Android Studio is Opened then Close any opened project and Reopen the project. The Android Studio Will automatic download all the required files.


(The required time is as per your Internet Speed (Download Size will be about "89 MB"). To see the progress of the downloading Go to C:\Users\ ~User Name~ \.gradle\wrapper\dists folder and check the size of the folder.)

How to define a Sql Server connection string to use in VB.NET?

Try

Dim connectionString AS String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"

And replace my_server, name_of_db, user_name and my_password with your values.

then Using sqlCon = New SqlConnection(connectionString) should work

also I think your SQL is wrong, it should be SET clickCount= clickCount + 1 I think.

And on a general note, the page you link to has a link called Connection String which shows you how to do this.

Run a vbscript from another vbscript

See if the following works

Dim objShell
Set objShell = Wscript.CreateObject("WScript.Shell")

objShell.Run "TestScript.vbs" 

' Using Set is mandatory
Set objShell = Nothing

Python check if list items are integers?

Fast, simple, but maybe not always right:

>>> [x for x in mylist if x.isdigit()]
['1', '2', '3', '4']

More traditional if you need to get numbers:

new_list = []
for value in mylist:
    try:
        new_list.append(int(value))
    except ValueError:
        continue

Note: The result has integers. Convert them back to strings if needed, replacing the lines above with:

try:
    new_list.append(str(int(value)))

get the data of uploaded file in javascript

The example below shows the basic usage of the FileReader to read the contents of an uploaded file. Here is a working Plunker of this example.

<!DOCTYPE html>
<html>
  <head>
    <script src="script.js"></script>
  </head>

  <body onload="init()">
    <input id="fileInput" type="file" name="file" />
    <pre id="fileContent"></pre>
  </body>
</html>

script.js

function init(){
  document.getElementById('fileInput').addEventListener('change', handleFileSelect, false);
}

function handleFileSelect(event){
  const reader = new FileReader()
  reader.onload = handleFileLoad;
  reader.readAsText(event.target.files[0])
}

function handleFileLoad(event){
  console.log(event);
  document.getElementById('fileContent').textContent = event.target.result;
}

Select max value of each group

select * from (select * from table order by value desc limit 999999999) v group by v.name

How do I close a single buffer (out of many) in Vim?

Use:

  • :ls - to list buffers
  • :bd#n - to close buffer where #n is the buffer number (use ls to get it)

Examples:

  • to delete buffer 2:

    :bd2
    

I cannot access tomcat admin console?

If you are running tomcat from eclipse (probably problem exists with another IDEs), it could have a different configuration- not based on files .

The solution is to edit tomcat users file, as you wrote, and then start tomcat from command prompt with

{tomcat-directory}/bin/startup

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

Autoincrement VersionCode with gradle extra properties

There are two solutions I really like. The first depends on the Play Store and the other depends on Git.

Using the Play Store, you can increment the version code by looking at the highest available uploaded version code. The benefit of this solution is that an APK upload will never fail since your version code is always one higher than whatever is on the Play Store. The downside is that distributing your APK outside of the Play Store becomes more difficult. You can set this up using Gradle Play Publisher by following the quickstart guide and telling the plugin to resolve version codes automatically:

plugins {
    id 'com.android.application'
    id 'com.github.triplet.play' version 'x.x.x'
}

android {
    ...
}

play {
    serviceAccountCredentials = file("your-credentials.json")
    resolutionStrategy = "auto"
}

Using Git, you can increment the version code based on how many commits and tags your repository has. The benefit here is that your output is reproducible and doesn't depend on anything outside your repo. The downside is that you have to make a new commit or tag to bump your version code. You can set this up by adding the Version Master Gradle plugin:

plugins {
    id 'com.android.application'
    id 'com.supercilex.gradle.versions' version 'x.x.x'
}

android {
    ...
}

How/When does Execute Shell mark a build as failure in Jenkins?

Simple and short answer to your question is

Please add following line into your "Execute shell" Build step.

#!/bin/sh

Now let me explain you the reason why we require this line for "Execute Shell" build job.

By default Jenkins take /bin/sh -xe and this means -x will print each and every command.And the other option -e, which causes shell to stop running a script immediately when any command exits with non-zero (when any command fails) exit code.

So by adding the #!/bin/sh will allow you to execute with no option.

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Jackson - best way writes a java list to a json array

This is overly complicated, Jackson handles lists via its writer methods just as well as it handles regular objects. This should work just fine for you, assuming I have not misunderstood your question:

public void writeListToJsonArray() throws IOException {  
    final List<Event> list = new ArrayList<Event>(2);
    list.add(new Event("a1","a2"));
    list.add(new Event("b1","b2"));

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    final ObjectMapper mapper = new ObjectMapper();

    mapper.writeValue(out, list);

    final byte[] data = out.toByteArray();
    System.out.println(new String(data));
}

Reading Data From Database and storing in Array List object

You are reusing the customer reference. Java works by reference for Obejcts. Not for primitives.

What you are doing is adding to the list the same customer and then modifying it. Thus setting the same values for all of objects. That's why you see the last. Because all are the same.

 while (rs.next()) {
        Customer customer = new Customer();
        customer.setId(rs.getInt("id"));

        ...

How to present UIAlertController when not in a view controller?

Shorthand way to do present the alert in Objective-C:

[[[[UIApplication sharedApplication] keyWindow] rootViewController] presentViewController:alertController animated:YES completion:nil];

Where alertController is your UIAlertController object.

NOTE: You'll also need to make sure your helper class extends UIViewController

What is the best way to get all the divisors of a number?

If you only care about using list comprehensions and nothing else matters to you!

from itertools import combinations
from functools import reduce

def get_devisors(n):
    f = [f for f,e in list(factorGenerator(n)) for i in range(e)]
    fc = [x for l in range(len(f)+1) for x in combinations(f, l)]
    devisors = [1 if c==() else reduce((lambda x, y: x * y), c) for c in set(fc)]
    return sorted(devisors)

Unable to show a Git tree in terminal

A solution is to create an Alias in your .gitconfig and call it easily:

[alias]
    tree = log --graph --decorate --pretty=oneline --abbrev-commit

And when you call it next time, you'll use:

git tree

To put it in your ~/.gitconfig without having to edit it, you can do:

git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"  

(If you don't use the --global it will put it in the .git/config of your current repo.)

How to initialize an array in one step using Ruby?

To prove There's More Than One Six Ways To Do It:

plus_1 = 1.method(:+)
Array.new(3, &plus_1) # => [1, 2, 3]

If 1.method(:+) wasn't possible, you could also do

plus_1 = Proc.new {|n| n + 1}
Array.new(3, &plus_1) # => [1, 2, 3]

Sure, it's overkill in this scenario, but if plus_1 was a really long expression, you might want to put it on a separate line from the array creation.

Simple JavaScript problem: onClick confirm not preventing default action

If you want to use small inline commands in the onclick tag you could go with something like this.

<button id="" class="delete" onclick="javascript:if(confirm('Are you sure you want to delete this entry?')){jQuery(this).parent().remove(); return false;}" type="button"> Delete </button>

font-weight is not working properly?

Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

How to control the width and height of the default Alert Dialog in Android?

This works as well by adding .getWindow().setLayout(width, height) after show()

alertDialogBuilder
            .setMessage("Click yes to exit!")
            .setCancelable(false)
            .setPositiveButton("Yes",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, close
                    // current activity
                    MainActivity.this.finish();
                }
              })
            .setNegativeButton("No",new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog,int id) {
                    // if this button is clicked, just close
                    // the dialog box and do nothing
                    dialog.cancel();
                }
            }).show().getWindow().setLayout(600,500);

What is the proper #include for the function 'sleep()'?

What is the proper #include for the function 'sleep()'?

sleep() isn't Standard C, but POSIX so it should be:

#include <unistd.h>

Difference between INNER JOIN and LEFT SEMI JOIN

An INNER JOIN can return data from the columns from both tables, and can duplicate values of records on either side have more than one match. A LEFT SEMI JOIN can only return columns from the left-hand table, and yields one of each record from the left-hand table where there is one or more matches in the right-hand table (regardless of the number of matches). It's equivalent to (in standard SQL):

SELECT name
FROM table_1 a
WHERE EXISTS(
    SELECT * FROM table_2 b WHERE (a.name=b.name))

If there are multiple matching rows in the right-hand column, an INNER JOIN will return one row for each match on the right table, while a LEFT SEMI JOIN only returns the rows from the left table, regardless of the number of matching rows on the right side. That's why you're seeing a different number of rows in your result.

I am trying to get the names within table_1 that only appear in table_2.

Then a LEFT SEMI JOIN is the appropriate query to use.

Create table (structure) from existing table

try this.. the below one copy the entire structure of the existing table but not the data.

create table AT_QUOTE_CART as select * from QUOTE_CART where 0=1 ;

if you want to copy the data then use the below one:

create table AT_QUOTE_CART as select * from QUOTE_CART ;

Merge development branch with master

If you are using gerrit, the following commands work perfectly.

git checkout master
git merge --no-ff development

You can save with the default commit message. Make sure, the change id has been generated. You can use the following command to make sure.

git commit --amend

Then push with the following command.

git push origin HEAD:refs/for/refs/heads/master

You might encounter an error message like the below.

! [remote rejected] HEAD -> refs/for/refs/heads/master (you are not allowed to upload merges)

To resolve this, the gerrit project admin has to create another reference in gerrit named 'refs/for/refs/heads/master' or 'refs/for/refs/heads/*' (which will cover all branches in future). Then grant 'Push Merge Commit' permission to this reference and 'Submit' permission if required to Submit the GCR.

Now, try the above push command again, and it should work.

Credits:

https://github.com/ReviewAssistant/reviewassistant/wiki/Merging-branches-in-Gerrit

https://stackoverflow.com/a/21199818/3877642

How to pass variable number of arguments to printf/sprintf

void Error(const char* format, ...)
{
    va_list argptr;
    va_start(argptr, format);
    vfprintf(stderr, format, argptr);
    va_end(argptr);
}

If you want to manipulate the string before you display it and really do need it stored in a buffer first, use vsnprintf instead of vsprintf. vsnprintf will prevent an accidental buffer overflow error.

How can I get the UUID of my Android phone in an application?

This works for me:

TelephonyManager tManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String uuid = tManager.getDeviceId();

EDIT :

You also need android.permission.READ_PHONE_STATE set in your Manifest. Since Android M, you need to ask this permission at runtime.

See this anwser : https://stackoverflow.com/a/38782876/1339179

Resize height with Highcharts

According to the API Reference:

By default the height is calculated from the offset height of the containing element. Defaults to null.

So, you can control it's height according to the parent div using redraw event, which is called when it changes it's size.

References

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How to parse JSON Array (Not Json Object) in Android

Create a POJO Java Class for the objects in the list like so:

class NameUrlClass{
       private String name;
       private String url;
       //Constructor
       public NameUrlClass(String name,String url){
              this.name = name;
              this.url = url; 
        }
}

Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:

List<NameUrlClass> obj = new ArrayList<NameUrlClass>;

You can use store the JSON array in this object

obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]

How can I remove all text after a character in bash?

In Bash (and ksh, zsh, dash, etc.), you can use parameter expansion with % which will remove characters from the end of the string or # which will remove characters from the beginning of the string. If you use a single one of those characters, the smallest matching string will be removed. If you double the character, the longest will be removed.

$ a='hello:world'

$ b=${a%:*}
$ echo "$b"
hello

$ a='hello:world:of:tomorrow'

$ echo "${a%:*}"
hello:world:of

$ echo "${a%%:*}"
hello

$ echo "${a#*:}"
world:of:tomorrow

$ echo "${a##*:}"
tomorrow

How to redirect the output of print to a TXT file

Redirect sys.stdout to an open file handle and then all printed output goes to a file:

import sys
filename  = open("outputfile",'w')
sys.stdout = filename
print "Anything printed will go to the output file"

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

Tensorflow 2.x Compatible Answer: Converting mrry's code to Tensorflow 2.x (>= 2.0) for the benefit of the community.

!pip install tensorflow==2.1
import tensorflow as tf

tf.compat.v1.disable_eager_execution()    

t = tf.constant(42.0)
sess = tf.compat.v1.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.compat.v1.get_default_session()
    assert t.eval() == sess.run(t)

#The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.multiply(t, u)
ut = tf.multiply(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

invalid new-expression of abstract class type

invalid new-expression of abstract class type 'box'

There is nothing unclear about the error message. Your class box has at least one member that is not implemented, which means it is abstract. You cannot instantiate an abstract class.

If this is a bug, fix your box class by implementing the missing member(s).

If it's by design, derive from box, implement the missing member(s) and use the derived class.