You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
A combination of @grahamparks and @snowindy answers with a couple of modifications is what worked for my Groovy scripts running on Tomcat:
Utils.groovy
class Utils {
def doSth() {...}
}
MyScript.groovy:
/* import Utils --> This import does not work. The class is not even defined at this time */
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(new File("full_path_to/Utils.groovy")); // Otherwise it assumes current dir is $CATALINA_HOME
def foo = groovyClass.newInstance(); // 'def' solves compile time errors!!
foo.doSth(); // Actually works!
There is no semicolon at the end of that instruction causing the error.
EDIT
Like RiverC pointed out, there is no semicolon at the end of the previous line!
require ("scripts/connect.php")
EDIT
It seems you have no-semicolons whatsoever.
http://php.net/manual/en/language.basic-syntax.instruction-separation.php
As in C or Perl, PHP requires instructions to be terminated with a semicolon at the end of each statement.
What you need to do is as follows:
That's it!
You don't need --header "Content-Length: $LENGTH".
curl --request POST --data-binary "@template_entry.xml" $URL
Note that GET request does not support content body widely.
Also remember that POST request have 2 different coding schema. This is first form:
$ nc -l -p 6666 & $ curl --request POST --data-binary "@README" http://localhost:6666 POST / HTTP/1.1 User-Agent: curl/7.21.0 (x86_64-pc-linux-gnu) libcurl/7.21.0 OpenSSL/0.9.8o zlib/1.2.3.4 libidn/1.15 libssh2/1.2.6 Host: localhost:6666 Accept: */* Content-Length: 9309 Content-Type: application/x-www-form-urlencoded Expect: 100-continue .. -*- mode: rst; coding: cp1251; fill-column: 80 -*- .. rst2html.py README README.html .. contents::
You probably request this:
-F/--form name=content (HTTP) This lets curl emulate a filled-in form in which a user has pressed the submit button. This causes curl to POST data using the Content- Type multipart/form-data according to RFC2388. This enables uploading of binary files etc. To force the 'content' part to be a file, prefix the file name with an @ sign. To just get the content part from a file, prefix the file name with the symbol <. The difference between @ and < is then that @ makes a file get attached in the post as a file upload, while the < makes a text field and just get the contents for that text field from a file.
You can also use shift()
.
var streetaddress = addy.split(',').shift();
According to MDN Web Docs:
The
shift()
method removes the first element from an array and returns that removed element. This method changes the length of the array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
Each of the three conditions is evaluated independently[1]:
id != 1 // false
id != 2 // true
id != 3 // true
Then it evaluates false || true || true
, which is true (a || b
is true if either a
or b
is true). I think you want
id != 1 && id != 2 && id != 3
which is only true if the ID is not 1 AND it's not 2 AND it's not 3.
[1]: This is not strictly true, look up short-circuit evaluation. In reality, only the first two clauses are evaluated because that is all that is necessary to determine the truth value of the expression.
BufferedImage is a(n) Image, so the implicit cast that you're doing in the second line is able to be compiled directly. If you knew an Image was really a BufferedImage, you would have to cast it explicitly like so:
Image image = ImageIO.read(new File(file));
BufferedImage buffered = (BufferedImage) image;
Because BufferedImage extends Image, it can fit in an Image container. However, any Image can fit there, including ones that are not a BufferedImage, and as such you may get a ClassCastException at runtime if the type does not match, because a BufferedImage cannot hold any other type unless it extends BufferedImage.
This is the correct way:
You should declare the length of the array after "="
Veicle[] cars = new Veicle[N];
While installing Netbeans itself, you will get an option which servers needs to be installed and integrated with Netbeans. First screen itself will show.
Another option is to reinstall Netbeans by closing all the open projects.
Eclipse C/C++ does not recognize the symbol std::unique_ptr
even though you have included the C++11 memory header in your file.
Assuming you are using the GNU C++ compiler, this is what I did to fix:
Project -> Properties -> C/C++ General -> Preprocessor Include Paths -> GNU C++ -> CDT User Setting Entries
Click on the "Add..." button
Select "Preprocessor Macro" from the dropdown menu
Name: __cplusplus Value: 201103L
Hit Apply, and then OK to go back to your project
Then rebuild you C++ index: Projects -> C/C++ Index -> Rebuild
I will post answer that helped me:
go to url:
chrome://settings/clearBrowserData
it should invoke popup and then..
cached images and files
.from beginning
You should use the Server.HtmlEncode method to protect your site from dangerous input.
This error mostly comes when we forcefully kill the weblogic server ("kill -9 process id"), so before restart kindly check all the ports status which weblogic using e.g. http port , DEBUG_PORT etc by using this command to see which whether this port is active or not.
netstat –an | grep (Admin: 7001 or something, Managed server- 7002, 7003 etc) eg: netstat –an | grep 7001
If it returns value then, option 1: wait for some time, so that background process can release the port option 2: execute stopweblogic.sh Option 3: Bounce the server/host or restart the system.
My issue was resolved by option 2.
I made a quick re-usable function in ES6 using Moment.js.
const getDaysDiff = (start_date, end_date, date_format = 'YYYY-MM-DD') => {_x000D_
const getDateAsArray = (date) => {_x000D_
return moment(date.split(/\D+/), date_format);_x000D_
}_x000D_
return getDateAsArray(end_date).diff(getDateAsArray(start_date), 'days') + 1;_x000D_
}_x000D_
_x000D_
console.log(getDaysDiff('2019-10-01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019/10/01', '2019/10/30'));_x000D_
console.log(getDaysDiff('2019.10-01', '2019.10 30'));_x000D_
console.log(getDaysDiff('2019 10 01', '2019 10 30'));_x000D_
console.log(getDaysDiff('+++++2019!!/###10/$$01', '2019-10-30'));_x000D_
console.log(getDaysDiff('2019-10-01-2019', '2019-10-30'));_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019', 'MM-DD-YYYY'));_x000D_
_x000D_
console.log(getDaysDiff('10-01-2019', '10-30-2019'));_x000D_
console.log(getDaysDiff('10-01-2019', '2019-10-30', 'MM-DD-YYYY'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
_x000D_
Arrays.fill(myArray, 'c');
Although it is quite possible that this is doing the loop in the background and is therefore not any more efficient than what you have (other than the lines of code savings). If you really care about efficiency, try the following in comparison to the above:
int size = 50;
char[] array = new char[size];
for (int i=0; i<size; i++){
array[i] = 'c';
}
Notice that the above doesn't call array.size() for each iteration.
Tried everything possible.. here is final piece of working code. Hope it helps someone who is looking for it.
<?
$url='https://www.googleapis.com/plus/v1/people/116599978027440206136?fields=image%2Furl&key=MY_API_KEY&fields=image';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_PROXYPORT, 3128);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$response = curl_exec($ch);
curl_close($ch);
$d = json_decode($response);
$avatar_url = $d->{'image'}->{'url'};
echo $avatar_url;
?>
I created these examples.
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
$rows.show().filter(function() {
var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
return !~text.indexOf(val);
}).hide();
});
Demo: http://jsfiddle.net/7BUmG/2/
More advanced functionality using regular expressions will allow you to search words in any order in the row. It will work the same if you type apple green
or green apple
:
var $rows = $('#table tr');
$('#search').keyup(function() {
var val = '^(?=.*\\b' + $.trim($(this).val()).split(/\s+/).join('\\b)(?=.*\\b') + ').*$',
reg = RegExp(val, 'i'),
text;
$rows.show().filter(function() {
text = $(this).text().replace(/\s+/g, ' ');
return !reg.test(text);
}).hide();
});
Demo: http://jsfiddle.net/dfsq/7BUmG/1133/
When you implement table filtering with search over multiple rows and columns it is very important that you consider performance and search speed/optimisation. Simply saying you should not run search function on every single keystroke, it's not necessary. To prevent filtering to run too often you should debounce it. Above code example will become:
$('#search').keyup(debounce(function() {
var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase();
// etc...
}, 300));
You can pick any debounce implementation, for example from Lodash _.debounce, or you can use something very simple like I use in next demos (debounce from here): http://jsfiddle.net/7BUmG/6230/ and http://jsfiddle.net/7BUmG/6231/.
A simple DIY way would be to make the grid yourself:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,2,3], [2,3,4], 'ro')
for xmaj in ax.xaxis.get_majorticklocs():
ax.axvline(x=xmaj, ls='-')
for xmin in ax.xaxis.get_minorticklocs():
ax.axvline(x=xmin, ls='--')
for ymaj in ax.yaxis.get_majorticklocs():
ax.axhline(y=ymaj, ls='-')
for ymin in ax.yaxis.get_minorticklocs():
ax.axhline(y=ymin, ls='--')
plt.show()
Your code is correct. You can also assign one directly to the other (see Joachim Pileborg's answer).
When you later come to compare the two structs, you need to be careful to compare the structs the long way, one member at a time, instead of using memcmp
; see How do you compare structs for equality in C?
An easy approach would be making all the blank cells NA
and only keeping complete cases. You might also look for na.omit
examples. It is a widely discussed topic.
df[df==""]<-NA
df<-df[complete.cases(df),]
If you like to remove last 5 characters, you can use:
path.substring(0,path.length() - 5)
( could contain off by one error ;) )
If you like to remove some variable string:
path.substring(0,path.lastIndexOf('yoursubstringtoremove));
(could also contain off by one error ;) )
The use of "closed" vs. "open" reflects whether or not we are locked in to using a certain position or data structure (this is an extremely vague description, but hopefully the rest helps).
For instance, the "open" in "open addressing" tells us the index (aka. address) at which an object will be stored in the hash table is not completely determined by its hash code. Instead, the index may vary depending on what's already in the hash table.
The "closed" in "closed hashing" refers to the fact that we never leave the hash table; every object is stored directly at an index in the hash table's internal array. Note that this is only possible by using some sort of open addressing strategy. This explains why "closed hashing" and "open addressing" are synonyms.
Contrast this with open hashing - in this strategy, none of the objects are actually stored in the hash table's array; instead once an object is hashed, it is stored in a list which is separate from the hash table's internal array. "open" refers to the freedom we get by leaving the hash table, and using a separate list. By the way, "separate list" hints at why open hashing is also known as "separate chaining".
In short, "closed" always refers to some sort of strict guarantee, like when we guarantee that objects are always stored directly within the hash table (closed hashing). Then, the opposite of "closed" is "open", so if you don't have such guarantees, the strategy is considered "open".
In VS 2005/2008 you can use private accessor to test private member,but this way was disappear in later version of VS
Even after trying suggested solution, it was not solving my problem because there where many instance of java path were entered by me.
I removed all java related path (different version java) from "Path, JAVA_HOME, JRE_HOME" and created from fresh.
i have set (path may changes as per different installation)
a. JAVA_HOME as C:\Program Files\Java\jdk1.8.0_191
b. JRE_HOME as C:\Program Files\Java\jdk1.8.0_191\jre\lib
c. add binary file path in path: C:\Program Files\Java\jdk1.8.0_191\bin
d. CLASSPATH as C:\apache-tomcat-7.0.93\lib
never try in the same command prompt if its already open while doing changes/creting system/user variables. close it and open new one.
The differences between the two, though subtle, are significant:
- Begins with the current element
- Travels up the DOM tree until it finds a match for the supplied selector
- The returned jQuery object contains zero or one element
- Begins with the parent element
- Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
- The returned jQuery object contains zero, one, or multiple elements
From jQuery docs
Check this:
hello.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View paramView) {
text.setText("hello");
}
});
You could just change this:
`create_date` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
To something like this:
`create_date` TIMESTAMP NOT NULL DEFAULT '2018-04-01 12:00:00',
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
The z-index
property only works on elements with a position
value other than static
(e.g. position: absolute;
, position: relative;
, or position: fixed
).
There is also position: sticky;
that is supported in Firefox, is prefixed in Safari, worked for a time in older versions of Chrome under a custom flag, and is under consideration by Microsoft to add to their Edge browser.
Important
For regular positioning, be sure to include position: relative
on the elements where you also set the z-index
. Otherwise, it won't take effect.
From a performance point of view, it doesn't matter in Python, and I'd assume the same for every modern language out there.
It really comes down to style and readability. Your second option (if-else block) is more readable than the first, and a lot more readable than the one-liner ternary operation.
It is SUBSTITUTE(B1," ","")
, not REPLACE(xx;xx;xx)
.
Run in a subshell to remove notifications and close STDOUT and STDERR:
(&>/dev/null script.sh &)
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
Edit (2020.12.28): GitHub change default master branch to main branch since October 2020. See https://github.com/github/renaming
Update March 2013
Git 1.8.2 added the possibility to track branches.
"
git submodule
" started learning a new mode to integrate with the tip of the remote branch (as opposed to integrating with the commit recorded in the superproject's gitlink).
# add submodule to track master branch
git submodule add -b master [URL to Git repo];
# update your submodule
git submodule update --remote
If you had a submodule already present you now wish would track a branch, see "how to make an existing submodule track a branch".
Also see Vogella's tutorial on submodules for general information on submodules.
Note:
git submodule add -b . [URL to Git repo];
^^^
A special value of
.
is used to indicate that the name of the branch in the submodule should be the same name as the current branch in the current repository.
See commit b928922727d6691a3bdc28160f93f25712c565f6:
submodule add
: If --branch
is given, record it in .gitmodules
This allows you to easily record a
submodule.<name>.branch
option in.gitmodules
when you add a new submodule. With this patch,
$ git submodule add -b <branch> <repository> [<path>]
$ git config -f .gitmodules submodule.<path>.branch <branch>
reduces to
$ git submodule add -b <branch> <repository> [<path>]
This means that future calls to
$ git submodule update --remote ...
will get updates from the same branch that you used to initialize the submodule, which is usually what you want.
Signed-off-by: W. Trevor King [email protected]
Original answer (February 2012):
A submodule is a single commit referenced by a parent repo.
Since it is a Git repo on its own, the "history of all commits" is accessible through a git log
within that submodule.
So for a parent to track automatically the latest commit of a given branch of a submodule, it would need to:
gitslave (that you already looked at) seems to be the best fit, including for the commit operation.
It is a little annoying to make changes to the submodule due to the requirement to check out onto the correct submodule branch, make the change, commit, and then go into the superproject and commit the commit (or at least record the new location of the submodule).
Other alternatives are detailed here.
All string functions as lower
, upper
, strip
are returning a string without modifying the original. If you try to modify a string, as you might think well it is an iterable
, it will fail.
x = 'hello'
x[0] = 'i' #'str' object does not support item assignment
There is a good reading about the importance of strings being immutable: Why are Python strings immutable? Best practices for using them
The asterisk (*) means "zero or more of the previous item".
If you want to match any single character use
sed -i 's/string-./string-0/g' file.txt
If you want to match any string (i.e. any single character zero or more times) use
sed -i 's/string-.*/string-0/g' file.txt
Ahhh, that's super simple, no programming required.
See: https://developers.facebook.com/docs/plugins/page-plugin
You'll want to keep the show stream
option turned on. You can adjust width and heigth and a few other things.
Simple HTML + Thymeleaf version. Code with Controller
<form action="/" method="post">
<input type="hidden" th:value="${post.getId_post()}" name="id_post">
<input type="hidden" th:value="-1" name="valueForChange">
<input type="submit" value="-">
</form>
This is how it looks - look of buttons you can change with style. https://i.stack.imgur.com/b97N1.png
For getting a table by name in SQL Server:
SELECT *
FROM sys.Tables
WHERE name LIKE '%Employees%'
For finding a stored procedure by name:
SELECT name
FROM sys.objects
WHERE name = 'spName'
To get all stored procedures related to a table:
----Option 1
SELECT DISTINCT so.name
FROM syscomments sc
INNER JOIN sysobjects so ON sc.id=so.id
WHERE sc.TEXT LIKE '%tablename%'
----Option 2
SELECT DISTINCT o.name, o.xtype
FROM syscomments c
INNER JOIN sysobjects o ON c.id=o.id
WHERE c.TEXT LIKE '%tablename%'
All Credit to @Jim Scott -- just added one touch. (ASP.NET 4.5 & C#)
Refractoring this a little more... if you pass the CheckBoxList as an object to the method, you can reuse it for any CheckBoxList. Also you can use either the Text or the Value.
private void SelectCheckBoxList(string valueToSelect, CheckBoxList lst)
{
ListItem listItem = lst.Items.FindByValue(valueToSelect);
//ListItem listItem = lst.Items.FindByText(valueToSelect);
if (listItem != null) listItem.Selected = true;
}
//How to call it -- in this case from a SQLDataReader and "chkRP" is my CheckBoxList`
SelectCheckBoxList(dr["kRPId"].ToString(), chkRP);`
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
In SSMS 2012, you'll have to use:
To enable single-user mode, in SQL instance properties, DO NOT go to "Advance" tag, there is already a "Startup Parameters" tag.
The answer is NO you can't. Why?
Because the LDAP standard describes a LDAP-SEARCH as kind of function with 4 parameters:
You are interested in the filter. You've got a summary here (it's provided by Microsoft for Active Directory, it's from a standard). The filter is composed, in a boolean way, by expression of the type Attribute Operator Value
.
So the filter you give does not mean anything.
On the theoretical point of view there is ExtensibleMatch that allows buildind filters on the DN path, but it's not supported by Active Directory.
As far as I know, you have to use an attribute in AD to make the distinction for users in the two OUs.
It can be any existing discriminator attribute, or, for example the attribute called OU which is inherited from organizationalPerson
class. you can set it (it's not automatic, and will not be maintained if you move the users) with "staff" for some users and "vendors" for others and them use the filter:
(&(objectCategory=person)(|(ou=staff)(ou=vendors)))
The class .show-grid is applying center aligned text in the example in the link.
You can always add style="text-align:center"
to your row div or some other class I would think.
You can still use the textmode and force the linefeed-newline with the keyword argument newline
f = open("./foo",'w',newline='\n')
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
$(".advanced ul li").live('click',function(e){
if(e.target != this) return;
//code
// this code will execute only when you click to li and not to a child
})
According to Apache Tomcat 7 JNDI Datasource HOW-TO page there must be a resource configuration in web.xml:
<resource-ref>
<description>DB Connection</description>
<res-ref-name>jdbc/TestDB</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
That works for me
Here is my contribution to the debate ... This returns a single array with the data separated and the headers listed. This works on the basis that CURL will return a headers chunk [ blank line ] data
curl_setopt($ch, CURLOPT_HEADER, 1); // we need this to get headers back
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, true);
// $output contains the output string
$output = curl_exec($ch);
$lines = explode("\n",$output);
$out = array();
$headers = true;
foreach ($lines as $l){
$l = trim($l);
if ($headers && !empty($l)){
if (strpos($l,'HTTP') !== false){
$p = explode(' ',$l);
$out['Headers']['Status'] = trim($p[1]);
} else {
$p = explode(':',$l);
$out['Headers'][$p[0]] = trim($p[1]);
}
} elseif (!empty($l)) {
$out['Data'] = $l;
}
if (empty($l)){
$headers = false;
}
}
You can also use a linear gradient and an image: http://codepen.io/anon/pen/RPweox
.background{
background: linear-gradient(rgba(0,0,0,.5), rgba(0,0,0,.5)),
url('http://www.imageurl.com');
}
This is because the linear gradient function creates an Image which is added to the background stack. https://developer.mozilla.org/en-US/docs/Web/CSS/linear-gradient
FETCH_HEAD
is a short-lived ref, to keep track of what has just been fetched from the remote repository.
Actually, ... not always considering that, with Git 2.29 (Q4 2020), "git fetch
"(man) learned --no-write-fetch-head
option to avoid writing the FETCH_HEAD
file.
See commit 887952b (18 Aug 2020) by Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit b556050, 24 Aug 2020)
fetch
: optionally allow disablingFETCH_HEAD
updateSigned-off-by: Derrick Stolee
If you run fetch but record the result in remote-tracking branches, and either if you do nothing with the fetched refs (e.g. you are merely mirroring) or if you always work from the remote-tracking refs (e.g. you fetch and then merge
origin/branchname
separately), you can get away with having noFETCH_HEAD
at all.Teach "
git fetch
"(man) a command line option "--[no-]write-fetch-head
".
- The default is to write
FETCH_HEAD,
and the option is primarily meant to be used with the "--no-
" prefix to override this default, because there is no matchingfetch.writeFetchHEAD
configuration variable to flip the default to off (in which case, the positive form may become necessary to defeat it).Note that under "
--dry-run
" mode,FETCH_HEAD
is never written; otherwise you'd see list of objects in the file that you do not actually have.Passing
--write-fetch-head
does not force[
git fetch](https://github.com/git/git/blob/887952b8c680626f4721cb5fa57704478801aca4/Documentation/git-fetch.txt)<sup>([man](https://git-scm.com/docs/git-fetch))</sup>
to write the file.
fetch-options
now includes in its man page:
--[no-]write-fetch-head
Write the list of remote refs fetched in the
FETCH_HEAD
file directly under$GIT_DIR
.
This is the default.Passing
--no-write-fetch-head
from the command line tells Git not to write the file.
Under--dry-run
option, the file is never written.
Consider also, still with Git 2.29 (Q4 2020), the FETCH_HEAD
is now always read from the filesystem regardless of the ref backend in use, as its format is much richer than the normal refs, and written directly by "git fetch
"(man) as a plain file..
See commit e811530, commit 5085aef, commit 4877c6c, commit e39620f (19 Aug 2020) by Han-Wen Nienhuys (hanwen
).
(Merged by Junio C Hamano -- gitster
-- in commit 98df75b, 27 Aug 2020)
refs
: readFETCH_HEAD
andMERGE_HEAD
genericallySigned-off-by: Han-Wen Nienhuys
The
FETCH_HEAD
andMERGE_HEAD
refs must be stored in a file, regardless of the type of ref backend. This is because they can hold more than just a single ref.To accomodate them for alternate ref backends, read them from a file generically in
refs_read_raw_ref()
.
With Git 2.29 (Q4 2020), Updates to on-demand fetching code in lazily cloned repositories.
See commit db3c293 (02 Sep 2020), and commit 9dfa8db, commit 7ca3c0a, commit 5c3b801, commit abcb7ee, commit e5b9421, commit 2b713c2, commit cbe566a (17 Aug 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit b4100f3, 03 Sep 2020)
fetch
: noFETCH_HEAD
display if --no-write-fetch-headSigned-off-by: Jonathan Tan
887952b8c6 ("
fetch
: optionally allow disablingFETCH_HEAD
update", 2020-08-18, Git v2.29.0 -- merge listed in batch #10) introduced the ability to disable writing toFETCH_HEAD
during fetch, but did not suppress the "<source> -> FETCH_HEAD"
message when this ability is used.This message is misleading in this case, because
FETCH_HEAD
is not written.Also, because "
fetch
" is used to lazy-fetch missing objects in a partial clone, this significantly clutters up the output in that case since the objects to be fetched are potentially numerous.Therefore, suppress this message when
--no-write-fetch-head
is passed (but not when--dry-run
is set).
As of 2.1, from bootstrap documentation at http://twitter.github.com/bootstrap/components.html#navs, you can.
Disabled state
For any nav component (tabs, pills, or list), add .disabled for gray links and no hover effects. Links will remain clickable, however, unless you remove the href attribute. Alternatively, you could implement custom JavaScript to prevent those clicks.
See https://github.com/twitter/bootstrap/issues/2764 for the feature add discussion.
There are several possibilities for concatenating 1D arrays, e.g.,
numpy.r_[a, a],
numpy.stack([a, a]).reshape(-1),
numpy.hstack([a, a]),
numpy.concatenate([a, a])
All those options are equally fast for large arrays; for small ones, concatenate
has a slight edge:
The plot was created with perfplot:
import numpy
import perfplot
perfplot.show(
setup=lambda n: numpy.random.rand(n),
kernels=[
lambda a: numpy.r_[a, a],
lambda a: numpy.stack([a, a]).reshape(-1),
lambda a: numpy.hstack([a, a]),
lambda a: numpy.concatenate([a, a]),
],
labels=["r_", "stack+reshape", "hstack", "concatenate"],
n_range=[2 ** k for k in range(19)],
xlabel="len(a)",
)
System.String
(with capital S) is already nullable, you do not need to declare it as such.
(string? myStr)
is wrong.
$(document).ready(function(){
$('#shares').val('');
});
Use the WINAPI CreateDirectory()
function to create a folder.
You can use this function without checking if the directory already exists as it will fail but GetLastError()
will return ERROR_ALREADY_EXISTS
:
if (CreateDirectory(OutputFolder.c_str(), NULL) ||
ERROR_ALREADY_EXISTS == GetLastError())
{
// CopyFile(...)
}
else
{
// Failed to create directory.
}
The code for constructing the target file is incorrect:
string(OutputFolder+CopiedFile).c_str()
this would produce "D:\testEmploi Nam.docx"
: there is a missing path separator between the directory and the filename. Example fix:
string(OutputFolder+"\\"+CopiedFile).c_str()
In my case I was trying to create a table from one database to another on MS SQL Server 2012. Right-clicking on a table and selecting Script Table as > DROP And CREATE To > New Query Editor Window, following script was created:
USE [SAMPLECOMPANY]
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
However when executing above script it was returning the error:
SELECT failed because the following SET options have incorrect settings: 'ANSI_PADDING'. Verify that SET options are correct for use with indexed views and/or indexes on computed columns and/or filtered indexes and/or query notifications and/or XML data type methods and/or spatial index operations.
The Solution I've found: Enabling the settings on the Top of the script like this:
USE [SAMPLECOMPANY]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
ALTER TABLE [dbo].[Employees] DROP CONSTRAINT [FK_Employees_Departments]
GO
/****** Object: Table [dbo].[Employees] Script Date: 8/24/2016 9:31:15 PM ******/
DROP TABLE [dbo].[Employees]
GO
CREATE TABLE [dbo].[Employees](
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentId] [int] NOT NULL,
[FullName] [varchar](50) NOT NULL,
[HireDate] [datetime] NULL
CONSTRAINT [PK_Employees] PRIMARY KEY CLUSTERED
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_Departments] FOREIGN KEY([DepartmentId])
REFERENCES [dbo].[Departments] ([DepartmentID])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
SET ANSI_PADDING OFF
GO
Hope this help.
You are somewhat close, but you should put your function inside the document.ready
event handler instead of the other-way-around.
Another way to do this is by placing your AJAX call in a generic function and call that function from an AJAX callback to loop through a set of requests in order:
$(function () {
//setup an array of AJAX options,
//each object will specify information for a single AJAX request
var ajaxes = [
{
url : '<url>',
data : {...},
callback : function (data) { /*do work on data*/ }
},
{
url : '<url2>',
data : {...},
callback : function (data) { /*maybe something different (maybe not)*/ }
}
],
current = 0;
//declare your function to run AJAX requests
function do_ajax() {
//check to make sure there are more requests to make
if (current < ajaxes.length) {
//make the AJAX request with the given info from the array of objects
$.ajax({
url : ajaxes[current].url,
data : ajaxes[current].data,
success : function (serverResponse) {
//once a successful response has been received,
//no HTTP error or timeout reached,
//run the callback for this request
ajaxes[current].callback(serverResponse);
},
complete : function () {
//increment the `current` counter
//and recursively call our do_ajax() function again.
current++;
do_ajax();
//note that the "success" callback will fire
//before the "complete" callback
}
});
}
}
//run the AJAX function for the first time once `document.ready` fires
do_ajax();
});
In this example, the recursive call to run the next AJAX request is being set as the complete
callback so that it runs regardless of the status of the current response. Meaning that if the request times out or returns an HTTP error (or invalid response), the next request will still run. If you require subsequent requests to only run when a request is successful, then using the success
callback to make your recursive call would likely be best.
Updated 2018-08-21 in regards to good points in comments.
You could give each position on each slider a different binary value from 1 to 1000000000 and then work with the sum.
Simple answer: You can't. Form elements have very limited styling capabilities.
The best alternative would be to set disabled=true
on the option (and maybe a gray colour, since only IE does that automatically), and this will make the option unclickable.
Alternatively, if you can, completely remove the option
element.
You need to use ?param instead of @param when performing queries to MySQL
str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_carSql
sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
sqlCommand.ExecuteNonQuery()
Change the catch block to see the actual exception:
Catch ex As Exception
MsgBox(ex.Message)
Return False
End Try
And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?
This is the value of User-Agent, the browser identification string.
For this reason, most Web browsers use a User-Agent string value as follows:
Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:
Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:
Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.
This value will be used to identify what browser is being used by end user.
Many (linked) answers change working directory with os.chdir()
. But you don't have to.
Recursively print all CSV files in /home/project/
directory:
pathname = "/home/project/**/*.csv"
for file in glob.iglob(pathname, recursive=True):
print(file)
Requires python 3.5+. From docs [1]:
pathname
can be either absolute (like /usr/src/Python-1.5/Makefile
) or relative (like ../../Tools/*/*.gif
)pathname
can contain shell-style wildcards.recursive
is true, the pattern **
will match any files and zero or more directories, subdirectories and symbolic links to directoriesPerhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:
DirectoryIndex test.html
For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level
By setting the scale, you decrease the precision. Try NUMBER(16,2).
Stop wasting your time, just add the following encoding="cp437"
and errors='ignore'
to your code in both read and write:
open('filename.csv', encoding="cp437", errors='ignore')
open(file_name, 'w', newline='', encoding="cp437", errors='ignore')
Godspeed
Local variables don't have a default value.
They have to be definitely assigned before you use them. It reduces the chance of using a variable you think you've given a sensible value to, when actually it's got some default value.
This may work for you:
select t1.*
from table t1
join (select t2.Chromosome, t2.Locus
from table2
group by t2.Chromosome, t2.Locus
having count(*) > 1) u on u.Chromosome = t1.Chromosome and u.Locus = t1.Locus
Moving your first line to the bottom does it for me: http://jsfiddle.net/tcloninger/SEmNX/
$(function () {
$('#serMemdd').change(function () {
var k = $(this).val();
if (k == 1) {
$("#serMemtb").attr("placeholder", "Type a name (Lastname, Firstname)").placeholder();
}
else if (k == 2) {
$("#serMemtb").attr("placeholder", "Type an ID").placeholder();
}
else if (k == 3) {
$("#serMemtb").attr("placeholder", "Type a Location").placeholder();
}
});
$('input[placeholder], textarea[placeholder]').placeholder();
});
I went through this post and everything didnt want to work correctly and eventually pieced the bits together from a few answers so I have a 100% working demo and will paste it here for reference - paste this into a php file and make sure includes are in the right place.
<?php if (isset($_GET['typeahead'])){
die(json_encode(array('options' => array('like','spike','dike','ikelalcdass'))));
}
?>
<link href="bootstrap.css" rel="stylesheet">
<input type="text" class='typeahead'>
<script src="jquery-1.10.2.js"></script>
<script src="bootstrap.min.js"></script>
<script>
$('.typeahead').typeahead({
source: function (query, process) {
return $.get('index.php?typeahead', { query: query }, function (data) {
return process(JSON.parse(data).options);
});
}
});
</script>
One way to 'minimise' the cmd window is to reduce the size of the console using something like...
echo DO NOT CLOSE THIS WINDOW
MODE CON COLS=30 LINES=2
You can reduce the COLS to about 18 and the LINES to 1 if you wish. The advantage is that it works under WinPE, 32-bit or 64-bit, and does not require any 3rd party utility.
Extrapolating from Edwin's answer:
from math import ceil, floor
def float_round(num, places = 0, direction = floor):
return direction(num * (10**places)) / float(10**places)
To use:
>>> float_round(0.21111, 3, ceil) #round up
>>> 0.212
>>> float_round(0.21111, 3) #round down
>>> 0.211
>>> float_round(0.21111, 3, round) #round naturally
>>> 0.211
Just a small addition...
If it works for you to only supply the http_proxy setting and not username and password I'd recommend putting the proxy settings in a project local nuget.config file and commit it to source control. That way all team members get the same settings.
Create an empty .\nuget.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
</configuration>
Then:
nuget config -Set http_proxy="http://myproxy.example.com:8080" -ConfigFile .\Nuget.Config
And finally commit your new project local Nuget.config file.
select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded
ping localhost -n (your time) >nul
example
@echo off
title Test
echo hi
ping localhost -n 3 >nul && :: will wait 3 seconds before going next command (it will not display)
echo bye! && :: still wont be any spaces (just below the hi command)
ping localhost -n 2 >nul && :: will wait 2 seconds before going to next command (it will not display)
@exit
Apart from being a simpler, more terse solution than the current answers (minus the future-looking ES6 ones), I perf tested this and it was much faster as well:
var uniqueArray = dupeArray.filter(function(item, i, self){
return self.lastIndexOf(item) == i;
});
One caveat: Array.lastIndexOf() was added in IE9, so if you need to go lower than that, you'll need to look elsewhere.
Well, I am quite surprised that the alternatives to this syntax have not been mentioned. Another common (but older) mechanism is to call a function that isn't defined and rely on the optimizer to compile-out the function call if your assertion is correct.
#define MY_COMPILETIME_ASSERT(test) \
do { \
extern void you_did_something_bad(void); \
if (!(test)) \
you_did_something_bad(void); \
} while (0)
While this mechanism works (as long as optimizations are enabled) it has the downside of not reporting an error until you link, at which time it fails to find the definition for the function you_did_something_bad(). That's why kernel developers starting using tricks like the negative sized bit-field widths and the negative-sized arrays (the later of which stopped breaking builds in GCC 4.4).
In sympathy for the need for compile-time assertions, GCC 4.3 introduced the error
function attribute that allows you to extend upon this older concept, but generate a compile-time error with a message of your choosing -- no more cryptic "negative sized array" error messages!
#define MAKE_SURE_THIS_IS_FIVE(number) \
do { \
extern void this_isnt_five(void) __attribute__((error( \
"I asked for five and you gave me " #number))); \
if ((number) != 5) \
this_isnt_five(); \
} while (0)
In fact, as of Linux 3.9, we now have a macro called compiletime_assert
which uses this feature and most of the macros in bug.h
have been updated accordingly. Still, this macro can't be used as an initializer. However, using by statement expressions (another GCC C-extension), you can!
#define ANY_NUMBER_BUT_FIVE(number) \
({ \
typeof(number) n = (number); \
extern void this_number_is_five(void) __attribute__(( \
error("I told you not to give me a five!"))); \
if (n == 5) \
this_number_is_five(); \
n; \
})
This macro will evaluate its parameter exactly once (in case it has side-effects) and create a compile-time error that says "I told you not to give me a five!" if the expression evaluates to five or is not a compile-time constant.
So why aren't we using this instead of negative-sized bit-fields? Alas, there are currently many restrictions of the use of statement expressions, including their use as constant initializers (for enum constants, bit-field width, etc.) even if the statement expression is completely constant its self (i.e., can be fully evaluated at compile-time and otherwise passes the __builtin_constant_p()
test). Further, they cannot be used outside of a function body.
Hopefully, GCC will amend these shortcomings soon and allow constant statement expressions to be used as constant initializers. The challenge here is the language specification defining what is a legal constant expression. C++11 added the constexpr keyword for just this type or thing, but no counterpart exists in C11. While C11 did get static assertions, which will solve part of this problem, it wont solve all of these shortcomings. So I hope that gcc can make a constexpr functionality available as an extension via -std=gnuc99 & -std=gnuc11 or some such and allow its use on statement expressions et. al.
Take a look at cat /proc/stat
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.
NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.
Current CPU usage can be potentially calculated with:
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)
@Borealid's answer is correct, but suppose that you don't care about preserving the exact merging history of a branch and just want to cherry-pick a linearized version of it. Here's an easy and safe way to do that:
Starting state: you are on branch X
, and you want to cherry-pick the commits Y..Z
.
git checkout -b tempZ Z
git rebase Y
git checkout -b newX X
git cherry-pick Y..tempZ
git branch -D tempZ
What this does is to create a branch tempZ
based on Z
, but with the history from Y
onward linearized, and then cherry-pick that onto a copy of X
called newX
. (It's safer to do this on a new branch rather than to mutate X
.) Of course there might be conflicts in step 4, which you'll have to resolve in the usual way (cherry-pick
works very much like rebase
in that respect). Finally it deletes the temporary tempZ
branch.
If step 2 gives the message "Current branch tempZ is up to date", then Y..Z
was already linear, so just ignore that message and proceed with steps 3 onward.
Then review newX
and see whether that did what you wanted.
(Note: this is not the same as a simple git rebase X
when on branch Z
, because it doesn't depend in any way on the relationship between X
and Y
; there may be commits between the common ancestor and Y
that you didn't want.)
var date = new Date()
console.log(" Date in MS last three digit = "+ date.getMilliseconds())
console.log(" MS = "+ Date.now())
Using this we can get date in milliseconds
Update - better version 18th July 2019.
Final summary, even though I've moved on to powershell for most windows console work anyway, but I decided to wrap this old cmd issue up, I had to get on a cmd console today, and the lack of this feature really struck me. This one finally works with spaces as well, where my previous answer would fail.
In addition, this one now is also able to use ~ as a prefix for other home sub-folders too, and it swaps forward-slashes to back-slashes as well. So here it is;
Step 1. Create these doskey macros, somewhere they get picked up every time cmd starts up.
DOSKEY cd=cdtilde.bat $*
DOSKEY cd~=chdir /D "%USERPROFILE%"
DOSKEY cd..=chdir ..
Step 2. Create the cdtilde.bat file and put it somewhere in your PATH
@echo off
set dirname=""
set dirname=%*
set orig_dirname=%*
:: remove quotes - will re-attach later.
set dirname=%dirname:\"=%
set dirname=%dirname:/"=%
set dirname=%dirname:"=%
:: restore dirnames that contained only "/"
if "%dirname%"=="" set dirname=%orig_dirname:"=%
:: strip trailing slash, if longer than 3
if defined dirname if NOT "%dirname:~3%"=="" (
if "%dirname:~-1%"=="\" set dirname="%dirname:~0,-1%"
if "%dirname:~-1%"=="/" set dirname="%dirname:~0,-1%"
)
set dirname=%dirname:"=%
:: if starts with ~, then replace ~ with userprofile path
if %dirname:~0,1%==~ (
set dirname="%USERPROFILE%%dirname:~1%"
)
set dirname=%dirname:"=%
:: replace forward-slashes with back-slashes
set dirname="%dirname:/=\%"
set dirname=%dirname:"=%
chdir /D "%dirname%"
Tested fine with;
cd ~ (traditional habit)
cd~ (shorthand version)
cd.. (shorthand for going up..)
cd / (eg, root of C:)
cd ~/.config (eg, the .config folder under my home folder)
cd /Program Files (eg, "C:\Program Files")
cd C:/Program Files (eg, "C:\Program Files")
cd \Program Files (eg, "C:\Program Files")
cd C:\Program Files (eg, "C:\Program Files")
cd "C:\Program Files (eg, "C:\Program Files")
cd "C:\Program Files" (eg, "C:\Program Files")
Oh, also it allows lazy quoting, which I found useful, even when spaces are in the folder path names, since it wraps all of the arguments as if it was one long string. Which means just an initial quote also works, or completely without quotes also works.
All other stuff below may be ignored now, it is left for historical reasons - so I dont make the same mistakes again
old update 19th Oct 2018.
In case anyone else tried my approach, my original answer below didn't handle spaces, eg, the following failed.
> cd "c:\Program Files"
Files""]==["~"] was unexpected at this time.
I think there must be a way to solve that. Will post again if I can improve my answer. (see above, I finally got it all working the way I wanted it to.)
My Original Answer, still needed work... 7th Oct 2018.
I was just trying to do it today, and I think I got it, this is what I think works well;
First, some doskey macros;
DOSKEY cd=cdtilde.bat $*
DOSKEY cd~=chdir /D "%USERPROFILE%"
DOSKEY cd..=chdir ..
and then then a bat file in my path;
cdtilde.bat
@echo off
if ["%1"]==["~"] (
chdir /D "%USERPROFILE%"
) else (
chdir /D %*
)
All these seem to work fine;
cd ~ (traditional habit)
cd~ (shorthand version)
cd.. (shorthand for going up..)
One option from DOM directly:
$(document).find("title").text();
Tested only on chrome & IE9, but logically should work on all browsers.
Or more generic
var title = document.getElementsByTagName("title")[0].innerHTML;
Wrapping a <a>
around won't work (unless you set the <div>
to display:inline-block;
or display:block;
to the <a>
) because the div is s a block-level element and the <a>
is not.
<a href="http://www.example.com" style="display:block;">
<div>
content
</div>
</a>
<a href="http://www.example.com">
<div style="display:inline-block;">
content
</div>
</a>
<a href="http://www.example.com">
<span>
content
</span >
</a>
<a href="http://www.example.com">
content
</a>
But maybe you should skip the <div>
and choose a <span>
instead, or just the plain <a>
. And if you really want to make the div clickable, you could attach a javascript redirect with a onclick handler, somethign like:
document.getElementById("myId").setAttribute('onclick', 'location.href = "url"');
but I would recommend against that.
Unless you can get PHP to label that element with a class you are better to use jQuery.
jQuery(document).ready(function () {
$count = jQuery("ul li").size() - 1;
alert($count);
jQuery("ul li:nth-child("+$count+")").css("color","red");
});
I actually managed to work out what I was doing wrong (and it was my fault).
I'm used to using pre-jQuery Rails, so when I included the Bootstrap JS files I didn't think that including the version of jQuery bundled with them would cause any issues, however when I removed that one JS file everything started working perfectly.
Lesson learnt, triple check which JS files are loaded, see if there's any conflicts.
I solved the error by modifying the following property in hibernate.cfg.xml
<property name="hibernate.hbm2ddl.auto">validate</property>
Earlier, the table was getting deleted each time I ran the program and now it doesnt, as hibernate only validates the schema and does not affect changes to it.
As far as I know you can also change from validate to update e.g.:
<property name="hibernate.hbm2ddl.auto">update</property>
The C99 way is
#include <inttypes.h>
int64_t my_int = 999999999999999999;
printf("%" PRId64 "\n", my_int);
Or you could cast!
printf("%ld", (long)my_int);
printf("%lld", (long long)my_int); /* C89 didn't define `long long` */
printf("%f", (double)my_int);
If you're stuck with a C89 implementation (notably Visual Studio) you can perhaps use an open source <inttypes.h>
(and <stdint.h>
): http://code.google.com/p/msinttypes/
Remove existing origin and add new origin to your project directory
>$ git remote show origin
>$ git remote rm origin
>$ git add .
>$ git commit -m "First commit"
>$ git remote add origin Copied_origin_url
>$ git remote show origin
>$ git push origin master
I had a similar problem with wget to my own live web site returning errors after installing a new SSL certificate. I'd already checked several browsers and they didn't report any errors:
wget --no-cache -O - "https://example.com/..." ERROR: The certificate of ‘example.com’ is not trusted. ERROR: The certificate of ‘example.com’ hasn't got a known issuer.
The problem was I had installed the wrong certificate authority .pem/.crt file from the issuer. Usually they bundle the SSL certificate and CA file as a zip file, but DigiCert email you the certificate and you have to figure out the matching CA on your own. https://www.digicert.com/help/ has an SSL certificate checker which lists the SSL authority and the hopefully matching CA with a nice blue link graphic if they agree:
`SSL Cert: Issuer GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1
CA: Subject GeoTrust TLS DV RSA Mixed SHA256 2020 CA-1 Valid from 16/Jul/2020 to 31/May/2023 Issuer DigiCert Global Root CA`
The problem with jeet's answer is that you load all bytes of the image into a byte array, which will likely crash the app in low-end devices. Instead, I would first write the image to a file and read it using Apache's Base64InputStream class. Then you can create the Base64 string directly from the InputStream of that file. It will look like this:
//Don't forget the manifest permission to write files
final FileOutputStream fos = new FileOutputStream(yourFileHere);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
final InputStream is = new Base64InputStream( new FileInputStream(yourFileHere) );
//Now that we have the InputStream, we can read it and put it into the String
final StringWriter writer = new StringWriter();
IOUtils.copy(is , writer, encoding);
final String yourBase64String = writer.toString();
As you can see, the above solution works directly with streams instead, avoiding the need to load all the bytes into a variable, therefore making the memory footprint much lower and less likely to crash in low-end devices. There is still the problem that putting the Base64 string itself into a String variable is not a good idea, because, again, it might cause OutOfMemory errors. But at least we have cut the memory consumption by half by eliminating the byte array.
If you want to skip the write-to-a-file step, you have to convert the OutputStream to an InputStream, which is not so straightforward to do (you must use PipedInputStream but that is a little more complex as the two streams must always be in different threads).
This removes trailing whitespace and blank lines from file.txt
PS C:\Users\> (gc file.txt) | Foreach {$_.TrimEnd()} | where {$_ -ne ""} | Set-Content file.txt
Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:]
for matching hex characters, which is simpler than the common 0-9a-fA-F
stuff.
So, the regex as requested (ie. with optional 0x
) is: /(0x)?[[:xdigit:]]+/
Handmade dll's collection folder
If you solution has a garbage folder for dll-files from different libraries
lib
, source
, libs
, etc.
You can get this trouble if you'll open your solution (for a firs time) in Visual Studio. And your dll's collecting folder is missed for somehow or a concrete dll-file is missed.
Visual Studio will try silently to substitute dll's reference for something on its own. If VS will succeed then a new reference will be persistent for your local solution. Not for other clones/checkouts.
I.e. your <HintPath>
will be ignored and you project file (.csproj) will not be changed.
As an example of me
<Reference Include="DocumentFormat.OpenXml, Version=2.0.5022.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>..\..\..\lib\DocumentFormat.OpenXml.dll</HintPath>
</Reference>
The DocumentFormat.OpenXml
will be referenced from C:\Program Files (x86)\Open XML SDK\V2.5\lib
not from a solution\..\lib
folder.
fast Workaround
right Workaround is to migrate to NuGet package manager.
Here you can find "Adobe Acrobat Forms JavaScript Object Specification Version 4.0"
Revised: January 27, 1999
It’s very old, but it is still useful.
$text="abc1234567890";
// truncate to 4 chars
echo substr(str_pad($text,4),0,4);
This avoids the problem of truncating a 4 char string to 10 chars .. (i.e. source is smaller than the required)
When creating an array like that, its size must be constant. If you want a dynamically sized array, you need to allocate memory for it on the heap and you'll also need to free it with delete
when you're done:
//allocate the array
int** arr = new int*[row];
for(int i = 0; i < row; i++)
arr[i] = new int[col];
// use the array
//deallocate the array
for(int i = 0; i < row; i++)
delete[] arr[i];
delete[] arr;
If you want a fixed size, then they must be declared const:
const int row = 8;
const int col = 8;
int arr[row][col];
Also,
int [row][col];
doesn't even provide a variable name.
I know this question was for iOS 5, but for the benefit of future readers, note that effective iOS 6 we can now use dequeueReusableHeaderFooterViewWithIdentifier
instead of dequeueReusableCellWithIdentifier
.
So in viewDidLoad
, call either registerNib:forHeaderFooterViewReuseIdentifier:
or registerClass:forHeaderFooterViewReuseIdentifier:
. Then in viewForHeaderInSection
, call tableView:dequeueReusableHeaderFooterViewWithIdentifier:
. You do not use a cell prototype with this API (it's either a NIB-based view or a programmatically created view), but this is the new API for dequeued headers and footers.
Microsoft.AspNetCore.All: v2.0.3 | Dapper: v1.50.2
I am not sure if I am using the best practices correctly or not, but I am doing it this way, in order to handle multiple connection strings.
Startup.cs
using System.Data;
using System.Data.SqlClient;
namespace DL.SO.Project.Web.UI
{
public class Startup
{
public IConfiguration Configuration { get; private set; }
// ......
public void ConfigureServices(IServiceCollection services)
{
// Read the connection string from appsettings.
string dbConnectionString = this.Configuration.GetConnectionString("dbConnection1");
// Inject IDbConnection, with implementation from SqlConnection class.
services.AddTransient<IDbConnection>((sp) => new SqlConnection(dbConnectionString));
// Register your regular repositories
services.AddScoped<IDiameterRepository, DiameterRepository>();
// ......
}
}
}
DiameterRepository.cs
using Dapper;
using System.Data;
namespace DL.SO.Project.Persistence.Dapper.Repositories
{
public class DiameterRepository : IDiameterRepository
{
private readonly IDbConnection _dbConnection;
public DiameterRepository(IDbConnection dbConnection)
{
_dbConnection = dbConnection;
}
public IEnumerable<Diameter> GetAll()
{
const string sql = @"SELECT * FROM TABLE";
// No need to use using statement. Dapper will automatically
// open, close and dispose the connection for you.
return _dbConnection.Query<Diameter>(sql);
}
// ......
}
}
Since Dapper
utilizes IDbConnection
, you need to think of a way to differentiate different database connections.
I tried to create multiple interfaces, 'inherited' from IDbConnection
, corresponding to different database connections, and inject SqlConnection
with different database connection strings on Startup
.
That failed because SqlConnection
inherits from DbConnection
, and DbConnection
inplements not only IDbConnection
but also Component
class. So your custom interfaces won't be able to use just the SqlConnection
implenentation.
I also tried to create my own DbConnection
class that takes different connection string. That's too complicated because you have to implement all the methods from DbConnection
class. You lost the help from SqlConnection
.
Startup
, I loaded all connection string values into a dictionary. I also created an enum
for all the database connection names to avoid magic strings. IDbConnection
, I created IDbConnectionFactory
and injected that as Transient for all repositories. Now all repositories take IDbConnectionFactory
instead of IDbConnection
.DatabaseConnectionName.cs
namespace DL.SO.Project.Domain.Repositories
{
public enum DatabaseConnectionName
{
Connection1,
Connection2
}
}
IDbConnectionFactory.cs
using System.Data;
namespace DL.SO.Project.Domain.Repositories
{
public interface IDbConnectionFactory
{
IDbConnection CreateDbConnection(DatabaseConnectionName connectionName);
}
}
DapperDbConenctionFactory - my own factory implementation
namespace DL.SO.Project.Persistence.Dapper
{
public class DapperDbConnectionFactory : IDbConnectionFactory
{
private readonly IDictionary<DatabaseConnectionName, string> _connectionDict;
public DapperDbConnectionFactory(IDictionary<DatabaseConnectionName, string> connectionDict)
{
_connectionDict = connectionDict;
}
public IDbConnection CreateDbConnection(DatabaseConnectionName connectionName)
{
string connectionString = null;
if (_connectDict.TryGetValue(connectionName, out connectionString))
{
return new SqlConnection(connectionString);
}
throw new ArgumentNullException();
}
}
}
Startup.cs
namespace DL.SO.Project.Web.UI
{
public class Startup
{
// ......
public void ConfigureServices(IServiceCollection services)
{
var connectionDict = new Dictionary<DatabaseConnectionName, string>
{
{ DatabaseConnectionName.Connection1, this.Configuration.GetConnectionString("dbConnection1") },
{ DatabaseConnectionName.Connection2, this.Configuration.GetConnectionString("dbConnection2") }
};
// Inject this dict
services.AddSingleton<IDictionary<DatabaseConnectionName, string>>(connectionDict);
// Inject the factory
services.AddTransient<IDbConnectionFactory, DapperDbConnectionFactory>();
// Register your regular repositories
services.AddScoped<IDiameterRepository, DiameterRepository>();
// ......
}
}
}
DiameterRepository.cs
using Dapper;
using System.Data;
namespace DL.SO.Project.Persistence.Dapper.Repositories
{
// Move the responsibility of picking the right connection string
// into an abstract base class so that I don't have to duplicate
// the right connection selection code in each repository.
public class DiameterRepository : DbConnection1RepositoryBase, IDiameterRepository
{
public DiameterRepository(IDbConnectionFactory dbConnectionFactory)
: base(dbConnectionFactory) { }
public IEnumerable<Diameter> GetAll()
{
const string sql = @"SELECT * FROM TABLE";
// No need to use using statement. Dapper will automatically
// open, close and dispose the connection for you.
return base.DbConnection.Query<Diameter>(sql);
}
// ......
}
}
DbConnection1RepositoryBase.cs
using System.Data;
using DL.SO.Project.Domain.Repositories;
namespace DL.SO.Project.Persistence.Dapper
{
public abstract class DbConnection1RepositoryBase
{
public IDbConnection DbConnection { get; private set; }
public DbConnection1RepositoryBase(IDbConnectionFactory dbConnectionFactory)
{
// Now it's the time to pick the right connection string!
// Enum is used. No magic string!
this.DbConnection = dbConnectionFactory.CreateDbConnection(DatabaseConnectionName.Connection1);
}
}
}
Then for other repositories that need to talk to the other connections, you can create a different repository base class for them.
using System.Data;
using DL.SO.Project.Domain.Repositories;
namespace DL.SO.Project.Persistence.Dapper
{
public abstract class DbConnection2RepositoryBase
{
public IDbConnection DbConnection { get; private set; }
public DbConnection2RepositoryBase(IDbConnectionFactory dbConnectionFactory)
{
this.DbConnection = dbConnectionFactory.CreateDbConnection(DatabaseConnectionName.Connection2);
}
}
}
using Dapper;
using System.Data;
namespace DL.SO.Project.Persistence.Dapper.Repositories
{
public class ParameterRepository : DbConnection2RepositoryBase, IParameterRepository
{
public ParameterRepository (IDbConnectionFactory dbConnectionFactory)
: base(dbConnectionFactory) { }
public IEnumerable<Parameter> GetAll()
{
const string sql = @"SELECT * FROM TABLE";
return base.DbConnection.Query<Parameter>(sql);
}
// ......
}
}
Hope all these help.
grep -r --include=*.{cc,h} "hello" .
This reads: search recursively (in all sub directories also) for all .cc OR .h files that contain "hello" at this .
(current) directory