How to pass a datetime parameter?
As a similar alternative to s k's answer, I am able to pass a date formatted by Date.prototype.toISOString()
in the query string. This is the standard ISO 8601 format, and it is accepted by .Net Web API controllers without any additional configuration of the route or action.
e.g.
var dateString = dateObject.toISOString(); // "2019-07-01T04:00:00.000Z"
How to cherry pick from 1 branch to another
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
JavaScript open in a new window, not tab
I just tried this with IE (11) and Chrome (54.0.2794.1 canary SyzyASan):
window.open(url, "_blank", "x=y")
... and it opened in a new window.
Which means that Clint pachl had it right when he said that providing any one parameter will cause the new window to open.
-- and apparently it doesn't have to be a legitimate parameter!
(YMMV - as I said, I only tested it in two places...and the next upgrade might invalidate the results, any way)
ETA: I just noticed, though - in IE, the window has no decorations.
Assert a function/method was not called using Mock
You can check the called
attribute, but if your assertion fails, the next thing you'll want to know is something about the unexpected call, so you may as well arrange for that information to be displayed from the start. Using unittest
, you can check the contents of call_args_list
instead:
self.assertItemsEqual(my_var.call_args_list, [])
When it fails, it gives a message like this:
AssertionError: Element counts were not equal:
First has 0, Second has 1: call('first argument', 4)
Looping over a list in Python
Here is the solution I was looking for. If you would like to create List2 that contains the difference of the number elements in List1.
list1 = [12, 15, 22, 54, 21, 68, 9, 73, 81, 34, 45]
list2 = []
for i in range(1, len(list1)):
change = list1[i] - list1[i-1]
list2.append(change)
Note that while len(list1)
is 11 (elements), len(list2)
will only be 10 elements because we are starting our for loop from element with index 1 in list1 not from element with index 0 in list1
What is a blob URL and why it is used?
Blob URLs (ref W3C, official name) or Object-URLs (ref. MDN and method name) are used with a Blob or a File object.
src="blob:https://crap.crap" I opened the blob url that was in src of
video it gave a error and i can't open but was working with the src
tag how it is possible?
Blob URLs can only be generated internally by the browser. URL.createObjectURL()
will create a special reference to the Blob or File object which later can be released using URL.revokeObjectURL()
. These URLs can only be used locally in the single instance of the browser and in the same session (ie. the life of the page/document).
What is blob url?
Why it is used?
Blob URL/Object URL is a pseudo protocol to allow Blob and File objects to be used as URL source for things like images, download links for binary data and so forth.
For example, you can not hand an Image object raw byte-data as it would not know what to do with it. It requires for example images (which are binary data) to be loaded via URLs. This applies to anything that require an URL as source. Instead of uploading the binary data, then serve it back via an URL it is better to use an extra local step to be able to access the data directly without going via a server.
It is also a better alternative to Data-URI which are strings encoded as Base-64. The problem with Data-URI is that each char takes two bytes in JavaScript. On top of that a 33% is added due to the Base-64 encoding. Blobs are pure binary byte-arrays which does not have any significant overhead as Data-URI does, which makes them faster and smaller to handle.
Can i make my own blob url on a server?
No, Blob URLs/Object URLs can only be made internally in the browser. You can make Blobs and get File object via the File Reader API, although BLOB just means Binary Large OBject and is stored as byte-arrays. A client can request the data to be sent as either ArrayBuffer or as a Blob. The server should send the data as pure binary data. Databases often uses Blob to describe binary objects as well, and in essence we are talking basically about byte-arrays.
if you have then Additional detail
You need to encapsulate the binary data as a BLOB object, then use URL.createObjectURL()
to generate a local URL for it:
var blob = new Blob([arrayBufferWithPNG], {type: "image/png"}),
url = URL.createObjectURL(blob),
img = new Image();
img.onload = function() {
URL.revokeObjectURL(this.src); // clean-up memory
document.body.appendChild(this); // add image to DOM
}
img.src = url; // can now "stream" the bytes
Note that URL
may be prefixed in webkit-browsers, so use:
var url = (URL || webkitURL).createObjectURL(...);
Android Studio and android.support.v4.app.Fragment: cannot resolve symbol
For me the cause of problem was broken class path:
Library Gradle: com.android.support:support-v4:28.0.0@aar has broken classes path:
/Users/YOUR_USER/.gradle/caches/transforms-1/files-1.1/support-v4-28.0.0.aar/0f378acce70d3d38db494e7ae5aa6008/res
So only removing transforms-1 folder and further Gradle Sync helped.
System.Net.WebException HTTP status code
You can try this code to get HTTP status code from WebException. It works in Silverlight too because SL does not have WebExceptionStatus.ProtocolError defined.
HttpStatusCode GetHttpStatusCode(WebException we)
{
if (we.Response is HttpWebResponse)
{
HttpWebResponse response = (HttpWebResponse)we.Response;
return response.StatusCode;
}
return null;
}
Create Local SQL Server database
After installation you need to connect to Server Name : localhost to start using the local instance of SQL Server.
Once you are connected to the local instance, right click on Databases and create a new database.
How do I trim whitespace from a string?
Well seeing this thread as a beginner got my head spinning. Hence came up with a simple shortcut.
Though str.strip() works to remove leading & trailing spaces it does nothing for spaces between characters.
words=input("Enter the word to test")
# If I have a user enter discontinous threads it becomes a problem
# input = " he llo, ho w are y ou "
n=words.strip()
print(n)
# output "he llo, ho w are y ou" - only leading & trailing spaces are removed
Instead use str.replace() to make more sense plus less error & more to the point.
The following code can generalize the use of str.replace()
def whitespace(words):
r=words.replace(' ','') # removes all whitespace
n=r.replace(',','|') # other uses of replace
return n
def run():
words=input("Enter the word to test") # take user input
m=whitespace(words) #encase the def in run() to imporve usability on various functions
o=m.count('f') # for testing
return m,o
print(run())
output- ('hello|howareyou', 0)
Can be helpful while inheriting the same in diff. functions.
How to get list of dates between two dates in mysql select query
Try:
select * from
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
(select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'
-for date ranges up to nearly 300 years in the future.
[Corrected following a suggested edit by UrvishAtSynapse.]
HashMap allows duplicates?
Doesn't allow duplicates in the sense, It allow to add you but it does'nt care about this key already have a value or not. So at present for one key there will be only one value
It silently overrides the value
for null
key. No exception.
When you try to get, the last inserted value with null
will be return.
That is not only with null
and for any key.
Have a quick example
Map m = new HashMap<String, String>();
m.put("1", "a");
m.put("1", "b"); //no exception
System.out.println(m.get("1")); //b
Xcode "Device Locked" When iPhone is unlocked
This happens at times while using Xcode 9.
There are multiple solution to this as mentioned below :
Note : Make sure that your device is not locked when Xcode is trying to install app.
Solution 1 :
i. Disconnect device
and connect again
Solution 2 :
i. Restart you device
Solution 3 :
i. Disconnect device
ii. Quit Xcode
(Shortcut key : cmd + Q)
iii. Open your project
iv. Clean project
(Shortcut key : cmd + shift + K
)
v. Now connect device
vi. Run
your project
For me Solution 3 worked perfectly
How to retrieve the dimensions of a view?
Simple Response: This worked for me with no Problem.
It seems the key is to ensure that the View has focus before you getHeight etc. Do this by using the hasFocus() method, then using getHeight() method in that order. Just 3 lines of code required.
ImageButton myImageButton1 =(ImageButton)findViewById(R.id.imageButton1);
myImageButton1.hasFocus();
int myButtonHeight = myImageButton1.getHeight();
Log.d("Button Height: ", ""+myButtonHeight );//Not required
Hope it helps.
Convert .cer certificate to .jks
keytool
comes with the JDK installation (in the bin
folder):
keytool -importcert -file "your.cer" -keystore your.jks -alias "<anything>"
This will create a new keystore and add just your certificate to it.
So, you can't convert a certificate to a keystore: you add a certificate to a keystore.
Java - sending HTTP parameters via POST method easily
I find HttpURLConnection
really cumbersome to use. And you have to write a lot of boilerplate, error prone code. I needed a lightweight wrapper for my Android projects and came out with a library which you can use as well: DavidWebb.
The above example could be written like this:
Webb webb = Webb.create();
webb.post("http://example.com/index.php")
.param("param1", "a")
.param("param2", "b")
.param("param3", "c")
.ensureSuccess()
.asVoid();
You can find a list of alternative libraries on the link provided.
How to get the current time in Python
import datetime
date_time = datetime.datetime.now()
date = date_time.date() # Gives the date
time = date_time.time() # Gives the time
print date.year, date.month, date.day
print time.hour, time.minute, time.second, time.microsecond
Do dir(date)
or any variables including the package. You can get all the attributes and methods associated with the variable.
Android Studio Gradle Configuration with name 'default' not found
Suppose you want to add a library (for example MyLib) to your project, You should follow these steps:
- Prepare your library as a gradle Android library if your library's type is Eclipse ADT
For this job it's enough to import it in Android Studio
- Copy your library folder, in this case MyLib folder, and paste it in your main project folder. It's a good practice to create a new folder in your main project folder and name it Libraries
- Go to Android Studio and open Settings.gradle file, there you should include your library in your main project. For example
include ':MyPrj', 'Libraries:MyLib'
. Note: Current directory for this include statement is your main project folder. If you paste your project into a folder you must mention it's address relative to the main project directory. In my case I paste MyLib into Libraries folder. This Libraries name is not a keyword and you can choose other names for it
- Open your Project Structure page(File->Project Structure...) click on modules then click on your main project go to dependencies tab click on
+
then choose Module dependency and there is your libraries and you can select them as you want
Hope it help
setting the id attribute of an input element dynamically in IE: alternative for setAttribute method
Forget setAttribute()
: it's badly broken and doesn't always do what you might expect in old IE (IE <= 8 and compatibility modes in later versions). Use the element's properties instead. This is generally a good idea, not just for this particular case. Replace your code with the following, which will work in all major browsers:
var hiddenInput = document.createElement("input");
hiddenInput.id = "uniqueIdentifier";
hiddenInput.type = "hidden";
hiddenInput.value = ID;
hiddenInput.className = "ListItem";
Update
The nasty hack in the second code block in the question is unnecessary, and the code above works fine in all major browsers, including IE 6. See http://www.jsfiddle.net/timdown/aEvUT/. The reason why you get null
in your alert()
is that when it is called, the new input is not yet in the document, hence the document.getElementById()
call cannot find it.
How can I create Min stl priority_queue?
You can do it in multiple ways:
1. Using greater
as comparison function :
#include <bits/stdc++.h>
using namespace std;
int main()
{
priority_queue<int,vector<int>,greater<int> >pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<< " ";
}
return 0;
}
2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :
int main()
{
priority_queue<int>pq2;
pq2.push(-1); //for +1
pq2.push(-2); //for +2
pq2.push(-3); //for +3
pq2.push(4); //for -4
while(!pq2.empty())
{
int r = pq2.top();
pq2.pop();
cout<<-r<<" ";
}
return 0;
}
3. Using custom structure or class :
struct compare
{
bool operator()(const int & a, const int & b)
{
return a>b;
}
};
int main()
{
priority_queue<int,vector<int>,compare> pq;
pq.push(1);
pq.push(2);
pq.push(3);
while(!pq.empty())
{
int r = pq.top();
pq.pop();
cout<<r<<" ";
}
return 0;
}
4. Using custom structure or class you can use priority_queue in any order.
Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.
struct people
{
int age,salary;
};
struct compare{
bool operator()(const people & a, const people & b)
{
if(a.salary==b.salary)
{
return a.age>b.age;
}
else
{
return a.salary>b.salary;
}
}
};
int main()
{
priority_queue<people,vector<people>,compare> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
Same result can be obtained by operator overloading :
struct people
{
int age,salary;
bool operator< (const people & p)const
{
if(salary==p.salary)
{
return age>p.age;
}
else
{
return salary>p.salary;
}
}};
In main function :
priority_queue<people> pq;
people person1,person2,person3;
person1.salary=100;
person1.age = 50;
person2.salary=80;
person2.age = 40;
person3.salary = 100;
person3.age=40;
pq.push(person1);
pq.push(person2);
pq.push(person3);
while(!pq.empty())
{
people r = pq.top();
pq.pop();
cout<<r.salary<<" "<<r.age<<endl;
}
How to get instance variables in Python?
built on dmark's answer to get the following, which is useful if you want the equiv of sprintf and hopefully will help someone...
def sprint(object):
result = ''
for i in [v for v in dir(object) if not callable(getattr(object, v)) and v[0] != '_']:
result += '\n%s:' % i + str(getattr(object, i, ''))
return result
How to detect scroll direction
Here is a sample showing an easy way to do it. The script is:
$(function() {
var _t = $("#container").scrollTop();
$("#container").scroll(function() {
var _n = $("#container").scrollTop();
if (_n > _t) {
$("#target").text("Down");
} else {
$("#target").text("Up");
}
_t = _n;
});
});
The #container
is your div id
. The #target
is just to see it working. Change to what you want when up or when down.
EDIT
The OP didn't say before, but since he's using a div with overflow: hidden
, scrolling doesn't occur, then the script to detect the scroll is the least of it. Well, how to detect something that does not happen?!
So, the OP himself posted the link with what he wants, so why not use that library? http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js.
The call is just:
$(function() {
$(".scrollable").scrollable({ vertical: true, mousewheel: true });
});
How to add elements of a string array to a string array list?
Arrays.asList()
method simply returns List
type
char [] arr = { 'c','a','t'};
ArrayList<Character> chars = new ArrayList<Character>();
To add the array into the list, first convert it to list and then call addAll
List arrList = Arrays.asList(arr);
chars.addAll(arrList);
The following line will cause compiler error
chars.addAll(Arrays.asList(arr));
Java: export to an .jar file in eclipse
No need for external plugins. In the Export JAR dialog, make sure you select all the necessary resources you want to export. By default, there should be no problem exporting other resource files as well (pictures, configuration files, etc...), see screenshot below.
JAVA How to remove trailing zeros from a double
You should use DecimalFormat("0.#")
For 4.3000
Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
output is:
4.3
In case of 5.000 we have
Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));
And the output is:
5
Finding square root without using sqrt function?
Here is a very awesome code to find sqrt and even faster than original sqrt function.
float InvSqrt (float x)
{
float xhalf = 0.5f*x;
int i = *(int*)&x;
i = 0x5f375a86 - (i>>1);
x = *(float*)&i;
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x = x*(1.5f - xhalf*x*x);
x=1/x;
return x;
}
Line continue character in C#
@"string here
that is long you mean"
But be careful, because
@"string here
and space before this text
means the space is also a part of the string"
It also escapes things in the string
@"c:\\folder" // c:\\folder
@"c:\folder" // c:\folder
"c:\\folder" // c:\folder
Related
With ng-bind-html-unsafe removed, how do I inject HTML?
Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind
. This is an unsafe option, but helpful when testing.
Example from the AngularJS documentation on $sce
:
angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
// Completely disable SCE. For demonstration purposes only!
// Do not use in new projects.
$sceProvider.enabled(false);
});
Attaching the above config section to your app will allow you inject html into ng-html-bind
, but as the doc remarks:
SCE gives you a lot of security benefits for little coding overhead.
It will be much harder to take an SCE disabled application and either
secure it on your own or enable SCE at a later stage. It might make
sense to disable SCE for cases where you have a lot of existing code
that was written before SCE was introduced and you're migrating them a
module at a time.
How to generate gcc debug symbol outside the build target?
Check out the "--only-keep-debug" option of the strip command.
From the link:
The intention is that this option will be used in conjunction with --add-gnu-debuglink to create a two part executable. One a stripped binary which will occupy less space in RAM and in a distribution and the second a debugging information file which is only needed if debugging abilities are required.
JTable won't show column headers
The main difference between this answer and the accepted answer is the use of setViewportView()
instead of add()
.
How to put JTable
in JScrollPane
using Eclipse IDE:
- Create
JScrollPane
container via Design tab.
- Stretch
JScrollPane
to desired size (applies to Absolute Layout).
- Drag and drop
JTable
component on top of JScrollPane
(Viewport area).
In Structure > Components, table
should be a child of scrollPane
.
The generated code would be something like this:
JScrollPane scrollPane = new JScrollPane();
...
JTable table = new JTable();
scrollPane.setViewportView(table);
Difference between View and ViewGroup in Android
A ViewGroup
is a special view that can contain other views (called children.) The view group is the base class for layouts and views containers. This class also defines the ViewGroup.LayoutParams
class which serves as the base class for layouts parameters.
View
class represents the basic building block for user interface components. A View occupies a rectangular area on the screen and is
responsible for drawing and event handling. View is the base class
for widgets, which are used to create interactive UI components
(buttons, text fields, etc.).
- Example : ViewGroup (LinearLayout), View (TextView)
Reference
CSS Pseudo-classes with inline styles
Rather than needing inline you could use Internal CSS
<a href="http://www.google.com" style="hover:text-decoration:none;">Google</a>
You could have:
<a href="http://www.google.com" id="gLink">Google</a>
<style>
#gLink:hover {
text-decoration: none;
}
</style>
Multiple conditions in a C 'for' loop
There is an operator in C called the comma operator. It executes each expression in order and returns the value of the last statement. It's also a sequence point, meaning each expression is guaranteed to execute in completely and in order before the next expression in the series executes, similar to &&
or ||
.
How to remove an element from an array in Swift
I came up with the following extension that takes care of removing elements from an Array
, assuming the elements in the Array
implement Equatable
:
extension Array where Element: Equatable {
mutating func removeEqualItems(_ item: Element) {
self = self.filter { (currentItem: Element) -> Bool in
return currentItem != item
}
}
mutating func removeFirstEqualItem(_ item: Element) {
guard var currentItem = self.first else { return }
var index = 0
while currentItem != item {
index += 1
currentItem = self[index]
}
self.remove(at: index)
}
}
Usage:
var test1 = [1, 2, 1, 2]
test1.removeEqualItems(2) // [1, 1]
var test2 = [1, 2, 1, 2]
test2.removeFirstEqualItem(2) // [1, 1, 2]
Create a txt file using batch file in a specific folder
You have it almost done. Just explicitly say where to create the file
@echo off
echo.>"d:\testing\dblank.txt"
This creates a file containing a blank line (CR + LF = 2 bytes).
If you want the file empty (0 bytes)
@echo off
break>"d:\testing\dblank.txt"
How do I limit the number of returned items?
In the latest mongoose (3.8.1 at the time of writing), you do two things differently: (1) you have to pass single argument to sort(), which must be an array of constraints or just one constraint, and (2) execFind() is gone, and replaced with exec() instead. Therefore, with the mongoose 3.8.1 you'd do this:
var q = models.Post.find({published: true}).sort({'date': -1}).limit(20);
q.exec(function(err, posts) {
// `posts` will be of length 20
});
or you can chain it together simply like that:
models.Post
.find({published: true})
.sort({'date': -1})
.limit(20)
.exec(function(err, posts) {
// `posts` will be of length 20
});
"FATAL: Module not found error" using modprobe
Insert this in your Makefile
$(MAKE) -C $(KDIR) M=$(PWD) modules_install
it will install the module in the directory /lib/modules/<var>/extra/
After make , insert module with modprobe module_name (without .ko extension)
OR
After your normal make, you copy module module_name.ko into directory /lib/modules/<var>/extra/
then do modprobe module_name (without .ko extension)
Spring schemaLocation fails when there is no internet connection
I had the same problem when I'm using spring-context version 4.0.6 and
spring-security version 4.1.0.
When changing spring-security version to 4.0.4 (because 4.0.6 of spring-security not available) in my pom and security xml-->schemaLocation, it gets compiled without internet.
So that mean you can also solve this by:
(any way spring-context to be newer or same version to spring-security)
How to call a function after a div is ready?
To do something after certain div load from function .load()
.
I think this exactly what you need:
$('#divIDer').load(document.URL + ' #divIDer',function() {
// call here what you want .....
//example
$('#mydata').show();
});
How to execute INSERT statement using JdbcTemplate class from Spring Framework
Use jdbcTemplate.update(String sql, Object... args)
method:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
var1, var2
);
or jdbcTemplate.update(String sql, Object[] args, int[] argTypes)
, if you need to map arguments to SQL types manually:
jdbcTemplate.update(
"INSERT INTO schema.tableName (column1, column2) VALUES (?, ?)",
new Object[]{var1, var2}, new Object[]{Types.TYPE_OF_VAR1, Types.TYPE_OF_VAR2}
);
Does the Java &= operator apply & or &&?
see 15.22.2 of the JLS. For boolean operands, the &
operator is boolean, not bitwise. The only difference between &&
and &
for boolean operands is that for &&
it is short circuited (meaning that the second operand isn't evaluated if the first operand evaluates to false).
So in your case, if b
is a primitive, a = a && b
, a = a & b
, and a &= b
all do the same thing.
Arrow operator (->) usage in C
Well I have to add something as well. Structure is a bit different than array because array is a pointer and structure is not. So be careful!
Lets say I write this useless piece of code:
#include <stdio.h>
typedef struct{
int km;
int kph;
int kg;
} car;
int main(void){
car audi = {12000, 230, 760};
car *ptr = &audi;
}
Here pointer ptr
points to the address (!) of the structure variable audi
but beside address structure also has a chunk of data (!)! The first member of the chunk of data has the same address than structure itself and you can get it's data by only dereferencing a pointer like this *ptr
(no braces).
But If you want to acess any other member than the first one, you have to add a designator like .km
, .kph
, .kg
which are nothing more than offsets to the base address of the chunk of data...
But because of the preceedence you can't write *ptr.kg
as access operator .
is evaluated before dereference operator *
and you would get *(ptr.kg)
which is not possible as pointer has no members! And compiler knows this and will therefore issue an error e.g.:
error: ‘ptr’ is a pointer; did you mean to use ‘->’?
printf("%d\n", *ptr.km);
Instead you use this (*ptr).kg
and you force compiler to 1st dereference the pointer and enable acess to the chunk of data and 2nd you add an offset (designator) to choose the member.
Check this image I made:
But if you would have nested members this syntax would become unreadable and therefore ->
was introduced. I think readability is the only justifiable reason for using it as this ptr->kg
is much easier to write than (*ptr).kg
.
Now let us write this differently so that you see the connection more clearly. (*ptr).kg
? (*&audi).kg
? audi.kg
. Here I first used the fact that ptr
is an "address of audi
" i.e. &audi
and fact that "reference" &
and "dereference" *
operators cancel eachother out.
How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?
I would suggest using System.Runtime.Serialization.Json
that is part of .NET 4.5.
[DataContract]
public class Foo
{
[DataMember(Name = "data")]
public Dictionary<string,string> Data { get; set; }
}
Then use it like this:
var serializer = new DataContractJsonSerializer(typeof(List<Foo>));
var jsonParams = @"{""data"": [{""Key"":""foo"",""Value"":""bar""}] }";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
var obj = serializer.ReadObject(stream);
Console.WriteLine(obj);
phpmailer error "Could not instantiate mail function"
For what it's worth I had this issue and had to go into cPanel where I saw the error message
"Attention! Please register your email IDs used in non-smtp mails through cpanel plugin. Unregistered email IDs will not be allowed in non-smtp emails sent through scripts. Go to Mail section and find "Registered Mail IDs" plugin in paper_lantern theme."
Registering the emails in cPanel (Register Mail IDs) and waiting 10 mins got mine to work.
Hope that helps someone.
Update Multiple Rows in Entity Framework from a list of ids
something like below
var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
var friends= db.Friends.Where(f=>idList.Contains(f.ID)).ToList();
friends.ForEach(a=>a.msgSentBy='1234');
db.SaveChanges();
}
UPDATE:
you can update multiple fields as below
friends.ForEach(a =>
{
a.property1 = value1;
a.property2 = value2;
});
How do I deal with corrupted Git object files?
For anyone stumbling across the same issue:
I fixed the problem by cloning the repo again at another location. I then copied my whole src dir (without .git dir obviously) from the corrupted repo into the freshly cloned repo. Thus I had all the recent changes and a clean and working repository.
Concatenate two slices in Go
append( ) function and spread operator
Two slices can be concatenated using append
method in the standard golang library. Which is similar to the variadic
function operation. So we need to use ...
package main
import (
"fmt"
)
func main() {
x := []int{1, 2, 3}
y := []int{4, 5, 6}
z := append([]int{}, append(x, y...)...)
fmt.Println(z)
}
output of the above code is: [1 2 3 4 5 6]
How to change button background image on mouseOver?
You can create a class based on a Button with specific images for MouseHover and MouseDown like this:
public class AdvancedImageButton : Button
{
public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }
protected override void OnMouseEnter(System.EventArgs e)
{
base.OnMouseEnter(e);
if (HoverImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = HoverImage;
}
protected override void OnMouseLeave(System.EventArgs e)
{
base.OnMouseLeave(e);
if (HoverImage == null) return;
base.Image = PlainImage;
}
protected override void OnMouseDown(MouseEventArgs e)
{
base.OnMouseDown(e);
if (PressedImage == null) return;
if (PlainImage == null) PlainImage = base.Image;
base.Image = PressedImage;
}
}
This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.
JavaScript variable number of arguments to function
Another option is to pass in your arguments in a context object.
function load(context)
{
// do whatever with context.name, context.address, etc
}
and use it like this
load({name:'Ken',address:'secret',unused:true})
This has the advantage that you can add as many named arguments as you want, and the function can use them (or not) as it sees fit.
How can I safely create a nested directory?
Call the function create_dir()
at the entry point of your program/project.
import os
def create_dir(directory):
if not os.path.exists(directory):
print('Creating Directory '+directory)
os.makedirs(directory)
create_dir('Project directory')
How do you tell if a checkbox is selected in Selenium for Java?
- Declare a variable.
- Store the checked property for the radio button.
- Have a if condition.
Lets assume
private string isChecked;
private webElement e;
isChecked =e.findElement(By.tagName("input")).getAttribute("checked");
if(isChecked=="true")
{
}
else
{
}
Hope this answer will be help for you. Let me know, if have any clarification in CSharp Selenium web driver.
Implement paging (skip / take) functionality with this query
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
displaying a string on the textview when clicking a button in android
You can do like this:
String hello;
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
mybtn = (Button)findViewById(R.id.mybtn);
txtView=(TextView)findViewById(R.id.txtView);
txtwidth = (TextView)findViewById(R.id.viewwidth);
hello="This is my first project";
mybtn.setOnClickListener(this);
}
public void onClick(View view){
txtView.setText(hello);
}
Check your textview names. Both are same . You must use different object names and you have mentioned that textview object which is not available in your xml layout file.
Hope this will help you.
How to iterate through a DataTable
The above examples are quite helpful. But, if we want to check if a particular row is having a particular value or not. If yes then delete and break and in case of no value found straight throw error. Below code works:
foreach (DataRow row in dtData.Rows)
{
if (row["Column_name"].ToString() == txtBox.Text)
{
// Getting the sequence number from the textbox.
string strName1 = txtRowDeletion.Text;
// Creating the SqlCommand object to access the stored procedure
// used to get the data for the grid.
string strDeleteData = "Sp_name";
SqlCommand cmdDeleteData = new SqlCommand(strDeleteData, conn);
cmdDeleteData.CommandType = System.Data.CommandType.StoredProcedure;
// Running the query.
conn.Open();
cmdDeleteData.ExecuteNonQuery();
conn.Close();
GetData();
dtData = (DataTable)Session["GetData"];
BindGrid(dtData);
lblMsgForDeletion.Text = "The row successfully deleted !!" + txtRowDeletion.Text;
txtRowDeletion.Text = "";
break;
}
else
{
lblMsgForDeletion.Text = "The row is not present ";
}
}
Substring a string from the end of the string
If it's an unknown amount of strings you could trim off the last character by doing
s = s.TrimEnd('','!').Trim();
Have you considered using a regular expression? If you only want to allow alpha numeric characters you can use regex to replace the symbols, What if instead of a ! you get a %?
ImportError: No module named win32com.client
I realize this post is old but I wanted to add that I had to take an extra step to get this to work.
Instead of just doing:
pip install pywin32
I had use use the -m
flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com
.
So to fix this you can give this a try:
python -m pip install pywin32
This worked for me and has worked on several version of python where just doing pip install pywin32
did not work.
Versions tested on:
3.6.2, 3.7.6, 3.8.0, 3.9.0a1.
Web Service vs WCF Service
What is the difference between web service and WCF?
Web service use only HTTP protocol while transferring data from one application to other application.
But WCF supports more protocols for transporting messages than ASP.NET Web services. WCF supports sending messages by using HTTP, as well as the Transmission Control Protocol (TCP), named pipes, and Microsoft Message Queuing (MSMQ).
To develop a service in Web Service, we will write the following code
[WebService]
public class Service : System.Web.Services.WebService
{
[WebMethod]
public string Test(string strMsg)
{
return strMsg;
}
}
To develop a service in WCF, we will write the following code
[ServiceContract]
public interface ITest
{
[OperationContract]
string ShowMessage(string strMsg);
}
public class Service : ITest
{
public string ShowMessage(string strMsg)
{
return strMsg;
}
}
Web Service is not architecturally more robust. But WCF is architecturally
more robust and promotes best practices.
Web Services use XmlSerializer but WCF uses DataContractSerializer. Which is
better in performance as compared to XmlSerializer?
For internal (behind firewall) service-to-service calls we use the net:tcp
binding, which is much faster than SOAP.
WCF is 25%—50% faster than ASP.NET Web Services, and approximately 25%
faster than .NET Remoting.
When would I opt for one over the other?
WCF is used to communicate between other applications which has been developed on other platforms and using other Technology.
For example, if I have to transfer data from .net platform to other application which is running on other OS (like Unix or Linux) and they are using other transfer protocol (like WAS, or TCP) Then it is only possible to transfer data using WCF.
Here is no restriction of platform, transfer protocol of application while transferring the data between one application to other application.
Security is very high as compare to web service
How do I copy SQL Azure database to my local development server?
In SQL Server 2016 Management Studio, the process for getting an azure database to your local machine has been streamlined.
Right click on the database you want to import, click Tasks > Export data-tier application, and export your database to a local .dacpac file.
In your local target SQL server instance, you can right click Databases > Import data-tier application, and once it's local, you can do things like backup and restore the database.
Determine path of the executing script
You can use the commandArgs
function to get all the options that were passed by Rscript to the actual R interpreter and search them for --file=
. If your script was launched from the path or if it was launched with a full path, the script.name
below will start with a '/'
. Otherwise, it must be relative to the cwd
and you can concat the two paths to get the full path.
Edit: it sounds like you'd only need the script.name
above and to strip off the final component of the path. I've removed the unneeded cwd()
sample and cleaned up the main script and posted my other.R
. Just save off this script and the other.R
script into the same directory, chmod +x
them, and run the main script.
main.R:
#!/usr/bin/env Rscript
initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.basename <- dirname(script.name)
other.name <- file.path(script.basename, "other.R")
print(paste("Sourcing",other.name,"from",script.name))
source(other.name)
other.R:
print("hello")
output:
burner@firefighter:~$ main.R
[1] "Sourcing /home/burner/bin/other.R from /home/burner/bin/main.R"
[1] "hello"
burner@firefighter:~$ bin/main.R
[1] "Sourcing bin/other.R from bin/main.R"
[1] "hello"
burner@firefighter:~$ cd bin
burner@firefighter:~/bin$ main.R
[1] "Sourcing ./other.R from ./main.R"
[1] "hello"
This is what I believe dehmann is looking for.
What is the MySQL JDBC driver connection string?
The method Class.forName()
is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}
Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?
The following is the un-installation for PostgreSQL 9.1 installed using the EnterpriseDB installer. You most probably have to replace folder /9.1/ with your version number. If /Library/Postgresql/
doesn't exist then you probably installed PostgreSQL with a different method like homebrew
or Postgres.app
.
To remove the EnterpriseDB One-Click install of PostgreSQL 9.1:
- Open a terminal window. Terminal is found in: Applications->Utilities->Terminal
Run the uninstaller:
sudo /Library/PostgreSQL/9.1/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh
If you installed with the Postgres Installer, you can do:
open /Library/PostgreSQL/9.2/uninstall-postgresql.app
It will ask for the administrator password and run the uninstaller.
Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.
sudo rm -rf /Library/PostgreSQL
Remove the ini file:
sudo rm /etc/postgres-reg.ini
Remove the PostgreSQL user using System Preferences -> Users & Groups.
- Unlock the settings panel by clicking on the padlock and entering your password.
- Select the PostgreSQL user and click on the minus button.
Restore your shared memory settings:
sudo rm /etc/sysctl.conf
That should be all! The uninstall wizard would have removed all icons and start-up applications files so you don't have to worry about those.
Is it possible to program iPhone in C++
I use Objective-C to slap the UI together.
But the hard guts of the code is still written in C++.
That is the main purpose of Objective-C the UI interface and handling the events.
And it works great for that purpose.
I still like C++ as the backend for the code though (but that's mainly becuase I like C++) you could quite easily use Objective-C for the backend of the application as well.
Drawable image on a canvas
You need to load your image as bitmap:
Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, R.drawable.your_image);
Then make the bitmap mutable and create a canvas over it:
Canvas canvas = new Canvas(bitmap.copy(Bitmap.Config.ARGB_8888, true));
You then can draw on the canvas.
git stash and git pull
When you have changes on your working copy, from command line do:
git stash
This will stash your changes and clear your status report
git pull
This will pull changes from upstream branch. Make sure it says fast-forward in the report. If it doesn't, you are probably doing an unintended merge
git stash pop
This will apply stashed changes back to working copy and remove the changes from stash unless you have conflicts. In the case of conflict, they will stay in stash so you can start over if needed.
if you need to see what is in your stash
git stash list
Can I replace groups in Java regex?
Use $n
(where n is a digit) to refer to captured subsequences in replaceFirst(...)
. I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.
Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
// replace first number with "number" and second number with the first
String output = m.replaceFirst("number $3$1"); // number 46
}
Consider (\D+)
for the second group instead of (.*)
. *
is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d)
has nothing to match, before it can match to the final digit.
Purpose of __repr__ method?
This is explained quite well in the Python documentation:
repr(object): Return a string containing a printable representation of an object. This is the same value yielded by conversions (reverse quotes). It is sometimes useful to be able to access this operation as an ordinary function. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval()
, otherwise the representation is a string enclosed in angle brackets that contains the name of the type of the object together with additional information often including the name and address of the object. A class can control what this function returns for its instances by defining a __repr__()
method.
So what you're seeing here is the default implementation of __repr__
, which is useful for serialization and debugging.
get data from mysql database to use in javascript
Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?
- Send AJAX request to php script
- PHP script processes request and builds table
- PHP script sends response back to JS in form of encoded HTML
- JS takes response and inserts it into the DOM
How do I set the rounded corner radius of a color drawable using xml?
mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).
I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.
Showing the same file in both columns of a Sublime Text window
Yes, you can. When a file is open, click on File -> New View Into File
. You can then drag the new tab to the other pane and view the file twice.
There are several ways to create a new pane. As described in other answers, on Linux and Windows, you can use AltShift2 (Option ?Command ?2 on OS X), which corresponds to View ? Layout ? Columns: 2
in the menu. If you have the excellent Origami
plugin installed, you can use View ? Origami ? Pane ? Create ? Right
, or the CtrlK, Ctrl? chord on Windows/Linux (replace Ctrl with ? on OS X).
Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script
Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.
Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7
It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/
Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run
pip install module-name.whl
I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.
People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"
Convert double to Int, rounded down
If you explicitly cast double
to int
, the decimal part will be truncated. For example:
int x = (int) 4.97542; //gives 4 only
int x = (int) 4.23544; //gives 4 only
Moreover, you may also use Math.floor()
method to round values in case you want double
value in return.
PostgreSQL create table if not exists
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION prc_create_sch_foo_table() RETURNS VOID AS $$
BEGIN
EXECUTE 'CREATE TABLE /* IF NOT EXISTS add for PostgreSQL 9.1+ */ sch.foo (
id serial NOT NULL,
demo_column varchar NOT NULL,
demo_column2 varchar NOT NULL,
CONSTRAINT pk_sch_foo PRIMARY KEY (id));
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column ON sch.foo(demo_column);
CREATE INDEX /* IF NOT EXISTS add for PostgreSQL 9.5+ */ idx_sch_foo_demo_column2 ON sch.foo(demo_column2);'
WHERE NOT EXISTS(SELECT * FROM information_schema.tables
WHERE table_schema = 'sch'
AND table_name = 'foo');
EXCEPTION WHEN null_value_not_allowed THEN
WHEN duplicate_table THEN
WHEN others THEN RAISE EXCEPTION '% %', SQLSTATE, SQLERRM;
END; $$ LANGUAGE plpgsql;
How to install multiple python packages at once using pip
Complementing the other answers, you can use the option --no-cache-dir
to disable caching in pip. My virtual machine was crashing when installing many packages at once with pip install -r requirements.txt
. What solved for me was:
pip install --no-cache-dir -r requirements.txt
Open link in new tab or window
set the target
attribute of your <a>
element to "_tab"
EDIT:
It works, however W3Schools says there is no such target attribute:
http://www.w3schools.com/tags/att_a_target.asp
EDIT2:
From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):
_blank Opens the linked document in a new window or tab
_self Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top Opens the linked document in the full body of the window
framename Opens the linked document in a named frame
Accessing value inside nested dictionaries
As always in python, there are of course several ways to do it, but there is one obvious way to do it.
tmpdict["ONE"]["TWO"]["THREE"]
is the obvious way to do it.
When that does not fit well with your algorithm, that may be a hint that your structure is not the best for the problem.
If you just want to just save you repetative typing, you can of course alias a subset of the dict:
>>> two_dict = tmpdict['ONE']['TWO'] # now you can just write two_dict for tmpdict['ONE']['TWO']
>>> two_dict["spam"] = 23
>>> tmpdict
{'ONE': {'TWO': {'THREE': 10, 'spam': 23}}}
SQL Server: Cannot insert an explicit value into a timestamp column
Assume Table1 and Table2 have three columns A, B and TimeStamp. I want to insert from Table1 into Table2.
This fails with the timestamp error:
Insert Into Table2
Select Table1.A, Table1.B, Table1.TimeStamp From Table1
This works:
Insert Into Table2
Select Table1.A, Table1.B, null From Table1
Regular Expression to match valid dates
If you're going to insist on doing this with a regular expression, I'd recommend something like:
( (0?1|0?3| <...> |10|11|12) / (0?1| <...> |30|31) |
0?2 / (0?1| <...> |28|29) )
/ (19|20)[0-9]{2}
This might make it possible to read and understand.
Tomcat is not deploying my web project from Eclipse
In my case, I configured an external Maven installation, and I made sure to be using a JDK instead of a JRE (in the eclipse configuration, and in the Server Environment). You can run a Maven Build of the project from eclipse to check everything is working ok.
After that, I updated the maven projects, cleaned and built the projects, cleaned the server, and redeployed the artifacts.
How to draw a line with matplotlib?
This will draw a line that passes through the points (-1, 1) and (12, 4), and another one that passes through the points (1, 3) et (10, 2)
x1 are the x coordinates of the points for the first line, y1 are the y coordinates for the same -- the elements in x1 and y1 must be in sequence.
x2 and y2 are the same for the other line.
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 4]
x2, y2 = [1, 10], [3, 2]
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
I suggest you spend some time reading / studying the basic tutorials found on the very rich matplotlib website to familiarize yourself with the library.
What if I don't want line segments?
There are no direct ways to have lines extend to infinity... matplotlib will either resize/rescale the plot so that the furthest point will be on the boundary and the other inside, drawing line segments in effect; or you must choose points outside of the boundary of the surface you want to set visible, and set limits for the x and y axis.
As follows:
import matplotlib.pyplot as plt
x1, y1 = [-1, 12], [1, 10]
x2, y2 = [-1, 10], [3, -1]
plt.xlim(0, 8), plt.ylim(-2, 8)
plt.plot(x1, y1, x2, y2, marker = 'o')
plt.show()
Change the encoding of a file in Visual Studio Code
So here's how to do that:
In the bottom bar of VSCode, you'll see the label UTF-8
. Click it. A
popup opens. Click Save with encoding
. You can now pick a new
encoding for that file.
Alternatively, you can change the setting globally in Workspace/User settings using the setting "files.encoding": "utf8"
. If using the graphical settings page in VSCode, simply search for encoding
. Do note however that this only applies to newly created files.
Hide/encrypt password in bash file to stop accidentally seeing it
Although this is not a built in Unix solution, I've implemented a solution for this using a shell script that can be included in whatever shell script you are using. This is usable on POSIX compliant setups. (sh, bash, ksh, zsh) The full description is available in the github repo -> https://github.com/plyint/encpass.sh. This solution will auto-generate a key for your script and store the key and your password (or other secrets) in a hidden directory under your user (i.e. ~/.encpass).
In your script you just need to source encpass.sh and then call the get_secret method. For example:
#!/bin/sh
. encpass.sh
password=$(get_secret)
Pasted below is lite version of the code for encpass.sh(you can get the full version over on github) for easier visibility:
#!/bin/sh
################################################################################
# Copyright (c) 2020 Plyint, LLC <[email protected]>. All Rights Reserved.
# This file is licensed under the MIT License (MIT).
# Please see LICENSE.txt for more information.
#
# DESCRIPTION:
# This script allows a user to encrypt a password (or any other secret) at
# runtime and then use it, decrypted, within a script. This prevents shoulder
# surfing passwords and avoids storing the password in plain text, which could
# inadvertently be sent to or discovered by an individual at a later date.
#
# This script generates an AES 256 bit symmetric key for each script (or user-
# defined bucket) that stores secrets. This key will then be used to encrypt
# all secrets for that script or bucket. encpass.sh sets up a directory
# (.encpass) under the user's home directory where keys and secrets will be
# stored.
#
# For further details, see README.md or run "./encpass ?" from the command line.
#
################################################################################
encpass_checks() {
[ -n "$ENCPASS_CHECKS" ] && return
if [ -z "$ENCPASS_HOME_DIR" ]; then
ENCPASS_HOME_DIR="$HOME/.encpass"
fi
[ ! -d "$ENCPASS_HOME_DIR" ] && mkdir -m 700 "$ENCPASS_HOME_DIR"
if [ -f "$ENCPASS_HOME_DIR/.extension" ]; then
# Extension enabled, load it...
ENCPASS_EXTENSION="$(cat "$ENCPASS_HOME_DIR/.extension")"
ENCPASS_EXT_FILE="encpass-$ENCPASS_EXTENSION.sh"
if [ -f "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE" ]; then
# shellcheck source=/dev/null
. "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE"
elif [ ! -z "$(command -v encpass-"$ENCPASS_EXTENSION".sh)" ]; then
# shellcheck source=/dev/null
. "$(command -v encpass-$ENCPASS_EXTENSION.sh)"
else
encpass_die "Error: Extension $ENCPASS_EXTENSION could not be found."
fi
# Extension specific checks, mandatory function for extensions
encpass_"${ENCPASS_EXTENSION}"_checks
else
# Use default OpenSSL implementation
if [ ! -x "$(command -v openssl)" ]; then
echo "Error: OpenSSL is not installed or not accessible in the current path." \
"Please install it and try again." >&2
exit 1
fi
[ ! -d "$ENCPASS_HOME_DIR/keys" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/keys"
[ ! -d "$ENCPASS_HOME_DIR/secrets" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/secrets"
[ ! -d "$ENCPASS_HOME_DIR/exports" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/exports"
fi
ENCPASS_CHECKS=1
}
# Checks if the enabled extension has implented the passed function and if so calls it
encpass_ext_func() {
[ ! -z "$ENCPASS_EXTENSION" ] && ENCPASS_EXT_FUNC="$(command -v "encpass_${ENCPASS_EXTENSION}_$1")" || return
[ ! -z "$ENCPASS_EXT_FUNC" ] && shift && $ENCPASS_EXT_FUNC "$@"
}
# Initializations performed when the script is included by another script
encpass_include_init() {
encpass_ext_func "include_init" "$@"
[ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ -n "$1" ] && [ -n "$2" ]; then
ENCPASS_BUCKET=$1
ENCPASS_SECRET_NAME=$2
elif [ -n "$1" ]; then
if [ -z "$ENCPASS_BUCKET" ]; then
ENCPASS_BUCKET=$(basename "$0")
fi
ENCPASS_SECRET_NAME=$1
else
ENCPASS_BUCKET=$(basename "$0")
ENCPASS_SECRET_NAME="password"
fi
}
encpass_generate_private_key() {
ENCPASS_KEY_DIR="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"
[ ! -d "$ENCPASS_KEY_DIR" ] && mkdir -m 700 "$ENCPASS_KEY_DIR"
if [ ! -f "$ENCPASS_KEY_DIR/private.key" ]; then
(umask 0377 && printf "%s" "$(openssl rand -hex 32)" >"$ENCPASS_KEY_DIR/private.key")
fi
}
encpass_set_private_key_abs_name() {
ENCPASS_PRIVATE_KEY_ABS_NAME="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key"
[ ! -n "$1" ] && [ ! -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ] && encpass_generate_private_key
}
encpass_set_secret_abs_name() {
ENCPASS_SECRET_ABS_NAME="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET/$ENCPASS_SECRET_NAME.enc"
[ ! -n "$1" ] && [ ! -f "$ENCPASS_SECRET_ABS_NAME" ] && set_secret
}
encpass_rmfifo() {
trap - EXIT
kill "$1" 2>/dev/null
rm -f "$2"
}
encpass_mkfifo() {
fifo="$ENCPASS_HOME_DIR/$1.$$"
mkfifo -m 600 "$fifo" || encpass_die "Error: unable to create named pipe"
printf '%s\n' "$fifo"
}
get_secret() {
encpass_checks
encpass_ext_func "get_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
[ "$(basename "$0")" != "encpass.sh" ] && encpass_include_init "$1" "$2"
encpass_set_private_key_abs_name
encpass_set_secret_abs_name
encpass_decrypt_secret "$@"
}
set_secret() {
encpass_checks
encpass_ext_func "set_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ "$1" != "reuse" ] || { [ -z "$ENCPASS_SECRET_INPUT" ] && [ -z "$ENCPASS_CSECRET_INPUT" ]; }; then
echo "Enter $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_SECRET_INPUT
stty echo
echo "Confirm $ENCPASS_SECRET_NAME:" >&2
stty -echo
read -r ENCPASS_CSECRET_INPUT
stty echo
# Use named pipe to securely pass secret to openssl
fifo="$(encpass_mkfifo set_secret_fifo)"
fi
if [ "$ENCPASS_SECRET_INPUT" = "$ENCPASS_CSECRET_INPUT" ]; then
encpass_set_private_key_abs_name
ENCPASS_SECRET_DIR="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"
[ ! -d "$ENCPASS_SECRET_DIR" ] && mkdir -m 700 "$ENCPASS_SECRET_DIR"
# Generate IV and create secret file
printf "%s" "$(openssl rand -hex 16)" > "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
ENCPASS_OPENSSL_IV="$(cat "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc")"
echo "$ENCPASS_SECRET_INPUT" > "$fifo" &
# Allow expansion now so PID is set
# shellcheck disable=SC2064
trap "encpass_rmfifo $! $fifo" EXIT HUP TERM INT TSTP
# Append encrypted secret to IV in the secret file
openssl enc -aes-256-cbc -e -a -iv "$ENCPASS_OPENSSL_IV" \
-K "$(cat "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key")" \
-in "$fifo" 1>> "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
else
encpass_die "Error: secrets do not match. Please try again."
fi
}
encpass_decrypt_secret() {
encpass_ext_func "decrypt_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return
if [ -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
ENCPASS_DECRYPT_RESULT="$(dd if="$ENCPASS_SECRET_ABS_NAME" ibs=1 skip=32 2> /dev/null | openssl enc -aes-256-cbc \
-d -a -iv "$(head -c 32 "$ENCPASS_SECRET_ABS_NAME")" -K "$(cat "$ENCPASS_PRIVATE_KEY_ABS_NAME")" 2> /dev/null)"
if [ ! -z "$ENCPASS_DECRYPT_RESULT" ]; then
echo "$ENCPASS_DECRYPT_RESULT"
else
# If a failed unlock command occurred and the user tries to show the secret
# Present either a locked or failed decrypt error.
if [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
# The locked file wasn't present as expected. Let's display a failure
echo "Error: Failed to decrypt"
fi
fi
elif [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
echo "**Locked**"
else
echo "Error: Unable to decrypt. The key file \"$ENCPASS_PRIVATE_KEY_ABS_NAME\" is not present."
fi
}
encpass_die() {
echo "$@" >&2
exit 1
}
#LITE
Best way to store a key=>value array in JavaScript?
You can use Map.
- A new data structure introduced in JavaScript ES6.
- Alternative to JavaScript Object for storing key/value pairs.
- Has useful methods for iteration over the key/value pairs.
var map = new Map();
map.set('name', 'John');
map.set('id', 11);
// Get the full content of the Map
console.log(map); // Map { 'name' => 'John', 'id' => 11 }
Get value of the Map using key
console.log(map.get('name')); // John
console.log(map.get('id')); // 11
Get size of the Map
console.log(map.size); // 2
Check key exists in Map
console.log(map.has('name')); // true
console.log(map.has('age')); // false
Get keys
console.log(map.keys()); // MapIterator { 'name', 'id' }
Get values
console.log(map.values()); // MapIterator { 'John', 11 }
Get elements of the Map
for (let element of map) {
console.log(element);
}
// Output:
// [ 'name', 'John' ]
// [ 'id', 11 ]
Print key value pairs
for (let [key, value] of map) {
console.log(key + " - " + value);
}
// Output:
// name - John
// id - 11
Print only keys of the Map
for (let key of map.keys()) {
console.log(key);
}
// Output:
// name
// id
Print only values of the Map
for (let value of map.values()) {
console.log(value);
}
// Output:
// John
// 11
Output in a table format in Java's System.out
I may be very late for the Answer but here a simple and generic solution
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
public class TableGenerator {
private int PADDING_SIZE = 2;
private String NEW_LINE = "\n";
private String TABLE_JOINT_SYMBOL = "+";
private String TABLE_V_SPLIT_SYMBOL = "|";
private String TABLE_H_SPLIT_SYMBOL = "-";
public String generateTable(List<String> headersList, List<List<String>> rowsList,int... overRiddenHeaderHeight)
{
StringBuilder stringBuilder = new StringBuilder();
int rowHeight = overRiddenHeaderHeight.length > 0 ? overRiddenHeaderHeight[0] : 1;
Map<Integer,Integer> columnMaxWidthMapping = getMaximumWidhtofTable(headersList, rowsList);
stringBuilder.append(NEW_LINE);
stringBuilder.append(NEW_LINE);
createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
stringBuilder.append(NEW_LINE);
for (int headerIndex = 0; headerIndex < headersList.size(); headerIndex++) {
fillCell(stringBuilder, headersList.get(headerIndex), headerIndex, columnMaxWidthMapping);
}
stringBuilder.append(NEW_LINE);
createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
for (List<String> row : rowsList) {
for (int i = 0; i < rowHeight; i++) {
stringBuilder.append(NEW_LINE);
}
for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
fillCell(stringBuilder, row.get(cellIndex), cellIndex, columnMaxWidthMapping);
}
}
stringBuilder.append(NEW_LINE);
createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
stringBuilder.append(NEW_LINE);
stringBuilder.append(NEW_LINE);
return stringBuilder.toString();
}
private void fillSpace(StringBuilder stringBuilder, int length)
{
for (int i = 0; i < length; i++) {
stringBuilder.append(" ");
}
}
private void createRowLine(StringBuilder stringBuilder,int headersListSize, Map<Integer,Integer> columnMaxWidthMapping)
{
for (int i = 0; i < headersListSize; i++) {
if(i == 0)
{
stringBuilder.append(TABLE_JOINT_SYMBOL);
}
for (int j = 0; j < columnMaxWidthMapping.get(i) + PADDING_SIZE * 2 ; j++) {
stringBuilder.append(TABLE_H_SPLIT_SYMBOL);
}
stringBuilder.append(TABLE_JOINT_SYMBOL);
}
}
private Map<Integer,Integer> getMaximumWidhtofTable(List<String> headersList, List<List<String>> rowsList)
{
Map<Integer,Integer> columnMaxWidthMapping = new HashMap<>();
for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
columnMaxWidthMapping.put(columnIndex, 0);
}
for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
if(headersList.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
{
columnMaxWidthMapping.put(columnIndex, headersList.get(columnIndex).length());
}
}
for (List<String> row : rowsList) {
for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) {
if(row.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
{
columnMaxWidthMapping.put(columnIndex, row.get(columnIndex).length());
}
}
}
for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
if(columnMaxWidthMapping.get(columnIndex) % 2 != 0)
{
columnMaxWidthMapping.put(columnIndex, columnMaxWidthMapping.get(columnIndex) + 1);
}
}
return columnMaxWidthMapping;
}
private int getOptimumCellPadding(int cellIndex,int datalength,Map<Integer,Integer> columnMaxWidthMapping,int cellPaddingSize)
{
if(datalength % 2 != 0)
{
datalength++;
}
if(datalength < columnMaxWidthMapping.get(cellIndex))
{
cellPaddingSize = cellPaddingSize + (columnMaxWidthMapping.get(cellIndex) - datalength) / 2;
}
return cellPaddingSize;
}
private void fillCell(StringBuilder stringBuilder,String cell,int cellIndex,Map<Integer,Integer> columnMaxWidthMapping)
{
int cellPaddingSize = getOptimumCellPadding(cellIndex, cell.length(), columnMaxWidthMapping, PADDING_SIZE);
if(cellIndex == 0)
{
stringBuilder.append(TABLE_V_SPLIT_SYMBOL);
}
fillSpace(stringBuilder, cellPaddingSize);
stringBuilder.append(cell);
if(cell.length() % 2 != 0)
{
stringBuilder.append(" ");
}
fillSpace(stringBuilder, cellPaddingSize);
stringBuilder.append(TABLE_V_SPLIT_SYMBOL);
}
public static void main(String[] args) {
TableGenerator tableGenerator = new TableGenerator();
List<String> headersList = new ArrayList<>();
headersList.add("Id");
headersList.add("F-Name");
headersList.add("L-Name");
headersList.add("Email");
List<List<String>> rowsList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
List<String> row = new ArrayList<>();
row.add(UUID.randomUUID().toString());
row.add(UUID.randomUUID().toString());
row.add(UUID.randomUUID().toString());
row.add(UUID.randomUUID().toString());
rowsList.add(row);
}
System.out.println(tableGenerator.generateTable(headersList, rowsList));
}
}
With this kind of Output
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
| Id | F-Name | L-Name | Email |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
| 70a56f25-d42a-499c-83ac-50188c45a0ac | aa04285e-c135-46e2-9f90-988bf7796cd0 | ac495ba7-d3c7-463c-8c24-9ffde67324bc | f6b5851b-41e0-4a4e-a237-74f8e0bff9ab |
| 6de181ca-919a-4425-a753-78d2de1038ef | c4ba5771-ccee-416e-aebd-ef94b07f4fa2 | 365980cb-e23a-4513-a895-77658f130135 | 69e01da1-078e-4934-afb0-5afd6ee166ac |
| f3285f33-5083-4881-a8b4-c8ae10372a6c | 46df25ed-fa0f-42a4-9181-a0528bc593f6 | d24016bf-a03f-424d-9a8f-9a7b7388fd85 | 4b976794-aac1-441e-8bd2-78f5ccbbd653 |
| ab799acb-a582-45e7-ba2f-806948967e6c | d019438d-0a75-48bc-977b-9560de4e033e | 8cb2ad11-978b-4a67-a87e-439d0a21ef99 | 2f2d9a39-9d95-4a5a-993f-ceedd5ff9953 |
| 78a68c0a-a824-42e8-b8a8-3bdd8a89e773 | 0f030c1b-2069-4c1a-bf7d-f23d1e291d2a | 7f647cb4-a22e-46d2-8c96-0c09981773b1 | 0bc944ef-c1a7-4dd1-9eef-915712035a74 |
+----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
Have log4net use application config file for configuration data
Add a line to your app.config in the configSections element
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler, log4net, Version=1.2.10.0,
Culture=neutral, PublicKeyToken=1b44e1d426115821" />
</configSections>
Then later add the log4Net section, but delegate to the actual log4Net config file elsewhere...
<log4net configSource="Config\Log4Net.config" />
In your application code, when you create the log, write
private static ILog GetLog(string logName)
{
ILog log = LogManager.GetLogger(logName);
return log;
}
'mvn' is not recognized as an internal or external command, operable program or batch file
To solve this problem please follow the steps below:
- Download the maven zip file from
http://maven.apache.org/download.cgi
- Extract the maven zip file
- Open the environment variable and in user variable section click on new button and make a variable called MAVEN_HOME and assign it the value of bin path of extracted maven zip
- Now in System Variable click on Path and click on Edit button --> Now Click on New button and paste the bin path of maven zip
- Now click on OK button
- Open CMD and type mvn -version
- Installed Maven version will be displayed and your setup is completed
Bootstrap - Removing padding or margin when screen size is smaller
The problem here is much more complex than removing the container padding since the grid structure relies on this padding when applying negative margins for the enclosed rows.
Removing the container padding in this case will cause an x-axis overflow caused by all the rows inside of this container class, this is one of the most stupid things about the Bootstrap Grid.
Logically it should be approached by
- Never using the
.container
class for anything other than rows
- Make a clone of the
.container
class that has no padding for use with non-grid html
- For removing the
.container
padding on mobile you can manually remove it with media queries then overflow-x: hidden;
which is not very reliable but works in most cases.
If you are using LESS
the end result will look like this
@media (max-width: @screen-md-max) {
.container{
padding: 0;
overflow-x: hidden;
}
}
Change the media query to whatever size you want to target.
Final thoughts, I would highly recommend using the Foundation Framework
Grid as its way more advanced
How do I run a terminal inside of Vim?
Split the screen and run command term ++curwin
to run the terminal inside the Vim buffer. Following command does both and worked for me:
:bo 10sp | term ++curwin
Java List.contains(Object with field value equal to x)
If you need to perform this List.contains(Object with field value equal to x)
repeatedly, a simple and efficient workaround would be:
List<field obj type> fieldOfInterestValues = new ArrayList<field obj type>;
for(Object obj : List) {
fieldOfInterestValues.add(obj.getFieldOfInterest());
}
Then the List.contains(Object with field value equal to x)
would be have the same result as fieldOfInterestValues.contains(x);
MVC Razor Radio Button
<p>@Html.RadioButtonFor(x => x.type, "Item1")Item1</p>
<p>@Html.RadioButtonFor(x => x.type, "Item2")Item2</p>
<p>@Html.RadioButtonFor(x => x.type, "Item3")Item3</p>
Block direct access to a file over http but allow php script access
How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?
<IfModule authz_core_module>
Require all denied
</IfModule>
<IfModule !authz_core_module>
Deny from all
</IfModule>
How to see the proxy settings on windows?
An update to @rleelr:
It's possible to view proxy settings in Google Chrome:
chrome://net-internals/#http2
Then select
View live HTTP/2 sessions
Then select one of the live sessions (you need to have some tabs open). There you find:
[...]
t=504112 [st= 0] +HTTP2_SESSION [dt=?]
--> host = "play.google.com:443"
--> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
============================
How to fix Invalid AES key length?
You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.
This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;
public class Encrypt {
static byte [] arr = {1,2,3,4,5,6,7,8,9};
// static byte [] arr = new byte[16];
public static void main(String...args) {
try {
// System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
Base64.Decoder decoder = Base64.getDecoder();
// static byte [] arr = new byte[16];
Security.setProperty("crypto.policy", "unlimited");
String key = "Your key";
// System.out.println("-------" + key);
String value = "Hey, i am adnan";
String IV = "0123456789abcdef";
// System.out.println(value);
// log.info(value);
IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
// IvParameterSpec iv = new IvParameterSpec(arr);
// System.out.println(key);
SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
// System.out.println(skeySpec);
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
// System.out.println("ddddddddd"+IV);
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
// System.out.println(cipher.getIV());
byte[] encrypted = cipher.doFinal(value.getBytes());
String encryptedString = Base64.getEncoder().encodeToString(encrypted);
System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
// vars.put("input-1",encryptedString);
// log.info("beanshell");
}catch (Exception e){
System.out.println(e.getMessage());
}
}
}
Best way to get user GPS location in background in Android
I have try to my code and got success try this
package com.mobeyosoft.latitudelongitude;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by 5943 6417 on 14-09-2016.
*/
public class LocationService extends Service
{
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 1;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
Context context;
Intent intent;
int counter = 0;
@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
context=this;
}
@Override
public void onStart(Intent intent, int startId) {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, listener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);
}
@Override
public IBinder onBind(Intent intent){
return null;
}
protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
return true;
}
return false;
}
/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public void onDestroy() {
// handler.removeCallbacks(sendUpdatesToUI);
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);
}
public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
@Override
public void run() {
try {
runnable.run();
} finally {
}
}
};
t.start();
return t;
}
public class MyLocationListener implements LocationListener{
public void onLocationChanged(final Location loc)
{
Log.i("**********", "Location changed");
if(isBetterLocation(loc, previousBestLocation)) {
loc.getLatitude();
loc.getLongitude();
Toast.makeText(context, "Latitude" + loc.getLatitude() + "\nLongitude"+loc.getLongitude(),Toast.LENGTH_SHORT).show();
intent.putExtra("Latitude", loc.getLatitude());
intent.putExtra("Longitude", loc.getLongitude());
intent.putExtra("Provider", loc.getProvider());
sendBroadcast(intent);
}
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
Get PostGIS version
As the above people stated, select PostGIS_full_version(); will answer your question. On my machine, where I'm running PostGIS 2.0 from trunk, I get the following output:
postgres=# select PostGIS_full_version();
postgis_full_version
-------------------------------------------------------------------------------------------------------------------------------------------------------
POSTGIS="2.0.0alpha4SVN" GEOS="3.3.2-CAPI-1.7.2" PROJ="Rel. 4.7.1, 23 September 2009" GDAL="GDAL 1.8.1, released 2011/07/09" LIBXML="2.7.3" USE_STATS
(1 row)
You do need to care about the versions of PROJ and GEOS that are included if you didn't install an all-inclusive package - in particular, there's some brokenness in GEOS prior to 3.3.2 (as noted in the postgis 2.0 manual) in dealing with geometry validity.
Non-static variable cannot be referenced from a static context
Let's analyze your program first..
In your program, your first method is main()
, and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.
Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing.
*Static method calls only the static method and use only the static variable.
*Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class)
*Because of this you call it as a class variable or a class method.
And a lot more is there about the "static" keyword.
I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).
And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.
OperationalError, no such column. Django
I had this problem recently, even though on a different tutorial. I had the django version 2.2.3 so I thought I should not have this kind of issue.
In my case, once I add a new field to a model and try to access it in admin
, it would say no such column
.
I learnt the 'right' way after three days of searching for solution with nothing working.
First, if you are making a change to a model, you should make sure that the server is not running. This is what caused my own problem.
And this is not easy to rectify. I had to rename the field (while server was not running) and re-apply migrations.
Second, I found that python manage.py makemigrations <app_name>
captured the change as opposed to just python manage.py makemigrations
. I don't know why.
You could also follow that up with python manage.py migrate <app_name>
. I'm glad I found this out by myself.
Difference between wait and sleep
source : http://www.jguru.com/faq/view.jsp?EID=47127
Thread.sleep()
sends the current thread into the "Not Runnable" state
for some amount of time. The thread keeps the monitors it has aquired
-- i.e. if the thread is currently in a synchronized block or method no other thread can enter this block or method. If another thread calls t.interrupt()
it will wake up the sleeping thread.
Note that sleep is a static method, which means that it always affects
the current thread (the one that is executing the sleep method). A
common mistake is to call t.sleep()
where t is a different thread;
even then, it is the current thread that will sleep, not the t thread.
t.suspend()
is deprecated. Using it is possible to halt a thread other
than the current thread. A suspended thread keeps all its monitors and
since this state is not interruptable it is deadlock prone.
object.wait()
sends the current thread into the "Not Runnable" state,
like sleep()
, but with a twist. Wait is called on an object, not a
thread; we call this object the "lock object." Before lock.wait()
is
called, the current thread must synchronize on the lock object; wait()
then releases this lock, and adds the thread to the "wait list"
associated with the lock. Later, another thread can synchronize on the
same lock object and call lock.notify()
. This wakes up the original,
waiting thread. Basically, wait()
/notify()
is like
sleep()
/interrupt()
, only the active thread does not need a direct
pointer to the sleeping thread, but only to the shared lock object.
onKeyDown event not working on divs in React
Using the div
trick with tab_index="0"
or tabIndex="-1"
works, but any time the user is focusing a view that's not an element, you get an ugly focus-outline on the entire website. This can be fixed by setting the CSS for the div to use outline: none
in the focus.
Here's the implementation with styled components:
import styled from "styled-components"
const KeyReceiver = styled.div`
&:focus {
outline: none;
}
`
and in the App class:
render() {
return (
<KeyReceiver onKeyDown={this.handleKeyPress} tabIndex={-1}>
Display stuff...
</KeyReceiver>
)
How can I set a cookie in react?
Little update. There is a hook available for react-cookie
1) First of all, install the dependency (just for a note)
yarn add react-cookie
or
npm install react-cookie
2) My usage example:
// SignInComponent.js
import { useCookies } from 'react-cookie'
const SignInComponent = () => {
// ...
const [cookies, setCookie] = useCookies(['access_token', 'refresh_token'])
async function onSubmit(values) {
const response = await getOauthResponse(values);
let expires = new Date()
expires.setTime(expires.getTime() + (response.data.expires_in * 1000))
setCookie('access_token', response.data.access_token, { path: '/', expires})
setCookie('refresh_token', response.data.refresh_token, {path: '/', expires})
// ...
}
// next goes my sign-in form
}
Hope it is helpful.
Suggestions to improve the example above are very appreciated!
Using CSS td width absolute, position
The reason it doesn't work in the link your provided is because you are trying to display a 300px column PLUS 52 columns the span 7 columns each. Shrink the number of columns and it works. You can't fit that many on the screen.
If you want to force the columns to fit try setting:
body {min-width:4150px;}
see my jsfiddle: http://jsfiddle.net/Mkq8L/6/
@mike I can't comment yet.
How to find all links / pages on a website
If this is a programming question, then I would suggest you write your own regular expression to parse all the retrieved contents. Target tags are IMG and A for standard HTML. For JAVA,
final String openingTags = "(<a [^>]*href=['\"]?|<img[^> ]* src=['\"]?)";
this along with Pattern and Matcher classes should detect the beginning of the tags. Add LINK tag if you also want CSS.
However, it is not as easy as you may have intially thought. Many web pages are not well-formed. Extracting all the links programmatically that human being can "recognize" is really difficult if you need to take into account all the irregular expressions.
Good luck!
Viewing local storage contents on IE
In IE11, you can see local storage in console on dev tools:
- Show dev tools (press F12)
- Click "Console" or press Ctrl+2
- Type
localStorage
and press Enter
Also, if you need to clear the localStorage, type localStorage.clear()
on console.
C++ cast to derived class
Think like this:
class Animal { /* Some virtual members */ };
class Dog: public Animal {};
class Cat: public Animal {};
Dog dog;
Cat cat;
Animal& AnimalRef1 = dog; // Notice no cast required. (Dogs and cats are animals).
Animal& AnimalRef2 = cat;
Animal* AnimalPtr1 = &dog;
Animal* AnimlaPtr2 = &cat;
Cat& catRef1 = dynamic_cast<Cat&>(AnimalRef1); // Throws an exception AnimalRef1 is a dog
Cat* catPtr1 = dynamic_cast<Cat*>(AnimalPtr1); // Returns NULL AnimalPtr1 is a dog
Cat& catRef2 = dynamic_cast<Cat&>(AnimalRef2); // Works
Cat* catPtr2 = dynamic_cast<Cat*>(AnimalPtr2); // Works
// This on the other hand makes no sense
// An animal object is not a cat. Therefore it can not be treated like a Cat.
Animal a;
Cat& catRef1 = dynamic_cast<Cat&>(a); // Throws an exception Its not a CAT
Cat* catPtr1 = dynamic_cast<Cat*>(&a); // Returns NULL Its not a CAT.
Now looking back at your first statement:
Animal animal = cat; // This works. But it slices the cat part out and just
// assigns the animal part of the object.
Cat bigCat = animal; // Makes no sense.
// An animal is not a cat!!!!!
Dog bigDog = bigCat; // A cat is not a dog !!!!
You should very rarely ever need to use dynamic cast.
This is why we have virtual methods:
void makeNoise(Animal& animal)
{
animal.DoNoiseMake();
}
Dog dog;
Cat cat;
Duck duck;
Chicken chicken;
makeNoise(dog);
makeNoise(cat);
makeNoise(duck);
makeNoise(chicken);
The only reason I can think of is if you stored your object in a base class container:
std::vector<Animal*> barnYard;
barnYard.push_back(&dog);
barnYard.push_back(&cat);
barnYard.push_back(&duck);
barnYard.push_back(&chicken);
Dog* dog = dynamic_cast<Dog*>(barnYard[1]); // Note: NULL as this was the cat.
But if you need to cast particular objects back to Dogs then there is a fundamental problem in your design. You should be accessing properties via the virtual methods.
barnYard[1]->DoNoiseMake();
What's the difference between console.dir and console.log?
Another useful difference in Chrome exists when sending DOM elements to the console.
Notice:
console.log
prints the element in an HTML-like tree
console.dir
prints the element in a JSON-like tree
Specifically, console.log
gives special treatment to DOM elements, whereas console.dir
does not. This is often useful when trying to see the full representation of the DOM JS object.
There's more information in the Chrome Console API reference about this and other functions.
ASP.NET MVC Custom Error Handling Application_Error Global.asax?
Brian,
This approach works great for non-Ajax requests, but as Lion_cl stated, if you have an error during an Ajax call, your Share/Error.aspx view (or your custom error page view) will be returned to the Ajax caller--the user will NOT be redirected to the error page.
Write values in app.config file
//if you want change
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings[key].Value = value;
//if you want add
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add("key", value);
Merge two rows in SQL
if one row has value in field1 column and other rows have null value then this Query might work.
SELECT
FK,
MAX(Field1) as Field1,
MAX(Field2) as Field2
FROM
(
select FK,ISNULL(Field1,'') as Field1,ISNULL(Field2,'') as Field2 from table1
)
tbl
GROUP BY FK
Python 3: ImportError "No Module named Setuptools"
For others with the same issue due to a different reason: This can also happen when there's a pyproject.toml
in the same directory as the setup.py
, even when setuptools
is available.
Removing pyproject.toml
fixed the issue for me.
Copy Paste Values only( xlPasteValues )
You may use this too
Sub CopyPaste()
Sheet1.Range("A:A").Copy
Sheet2.Activate
col = 1
Do Until Sheet2.Cells(1, col) = ""
col = col + 1
Loop
Sheet2.Cells(1, col).PasteSpecial xlPasteValues
End Sub
How to iterate through SparseArray?
The answer is no because SparseArray
doesn't provide it. As pst
put it, this thing doesn't provide any interfaces.
You could loop from 0 - size()
and skip values that return null
, but that is about it.
As I state in my comment, if you need to iterate use a Map
instead of a SparseArray
. For example, use a TreeMap
which iterates in order by the key.
TreeMap<Integer, MyType>
Provide schema while reading csv file as a dataframe
This is one of option where we can pass the column names to the dataframe while loading CSV.
import pandas
names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']
dataset = pandas.read_csv("C:/Users/NS00606317/Downloads/Iris.csv", names=names, header=0)
print(dataset.head(10))
Output
sepal-length sepal-width petal-length petal-width class
1 5.1 3.5 1.4 0.2 Iris-setosa
2 4.9 3.0 1.4 0.2 Iris-setosa
3 4.7 3.2 1.3 0.2 Iris-setosa
4 4.6 3.1 1.5 0.2 Iris-setosa
5 5.0 3.6 1.4 0.2 Iris-setosa
6 5.4 3.9 1.7 0.4 Iris-setosa
7 4.6 3.4 1.4 0.3 Iris-setosa
8 5.0 3.4 1.5 0.2 Iris-setosa
9 4.4 2.9 1.4 0.2 Iris-setosa
10 4.9 3.1 1.5 0.1 Iris-setosa
How to position a Bootstrap popover?
I solved this (partially) by adding some lines of code to the bootstrap css library. You will have to modify tooltip.js, tooltip.less, popover.js, and popover.less
in tooltip.js, add this case in the switch statement there
case 'bottom-right':
tp = {top: pos.top + pos.height, left: pos.left + pos.width}
break
in tooltip.less, add these two lines in .tooltip{}
&.bottom-right { margin-top: -2px; }
&.bottom-right .tooltip-arrow { #popoverArrow > .bottom(); }
do the same in popover.js and popover.less. Basically, wherever you find code where other positions are mentioned, add your desired position accordingly.
As I mentioned earlier, this solved the problem partially. My problem now is that the little arrow of the popover does not appear.
note: if you want to have the popover in top-left, use top attribute of '.top' and left attribute of '.left'
How to determine equality for two JavaScript objects?
I'd advise against hashing or serialization (as the JSON solution suggest). If you need to test if two objects are equal, then you need to define what equals means. It could be that all data members in both objects match, or it could be that must the memory locations match (meaning both variables reference the same object in memory), or may be that only one data member in each object must match.
Recently I developed an object whose constructor creates a new id (starting from 1 and incrementing by 1) each time an instance is created. This object has an isEqual function that compares that id value with the id value of another object and returns true if they match.
In that case I defined "equal" as meaning the the id values match. Given that each instance has a unique id this could be used to enforce the idea that matching objects also occupy the same memory location. Although that is not necessary.
How to add element to C++ array?
You don't have to use vectors. If you want to stick with plain arrays, you can do something like this:
int arr[] = new int[15];
unsigned int arr_length = 0;
Now, if you want to add an element to the end of the array, you can do this:
if (arr_length < 15) {
arr[arr_length++] = <number>;
} else {
// Handle a full array.
}
It's not as short and graceful as the PHP equivalent, but it accomplishes what you were attempting to do. To allow you to easily change the size of the array in the future, you can use a #define.
#define ARRAY_MAX 15
int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
if (arr_length < ARRAY_MAX) {
arr[arr_length++] = <number>;
} else {
// Handle a full array.
}
This makes it much easier to manage the array in the future. By changing 15 to 100, the array size will be changed properly in the whole program. Note that you will have to set the array to the maximum expected size, as you can't change it once the program is compiled. For example, if you have an array of size 100, you could never insert 101 elements.
If you will be using elements off the end of the array, you can do this:
if (arr_length > 0) {
int value = arr[arr_length--];
} else {
// Handle empty array.
}
If you want to be able to delete elements off the beginning, (ie a FIFO), the solution becomes more complicated. You need a beginning and end index as well.
#define ARRAY_MAX 15
int arr[] = new int[ARRAY_MAX];
unsigned int arr_length = 0;
unsigned int arr_start = 0;
unsigned int arr_end = 0;
// Insert number at end.
if (arr_length < ARRAY_MAX) {
arr[arr_end] = <number>;
arr_end = (arr_end + 1) % ARRAY_MAX;
arr_length ++;
} else {
// Handle a full array.
}
// Read number from beginning.
if (arr_length > 0) {
int value = arr[arr_start];
arr_start = (arr_start + 1) % ARRAY_MAX;
arr_length --;
} else {
// Handle an empty array.
}
// Read number from end.
if (arr_length > 0) {
int value = arr[arr_end];
arr_end = (arr_end + ARRAY_MAX - 1) % ARRAY_MAX;
arr_length --;
} else {
// Handle an empty array.
}
Here, we are using the modulus operator (%) to cause the indexes to wrap. For example, (99 + 1) % 100 is 0 (a wrapping increment). And (99 + 99) % 100 is 98 (a wrapping decrement). This allows you to avoid if statements and make the code more efficient.
You can also quickly see how helpful the #define is as your code becomes more complex. Unfortunately, even with this solution, you could never insert over 100 items (or whatever maximum you set) in the array. You are also using 100 bytes of memory even if only 1 item is stored in the array.
This is the primary reason why others have recommended vectors. A vector is managed behind the scenes and new memory is allocated as the structure expands. It is still not as efficient as an array in situations where the data size is already known, but for most purposes the performance differences will not be important. There are trade-offs to each approach and it's best to know both.
Difference between os.getenv and os.environ.get
While there is no functional difference between os.environ.get
and os.getenv
, there is a massive difference between os.putenv
and setting entries on os.environ
. os.putenv
is broken, so you should default to os.environ.get
simply to avoid the way os.getenv
encourages you to use os.putenv
for symmetry.
os.putenv
changes the actual OS-level environment variables, but in a way that doesn't show up through os.getenv
, os.environ
, or any other stdlib way of inspecting environment variables:
>>> import os
>>> os.environ['asdf'] = 'fdsa'
>>> os.environ['asdf']
'fdsa'
>>> os.putenv('aaaa', 'bbbb')
>>> os.getenv('aaaa')
>>> os.environ.get('aaaa')
You'd probably have to make a ctypes call to the C-level getenv
to see the real environment variables after calling os.putenv
. (Launching a shell subprocess and asking it for its environment variables might work too, if you're very careful about escaping and --norc
/--noprofile
/anything else you need to do to avoid startup configuration, but it seems a lot harder to get right.)
TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"
Thank you to all the commenters on this page. When I first installed the latest TortoiseSVN I got this error.
I was using the latest version, so decided to downgrade to 1.5.9 (as the rest of my colleagues were using) and this got it to work. Then, once built, my machine was moved onto another subnet and the problem started again.
I went to TortoiseSVN->Settings->Saved Data and cleared the Authentication data. After this it worked fine.
Where can I get Google developer key
If you are only calling APIs that do not require user data, such as
the Google Custom Search API, then API keys might be simpler to use
than OAuth 2.0 access tokens. However, if your application already
uses an OAuth 2.0 access token, then there is no need to generate an
API key as well. Google ignores passed API keys if a passed OAuth 2.0
access token is already associated with the corresponding project.
Note: You must use either an OAuth 2.0 access token or an API key for
all requests to Google APIs represented in the Google Developers
Console. Not all APIs require authorized calls. To learn whether
authorization is required for a specific call, see your API
documentation.
Reference: https://developers.google.com/console/help/new/?hl=en_US#credentials-access-security-and-identity
Is it safe to expose Firebase apiKey to the public?
You should not expose this info. in public, specially api keys.
It may lead to a privacy leak.
Before making the website public you should hide it. You can do it in 2 or more ways
- Complex coding/hiding
- Simply put firebase SDK codes at bottom of your website or app thus firebase automatically does all works. you don't need to put API keys anywhere
Angular is automatically adding 'ng-invalid' class on 'required' fields
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
How do I set the background color of my main screen in Flutter?
On the basic example of Flutter you can set with backgroundColor: Colors.X
of Scaffold
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
backgroundColor: Colors.blue,
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add_circle),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
get the latest fragment in backstack
The answer given by deepak goel does not work for me because I always get null from entry.getName()
;
What I do is to set a Tag to the fragment this way:
ft.add(R.id.fragment_container, fragmentIn, FRAGMENT_TAG);
Where ft is my fragment transaction and FRAGMENT_TAG
is the tag. Then I use this code to get the fragment:
Fragment prev_fragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG);
TimeStamp on file name using PowerShell
I needed to export our security log and wanted the date and time in Coordinated Universal Time. This proved to be a challenge to figure out, but so simple to execute:
wevtutil export-log security c:\users\%username%\SECURITYEVENTLOG-%computername%-$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ")).evtx
The magic code is just this part:
$(((get-date).ToUniversalTime()).ToString("yyyyMMddTHHmmssZ"))
How to create a new instance from a class object in Python
Just call the "type" built in using three parameters, like this:
ClassName = type("ClassName", (Base1, Base2,...), classdictionary)
update
as stated in the comment bellow this is not the answer to this question at all. I will keep it undeleted, since there are hints some people get here trying to dynamically create classes - which is what the line above does.
To create an object of a class one has a reference too, as put in the accepted answer, one just have to call the class:
instance = ClassObject()
The mechanism for instantiation is thus:
Python does not use the new
keyword some languages use - instead it's data model explains the mechanism used to create an instantance of a class when it is called with the same syntax as any other callable:
Its class' __call__
method is invoked (in the case of a class, its class is the "metaclass" - which is usually the built-in type
). The normal behavior of this call is to invoke the (pseudo) static __new__
method on the class being instantiated, followed by its __init__
. The __new__
method is responsible for allocating memory and such, and normally is done by the __new__
of object
which is the class hierarchy root.
So calling ClassObject()
invokes ClassObject.__class__.call()
(which normally will be type.__call__
) this __call__
method will receive ClassObject itself as the first parameter - a Pure Python implementation would be like this: (the cPython version is of course, done in C, and with lots of extra code for cornercases and optimizations)
class type:
...
def __call__(cls, *args, **kw):
constructor = getattr(cls, "__new__")
instance = constructor(cls) if constructor is object.__new__ else constructor(cls, *args, **kw)
instance.__init__(cls, *args, **kw)
return instance
(I don't recall seeing on the docs the exact justification (or mechanism) for suppressing extra parameters to the root __new__
and passing it to other classes - but it is what happen "in real life" - if object.__new__
is called with any extra parameters it raises a type error - however, any custom implementation of a __new__
will get the extra parameters normally)
VHDL - How should I create a clock in a testbench?
Concurrent signal assignment:
library ieee;
use ieee.std_logic_1164.all;
entity foo is
end;
architecture behave of foo is
signal clk: std_logic := '0';
begin
CLOCK:
clk <= '1' after 0.5 ns when clk = '0' else
'0' after 0.5 ns when clk = '1';
end;
ghdl -a foo.vhdl
ghdl -r foo --stop-time=10ns --wave=foo.ghw
ghdl:info: simulation stopped by --stop-time
gtkwave foo.ghw
Simulators simulate processes and it would be transformed into the equivalent process to your process statement. Simulation time implies the use of wait for or after when driving events for sensitivity clauses or sensitivity lists.