Same error, I upgrade my Junit
and resolve it
org.junit.jupiter:junit-jupiter-api:5.0.0-M6
to
org.junit.jupiter:junit-jupiter-api:5.0.0
In my case, with letsencrypt https, this was caused by using cert.pem
instead of fullchain.pem
as the certificate file on the requested server. See this thread for details.
From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.
The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.
If this issue is causing serious problems, here are a few things I would suggest:
Revert back to JDK 1.7.0_25 until a fix is added to the JDK.
Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.
Try the JDK early releases as they come out. One of them might fix your problem.
Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.
If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like
/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home
Rather than user home...
If you are using shared hosting, then there are chances that outbound port might be disabled by your hosting provider. So please contact your hosting provider and they will open the outbound port for you
Right click on the .svc file in Solution Explorer and click View Markup
<%@ ServiceHost Language="C#" Debug="true"
Service="MyService.**GetHistoryInfo**"
CodeBehind="GetHistoryInfo.svc.cs" %>
Update the service reference where you are referring to.
A few things here...
If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.
Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.
Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...
<a href=# onclick="ReAssign('valuationId', window.user)">Re-Assign</a>
There are a few extra things to note here, if you want more than a quick solution.
You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).
Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:
.runjs {
cursor: pointer;
text-decoration: underline;
color: blue;
}
This lets you leave out the href attribute which you weren't using anyways.
Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...
var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
links[i].onclick = function() { ReAssign('valuationId', window.user); };
While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.
Change:
struct timeval, tvalBefore, tvalAfter; /* Looks like an attempt to
delcare a variable with
no name. */
to:
struct timeval tvalBefore, tvalAfter;
It is less likely (IMO) to make this mistake if there is a single declaration per line:
struct timeval tvalBefore;
struct timeval tvalAfter;
It becomes more error prone when declaring pointers to types on a single line:
struct timeval* tvalBefore, tvalAfter;
tvalBefore
is a struct timeval*
but tvalAfter
is a struct timeval
.
javac should know where to search for classes. Try this:
javac -cp . p1.java
You shouldn't need to specify classpath. Are you sure the file p1.java exists?
Check Permissions In KOTLIN (RunTime)
In Manifest: (android.permission.WRITE_EXTERNAL_STORAGE)
fun checkPermissions(){
var permission_array=arrayOf(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
if((ContextCompat.checkSelfPermission(this,permission_array[0]))==PackageManager.PERMI SSION_DENIED){
requestPermissions(permission_array,0)
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if(requestCode==0 && grantResults[0]==PackageManager.PERMISSION_GRANTED){
//Do Your Operations Here
---------->
//
}
}
Creating static library worked for me, compiling using g++ -static
. It bundles the dependent libraries along with the build.
I think the answer may be easier to understand like this:
$('#empid').on('change',function() {_x000D_
alert($(this).val());_x000D_
console.log($(this).val());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<select id="empid" name="empname" multiple="multiple">_x000D_
<option value="0">Potato</option>_x000D_
<option value="1">Carrot</option>_x000D_
<option value="2">Apple</option>_x000D_
<option value="3">Raisins</option>_x000D_
<option value="4">Peanut</option>_x000D_
</select>_x000D_
<br />_x000D_
Hold CTRL / CMD for selecting multiple fields
_x000D_
If you select "Carrot" and "Raisins" in the list, the output will be "1,3".
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
I was able to solve this using this alter statement on my table that had two datetime fields.
ALTER TABLE `test_table`
CHANGE COLUMN `created_dt` `created_dt` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
CHANGE COLUMN `updated_dt` `updated_dt` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.
CREATE TRIGGER trig_test_table_insert BEFORE INSERT ON `test_table`
FOR EACH ROW SET NEW.created_dt = NOW();
The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Generate the migration file:
rails g migration FixName
# Creates db/migrate/xxxxxxxxxx.rb
Edit the migration to do your will.
class FixName < ActiveRecord::Migration
def change
rename_column :table_name, :old_column, :new_column
end
end
I would place this as a comment to Triptych, but I can't comment yet due to lack of rating:
Using the enumerator method to match on sub-indices in a list of tuples. e.g.
li = [(1,2,3,4), (11,22,33,44), (111,222,333,444), ('a','b','c','d'),
('aa','bb','cc','dd'), ('aaa','bbb','ccc','ddd')]
# want pos of item having [22,44] in positions 1 and 3:
def getIndexOfTupleWithIndices(li, indices, vals):
# if index is a tuple of subindices to match against:
for pos,k in enumerate(li):
match = True
for i in indices:
if k[i] != vals[i]:
match = False
break;
if (match):
return pos
# Matches behavior of list.index
raise ValueError("list.index(x): x not in list")
idx = [1,3]
vals = [22,44]
print getIndexOfTupleWithIndices(li,idx,vals) # = 1
idx = [0,1]
vals = ['a','b']
print getIndexOfTupleWithIndices(li,idx,vals) # = 3
idx = [2,1]
vals = ['cc','bb']
print getIndexOfTupleWithIndices(li,idx,vals) # = 4
I use Pokémon database as an example, the columns for my data base are
['Name', '#', 'Type 1', 'Type 2', 'Total', 'HP', 'Attack', 'Defense', 'Sp. Atk', 'Sp. Def', 'Speed', 'Generation', 'Legendary']
Here is the code:
import pandas as pd
df = pd.read_html('https://gist.github.com/armgilles/194bcff35001e7eb53a2a8b441e8b2c6')[0]
cols = df.columns.to_list()
cos_end= ["Name", "Total", "HP", "Defense"]
for i, j in enumerate(cos_end, start=(len(cols)-len(cos_end))):
cols.insert(i, cols.pop(cols.index(j)))
print(cols)
df = df.reindex(columns=cols)
print(df)
::
is used to link something ( a variable, a function, a class, a typedef etc...) to a namespace, or to a class.
if there is no left hand side before ::
, then it underlines the fact you are using the global namespace.
e.g.:
::doMyGlobalFunction();
Without VBA...
If you can use a helper column, you can use the MATCH
function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match
To simply identify duplicates, use a helper column
Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:
=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")
Drag/copy this forumla down, and it should identify the duplicates.
To highlight cells, use conditional formatting:
With some tinkering, you can use this MATCH
function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.
Something like:
=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))
For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:
=B1="Duplicate"
This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.
For me, changing the Start In location (of git-gui at least) did not affect where it looked for .gitconfig. My setup at work mounts U: for our home, but we do not have permission to write in U: directly, only subdirectories which were created for us inside, so this was a deal-breaker for me.
I solved the problem by making a batch script which would override the HOMEDRIVE and HOMEPATH env variables just for that application. Then changed my Start menu shortcut to point to that batch script instead.
I agree with:
hashCode()
implementation could result to multiple collisions, which means that in the worst case every object goes to the same bucket, thus O(N) if each bucket is backed by a List
.HashMap
dynamically replaces the Nodes (linked list) used in each bucket with TreeNodes (red-black tree when a list gets bigger than 8 elements) resulting to a worst performance of O(logN).But, this is not the full truth if we want to be 100% precise. The implementation of hashCode()
and the type of key Object
(immutable/cached or being a Collection) might also affect real time complexity in strict terms.
Let's assume the following three cases:
HashMap<Integer, V>
HashMap<String, V>
HashMap<List<E>, V>
Do they have the same complexity? Well, the amortised complexity of the 1st one is, as expected, O(1). But, for the rest, we also need to compute hashCode()
of the lookup element, which means we might have to traverse arrays and lists in our algorithm.
Lets assume that the size of all of the above arrays/lists is k.
Then, HashMap<String, V>
and HashMap<List<E>, V>
will have O(k) amortised complexity and similarly, O(k + logN) worst case in Java8.
*Note that using a String
key is a more complex case, because it is immutable and Java caches the result of hashCode()
in a private variable hash
, so it's only computed once.
/** Cache the hash code for the string */
private int hash; // Default to 0
But, the above is also having its own worst case, because Java's String.hashCode()
implementation is checking if hash == 0
before computing hashCode
. But hey, there are non-empty Strings that output a hashcode
of zero, such as "f5a5a608", see here, in which case memoization might not be helpful.
you can't get city location by ip. here you can get country with jquery:
$.get("http://ip-api.com/json", function(response) {
console.log(response.country);}, "jsonp");
Others have already properly compared delete
with splice
.
Another interesting comparison is delete
versus undefined
: a deleted array item uses less memory than one that is just set to undefined
;
For example, this code will not finish:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
It produces this error:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
So, as you can see undefined
actually takes up heap memory.
However, if you also delete
the ary-item (instead of just setting it to undefined
), the code will slowly finish:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
These are extreme examples, but they make a point about delete
that I haven't seen anyone mention anywhere.
You can use the utility method Arrays.asList
and feed that result into a new ArrayList
.
List<String> list = new ArrayList<String>(Arrays.asList(s));
Other options:
List<String> list = new ArrayList<String>(Collections.nCopies(1, s));
and
List<String> list = new ArrayList<String>(Collections.singletonList(s));
ArrayList(Collection)
constructor.Arrays.asList
method.Collections.nCopies
method.Collections.singletonList
method.With Java 7+, you may use the "diamond operator", replacing new ArrayList<String>(...)
with new ArrayList<>(...)
.
Java 9
If you're using Java 9+, you can use the List.of
method:
List<String> list = new ArrayList<>(List.of(s));
Regardless of the use of each option above, you may choose not to use the new ArrayList<>()
wrapper if you don't need your list to be mutable.
Its quite easy on computer a you don't need to do anything just make sure both system are on same network if its not internet access(for this you need static ip). Okay now on computer b go to start menu find configuration under oracle folder click Net Configuration Assistant under that folder when window pop up click Local net configuration option it must be third option.
Now click add and click next in next screen it will ask service name here you need to add oracle global database name of computer A(Normally I use oracle86 for my installation) now click next next screen choose protocol normally its tcp click next in host name enter computer A's name you can found that in my computer properties. Click next don't change port untill you have changed that in Computer A click next and choose test connection now here you can check your connection working or not if the error is username and password not correct then click login credential button and fill correct username and password. If its saying unable to reach computer ot target not found than you must add exception in firewall for 1521 port or just disable firewall on computer A.
set display:none
for all other elements which are not for prints.
setting visibility:hidden
will keep them hidden, but they all are still there and have taken space for them. empty page is for those hidden elements.
First you should come out of the mongo
shell and then execute the mongoimport
command like this:
Manojs-MacBook-Air:bin Aditya$ mongoimport -d marketdata -c minibars
--type csv
--headerline
--file '/Users/Aditya/Downloads/mstf.csv'
2017-05-13T20:00:41.989+0800 connected to: localhost
2017-05-13T20:00:44.123+0800 imported 97609 documents
Manojs-MacBook-Air:bin Aditya$
At the moment this doesn't really exist (although you can of course write your own). There is an open connect bug for it: https://connect.microsoft.com/SQLServer/Feedback/Details/3130221, which as of this writing has just 1 vote.
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
Matcher matcher = pattern.matcher("Teststring123");
if(matcher.matches()) {
// yay! alphanumeric!
}
I use one Factory
module that contains one (or more) constructor per class which calls the Init
member of each class.
For example a Point
class:
Class Point
Private X, Y
Sub Init(X, Y)
Me.X = X
Me.Y = Y
End Sub
A Line
class
Class Line
Private P1, P2
Sub Init(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
If P1 Is Nothing Then
Set Me.P1 = NewPoint(X1, Y1)
Set Me.P2 = NewPoint(X2, Y2)
Else
Set Me.P1 = P1
Set Me.P2 = P2
End If
End Sub
And a Factory
module:
Module Factory
Function NewPoint(X, Y)
Set NewPoint = New Point
NewPoint.Init X, Y
End Function
Function NewLine(Optional P1, Optional P2, Optional X1, Optional X2, Optional Y1, Optional Y2)
Set NewLine = New Line
NewLine.Init P1, P2, X1, Y1, X2, Y2
End Function
Function NewLinePt(P1, P2)
Set NewLinePt = New Line
NewLinePt.Init P1:=P1, P2:=P2
End Function
Function NewLineXY(X1, Y1, X2, Y2)
Set NewLineXY = New Line
NewLineXY.Init X1:=X1, Y1:=Y1, X2:=X2, Y2:=Y2
End Function
One nice aspect of this approach is that makes it easy to use the factory functions inside expressions. For example it is possible to do something like:
D = Distance(NewPoint(10, 10), NewPoint(20, 20)
or:
D = NewPoint(10, 10).Distance(NewPoint(20, 20))
It's clean: the factory does very little and it does it consistently across all objects, just the creation and one Init
call on each creator.
And it's fairly object oriented: the Init
functions are defined inside the objects.
EDIT
I forgot to add that this allows me to create static methods. For example I can do something like (after making the parameters optional):
NewLine.DeleteAllLinesShorterThan 10
Unfortunately a new instance of the object is created every time, so any static variable will be lost after the execution. The collection of lines and any other static variable used in this pseudo-static method must be defined in a module.
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
Instructions
Window
> Preferences
.Remote Systems
drop-down root menu. Select File Cache
.Clear Cached Files
button in the File Cache window. Note
that this will automatically close any open remote files on your
computer.Apply
and OK
to save your changes and exit out of the
Preferences window.Potential danger of INSERT IGNORE. If you are trying to insert VARCHAR value longer then column was defined with - the value will be truncated and inserted EVEN IF strict mode is enabled.
check if a key is pressed, if yes, then do stuff
Consider 'select()', if this (reportedly Posix) function is available on your os.
'select()' uses 3 sets of bits, which you create using functions provided (see man select, FD_SET, etc). You probably only need create the input bits (for now)
from man page:
'select()' "allow a program to monitor multiple file descriptors, waiting until one or more of the file descriptors become "ready" for some class of I/O operation (e.g., input possible). A file descriptor is considered ready if it is possible to perform a corresponding I/O operation (e.g., read(2) without blocking...)"
When select is invoked:
a) the function looks at each fd identified in the sets, and if that fd state indicates you can do something (perhaps read, perhaps write), select will return and let you go do that ... 'all you got to do' is scan the bits, find the set bit, and take action on the fd associated with that bit.
The 1st set (passed into select) contains active input fd's (typically devices). Probably 1 bit in this set is all you will need. And with only 1 fd (i.e. an input from keyboard), 1 bit, this is all quite simple. With this return from select, you can 'do-stuff' (perhaps, after you have fetched the char).
b) the function also has a timeout, with which you identify how much time to await a change of the fd state. If the fd state does not change, the timeout will cause 'select()' to return with a 0. (i.e. no keyboard input) Your code can do something at this time, too, perhaps an output.
fyi - fd's are typically 0,1,2... Remembe that C uses 0 as STDIN, 1 and STDOUT.
Simple test set up: I open a terminal (separate from my console), and type the tty command in that terminal to find its id. The response is typically something like "/dev/pts/0", or 3, or 17...
Then I get an fd to use in 'select()' by using open:
// flag options are: O_RDONLY, O_WRONLY, or O_RDWR
int inFD = open( "/dev/pts/5", O_RDONLY );
It is useful to cout this value.
Here is a snippet to consider (from man select):
fd_set rfds;
struct timeval tv;
int retval;
/* Watch stdin (fd 0) to see when it has input. */
FD_ZERO(&rfds);
FD_SET(0, &rfds);
/* Wait up to five seconds. */
tv.tv_sec = 5;
tv.tv_usec = 0;
retval = select(1, &rfds, NULL, NULL, &tv);
/* Don't rely on the value of tv now! */
if (retval == -1)
perror("select()");
else if (retval)
printf("Data is available now.\n"); // i.e. doStuff()
/* FD_ISSET(0, &rfds) will be true. */
else
printf("No data within five seconds.\n"); // i.e. key not pressed
You will have to provide a link to your file that is accessible through the browser, that is for instance:
<a href="http://my.domain.com/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
versus
<a href="C:/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
If you expose your "Projecten" folder directly to the public, then you may only have to provide the link as such:
<a href="/Projecten/Protocollen/346/Uitvoeringsoverzicht.xls">
But beware, that your files can then be indexed by search engines, can be accessed by anybody having this link, etc.
It will work.
long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));
I had the same problem.
The cause for me was that the Command
option in Configuration Properties | Debugging
had been reset to its default value.
This appears to be a very simple answer on how to differentiate between fact and dimension tables!
It may help to think of dimensions as things or objects. A thing such as a product can exist without ever being involved in a business event. A dimension is your noun. It is something that can exist independent of a business event, such as a sale. Products, employees, equipment, are all things that exist. A dimension either does something, or has something done to it.
Employees sell, customers buy. Employees and customers are examples of dimensions, they do.
Products are sold, they are also dimensions as they have something done to them.
Facts, are the verb. An entry in a fact table marks a discrete event that happens to something from the dimension table. A product sale would be recorded in a fact table. The event of the sale would be noted by what product was sold, which employee sold it, and which customer bought it. Product, Employee, and Customer are all dimensions that describe the event, the sale.
In addition fact tables also typically have some kind of quantitative data. The quantity sold, the price per item, total price, and so on.
Source: http://arcanecode.com/2007/07/23/dimensions-versus-facts-in-data-warehousing/
I would use VMs. Create an XP (or whatever) VM using VMware Workstation or similar product, and snapshot it. That is your oldest version. Then perform the upgrades one at a time, and snapshot each time. Then you can switch to any snapshot you need later, or clone independent VMs based on all the snapshots so you can run them all at once. You probably want to test on different operating systems as well as different versions, so VMs generalize that solution as well rather than some one-off solution of hacking multiple IEs to coexist on a single instance of Windows.
Some answers seem to be a little misleading.
.cpp
file for initializing since it can be done in the same Header file.Also, you can even initialize a static object in the same class scope just like a normal variable using the inline
keyword.
Initialize with no values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str;
int A::x;
Initialize with values in the same file
#include <string>
class A
{
static std::string str;
static int x;
};
std::string A::str = "SO!";
int A::x = 900;
Initialize in the same class scope using the inline
keyword
#include <string>
class A
{
static inline std::string str = "SO!";
static inline int x = 900;
};
Since at this point this question is almost a support group for people who suffer with various reasons on why WhatsApp wouldn't load the image preview, here's what was the root cause for my case, hoping it may help someone eventually:
og:image
content link is using HTTPSWhen I made my website available through https
, I forgot to specifically change the meta tags from http
to https
. Every other social media preview handled the image regardless, except for WhatsApp.
Simply making it https
fixed it for me.
Create a CustomAdapter and in that you have the getView() so there if you want to change the listview background color use this :
v.setBackgroundColor(Color.CYAN);
If you want to change the textColor then do this :
tv.setTextColor(Color.RED);
and for the textSize :
tv.setTextSize(20);
where 'v' is the listview and 'tv' is the textview
None of the above solutions were suitable for my scenario, handling .Navigated and .FileDownload events seemed like a good fit but accessing the WebBrowser.Document property threw an UnauthorizedAccessException which is caused by cross frame scripting security (our web content contains frames - all on the same domain/address but frames have their own security holes that are being blocked).
The solution that worked was to override IOleCommandTarget and to catch the script error commands at that level. Here's the WebBrowser sub-class to achieve this:
/// <summary>
/// Subclassed WebBrowser that suppresses error pop-ups.
///
/// Notes.
/// ScriptErrorsSuppressed property is not used because this actually suppresses *all* pop-ups.
///
/// More info at:
/// http://stackoverflow.com/questions/2476360/disable-javascript-error-in-webbrowser-control
/// </summary>
public class WebBrowserEx : WebBrowser
{
#region Constructor
/// <summary>
/// Default constructor.
/// Initialise browser control and attach customer event handlers.
/// </summary>
public WebBrowserEx()
{
this.ScriptErrorsSuppressed = false;
}
#endregion
#region Overrides
/// <summary>
/// Override to allow custom script error handling.
/// </summary>
/// <returns></returns>
protected override WebBrowserSiteBase CreateWebBrowserSiteBase()
{
return new WebBrowserSiteEx(this);
}
#endregion
#region Inner Class [WebBrowserSiteEx]
/// <summary>
/// Sub-class to allow custom script error handling.
/// </summary>
protected class WebBrowserSiteEx : WebBrowserSite, NativeMethods.IOleCommandTarget
{
/// <summary>
/// Default constructor.
/// </summary>
public WebBrowserSiteEx(WebBrowserEx webBrowser) : base (webBrowser)
{
}
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of OLECMD structures that indicate the commands for which the caller needs status information. This method fills the <paramref name="cmdf" /> member of each structure with values taken from the OLECMDF enumeration.</param>
/// <param name="pCmdText">An OLECMDTEXT structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
public int QueryStatus(ref Guid pguidCmdGroup, int cCmds, NativeMethods.OLECMD prgCmds, IntPtr pCmdText)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == prgCmds.cmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
public int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, object[] pvaIn, int pvaOut)
{
if((int)NativeMethods.OLECMDID.OLECMDID_SHOWSCRIPTERROR == nCmdID)
{ // Do nothing (suppress script errors)
return NativeMethods.S_OK;
}
// Indicate that command is unknown. The command will then be handled by another IOleCommandTarget.
return NativeMethods.OLECMDERR_E_UNKNOWNGROUP;
}
}
#endregion
}
~
/// <summary>
/// Native (unmanaged) methods, required for custom command handling for the WebBrowser control.
/// </summary>
public static class NativeMethods
{
/// From docobj.h
public const int OLECMDERR_E_UNKNOWNGROUP = -2147221244;
/// <summary>
/// From Microsoft.VisualStudio.OLE.Interop (Visual Studio 2010 SDK).
/// </summary>
public enum OLECMDID
{
/// <summary />
OLECMDID_OPEN = 1,
/// <summary />
OLECMDID_NEW,
/// <summary />
OLECMDID_SAVE,
/// <summary />
OLECMDID_SAVEAS,
/// <summary />
OLECMDID_SAVECOPYAS,
/// <summary />
OLECMDID_PRINT,
/// <summary />
OLECMDID_PRINTPREVIEW,
/// <summary />
OLECMDID_PAGESETUP,
/// <summary />
OLECMDID_SPELL,
/// <summary />
OLECMDID_PROPERTIES,
/// <summary />
OLECMDID_CUT,
/// <summary />
OLECMDID_COPY,
/// <summary />
OLECMDID_PASTE,
/// <summary />
OLECMDID_PASTESPECIAL,
/// <summary />
OLECMDID_UNDO,
/// <summary />
OLECMDID_REDO,
/// <summary />
OLECMDID_SELECTALL,
/// <summary />
OLECMDID_CLEARSELECTION,
/// <summary />
OLECMDID_ZOOM,
/// <summary />
OLECMDID_GETZOOMRANGE,
/// <summary />
OLECMDID_UPDATECOMMANDS,
/// <summary />
OLECMDID_REFRESH,
/// <summary />
OLECMDID_STOP,
/// <summary />
OLECMDID_HIDETOOLBARS,
/// <summary />
OLECMDID_SETPROGRESSMAX,
/// <summary />
OLECMDID_SETPROGRESSPOS,
/// <summary />
OLECMDID_SETPROGRESSTEXT,
/// <summary />
OLECMDID_SETTITLE,
/// <summary />
OLECMDID_SETDOWNLOADSTATE,
/// <summary />
OLECMDID_STOPDOWNLOAD,
/// <summary />
OLECMDID_ONTOOLBARACTIVATED,
/// <summary />
OLECMDID_FIND,
/// <summary />
OLECMDID_DELETE,
/// <summary />
OLECMDID_HTTPEQUIV,
/// <summary />
OLECMDID_HTTPEQUIV_DONE,
/// <summary />
OLECMDID_ENABLE_INTERACTION,
/// <summary />
OLECMDID_ONUNLOAD,
/// <summary />
OLECMDID_PROPERTYBAG2,
/// <summary />
OLECMDID_PREREFRESH,
/// <summary />
OLECMDID_SHOWSCRIPTERROR,
/// <summary />
OLECMDID_SHOWMESSAGE,
/// <summary />
OLECMDID_SHOWFIND,
/// <summary />
OLECMDID_SHOWPAGESETUP,
/// <summary />
OLECMDID_SHOWPRINT,
/// <summary />
OLECMDID_CLOSE,
/// <summary />
OLECMDID_ALLOWUILESSSAVEAS,
/// <summary />
OLECMDID_DONTDOWNLOADCSS,
/// <summary />
OLECMDID_UPDATEPAGESTATUS,
/// <summary />
OLECMDID_PRINT2,
/// <summary />
OLECMDID_PRINTPREVIEW2,
/// <summary />
OLECMDID_SETPRINTTEMPLATE,
/// <summary />
OLECMDID_GETPRINTTEMPLATE
}
/// <summary>
/// From Microsoft.VisualStudio.Shell (Visual Studio 2010 SDK).
/// </summary>
public const int S_OK = 0;
/// <summary>
/// OLE command structure.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public class OLECMD
{
/// <summary>
/// Command ID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdID;
/// <summary>
/// Flags associated with cmdID.
/// </summary>
[MarshalAs(UnmanagedType.U4)]
public int cmdf;
}
/// <summary>
/// Enables the dispatching of commands between objects and containers.
/// </summary>
[ComVisible(true), Guid("B722BCCB-4E68-101B-A2BC-00AA00404770"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[ComImport]
public interface IOleCommandTarget
{
/// <summary>Queries the object for the status of one or more commands generated by user interface events.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="cCmds">The number of commands in <paramref name="prgCmds" />.</param>
/// <param name="prgCmds">An array of <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMD" /> structures that indicate the commands for which the caller needs status information.</param>
/// <param name="pCmdText">An <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDTEXT" /> structure in which to return name and/or status information of a single command. This parameter can be null to indicate that the caller does not need this information.</param>
/// <returns>This method returns S_OK on success. Other possible return values include the following.
/// E_FAIL The operation failed.
/// E_UNEXPECTED An unexpected error has occurred.
/// E_POINTER The <paramref name="prgCmds" /> argument is null.
/// OLECMDERR_E_UNKNOWNGROUPThe <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int QueryStatus(ref Guid pguidCmdGroup, int cCmds, [In] [Out] NativeMethods.OLECMD prgCmds, [In] [Out] IntPtr pCmdText);
/// <summary>Executes the specified command.</summary>
/// <param name="pguidCmdGroup">The GUID of the command group.</param>
/// <param name="nCmdID">The command ID.</param>
/// <param name="nCmdexecopt">Specifies how the object should execute the command. Possible values are taken from the <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDEXECOPT" /> and <see cref="T:Microsoft.VisualStudio.OLE.Interop.OLECMDID_WINDOWSTATE_FLAG" /> enumerations.</param>
/// <param name="pvaIn">The input arguments of the command.</param>
/// <param name="pvaOut">The output arguments of the command.</param>
/// <returns>This method returns S_OK on success. Other possible return values include
/// OLECMDERR_E_UNKNOWNGROUP The <paramref name="pguidCmdGroup" /> parameter is not null but does not specify a recognized command group.
/// OLECMDERR_E_NOTSUPPORTED The <paramref name="nCmdID" /> parameter is not a valid command in the group identified by <paramref name="pguidCmdGroup" />.
/// OLECMDERR_E_DISABLED The command identified by <paramref name="nCmdID" /> is currently disabled and cannot be executed.
/// OLECMDERR_E_NOHELP The caller has asked for help on the command identified by <paramref name="nCmdID" />, but no help is available.
/// OLECMDERR_E_CANCELED The user canceled the execution of the command.</returns>
[PreserveSig]
[return: MarshalAs(UnmanagedType.I4)]
int Exec(ref Guid pguidCmdGroup, int nCmdID, int nCmdexecopt, [MarshalAs(UnmanagedType.LPArray)] [In] object[] pvaIn, int pvaOut);
}
}
I decided to use the json2 library and I got an error about “cyclic data structures”.
I got it solved by telling json2 how to convert my complex object. Not only it works now but also I have included only the fields I need. Here is how I did it:
OBJ.prototype.toJSON = function (key) {
var returnObj = new Object();
returnObj.devid = this.devid;
returnObj.name = this.name;
returnObj.speed = this.speed;
returnObj.status = this.status;
return returnObj;
}
I needed to just download a file onClick but I needed to run some logic to either fetch or compute the actual url where the file existed. I also did not want to use any anti-react imperative patterns like setting a ref and manually clicking it when I had the resource url. The declarative pattern I used was
onClick = () => {
// do something to compute or go fetch
// the url we need from the server
const url = goComputeOrFetchURL();
// window.location forces the browser to prompt the user if they want to download it
window.location = url
}
render() {
return (
<Button onClick={ this.onClick } />
);
}
On my machine:
C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data
To compare entire revisions, it's simply:
svn diff -r 8979:11390
If you want to compare the last committed state against your currently saved working files, you can use convenience keywords:
svn diff -r PREV:HEAD
(Note, without anything specified afterwards, all files in the specified revisions are compared.)
You can compare a specific file if you add the file path afterwards:
svn diff -r 8979:HEAD /path/to/my/file.php
public class VcareSharedPreference {
private static VcareSharedPreference sharePref = new VcareSharedPreference();
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
private VcareSharedPreference() {
}
public static VcareSharedPreference getInstance(Context context) {
if (sharedPreferences == null) {
sharedPreferences = context.getSharedPreferences(context.getPackageName(), Activity.MODE_PRIVATE);
editor = sharedPreferences.edit();
}
return sharePref;
}
public void save(String KEY, String text) {
editor.putString(KEY, text);
editor.commit();
}
public String getValue(String PREFKEY) {
String text;
//settings = PreferenceManager.getDefaultSharedPreferences(context);
text = sharedPreferences.getString(PREFKEY, null);
return text;
}
public void removeValue(String KEY) {
editor.remove(KEY);
editor.commit();
}
public void clearAll() {
editor.clear();
editor.commit();
}
public void saveArrayList(String key, ArrayList<ModelWelcome> modelCourses) {
Gson gson = new Gson();
String json = gson.toJson(modelCourses);
editor.putString(key, json);
editor.apply();
}
public ArrayList<ModelWelcome> getArray(String key) {
Gson gson = new Gson();
String json = sharedPreferences.getString(key, null);
Type type = new TypeToken<ArrayList<ModelWelcome>>() {
}.getType();
return gson.fromJson(json, type);}}
You can please try this code to call the handler every 15 seconds via onResume() and stop it when the activity is not visible, via onPause().
Handler handler = new Handler();
Runnable runnable;
int delay = 15*1000; //Delay for 15 seconds. One second = 1000 milliseconds.
@Override
protected void onResume() {
//start handler as activity become visible
handler.postDelayed( runnable = new Runnable() {
public void run() {
//do something
handler.postDelayed(runnable, delay);
}
}, delay);
super.onResume();
}
// If onPause() is not included the threads will double up when you
// reload the activity
@Override
protected void onPause() {
handler.removeCallbacks(runnable); //stop handler when activity not visible
super.onPause();
}
The code says everything:
max@serv$ chmod 777 .
Okay, it doesn't say everything.
In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.
Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.
On your terminal, try running:
which -a ruby
This will output all the installed Ruby versions (via RVM, or otherwise) on your system in your PATH. If 1.8.7 is your system Ruby version, you can uninstall the system Ruby using:
sudo apt-get purge ruby
Once you have made sure you have Ruby installed via RVM alone, in your login
shell you can type:
rvm --default use 2.0.0
You don't need to do this if you have only one Ruby version installed.
If you still face issues with any system Ruby files, try running:
dpkg-query -l '*ruby*'
This will output a bunch of Ruby-related files and packages which are, or were, installed on your system at the system level. Check the status of each to find if any of them is native and is causing issues.
You should try this one:
Console.WriteLine("{0}.{1}.{2}", mon, da, yet);
See http://www.dotnetperls.com/console-writeline for more details.
Try this...
var start = new Date(document.getElementById('Stardate').value);
var y = start.getFullYear();
You can extend the abstract class with an anonymous class in your test. For example (using Junit 4):
private AbstractClassName classToTest;
@Before
public void preTestSetup()
{
classToTest = new AbstractClassName() { };
}
// Test the AbstractClassName methods.
Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"):
using System.Text;
/// <summary>
/// Compares a supplied date to the current date and generates a friendly English
/// comparison ("5 days ago", "5 days from now")
/// </summary>
/// <param name="date">The date to convert</param>
/// <param name="approximate">When off, calculate timespan down to the second.
/// When on, approximate to the largest round unit of time.</param>
/// <returns></returns>
public static string ToRelativeDateString(this DateTime value, bool approximate)
{
StringBuilder sb = new StringBuilder();
string suffix = (value > DateTime.Now) ? " from now" : " ago";
TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));
if (timeSpan.Days > 0)
{
sb.AppendFormat("{0} {1}", timeSpan.Days,
(timeSpan.Days > 1) ? "days" : "day");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Hours > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Minutes > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute");
if (approximate) return sb.ToString() + suffix;
}
if (timeSpan.Seconds > 0)
{
sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty,
timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second");
if (approximate) return sb.ToString() + suffix;
}
if (sb.Length == 0) return "right now";
sb.Append(suffix);
return sb.ToString();
}
The attribute packed
means that the compiler will not add padding between fields of the struct
. Padding is usually used to make fields aligned to their natural size, because some architectures impose penalties for unaligned access or don't allow it at all.
aligned(4)
means that the struct should be aligned to an address that is divisible by 4.
Why do you need to encrypt the database? The user could easily disassemble your program and figure out the key. If you're encrypting it for network transfer, then consider using PGP instead of squeezing an encryption layer into a database layer.
Method Object JComboBox.getSelectedItem()
returns a value that is wrapped by Object
type so you have to cast it accordingly.
Syntax:
YourType varName = (YourType)comboBox.getSelectedItem();`
String value = comboBox.getSelectedItem().toString();
Use
System.getProperty("java.class.path")
see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
You can also split it into it's elements easily
String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);
You can filter all characters from the string that are not printable using string.printable, like this:
>>> s = "some\x00string. with\x15 funny characters"
>>> import string
>>> printable = set(string.printable)
>>> filter(lambda x: x in printable, s)
'somestring. with funny characters'
string.printable on my machine contains:
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c
EDIT: On Python 3, filter will return an iterable. The correct way to obtain a string back would be:
''.join(filter(lambda x: x in printable, s))
var date = new Date("enter your date");//2018-01-17 14:58:29.013
Just one line is enough no need to do any kind of split
, join
, etc.:
$scope.ssdate=date.toLocaleDateString();// mm/dd/yyyy format
<?php
// sample array
$fruits3 = [
"iron",
1,
"ascorbic",
"potassium",
"ascorbic",
2,
"2",
"1",
];
// Let's say we are looking for the item "ascorbic", in the above array
//a PHP function matching indexOf() from JS
echo(array_search("ascorbic", $fruits3, true)); //returns "2"
// a PHP function matching lastIndexOf() from JS world
function lastIndexOf($needle, $arr)
{
return array_search($needle, array_reverse($arr, true), true);
}
echo(lastIndexOf("ascorbic", $fruits3)); //returns "4"
// so these (above) are the two ways to run a function similar to indexOf and lastIndexOf()
string input = "0.55";
var regex1 = new System.Text.RegularExpressions.Regex("(?<=[\\.])[0-9]+");
if (regex1.IsMatch(input))
{
string dp= regex1.Match(input ).Value;
}
Swift 4:
tableView.deselectRow(at: indexPath, animated: true)
Setting Up the database
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "database_name";
// Table Names
private static final String DB_TABLE = "table_image";
// column names
private static final String KEY_NAME = "image_name";
private static final String KEY_IMAGE = "image_data";
// Table create statement
private static final String CREATE_TABLE_IMAGE = "CREATE TABLE " + DB_TABLE + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
// creating table
db.execSQL(CREATE_TABLE_IMAGE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// on upgrade drop older tables
db.execSQL("DROP TABLE IF EXISTS " + DB_TABLE);
// create new table
onCreate(db);
}
}
Insert in the Database:
public void addEntry( String name, byte[] image) throws SQLiteException{
SQLiteDatabase database = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE, null, cv );
}
Retrieving data:
byte[] image = cursor.getBlob(1);
Note:
Below is an Utility class which I hope could help you:
public class DbBitmapUtility {
// convert from bitmap to byte array
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
}
Further reading
If you are not familiar how to insert and retrieve into a database, go through this tutorial.
In my case, I had made a stupid typo in the shebang.
So in case someone else on with fat fingers stumbles across this question:
Whoops: #!/usr/local/bin ruby
I meant to write: #!/usr/bin/env ruby
The vague error ZSH gives sent me down the wrong path:
ZSH: zsh: permission denied: ./foo.rb
Bash: bash: ./foo.rb: /usr/local/bin: bad interpreter: Permission denied
For get response in JSON format :
1.$response = (string) $res->getBody();
$response =json_decode($response); // Using this you can access any key like below
$key_value = $response->key_name; //access key
2. $response = json_decode($res->getBody(),true);
$key_value = $response['key_name'];//access key
A simple way of doing this is via nargin
(N arguments in). The downside is you have to make sure that your argument list and the nargin checks match.
It is worth remembering that all inputs are optional, but the functions will exit with an error if it calls a variable which is not set. The following example sets defaults for b
and c
. Will exit if a
is not present.
function [ output_args ] = input_example( a, b, c )
if nargin < 1
error('input_example : a is a required input')
end
if nargin < 2
b = 20
end
if nargin < 3
c = 30
end
end
hi,that maybe the project's problem,
chose the project and setting you eclipse:
project -> clean...
As a supplement to @jyore's answer, and in case you still want to keep the original array:
var originalArray = [1,2,3,4,5,6,7,8];
var splitArray = function (arr, size) {
var arr2 = arr.slice(0),
arrays = [];
while (arr2.length > 0) {
arrays.push(arr2.splice(0, size));
}
return arrays;
}
splitArray(originalArray, 2);
// originalArray is still = [1,2,3,4,5,6,7,8];
I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.
Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.
If you cannot upgrade jQuery and you are getting:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
You can work around it like so:
$(selector).closest('.ui-dialog-content').dialog('close');
Or if you control the view and know no other dialogs should be in use at all on the entire page, you could do:
$('.ui-dialog-content').dialog('close');
I would only recommend doing this if using closest
causes a performance issue. There are likely other ways to work around it without doing a global close on all dialogs.
One can replace unicode
with u''.__class__
to handle the missing unicode
class in Python 3. For both Python 2 and 3, you can use the construct
isinstance(unicode_or_str, u''.__class__)
or
type(unicode_or_str) == type(u'')
Depending on your further processing, consider the different outcome:
Python 3
>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True
Python 2
>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False
If you want to show a divider with margins and without stretching it - use InsetDrawable (size must be in a format, about which said @Nik Reiman):
ListView:
<ListView
android:id="@+id/listView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#00000000"
android:divider="@drawable/separator_line"
android:dividerHeight="10.0px"/>
@drawable/separator_line:
<?xml version="1.0" encoding="utf-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetLeft="5.0px"
android:insetRight="5.0px"
android:insetTop="8.0px"
android:insetBottom="8.0px">
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="@color/colorStart"
android:centerColor="@color/colorCenter"
android:endColor="@color/colorEnd"
android:type="linear"
android:angle="0">
</gradient>
</shape>
</inset>
LDPI should be 36 x 36.
MDPI 48 x 48.
TVDPI 64 x 64.
HDPI 72 x 72.
XHDPI 96 x 96.
XXHDPI 144 x 144.
XXXHDPI 192 x 192.
try this
Jobs
select s.name,l.name
from msdb..sysjobs s
left join master.sys.syslogins l on s.owner_sid = l.sid
Packages
select s.name,l.name
from msdb..sysssispackages s
left join master.sys.syslogins l on s.ownersid = l.sid
You could check for the count of the Object keys:
if (Object.keys(a).length > 0) {
// not empty
}
Select T.Tamil, T.English, T.Maths, T.Total, Dense_Rank()Over(Order by T.Total Desc) as Std_Rank From (select Tamil,English,Maths,(Tamil+English+Maths) as Total From Student) as T
When I had the same problem,
I solved it by removing the file "passwd" in
C:\Users\<USERNAME>\AppData\Local\Atlassian\SourceTree
After removing Sourcetree will prompt for the password.
Note:
OS Version : win10
Sourcetree Version: 3.1
Trying from the CodeBehind:
Textbox1.Attributes.Add("autocomplete", "off");
The double arrow operator, =>
, is used as an access mechanism for arrays. This means that what is on the left side of it will have a corresponding value of what is on the right side of it in array context. This can be used to set values of any acceptable type into a corresponding index of an array. The index can be associative (string based) or numeric.
$myArray = array(
0 => 'Big',
1 => 'Small',
2 => 'Up',
3 => 'Down'
);
The object operator, ->
, is used in object scope to access methods and properties of an object. It’s meaning is to say that what is on the right of the operator is a member of the object instantiated into the variable on the left side of the operator. Instantiated is the key term here.
// Create a new instance of MyObject into $obj
$obj = new MyObject();
// Set a property in the $obj object called thisProperty
$obj->thisProperty = 'Fred';
// Call a method of the $obj object named getProperty
$obj->getProperty();
This is a ternary operator, it's basically an inline if statement
x ? y : z
works like
if(x) y else z
except, instead of statements you have expressions; so you can use it in the middle of a more complex statement.
It's useful for writing succinct code, but can be overused to create hard to maintain code.
To check weather keyboard is appeared, we can use the Keyboard predefined notifications.
UIKeyboardDidShowNotification ,UIKeyboardDidHideNotification
For example I can use the following code to listen the keyboard notification
// Listen for keyboard appearances and disappearances
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidShow:)
name:UIKeyboardDidShowNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(keyboardDidHide:)
name:UIKeyboardDidHideNotification
object:nil];
in the methods I can get notifications
- (void)keyboardDidShow: (NSNotification *) notifyKeyBoardShow{
// key board is closed
}
- (void)keyboardDidHide: (NSNotification *) notifyKeyBoardHide{
// key board is opened
}
The other answers lack a concrete example, so here it goes:
Given the following People table:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Thomas | More | 1478
Thomas | Jefferson | 1826
If you execute the query below:
SELECT * FROM People ORDER BY FirstName DESC, YearOfBirth ASC
The result set will look like this:
FirstName | LastName | YearOfBirth
----------------------------------------
Thomas | More | 1478
Thomas | Jefferson | 1826
Thomas | Alva Edison | 1847
Benjamin | Franklin | 1706
Update: See the top-voted answer please.
My own is currently obsolete. Only kept here for historical reasons.
Distinct in HQL is usually needed in Joins and not in simple examples like your own.
Node.js supports circular dependencies.
Making use of circular dependencies instead of require('./routes')(app) cleans up a lot of code and makes each module less interdependent on its loading file:
var app = module.exports = express(); //now app.js can be required to bring app into any file
//some app/middleware setup, etc, including
app.use(app.router);
require('./routes'); //module.exports must be defined before this line
var app = require('../app');
app.get('/', function(req, res, next) {
res.render('index');
});
//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
Example from their new generator:
Writing the route:
https://github.com/expressjs/generator/blob/master/templates/js/routes/index.js
Adding/namespacing it to the app:
https://github.com/expressjs/generator/blob/master/templates/js/app.js#L24
There are still usecases for accessing app from other resources, so circular dependencies are still a valid solution.
I was stuck on this for a long time. After a lot of tries I was able to configured it properly.
There can be different reasons of raising the error. I am trying to provide the reason and the solution to overcome from that situation.
6379 Port
is not allowed by ufw firewall.
Solution: type following command sudo ufw allow 6379
The issue can be related to permission of redis
user. May be redis user doesn't have permission of modifying necessary redis
directories. The redis
user should have permissions in the following directories:
/var/lib/redis
/var/log/redis
/run/redis
/etc/redis
To give the owner permission to redis
user, type the following commands:
sudo chown -R redis:redis /var/lib/redis
sudo chown -R redis:redis /var/log/redis
sudo chown -R redis:redis /run/redis
sudo chown -R redis:redis /etc/redis
.Now restart redis-server
by following command:
sudo systemctl restart redis-server
Hope this will be helpful for somebody.
Composer should be installed globally: Run this in your terminal:
mv composer.phar /usr/local/bin/composer
Now composer commands will work.
git pull
is really just a shorthand for git pull <remote> <branchname>
, in most cases it's equivalent to git pull origin master
. You will need to add another remote and pull explicitly from it. This page describes it in detail:
I use a simple solution to switch from a version to another version of python, you can install all version you want. All you have to do is creating some variable environment. In my case, I have installed python 2.7 and python 3.8.1, so I have created this environment variables:
PYTHON_HOME_2.7=<path_python_2.7> PYTHON_HOME_3.8.1=<path_python_3.8.1> PYTHON_HOME=%PYTHON_HOME_2.7%
then in my PATH environment variable I put only %PYTHON_HOME% and %PYTHON_HOME%\Scripts. In the example above I'm using the version 2.7, when I want to switch to the other version I have only to set the PYTHON_HOME=%PYTHON_HOME_3.8.1%. I use this method to switch quickly from a version to another also for JAVA, MAVEN, GRADLE,ANT, and so on.
The Lazy
Fetch type is by default selected by Hibernate unless you explicitly mark Eager
Fetch type. To be more accurate and concise, difference can be stated as below.
FetchType.LAZY
= This does not load the relationships unless you invoke it via the getter method.
FetchType.EAGER
= This loads all the relationships.
Pros and Cons of these two fetch types.
Lazy initialization
improves performance by avoiding unnecessary computation and reduce memory requirements.
Eager initialization
takes more memory consumption and processing speed is slow.
Having said that, depends on the situation either one of these initialization can be used.
If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index
, when called without a block, return an Enumerator
object, which you can call Enumerable
methods like map
on. So you can do:
arr.each_with_index.map { |x,i| [x, i+2] }
In 1.8.6 you can do:
require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }
I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.
You can access this by
To make angular ui $modal work with bootstrap 3 you need to overwrite the styles
.modal {
display: block;
}
.modal-body:before,
.modal-body:after {
display: table;
content: " ";
}
.modal-header:before,
.modal-header:after {
display: table;
content: " ";
}
(The last ones are necessary if you use custom directives) and encapsulate the html with
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
You can try to do json.loads()
, which will throw a ValueError
if the string you pass can't be decoded as JSON.
In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.
sh
(or the Shell Command Language) is a programming language described by the POSIX
standard.
It has many implementations (ksh88
, dash
, ...). bash
can also be
considered an implementation of sh
(see below).
Because sh
is a specification, not an implementation, /bin/sh
is a symlink
(or a hard link) to an actual implementation on most POSIX systems.
bash
started as an sh
-compatible implementation (although it predates the POSIX standard by a few years), but as time passed it has acquired many extensions. Many of these extensions may change the behavior of valid POSIX shell scripts, so by itself bash
is not a valid POSIX shell. Rather, it is a dialect of the POSIX shell language.
bash
supports a --posix
switch, which makes it more POSIX-compliant. It also tries to mimic POSIX if invoked as sh
.
For a long time, /bin/sh
used to point to /bin/bash
on most GNU/Linux systems. As a result, it had almost become safe to ignore the difference between the two. But that started to change recently.
Some popular examples of systems where /bin/sh
does not point to /bin/bash
(and on some of which /bin/bash
may not even exist) are:
sh
to dash
by default;initramfs
. It uses the ash
shell implementation.pdksh
, a descendant of the Korn shell. FreeBSD's sh
is a descendant of the original UNIX Bourne shell. Solaris has its own sh
which for a long time was not POSIX-compliant; a free implementation is available from the Heirloom project.How can you find out what /bin/sh
points to on your system?
The complication is that /bin/sh
could be a symbolic link or a hard link.
If it's a symbolic link, a portable way to resolve it is:
% file -h /bin/sh
/bin/sh: symbolic link to bash
If it's a hard link, try
% find -L /bin -samefile /bin/sh
/bin/sh
/bin/bash
In fact, the -L
flag covers both symlinks and hardlinks,
but the disadvantage of this method is that it is not portable —
POSIX does not require find
to support the -samefile
option,
although both GNU find and FreeBSD find support it.
Ultimately, it's up to you to decide which one to use, by writing the «shebang» line as the very first line of the script.
E.g.
#!/bin/sh
will use sh
(and whatever that happens to point to),
#!/bin/bash
will use /bin/bash
if it's available (and fail with an error message if it's not). Of course, you can also specify another implementation, e.g.
#!/bin/dash
For my own scripts, I prefer sh
for the following reasons:
bash
, they are required to have sh
There are advantages to using bash
as well. Its features make programming more convenient and similar to programming in other modern programming languages. These include things like scoped local variables and arrays. Plain sh
is a very minimalistic programming language.
This probably has the same table to other schema the reason why you're getting that error.
You need to drop first the child row then the parent row.
You should add then
function to instance. Promise
will recognize it as a thenable object with Promise.resolve
automatically
const asyncSymbol = Symbol();
class MyClass {
constructor() {
this.asyncData = null
}
then(resolve, reject) {
return (this[asyncSymbol] = this[asyncSymbol] || new Promise((innerResolve, innerReject) => {
this.asyncData = { a: 1 }
setTimeout(() => innerResolve(this.asyncData), 3000)
})).then(resolve, reject)
}
}
async function wait() {
const asyncData = await new MyClass();
alert('run 3s later')
alert(asyncData.a)
}
main()
has it's own thread and stack variables. either allocate memory for 'args' in the heap or make it global:
struct arg_struct {
int arg1;
int arg2;
}args;
//declares args as global out of main()
Then of course change the references from args->arg1
to args.arg1
etc..
Use double quotes while using BASH variables.
mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"
BASH doesn't expand variables in single quotes.
(When trying to find out how to use kdiff3 from WSL git I ended up here and got the final pieces, so I'll post my solution for anyone else also stumbling in here while trying to find that answer)
With Windows update 1903 it is a lot easier; just use wslpath and there is no need to share TMP from Windows to WSL since the Windows side now has access to the WSL filesystem via \wsl$:
[merge]
renormalize = true
guitool = kdiff3
[diff]
tool = kdiff3
[difftool]
prompt = false
[difftool "kdiff3"]
# Unix style paths must be converted to windows path style
cmd = kdiff3.exe \"`wslpath -w $LOCAL`\" \"`wslpath -w $REMOTE`\"
trustExitCode = false
[mergetool]
keepBackup = false
prompt = false
[mergetool "kdiff3"]
path = kdiff3.exe
trustExitCode = false
Steps for using kdiff3 installed on Windows 10 as diff/merge tool for git in WSL:
# If TMP is passed via WSLENV then use it as TMPDIR
[[ ! -z "$WSLENV" && ! -z "$TMP" ]] && export TMPDIR=$TMP
[merge]
renormalize = true
guitool = kdiff3
[diff]
tool = kdiff3
[difftool]
prompt = false
[difftool "kdiff3"]
#path = kdiff3.exe
# Unix style paths must be converted to windows path style by changing '/mnt/c/' or '/c/' to 'c:/'
cmd = kdiff3.exe \"`echo $LOCAL | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\" \"`echo $REMOTE | sed 's_^\\(/mnt\\)\\?/\\([a-z]\\)/_\\2:/_'`\"
trustExitCode = false
[mergetool]
keepBackup = false
prompt = false
[mergetool "kdiff3"]
path = kdiff3.exe
trustExitCode = false
You cannot exit your application. Using android.finish()
won't exit
the application, it just kills the activity. It's used when we don't
want to see the previous activity on back button click. The
application automatically exits when you switch off the device. The
Android architecture does not support exiting the app. If you want,
you can forcefully exit the app, but that's not considered good
practice.
You need an external tool, in example: SoftInterface.com - Convert XLSX to CSV.
After installing it, you can use following command in your batch:
"c:\Program Files\Softinterface, Inc\Convert XLS\ConvertXLS.EXE" /S"C:\MyExcelFile.xlsx" /F51 /N"Sheet1" /T"C:\MyExcelFile.CSV" /C6 /M1 /V
You basically have two options, either define it as a service, or place it on your root scope. I would suggest that you make a service out of it to avoid polluting the root scope. You create a service and make it available in your controller like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.factory('myService', function() {
return {
foo: function() {
alert("I'm foo!");
}
};
});
myApp.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.callFoo = function() {
myService.foo();
}
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="callFoo()">Call foo</button>
</body>
</html>
If that's not an option for you, you can add it to the root scope like this:
<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.1.2/angular.min.js"></script>
<script type="text/javascript">
var myApp = angular.module('myApp', []);
myApp.run(function($rootScope) {
$rootScope.globalFoo = function() {
alert("I'm global foo!");
};
});
myApp.controller('MainCtrl', ['$scope', function($scope){
}]);
</script>
</head>
<body ng-controller="MainCtrl">
<button ng-click="globalFoo()">Call global foo</button>
</body>
</html>
That way, all of your templates can call globalFoo()
without having to pass it to the template from the controller.
You need to create a object from your list like:
List<CartProduct> lst = new List<CartProduct>();
CartProduct obj = lst.Find(x => (x.Name == "product name"));
That object get the looked value searching by their properties: x.name
Then you can use List methods like Contains or Remove
if (lst.Contains(obj))
{
lst.Remove(obj);
}
On OS X, I like my date to be in the format of YYYY-MM-DD HH:MM
in the output for the file.
So to specify a file I would use:
stat -f "%Sm" -t "%Y-%m-%d %H:%M" [filename]
If I want to run it on a range of files, I can do something like this:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
done
This example will print out the last time I ran the sudo periodic daily weekly monthly
command as it references the log files.
To add the filenames under each date, I would run the following instead:
#!/usr/bin/env bash
for i in /var/log/*.out; do
stat -f "%Sm" -t "%Y-%m-%d %H:%M" "$i"
echo "$i"
done
The output would was the following:
2016-40-01 16:40
/var/log/daily.out
2016-40-01 16:40
/var/log/monthly.out
2016-40-01 16:40
/var/log/weekly.out
Unfortunately I'm not sure how to prevent the line break and keep the file name appended to the end of the date without adding more lines to the script.
PS - I use #!/usr/bin/env bash
as I'm a Python user by day, and have different versions of bash
installed on my system instead of #!/bin/bash
Create a new SSH key in your terminal/command line.
ssh-keygen -t rsa -C “your-email-address”
The following will then show:
Generating public/private rsa key pair. Enter file in which to save the key (/home/your_username/.ssh/id_rsa):
Copy and paste the path followed by an identifiable name for the file:
/home/your_username/.ssh/id_rsa_personal
4) It will then ask you for the following:
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
5) You can now type in the following command to see all the SSH keys you have on your local machine:
ls -al ~/.ssh
You should be able to see your new SSH key file. As you can see in my one I have both id_rsa_test and id_rsa_personal.pub.
drwx------ 2 gmadmin gmadmin 4096 Nov 16 22:20 .
drwxr-xr-x 42 gmadmin gmadmin 4096 Nov 16 21:03 ..
-rw------- 1 gmadmin gmadmin 1766 Nov 16 22:20 id_rsa_personal
-rw-r--r-- 1 gmadmin gmadmin 414 Nov 16 22:20 id_rsa_personal.pub
-rw-r--r-- 1 gmadmin gmadmin 444 Nov 6 11:32 known_hosts
6) Next you need to copy the SSH key which is stored in id_rsa_personal.pub file. You can open this in text editor of your choice. I am currently using atom so I opened the file using the following command:
atom ~/.ssh/id_rsa_personal.pub
You will then get something similar to this:
ssh-rsa AAB3HKJLKC1yc2EAAAADAQABAAABAQCgU5+ELtwsKkmcoeF3hNd7d6CjW+dWut83R/Dc01E/YzLc5ZFri18doOwuQoeTPpmIRVDGuQQsZshjDrTkFy8rwKWMlXl7va5olnGICcpg4qydEtsW+MELDmayW1HHsi2xHMMGHlNv
7) Copy this and navigate to your GitHub account ? Settings ? SSH and GPG keys 8) Click on New SSH key. Copy the key, give it a title and add it. 9) Add key from terminal
ssh-add ~/.ssh/id_rsa_personal
Enter passphrase for /home/your_username/.ssh/id_rsa_personal:
10) Configure user and password.
git config --global user.name "gitusername"
git config --global user.email "gitemail"
11) We are ready to commit and push now.
git init
git add .
git commit
git push
For languages not specifying a memory model, you are writing code for the language and the memory model specified by the processor architecture. The processor may choose to re-order memory accesses for performance. So, if your program has data races (a data race is when it's possible for multiple cores / hyper-threads to access the same memory concurrently) then your program is not cross platform because of its dependence on the processor memory model. You may refer to the Intel or AMD software manuals to find out how the processors may re-order memory accesses.
Very importantly, locks (and concurrency semantics with locking) are typically implemented in a cross platform way... So if you are using standard locks in a multithreaded program with no data races then you don't have to worry about cross platform memory models.
Interestingly, Microsoft compilers for C++ have acquire / release semantics for volatile which is a C++ extension to deal with the lack of a memory model in C++ http://msdn.microsoft.com/en-us/library/12a04hfd(v=vs.80).aspx. However, given that Windows runs on x86 / x64 only, that's not saying much (Intel and AMD memory models make it easy and efficient to implement acquire / release semantics in a language).
see http://editorconfig.org and https://docs.microsoft.com/en-us/visualstudio/ide/create-portable-custom-editor-options?view=vs-2017
If it does not exist, add a new file called .editorconfig for your project
manipulate editor config to use your preferred behaviour.
I prefer spaces over tabs, and CRLF for all code files.
Here's my .editorconfig
# http://editorconfig.org
root = true
[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.tmpl.html]
indent_size = 4
[*.scss]
indent_size = 2
I feel that MWV (Model View Whatever) or MV* is a more flexible term to describe some of the uniqueness of Angularjs in my opinion. It helped me to understand that it is more than a MVC (Model View Controller) JavaScript framework, but it still uses MVC as it has a Model View, and Controller.
It also can be considered as a MVP (Model View Presenter) pattern. I think of a Presenter as the user-interface business logic in Angularjs for the View. For example by using filters that can format data for display. It's not business logic, but display logic and it reminds me of the MVP pattern I used in GWT.
In addition, it also can be a MVVM (Model View View Model) the View Model part being the two-way binding between the two. Last of all it is MVW as it has other patterns that you can use as well as mentioned by @Steve Chambers.
I agree with the other answers that getting pedantic on these terms can be detrimental, as the point is to understand the concepts from the terms, but by the same token, fully understanding the terms helps one when they are designing their application code, knowing what goes where and why.
If expr is greater than or equal to min and expr is less than or equal to max,
BETWEEN
returns 1, otherwise it returns 0.
The important part here is EQUAL to max., which 1st of July is.
IMO the nicest way is to use the next()
function:
router.get('/', function(req, res, next) {
var err = new Error('Not found');
err.status = 404;
return next(err);
}
Then the error is handled by your error handler and you can style the error nicely using HTML.
I had this error because I included the requirejs file along with other librairies included directly in a script tag. Those librairies (like lodash) used a define function that was conflicting with require's define. The requirejs file was loading asynchronously so I suspect that the require's define was defined after the other libraries define, hence the conflict.
To get rid of the error, include all your other js files by using requirejs.
My recommendation is TORA
persistence.xml
<persistence-unit name="PU2" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>jndi_ws2</non-jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
codigo java
String PERSISTENCE_UNIT_NAME = "PU2";
EntityManagerFactory factory2;
factory2 = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em2 = factory2.createEntityManager();
boolean committed = false;
try {
try {
StoredProcedureQuery storedProcedure = em2.createStoredProcedureQuery("PKCREATURNO.INSERTATURNO");
// set parameters
storedProcedure.registerStoredProcedureParameter("inuPKEMPRESA", BigDecimal.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("inuPKSERVICIO", BigDecimal.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("inuPKAREA", BigDecimal.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("isbCHSIGLA", String.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("INUSINCALIFICACION", BigInteger.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("INUTIMBRAR", BigInteger.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("INUTRANSFERIDO", BigInteger.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("INTESTADO", BigInteger.class, ParameterMode.IN);
storedProcedure.registerStoredProcedureParameter("inuContador", BigInteger.class, ParameterMode.OUT);
BigDecimal inuPKEMPRESA = BigDecimal.valueOf(1);
BigDecimal inuPKSERVICIO = BigDecimal.valueOf(5);
BigDecimal inuPKAREA = BigDecimal.valueOf(23);
String isbCHSIGLA = "";
BigInteger INUSINCALIFICACION = BigInteger.ZERO;
BigInteger INUTIMBRAR = BigInteger.ZERO;
BigInteger INUTRANSFERIDO = BigInteger.ZERO;
BigInteger INTESTADO = BigInteger.ZERO;
BigInteger inuContador = BigInteger.ZERO;
storedProcedure.setParameter("inuPKEMPRESA", inuPKEMPRESA);
storedProcedure.setParameter("inuPKSERVICIO", inuPKSERVICIO);
storedProcedure.setParameter("inuPKAREA", inuPKAREA);
storedProcedure.setParameter("isbCHSIGLA", isbCHSIGLA);
storedProcedure.setParameter("INUSINCALIFICACION", INUSINCALIFICACION);
storedProcedure.setParameter("INUTIMBRAR", INUTIMBRAR);
storedProcedure.setParameter("INUTRANSFERIDO", INUTRANSFERIDO);
storedProcedure.setParameter("INTESTADO", INTESTADO);
storedProcedure.setParameter("inuContador", inuContador);
// execute SP
storedProcedure.execute();
// get result
try {
long _inuContador = (long) storedProcedure.getOutputParameterValue("inuContador");
varCon = _inuContador + "";
} catch (Exception e) {
}
} finally {
}
} finally {
em2.close();
}
Have you tried using the dollar sign and brackets like this:
SELECT *
FROM foo
WHERE day >= '${CURRENT_DATE}';
For setting the Socket timeout, you need to follow these steps:
import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.
A good reason is for security - this can prevent CSRF attacks because this header cannot be added to the AJAX request cross domain without the consent of the server via CORS.
Only the following headers are allowed cross domain:
- Accept
- Accept-Language
- Content-Language
- Last-Event-ID
- Content-Type
any others cause a "pre-flight" request to be issued in CORS supported browsers.
Without CORS it is not possible to add X-Requested-With
to a cross domain XHR request.
If the server is checking that this header is present, it knows that the request didn't initiate from an attacker's domain attempting to make a request on behalf of the user with JavaScript. This also checks that the request wasn't POSTed from a regular HTML form, of which it is harder to verify it is not cross domain without the use of tokens. (However, checking the Origin
header could be an option in supported browsers, although you will leave old browsers vulnerable.)
You may wish to combine this with a token, because Flash running on Safari on OSX can set this header if there's a redirect step. It appears it also worked on Chrome, but is now remediated. More details here including different versions affected.
OWASP Recommend combining this with an Origin and Referer check:
This defense technique is specifically discussed in section 4.3 of Robust Defenses for Cross-Site Request Forgery. However, bypasses of this defense using Flash were documented as early as 2008 and again as recently as 2015 by Mathias Karlsson to exploit a CSRF flaw in Vimeo. But, we believe that the Flash attack can't spoof the Origin or Referer headers so by checking both of them we believe this combination of checks should prevent Flash bypass CSRF attacks. (NOTE: If anyone can confirm or refute this belief, please let us know so we can update this article)
However, for the reasons already discussed checking Origin can be tricky.
Written a more in depth blog post on CORS, CSRF and X-Requested-With here.
If there's only some few components of your webview that is slow or laggy, try adding this to the elements css:
transform: translate3d(0,0,0);
-webkit-transform: translate3d(0,0,0);
This has been the only speedhack that really had a effect on my webview. But be careful not to overuse it! (you can read more about the hack in this article.)
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
To deselect all rows and cells in a DataGridView
, you can use the ClearSelection
method:
myDataGridView.ClearSelection()
If you don't want even the first row/cell to appear selected, you can set the CurrentCell
property to Nothing
/null
, which will temporarily hide the focus rectangle until the control receives focus again:
myDataGridView.CurrentCell = Nothing
To determine when the user has clicked on a blank part of the DataGridView
, you're going to have to handle its MouseUp
event. In that event, you can HitTest
the click location and watch for this to indicate HitTestInfo.Nowhere
. For example:
Private Sub myDataGridView_MouseUp(ByVal sender as Object, ByVal e as System.Windows.Forms.MouseEventArgs)
''# See if the left mouse button was clicked
If e.Button = MouseButtons.Left Then
''# Check the HitTest information for this click location
If myDataGridView.HitTest(e.X, e.Y) = DataGridView.HitTestInfo.Nowhere Then
myDataGridView.ClearSelection()
myDataGridView.CurrentCell = Nothing
End If
End If
End Sub
Of course, you could also subclass the existing DataGridView
control to combine all of this functionality into a single custom control. You'll need to override its OnMouseUp
method similar to the way shown above. I also like to provide a public DeselectAll
method for convenience that both calls the ClearSelection
method and sets the CurrentCell
property to Nothing
.
(Code samples are all arbitrarily in VB.NET because the question doesn't specify a language—apologies if this is not your native dialect.)
Use the display: inline
CSS property.
Ideal: In the stylesheet:
#container p { display: inline }
Bad/Extreme situation: Inline:
<p style="display:inline">...</p>
For an excellent discussion of this topic have a read of this article from Sun.
It goes into all the benefits including being able to insert interposing libraries. More detail on interposing can be found in this article here.
I had this problem. The solution was to allow node.js through the server's firewall.
Based on what you all shared I was able to put this together:
#!/usr/bin/env bash
VAR1="192.168.1.20 192.168.1.126 192.168.1.36"
for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"
Exit 1
This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt
String.format()
to the rescue!!
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
To create AAR
while creating follow below steps.
File->New->New Module->Android Library and create
.
To generate AAR
Go to gradle at top right pane in android studio follow below steps.
Gradle->Drop down library name -> tasks-> build-> assemble or assemble release
AAR will be generated in build/outputs/aar/
But if we want AAR to get generated in specific folder in project directory with name you want, modify your app level build.gradle
like below
defaultConfig {
minSdkVersion 26
targetSdkVersion 28
versionCode System.getenv("BUILD_NUMBER") as Integer ?: 1
versionName "0.0.${versionCode}"
libraryVariants.all { variant ->
variant.outputs.all { output ->
outputFileName = "/../../../../release/" + ("your_recommended_name.aar")
}
}
}
Now it will create folder with name "release" in project directory which will be having AAR.
To import "aar" into project,check below link.
How to manually include external aar package using new Gradle Android Build System
This is the solution to find is the checkbox is checked or not. Use the #prop() function//
$("#c_checkbox").on('change', function () {
if ($(this).prop('checked')) {
// do stuff//
}
});
If it's a phantom breakpoint:
1 Delete the offending line of code
2 Run the code again
3 Repaste the line
I found this laughably simple solution after spending a couple days wading through all the answers here and elsewhere. I figured, if I link it to my original question it might help some other poor chap, since the question it's on is VBA break execution when there's no break key on keyboard and this is more applicable.
The language used by Facebook is PHP.
Also, do any other social networking sites use the same language?
The other one I know of is friendster.
I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"
Apparently the differences between these date formats are as follow:
DT_DATE A date structure that consists of year, month, day, and hour.
DT_DBDATE A date structure that consists of year, month, and day.
DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction
By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.
I got tired of having to re-learn this every six months, so I just published an npm module to abstract away the implementation details:
https://www.npmjs.com/package/streamify-string
This is the core of the module:
const Readable = require('stream').Readable;
const util = require('util');
function Streamify(str, options) {
if (! (this instanceof Streamify)) {
return new Streamify(str, options);
}
Readable.call(this, options);
this.str = str;
}
util.inherits(Streamify, Readable);
Streamify.prototype._read = function (size) {
var chunk = this.str.slice(0, size);
if (chunk) {
this.str = this.str.slice(size);
this.push(chunk);
}
else {
this.push(null);
}
};
module.exports = Streamify;
str
is the string
that must be passed to the constructor upon invokation, and will be outputted by the stream as data. options
are the typical options that may be passed to a stream, per the documentation.
According to Travis CI, it should be compatible with most versions of node.
The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.
After a search I found a Translate class within the HTML Parser library.
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */
Found that in .Net Core, placing the favicon.ico in /lib rather than wwwroot fixes the issue
test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
ls.append(key)
print(ls[0])
Conventional way of appending the keys to a statically defined list and then indexing it for same
For find method in all files you can press CTRL + P
and then start search with #
example : #signin
The SSPI context error definitely indicates authentication is being attempted using Kerberos.
Since Kerberos authentication SQL Server's Windows Authentication relies on Active Directory, which requires a thrusted relationship between your computer and your network domain controller, you should start by validating that relationship.
You can quickly check that relationship, thru the following Powershell command Test-ComputerSecureChannel.
Test-ComputerSecureChannel -verbose
If it returns False, you must repair your computer Active Directory secure channel, since without it no domain credencials validation is possible outside your computer.
You can repair your Computer Secure Channel, thru the following Powershell command:
Test-ComputerSecureChannel -Repair
Check the security event logs, if you are using kerberos you should see logon attempts with authentication package: Kerberos.
The NTLM authentication may be failing and so a kerberos authentication attempt is being made. You might also see an NTLM logon attempt failure in your security event log?
You can turn on kerberos event logging in dev to try to debug why the kerberos is failing, although it is very verbose.
Microsoft's Kerberos Configuration Manager for SQL Server may help you quickly diagnose and fix this issue.
Here is a good story to read: http://houseofbrick.com/microsoft-made-an-easy-button-for-spn-and-double-hop-issues/
$.each(result, function(key, value) {
console.log(key+ ':' + value);
});
For VS2010:
SET VS90COMNTOOLS=%VS100COMNTOOLS%
For VS2012:
SET VS90COMNTOOLS=%VS110COMNTOOLS%
then Call:
pip install pyCrypto
As a few people have mentioned, the parameters in paramMap
should be accessed using the common Map
API:
To get a snapshot of the params, when you don't care that they may change:
this.bankName = this.route.snapshot.paramMap.get('bank');
To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)
this.route.paramMap.subscribe( paramMap => {
this.bankName = paramMap.get('bank');
})
Since Angular 4, params
have been deprecated in favor of the new interface paramMap
. The code for the problem above should work if you simply substitute one for the other.
If you inject ActivatedRoute
in your component, you'll be able to extract the route parameters
import {ActivatedRoute} from '@angular/router';
...
constructor(private route:ActivatedRoute){}
bankName:string;
ngOnInit(){
// 'bank' is the name of the route parameter
this.bankName = this.route.snapshot.params['bank'];
}
If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:
ngOnInit(){
this.route.params.subscribe( params =>
this.bankName = params['bank'];
)
}
For the docs, including the differences between the two check out this link and search for "activatedroute"
Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
inputSearch.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
MainActivity.this.adapter.getFilter().filter(cs);
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
@Override
public void afterTextChanged(Editable arg0) {}
});
The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.
EDIT
To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.
class CustomAdapter extends BaseAdapter implements Filterable {
public View getView(){
...
}
public Integer getCount()
{
...
}
@Override
public Filter getFilter() {
Filter filter = new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
arrayListNames = (List<String>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
ArrayList<String> FilteredArrayNames = new ArrayList<String>();
// perform your search here using the searchConstraint String.
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mDatabaseOfNames.size(); i++) {
String dataNames = mDatabaseOfNames.get(i);
if (dataNames.toLowerCase().startsWith(constraint.toString())) {
FilteredArrayNames.add(dataNames);
}
}
results.count = FilteredArrayNames.size();
results.values = FilteredArrayNames;
Log.e("VALUES", results.values.toString());
return results;
}
};
return filter;
}
}
Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.
You can initialize the values as empty strings and fill them in later as they are found.
dictionary = {'one':'','two':''}
dictionary['one']=1
dictionary['two']=2
Found the solution as below.... posting it as it could help somebody else too :)
DateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = format.parse("2014-04-24 11:15:00");
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(date);
XMLGregorianCalendar xmlGregCal = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal);
System.out.println(xmlGregCal);
Output:
2014-04-24T11:15:00.000+02:00
You could also use deconstruction and tuples and try something like this:
@foreach (var (index, member) in @Model.Members.Select((member, i) => (i, member)))
{
<div>@index - @member.anyProperty</div>
if(index > 0 && index % 4 == 0) { // display clear div every 4 elements
@: <div class="clear"></div>
}
}
For more info you can have a look at this link
If you are setting the spinner values by arraylist
or array
you can set the spinner's selection by using the index of the value.
String myString = "some value"; //the value you want the position for
ArrayAdapter myAdap = (ArrayAdapter) mySpinner.getAdapter(); //cast to an ArrayAdapter
int spinnerPosition = myAdap.getPosition(myString);
//set the default according to value
spinner.setSelection(spinnerPosition);
see the link How to set selected item of Spinner by value, not by position?
Typing /**
+ then pressing Enter above a method signature will create Javadoc stubs for you.
To upgrade any python package, use pip install <pkg_name> --upgrade
.
So in your case it would be pip install tensorflow --upgrade
. Just updated to 1.1.0
Empty the bin folder. Build all the dependent class libraries and refer them in the main project, and build the complete solution.
$date = '2013-01-22';
$time = strtotime($date) + 86400;
echo date('Y-m-d', $time);
Where 86400 is the # of seconds in a day.
You can try with textContent.
var productId = val[key].textContent;
import shutil
shutil.rmtree('/folder_name')
Standard Library Reference: shutil.rmtree.
By design, rmtree
fails on folder trees containing read-only files. If you want the folder to be deleted regardless of whether it contains read-only files, then use
shutil.rmtree('/folder_name', ignore_errors=True)
You have many JSON parsers for Java:
JSONObject.java
A JSONObject is an unordered collection of name/value pairs. Its external form is a string wrapped in curly braces with colons between the names and values, and commas between the values and names. The internal form is an object having get() and opt() methods for accessing the values by name, and put() methods for adding or replacing values by name. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONArray.java
A JSONArray is an ordered sequence of values. Its external form is a string wrapped in square brackets with commas between the values. The internal form is an object having get() and opt() methods for accessing the values by index, and put() methods for adding or replacing values. The values can be any of these types: Boolean, JSONArray, JSONObject, Number, and String, or the JSONObject.NULL object.
JSONStringer.java
A JSONStringer is a tool for rapidly producing JSON text.
JSONWriter.java
A JSONWriter is a tool for rapidly writing JSON text to streams.
JSONTokener.java
A JSONTokener takes a source string and extracts characters and tokens from it. It is used by the JSONObject and JSONArray constructors to parse JSON source strings.
JSONException.java
A JSONException is thrown when a syntax or procedural error is detected.
JSONString.java
The JSONString is an interface that allows classes to implement their JSON serialization.
VonC mentioned in his answer how to remote debug from Eclipse.
I would like to add that the JAVA_OPTS
settings are already in run.conf.bat
. You just have to uncomment them:
in JBOSS_HOME\bin\run.conf.bat
on Windows:
rem # Sample JPDA settings for remote socket debugging
set "JAVA_OPTS=%JAVA_OPTS% -Xrunjdwp:transport=dt_socket,address=8787,server=y,suspend=n"
The Linux version is similar and is located at JBOSS_HOME/bin/run.conf
This PL*SQL will write to DBMS_OUTPUT a script that will drop each constraint that does not have delete cascade and recreate it with delete cascade.
NOTE: running the output of this script is AT YOUR OWN RISK. Best to read over the resulting script and edit it before executing it.
DECLARE
CURSOR consCols (theCons VARCHAR2, theOwner VARCHAR2) IS
select * from user_cons_columns
where constraint_name = theCons and owner = theOwner
order by position;
firstCol BOOLEAN := TRUE;
begin
-- For each constraint
FOR cons IN (select * from user_constraints
where delete_rule = 'NO ACTION'
and constraint_name not like '%MODIFIED_BY_FK' -- these constraints we do not want delete cascade
and constraint_name not like '%CREATED_BY_FK'
order by table_name)
LOOP
-- Drop the constraint
DBMS_OUTPUT.PUT_LINE('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' DROP CONSTRAINT ' || cons.CONSTRAINT_NAME || ';');
-- Re-create the constraint
DBMS_OUTPUT.PUT('ALTER TABLE ' || cons.OWNER || '.' || cons.TABLE_NAME || ' ADD CONSTRAINT ' || cons.CONSTRAINT_NAME
|| ' FOREIGN KEY (');
firstCol := TRUE;
-- For each referencing column
FOR consCol IN consCols(cons.CONSTRAINT_NAME, cons.OWNER)
LOOP
IF(firstCol) THEN
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT(') REFERENCES ');
firstCol := TRUE;
-- For each referenced column
FOR consCol IN consCols(cons.R_CONSTRAINT_NAME, cons.R_OWNER)
LOOP
IF(firstCol) THEN
DBMS_OUTPUT.PUT(consCol.OWNER);
DBMS_OUTPUT.PUT('.');
DBMS_OUTPUT.PUT(consCol.TABLE_NAME); -- This seems a bit of a kluge.
DBMS_OUTPUT.PUT(' (');
firstCol := FALSE;
ELSE
DBMS_OUTPUT.PUT(',');
END IF;
DBMS_OUTPUT.PUT(consCol.COLUMN_NAME);
END LOOP;
DBMS_OUTPUT.PUT_LINE(') ON DELETE CASCADE ENABLE VALIDATE;');
END LOOP;
end;
Silly, but I forgot to add [OperationContract]
to my service interface (the one marked with [ServiceContract]
) and then you also get this error.
If you use OmniFaces you can also use it's EL functions like of:formatDate()
to format Date
objects. You would use it like this:
<h:outputText value="#{of:formatDate(someBean.dateField, 'dd.MM.yyyy HH:mm')}" />
This way you can not only use it for output but also to pass it on to other JSF components.
$ git rev-parse HEAD 273cf91b4057366a560b9ddcee8fe58d4c21e6cb
Update:
Alternatively (if you have tags):
(Good for naming a version, not very good for passing back to git.)
$ git describe v0.1.49-localhost-ag-1-g273cf91
Or (as Mark suggested, listing here for completeness):
$ git show --oneline -s c0235b7 Autorotate uploaded images based on EXIF orientation
Actually using 100% will not make the image bigger if the image is smaller than the div size you specified. You need to set one of the dimensions, height or width in order to have all images fill the space. In my experience it's better to have the height set so each row is the same size, then all items wrap to next line properly. This will produce an output similar to fotolia.com (stock image website)
with css:
parent {
width: 42px; /* I took the width from your post and placed it in css */
height: 42px;
}
/* This will style any <img> element in .parent div */
.parent img {
height: 42px;
}
without:
<div style="height:42px;width:42px">
<img style="height:42px" src="http://someimage.jpg">
</div>
You could change the lists to sets and then compare both sets using the & function. eg:
list1 = [1, 2, 3, 4, 5]
list2 = [5, 6, 7, 8, 9]
if set(list1) & set(list2):
print "Number was found"
else:
print "Number not in list"
The "&" operator gives the intersection point between the two sets. If there is an intersection, a set with the intersecting points will be returned. If there is no intersecting points then an empty set will be returned.
When you evaluate an empty set/list/dict/tuple with the "if" operator in Python the boolean False is returned.
Very often it happens when the foreign key and the reference key don't have the same type or same length.
My favorite IDE was good old msdev.exe
, a.k.a., Microsoft Development Studio, a.k.a., Microsoft Visual C++ 6. It was the last version of Visual C++ that didn't require me to get new hardware just to run it.
However, the compiler wasn't standard-compliant. Not even remotely.
I don't recommend StartNew
unless you need that level of complexity.
If your async method is dependent on other async methods, the easiest approach is to use the async
keyword:
private static async Task<DateTime> CountToAsync(int num = 10)
{
for (int i = 0; i < num; i++)
{
await Task.Delay(TimeSpan.FromSeconds(1));
}
return DateTime.Now;
}
If your async method is doing CPU work, you should use Task.Run
:
private static async Task<DateTime> CountToAsync(int num = 10)
{
await Task.Run(() => ...);
return DateTime.Now;
}
You may find my async
/await
intro helpful.
Another simple example.
For this sample we can use 100x100 DIV-box:
<div id="box" style="width: 100px; height: 100px; border: solid 1px red;">
// Red box contents here...
</div>
And small jQuery trick:
<script type="text/javascript">
jQuery("#box").bind("resize", function() {
alert("Box was resized from 100x100 to 200x200");
});
jQuery("#box").width(200).height(200).trigger("resize");
</script>
Steps:
That's all. ;-)
initial_data = {'lib': np.array([1,2,3,4]), 'qty1': [1,2,3,4], 'qty2': [1,2,3,4]}
df = pd.DataFrame(initial_data)
df
lib qty1 qty2
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
val_1 = [10]
val_2 = [14]
val_3 = [20]
df.append(pd.DataFrame({'lib': val_1, 'qty1': val_2, 'qty2': val_3}))
lib qty1 qty2
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
0 10 14 20
You can use for loop to iterate through values or can add arrays of values
val_1 = [10, 11, 12, 13]
val_2 = [14, 15, 16, 17]
val_3 = [20, 21, 22, 43]
df.append(pd.DataFrame({'lib': val_1, 'qty1': val_2, 'qty2': val_3}))
lib qty1 qty2
0 1 1 1
1 2 2 2
2 3 3 3
3 4 4 4
0 10 14 20
1 11 15 21
2 12 16 22
3 13 17 43
Alternatively you can have your class implement the InitializingBean
interface to provide a callback function (afterPropertiesSet()
) which the ApplicationContext will invoke when the bean is constructed.
You can have all the different styles to datetime conversion
:
https://www.w3schools.com/sql/func_sqlserver_convert.asp
This has range of values :-
CONVERT(data_type(length),expression,style)
For style values,
Choose anyone you need like I needed 106.
In spring pre-3.0 it doesn't matter which one.
In spring 3.0 there's support for the standard (JSR-330) annotation @javax.inject.Inject
- use it, with a combination of @Qualifier
. Note that spring now also supports the @javax.inject.Qualifier
meta-annotation:
@Qualifier
@Retention(RUNTIME)
public @interface YourQualifier {}
So you can have
<bean class="com.pkg.SomeBean">
<qualifier type="YourQualifier"/>
</bean>
or
@YourQualifier
@Component
public class SomeBean implements Foo { .. }
And then:
@Inject @YourQualifier private Foo foo;
This makes less use of String-names, which can be misspelled and are harder to maintain.
As for the original question: both, without specifying any attributes of the annotation, perform injection by type. The difference is:
@Resource
allows you to specify a name of the injected bean@Autowired
allows you to mark it as non-mandatory.Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
Edit: I just noticed that you said you had already created some commits. In that case, use git merge --squash
to make a single commit:
git checkout cleanchanges
git merge --squash master
git commit -m "nice commit comment for all my changes"
(Edit: The following answer applies if you have uncommitted changes.)
Just switch branches with git checkout cleanchanges
. If the branches refer to the same ref, then all your uncommitted changes will be preserved in your working directory when you switch.
The only time you would have a conflict is if some file in the repository is different between origin/master
and cleanchanges
. If you just created the branch, then no problem.
As always, if you're at all concerned about losing work, make a backup copy first. Git is designed to not throw away work without asking you first.
Try this:
int index = row.Table.Columns["ColumnName"].Ordinal;
<!DOCTYPE html>
<html>
<head>
<title>float object center</title>
<style type="text/css">
#warp{
width:500px;
margin:auto;
}
.ser{
width: 200px;
background-color: #ffffff;
display: block;
float: left;
margin-right: 50px;
}
.inim{
width: 120px;
margin-left: 40px;
}
</style>
</head>
<body>
<div id="warp">
<div class="ser">
<img class="inim" src="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
<div class="ser">
<img class="inim" sr`enter code here`c="http://123greetingsquotes.com/wp-content/uploads/2015/01/republic-day-parade-india-images-120x120.jpg">
</div>
</div>
</body>
</html>
create two or more div's you want and give them a definite width like 100px for each then float it left or right
then warp these two div's in another div and give it the width of 200px. to this div apply margin auto. boom it works pretty well. check the above example.
I use
SELECT st.NAME, sc.NAME, sc.system_type_id
FROM sys.tables st
INNER JOIN sys.columns sc ON st.object_id = sc.object_id
WHERE st.name LIKE '%Tablename%'
Schema information which is designed to be very close to that of the SQL-92 INFORMATION_SCHEMA may be obtained for the Jet/ACE engine (which is what I assume you mean by 'access') via the OLE DB providers.
See:
If you want to find dependencies recursively (including dependencies of dependencies, dependencies of dependencies of dependencies and so on)…
You may use ldd
command.
ldd - print shared library dependencies
I had that problem while using IntelliJ
(14.1.3 Ultimate), I wanted to revert changes in some file.
Solved by closing Git Bash
opened in another window - another revert trial in IntelliJ
worked.
Print the full path (also called resolved path) with:
realpath README.md
In interactive mode you can use shell expansion to list all files in the directory with their full paths:
realpath *
If you're programming a bash script, I guess you'll have a variable for the individual file names.
Thanks to VIPIN KUMAR for pointing to the related readlink
command.
If you just need to insert a new row with a data from another row,
insert into ORDER_ITEM select * from ORDER_ITEM where ITEM_NUMBER =123;
$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })
I think you can simple call like this, this will give you result value.
this.$route.query.page
Look image $route is object in Vue Instance and you can access with this keyword and next you can select object properties like above one :
Have a look Vue-router document for selecting queries value :
I wanted do download all the files from a webpage. I tried wget
but it was failing so I decided for the Python route and I found this thread.
After reading it, I have made a little command line application, soupget
, expanding on the excellent answers of PabloG and Stan and adding some useful options.
It uses BeatifulSoup to collect all the URLs of the page and then download the ones with the desired extension(s). Finally it can download multiple files in parallel.
Here it is:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function, unicode_literals)
import sys, os, argparse
from bs4 import BeautifulSoup
# --- insert Stan's script here ---
# if sys.version_info >= (3,):
#...
#...
# def download_file(url, dest=None):
#...
#...
# --- new stuff ---
def collect_all_url(page_url, extensions):
"""
Recovers all links in page_url checking for all the desired extensions
"""
conn = urllib2.urlopen(page_url)
html = conn.read()
soup = BeautifulSoup(html, 'lxml')
links = soup.find_all('a')
results = []
for tag in links:
link = tag.get('href', None)
if link is not None:
for e in extensions:
if e in link:
# Fallback for badly defined links
# checks for missing scheme or netloc
if bool(urlparse.urlparse(link).scheme) and bool(urlparse.urlparse(link).netloc):
results.append(link)
else:
new_url=urlparse.urljoin(page_url,link)
results.append(new_url)
return results
if __name__ == "__main__": # Only run if this file is called directly
# Command line arguments
parser = argparse.ArgumentParser(
description='Download all files from a webpage.')
parser.add_argument(
'-u', '--url',
help='Page url to request')
parser.add_argument(
'-e', '--ext',
nargs='+',
help='Extension(s) to find')
parser.add_argument(
'-d', '--dest',
default=None,
help='Destination where to save the files')
parser.add_argument(
'-p', '--par',
action='store_true', default=False,
help="Turns on parallel download")
args = parser.parse_args()
# Recover files to download
all_links = collect_all_url(args.url, args.ext)
# Download
if not args.par:
for l in all_links:
try:
filename = download_file(l, args.dest)
print(l)
except Exception as e:
print("Error while downloading: {}".format(e))
else:
from multiprocessing.pool import ThreadPool
results = ThreadPool(10).imap_unordered(
lambda x: download_file(x, args.dest), all_links)
for p in results:
print(p)
An example of its usage is:
python3 soupget.py -p -e <list of extensions> -d <destination_folder> -u <target_webpage>
And an actual example if you want to see it in action:
python3 soupget.py -p -e .xlsx .pdf .csv -u https://healthdata.gov/dataset/chemicals-cosmetics
This should be a good case for map and lambda
with open ('names.txt','r') as f :
Names = map (lambda x : x.strip(),f_in.readlines())
I stand corrected (or at least improved). List comprehensions is even more elegant
with open ('names.txt','r') as f :
Names = [name.rstrip() for name in f]
I think this is what you want...
Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"
For Each WS In Application.ActiveWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
' about overwriting the original file.
End Sub
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
From SQL database get enum like:
SqlDataReader dr = selectCmd.ExecuteReader();
while (dr.Read()) {
EnumType et = (EnumType)Enum.Parse(typeof(EnumType), dr.GetString(0));
....
}
For single check try
myCheckBox.checked=1
_x000D_
<input type="checkbox" id="myCheckBox"> Call to her
_x000D_
for multi try
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
_x000D_
Buy wine: <input type="checkbox" class="imChecked"><br>_x000D_
Play smooth-jazz music: <input type="checkbox"><br>_x000D_
Shave: <input type="checkbox" class="imChecked"><br>
_x000D_
Go to MongoDB website, Login > Connect > Connect Application > Copy > Paste in 'database_url' > Collections > Copy/Paste in 'collection' .
var mongoose = require("mongoose");
mongoose.connect(' database_url ');
var conn = mongoose.connection;
conn.on('error', console.error.bind(console, 'connection error:'));
conn.once('open', function () {
conn.db.collection(" collection ", function(err, collection){
collection.find({}).toArray(function(err, data){
console.log(data); // data printed in console
})
});
});
Happy to Help. by RTTSS.
You dont have a function named assign()
, but a method with this name. PHP is not Java and in PHP you have to make clear, if you want to call a function
assign()
or a method
$object->assign()
In your case the call to the function resides inside another method. $this
always refers to the object, in which a method exists, itself.
$this->assign()
You might mean this:
var unEnumeratedArray = [];
var wtfObject = {
key : 'val',
0 : (undefined = 'Look, I\'m defined'),
'new' : 'keyword',
'{!}' : 'use bracket syntax',
' ': '8 spaces'
};
for(var key in wtfObject){
unEnumeratedArray[key] = wtfObject[key];
}
console.log('HAS KEYS PER VALUE NOW:', unEnumeratedArray, unEnumeratedArray[0],
unEnumeratedArray.key, unEnumeratedArray['new'],
unEnumeratedArray['{!}'], unEnumeratedArray[' ']);
You can set an enumerable for an Object like: ({})[0] = 'txt';
and you can set a key for an Array like: ([])['myKey'] = 'myVal';
Hope this helps :)
I got this error recently by introducing an old plugin to wordpress. It loaded an older version of jquery, which happened to be placed before the jquery mouse file. There was no jquery widget file loaded with the second version, which caused the error.
No error for using the extra jquery library -- that's a problem especially if a silent fail might have happened, causing a not so silent fail later on.
A potential way around it for wordpress might be to be explicit about the dependencies that way the jquery mouse would follow the widget which would follow the correct core leaving the other jquery to be loaded afterwards. Still might cause a production error later if you don't catch that and change the default function for jquery for the second version in all the files associated with it.
Rails 6.1 added a new 'syntax' for comparison operators in where
conditions, for example:
Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)
So your query can be rewritten as follows:
Note
.where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
.order(date: :asc, created_at: :asc)
Here is a link to PR where you can find more examples.
Did you try to set timezone by func: http://pl.php.net/manual/en/function.date-default-timezone-set.php
ssh-key with passphrase, with keychain
keychain is a small utility which manages ssh-agent on your behalf and allows the ssh-agent to remain running when the login session ends. On subsequent logins, keychain will connect to the existing ssh-agent instance. In practice, this means that the passphrase must be be entered only during the first login after a reboot. On subsequent logins, the unencrypted key from the existing ssh-agent instance is used. This can also be useful for allowing passwordless RSA/DSA authentication in cron jobs without passwordless ssh-keys.
To enable keychain, install it and add something like the following to ~/.bash_profile:
eval keychain --agents ssh --eval id_rsa
From a security point of view, ssh-ident and keychain are worse than ssh-agent instances limited to the lifetime of a particular session, but they offer a high level of convenience. To improve the security of keychain, some people add the --clear option to their ~/.bash_profile keychain invocation. By doing this passphrases must be re-entered on login as above, but cron jobs will still have access to the unencrypted keys after the user logs out. The keychain wiki page has more information and examples.
Got this info from;
Hope this helps
I have personally been able to automatically enter my passphrase upon terminal launch by doing this: (you can, of course, modify the script and fit it to your needs)
edit the bashrc file to add this script;
if [ -z "$SSH_AUTH_SOCK" ] ; then exec ssh-agent bash -c "ssh-add ; $0" echo "The SSH agent was awakened" exit fi
./ssh.exp
here's the content of this expect script
#!/usr/bin/expect
set timeout 20
set passphrase "test"
spawn "./keyadding.sh"
expect "Enter passphrase for /the/path/of/yourkey_id_rsa:"
send "$passphrase\r";
interact
Here's the content of my keyadding.sh script (you must put both scripts in your home folder, usually /home/user)
#!/bin/bash
ssh-add /the/path/of/yourkey_id_rsa
exit 0
I would HIGHLY suggest encrypting the password on the .exp script as well as renaming this .exp file to something like term_boot.exp or whatever else for security purposes. Don't forget to create the files directly from the terminal using nano or vim (ex: nano ~/.bashrc | nano term_boot.exp
) and also a chmod +x script.sh
to make it executable. A chmod +r term_boot.exp
would be also useful but you'll have to add sudo before ./ssh.exp in your bashrc file. So you'll have to enter your sudo password each time you launch your terminal. For me, it's more convenient than the passphrase cause I remember my admin (sudo) password by the hearth.
Also, here's another way to do it I think; https://www.cyberciti.biz/faq/noninteractive-shell-script-ssh-password-provider/
Will certainly change my method for this one when I'll have the time.
Unfortunately you cannot run MacOS X on anything but a genuine Mac.
MacOS X Server however can be run in VMWare. A stopgap solution would be to install it inside a VM. But you should be aware that MacOS X Server and MacOS X are not exactly the same, and your testing is not going to be exactly what the user has. Not to mention the $499 price tag.
Simplest way is to buy yourself a cheap mac mini or a laptop with a broken screen used on ebay, plug it onto your network and access it via VNC to do your testing.
For Windows users who want to use neovim with the Windows Subsystem for Linux:
git config core.editor "C:/Windows/system32/bash.exe --login -c 'nvim .git/COMMIT_EDITMSG'"
This is not a fool-proof solution as it doesn't handle interactive rebasing (for example). Improvements very welcome!
I recommend the answers with sed
and awk
for just getting the line number, rather than using grep
to get the entire matching line and then removing that from the output with cut
or another tool. For completeness, you can also use Perl:
perl -nE '/pattern/ && say $.' filename
or Ruby:
ruby -ne 'puts $. if /pattern/' filename
Just to correct mingos' answer:
If you set the expiration time to 0, the cookie won't be created at all. I've tested this on Google Chrome at least, and when set to 0 that was the result. The cookie, I guess, expires immediately after creation.
To set a cookie so it expires at the end of the browsing session, simply OMIT the expiration parameter altogether.
Example:
Instead of:
document.cookie = "cookie_name=cookie_value; 0; path=/";
Just write:
document.cookie = "cookie_name=cookie_value; path=/";
Browsers aren't allowed to access the local file system unless you're accessing a local html page. You have to upload the image somewhere. If it's in the same directory as the html file, then you can use <img src="localfile.jpg"/>
To turn on "Install via USB" and "USB Debugging(Security changes)" need to sign in to xiaomi account then these 2 can be turned on and work with redmi as developer
Note:When turning on USB Debugging(Security changes) few security alerts will be poped up all need to be accepted to work on developer mode
Well you are trying to compare Date with Nvarchar which is wrong. Should be
Where dates between date1 And date2
-- both date1 & date2 should be date/datetime
If date1,date2 strings; server will convert them to date type before filtering.
Compile all answers in one class. Outputs PIL image.
#!/usr/bin/env python
# encoding: utf-8
"""
screengrab.py
Created by Alex Snet on 2011-10-10.
Copyright (c) 2011 CodeTeam. All rights reserved.
"""
import sys
import os
import Image
class screengrab:
def __init__(self):
try:
import gtk
except ImportError:
pass
else:
self.screen = self.getScreenByGtk
try:
import PyQt4
except ImportError:
pass
else:
self.screen = self.getScreenByQt
try:
import wx
except ImportError:
pass
else:
self.screen = self.getScreenByWx
try:
import ImageGrab
except ImportError:
pass
else:
self.screen = self.getScreenByPIL
def getScreenByGtk(self):
import gtk.gdk
w = gtk.gdk.get_default_root_window()
sz = w.get_size()
pb = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB,False,8,sz[0],sz[1])
pb = pb.get_from_drawable(w,w.get_colormap(),0,0,0,0,sz[0],sz[1])
if pb is None:
return False
else:
width,height = pb.get_width(),pb.get_height()
return Image.fromstring("RGB",(width,height),pb.get_pixels() )
def getScreenByQt(self):
from PyQt4.QtGui import QPixmap, QApplication
from PyQt4.Qt import QBuffer, QIODevice
import StringIO
app = QApplication(sys.argv)
buffer = QBuffer()
buffer.open(QIODevice.ReadWrite)
QPixmap.grabWindow(QApplication.desktop().winId()).save(buffer, 'png')
strio = StringIO.StringIO()
strio.write(buffer.data())
buffer.close()
del app
strio.seek(0)
return Image.open(strio)
def getScreenByPIL(self):
import ImageGrab
img = ImageGrab.grab()
return img
def getScreenByWx(self):
import wx
wx.App() # Need to create an App instance before doing anything
screen = wx.ScreenDC()
size = screen.GetSize()
bmp = wx.EmptyBitmap(size[0], size[1])
mem = wx.MemoryDC(bmp)
mem.Blit(0, 0, size[0], size[1], screen, 0, 0)
del mem # Release bitmap
#bmp.SaveFile('screenshot.png', wx.BITMAP_TYPE_PNG)
myWxImage = wx.ImageFromBitmap( myBitmap )
PilImage = Image.new( 'RGB', (myWxImage.GetWidth(), myWxImage.GetHeight()) )
PilImage.fromstring( myWxImage.GetData() )
return PilImage
if __name__ == '__main__':
s = screengrab()
screen = s.screen()
screen.show()
You can't return because you're not in a function. You can exit
though.
import sys
sys.exit(0)
0 (the default) means success, non-zero means failure.
Use btoa()
for encode and atob()
for decode
text_val:any="your encoding text";
Encoded Text: console.log(btoa(this.text_val)); //eW91ciBlbmNvZGluZyB0ZXh0
Decoded Text: console.log(atob("eW91ciBlbmNvZGluZyB0ZXh0")); //your encoding text
Further on to @Xavier's response, here's a page that does speed comparisons between several different ways to do the conversion from 100 iterations up to 21,474,836 iterations.
It seems pretty much a tie between:
int someInt = 0;
someInt.ToString(); //this was fastest half the time
//and
Convert.ToString(someInt); //this was the fastest the other half the time
Instead of opening a folder, try adding a folder by going to "Project" -> "Add Folder to Project..." which opens a Folder choosing dialog. This way the folder won't open in a new window and will be added to your current workspace.
If you then go to "Project" -> "Save Project As..." you can even save your current setup (cells setup, opened files, unsaved changes, etc...), this makes it easy to hotswitch between multiple projects without loosing control and unsaved changes which could be unsafe to be saved right now, but would be a loss if you just ditched them.
(Just be sure to have the "hot_exit"
setting set to true
.)
And Ctrl + Alt + P (Linux and Windows) / Super + Ctrl + P (Mac) lets you switch between the saved projects.
This way you don't have to setup your editor every time you want to work on one of your projects.
Hint: Try http://sublime-text-unofficial-documentation.readthedocs.org/en/sublime-text-2/ which is a wonderful resource for beginners, it teaches you the ropes and shows you the power of your "new" editor, just start with the "Editing" chapter.
As answered previously, you do not need to set the environment variable on the remote host. Instead, you can simply do the meta-expansion on the local host, and pass the value to the remote host.
ssh [email protected] '~/tools/run_pvt.pl $BUILD_NUMBER'
If you really want to set the environment variable on the remote host and use it, you can use the env
program
ssh [email protected] "env BUILD_NUMBER=$BUILD_NUMBER ~/tools/run_pvt.pl \$BUILD_NUMBER"
In this case this is a bit of an overkill, and note
env BUILD_NUMBER=$BUILD_NUMBER
does the meta expansion on the local
hostBUILD_NUMBER
environment variable will be used byBelow code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.
// works for any Object Including JSON(key value pair) or Array.
// var arr = [];
// var jsonObj = {};
if (jQuery.isEmptyObject(anyObjectIncludingJSON))
{
console.log("Empty Object");
}
building on an answer from another posting.. I've come up with a more generic way to build out a list, utilizing dynamic retrieval with Json.NET version 12.x
using Newtonsoft.Json;
static class JsonObj
{
/// <summary>
/// Deserializes a json file into an object list
/// Author: Joseph Poirier 2/26/2019
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="fileName"></param>
/// <returns></returns>
public static List<T> DeSerializeObject<T>(string fileName)
{
List<T> objectOut = new List<T>();
if (string.IsNullOrEmpty(fileName)) { return objectOut; }
try
{
// reading in full file as text
string ss = File.ReadAllText(fileName);
// went with <dynamic> over <T> or <List<T>> to avoid error..
// unexpected character at line 1 column 2
var output = JsonConvert.DeserializeObject<dynamic>(ss);
foreach (var Record in output)
{
foreach (T data in Record)
{
objectOut.Add(data);
}
}
}
catch (Exception ex)
{
//Log exception here
Console.Write(ex.Message);
}
return objectOut;
}
}
call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = JsonObj.DeSerializeObject<string>(fname);
}
or this call to process
{
string fname = "../../Names.json"; // <- your json file path
// for alternate types replace string with custom class below
List<string> jsonFile = new List<string>();
jsonFile.AddRange(JsonObj.DeSerializeObject<string>(fname));
}
/* Keyword value */
cursor: pointer;
cursor: auto;
/* URL, with a keyword fallback */
cursor: url(hand.cur), pointer;
/* URL and coordinates, with a keyword fallback */
cursor: url(cursor1.png) 4 12, auto;
cursor: url(cursor2.png) 2 2, pointer;
/* Global values */
cursor: inherit;
cursor: initial;
cursor: unset;
/* 2 URLs and coordinates, with a keyword fallback */
cursor: url(one.svg) 2 2, url(two.svg) 5 5, progress;
Note: cursor support for many format icons!
such as .cur, .png, .svg, .jpeg, .webp
, and so on
li:hover{
cursor: url("https://cdn.xgqfrms.xyz/cursor/mouse.cur"), pointer;
color: #0f0;
background: #000;
}
/*
li:hover{
cursor: url("../icons/hand.cur"), pointer;
}
*/
li{
height: 30px;
width: 100px;
background: #ccc;
color: #fff;
margin: 10px;
text-align: center;
list-style: none;
}
_x000D_
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
</ul>
_x000D_