on my system i had to insert apc.shm_size = 64M into /usr/local/etc/php.ini (FreeBSD 9.1) then when i looked at apc.php (which i copied from /usr/local/share/doc/APC/apc.php to /usr/local/www/apache24/data) i found that the cache size had increased from the default of 32M to 64M and i was no longer getting a large cache full count
references: http://au1.php.net/manual/en/apc.configuration.php also read Bokan's comments, they were very helpful
If you want PHP file caching only, you can use eAccelerator directly. Very easy to install and configure, and give great results.
But too bad, they removed the eaccelerator_put and eaccelerator_put from the latest version 0.9.6.
I know it's not for everyone but: why not to do a graceful Apache restart?
For e.g. in case of Centos/RedHat Linux:
sudo service httpd graceful
Ubuntu:
sudo service apache2 graceful
(This is for CentOS)
Rename the config file and restart apache.
sudo mv /etc/php.d/xdebug.ini /etc/php.d/xdebug.ini.old
sudo service httpd restart
Do the reverse to re-enable.
Extending Alex's answer slightly:
class User:
def __init__(self):
self.data = [1,2,3]
self.other_data = [4,5,6]
def doSomething(self, source):
dataSource = getattr(self,source)
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
will yield:
[1, 2, 3] [4, 5, 6]
However, personally I don't think that's great style - getattr
will let you access any attribute of the instance, including things like the doSomething
method itself, or even the __dict__
of the instance. I would suggest that instead you implement a dictionary of data sources, like so:
class User:
def __init__(self):
self.data_sources = {
"data": [1,2,3],
"other_data":[4,5,6],
}
def doSomething(self, source):
dataSource = self.data_sources[source]
return dataSource
A = User()
print A.doSomething("data")
print A.doSomething("other_data")
again yielding:
[1, 2, 3] [4, 5, 6]
what platform are you running?..
if its unix, maybe adding
alias java='java -Xmx1g'
to .bashrc (or similar) work
edit: Changing XmX to Xmx
Try this in Swift :
var urlString = myUrl.absoluteString
Objective-C:
NSString *urlString = [myURL absoluteString];
var res = from s in Splitting
join c in Customer on s.CustomerId equals c.Id
where c.Id == customrId
&& c.CompanyId == companyId
select s;
Using Extension methods
:
var res = Splitting.Join(Customer,
s => s.CustomerId,
c => c.Id,
(s, c) => new { s, c })
.Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
.Select(sc => sc.s);
You can also do it like:
str = str.replace(/\s/g, "+");
Have a look at this fiddle.
this is how you mock requests.post, change it to your http method
@patch.object(requests, 'post')
def your_test_method(self, mockpost):
mockresponse = Mock()
mockpost.return_value = mockresponse
mockresponse.text = 'mock return'
#call your target method now
I typically prefer if/else constructs over switch statements, especially in languages that allows fall-through cases. What I've found, often, is as the projects age, and multiple developers gets involved, you'll start having trouble with the construction of a switch statement.
If they (the statements) become anything more than simple, many programmers become lazy and instead of reading the entire statement to understand it, they'll simply pop in a case to cover whatever case they're adding into the statement.
I've seen many cases where code repeats in a switch statement because a person's test was already covered, a simple fall-though case would have sufficed, but laziness forced them to add the redundant code at the end instead of trying to understand the switch. I've also seen some nightmarish switch statements with many cases that were poorly constructed, and simply trying to follow all the logic, with many fall-through cases dispersed throughout, and many cases which weren't, becomes difficult ... which kind of leads to the first/redundancy problem I talked about.
Theoretically, the same problem could exist with if/else constructs, but in practice this just doesn't seem to happen as often. Maybe (just a guess) programmers are forced to read a bit more carefully because you need to understand the, often, more complex conditions being tested within the if/else construct? If you're writing something simple that you know others are likely to never touch, and you can construct it well, then I guess it's a toss-up. In that case, whatever is more readable and feels best to you is probably the right answer because you're likely to be sustaining that code.
Switch statements often perform faster than if-else constructs (but not always). Since the possible values of a switch statement are laid out beforehand, compilers are able to optimize performance by constructing jump tables. Each condition doesn't have to be tested as in an if/else construct (well, until you find the right one, anyway).
However this isn't always the case, though. If you have a simple switch, say, with possible values of 1 to 10, this will be the case. The more values you add requires the jump tables to be larger and the switch becomes less efficient (not than an if/else, but less efficient than the comparatively simple switch statement). Also, if the values are highly variant ( i.e. instead of 1 to 10, you have 10 possible values of, say, 1, 1000, 10000, 100000, and so on to 100000000000), the switch is less efficient than in the simpler case.
Hope this helps.
Running the command prompt or Powershell ISE as an administrator fixed this for me.
I use this approach:
if (null == drawable) {
//do stuff
} else {
//other things
}
This way I find improves the readability of the line - as I read quickly through a source file I can see it's a null check.
With regards to why you can't call .equals()
on an object which may be null
; if the object reference you have (namely 'drawable') is in fact null
, it doesn't point to an object on the heap. This means there's no object on the heap on which the call to equals()
can succeed.
Best of luck!
public static String removeSpace(String s) {
String withoutspaces = "";
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ')
withoutspaces += s.charAt(i);
}
return withoutspaces;
}
This is the easiest and most straight forward method to remove spaces from a String.
Because some database can throw an exception at dbContextTransaction.Commit() so better this:
using (var context = new BloggingContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
context.Database.ExecuteSqlCommand(
@"UPDATE Blogs SET Rating = 5" +
" WHERE Name LIKE '%Entity Framework%'"
);
var query = context.Posts.Where(p => p.Blog.Rating >= 5);
foreach (var post in query)
{
post.Title += "[Cool Blog]";
}
context.SaveChanges(false);
dbContextTransaction.Commit();
context.AcceptAllChanges();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
Just use dynamic
as the argument:
var list = new List<dynamic>();
yes... This is for each loop in java.
Generally this loop is become useful when you are retrieving data or object from the database.
Syntex :
for(Object obj : Collection obj)
{
//Code enter code here
}
Example :
for(User user : userList)
{
System.out.println("USer NAme :" + user.name);
// etc etc
}
This is for each loop.
it will incremental by automatically. one by one from collection to USer object data has been filled. and working.
Use sub query e.g:
SELECT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1 GROUP BY field1,field2
OR
SELECT DISTINCT field1,field2,(SELECT distinct field3 FROM tbl2 WHERE criteria) AS field3
FROM tbl1
Numerical_variables <- which(sapply(df, is.numeric))
# then extract column names
Names <- names(Numerical_variables)
A POD (plain old data) object has one of these data types--a fundamental type, pointer, union, struct, array, or class--with no constructor. Conversely, a non-POD object is one for which a constructor exists. A POD object begins its lifetime when it obtains storage with the proper size for its type and its lifetime ends when the storage for the object is either reused or deallocated.
PlainOldData types also must not have any of:
A looser definition of PlainOldData includes objects with constructors; but excludes those with virtual anything. The important issue with PlainOldData types is that they are non-polymorphic. Inheritance can be done with POD types, however it should only be done for ImplementationInheritance (code reuse) and not polymorphism/subtyping.
A common (though not strictly correct) definition is that a PlainOldData type is anything that doesn't have a VeeTable.
vagrant init laravel/homestead
and then
vagrant up
Was what worked for me.
var list = {
"you": 100,
"me": 75,
"foo": 116,
"bar": 15
};
var tmpList = {};
while (Object.keys(list).length) {
var key = Object.keys(list).reduce((a, b) => list[a] > list[b] ? a : b);
tmpList[key] = list[key];
delete list[key];
}
list = tmpList;
console.log(list); // { foo: 116, you: 100, me: 75, bar: 15 }
Use Immersive Full-Screen Mode
call fullScreen()
on ImageView
click.
public void fullScreen() {
// BEGIN_INCLUDE (get_current_ui_flags)
// The UI options currently enabled are represented by a bitfield.
// getSystemUiVisibility() gives us that bitfield.
int uiOptions = getWindow().getDecorView().getSystemUiVisibility();
int newUiOptions = uiOptions;
// END_INCLUDE (get_current_ui_flags)
// BEGIN_INCLUDE (toggle_ui_flags)
boolean isImmersiveModeEnabled =
((uiOptions | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY) == uiOptions);
if (isImmersiveModeEnabled) {
Log.i(TAG, "Turning immersive mode mode off. ");
} else {
Log.i(TAG, "Turning immersive mode mode on.");
}
// Navigation bar hiding: Backwards compatible to ICS.
if (Build.VERSION.SDK_INT >= 14) {
newUiOptions ^= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
}
// Status bar hiding: Backwards compatible to Jellybean
if (Build.VERSION.SDK_INT >= 16) {
newUiOptions ^= View.SYSTEM_UI_FLAG_FULLSCREEN;
}
// Immersive mode: Backward compatible to KitKat.
// Note that this flag doesn't do anything by itself, it only augments the behavior
// of HIDE_NAVIGATION and FLAG_FULLSCREEN. For the purposes of this sample
// all three flags are being toggled together.
// Note that there are two immersive mode UI flags, one of which is referred to as "sticky".
// Sticky immersive mode differs in that it makes the navigation and status bars
// semi-transparent, and the UI flag does not get cleared when the user interacts with
// the screen.
if (Build.VERSION.SDK_INT >= 18) {
newUiOptions ^= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
getWindow().getDecorView().setSystemUiVisibility(newUiOptions);
//END_INCLUDE (set_ui_flags)
}
Read more
Example Download
One approach that's both general and yields fairly-readable code is to use the filter()
function and the across()
helper functions from the {dplyr} package.
library(dplyr)
vars_to_check <- c("rnor", "cfam")
# Filter a specific list of columns to keep only non-missing entries
df %>%
filter(across(one_of(vars_to_check),
~ !is.na(.x)))
# Filter all the columns to exclude NA
df %>%
filter(across(everything(),
~ !is.na(.)))
# Filter only numeric columns
df %>%
filter(across(where(is.numeric),
~ !is.na(.)))
Similarly, there are also the variant functions in the dplyr package (filter_all
, filter_at
, filter_if
) which accomplish the same thing:
library(dplyr)
vars_to_check <- c("rnor", "cfam")
# Filter a specific list of columns to keep only non-missing entries
df %>%
filter_at(.vars = vars(one_of(vars_to_check)),
~ !is.na(.))
# Filter all the columns to exclude NA
df %>%
filter_all(~ !is.na(.))
# Filter only numeric columns
df %>%
filter_if(is.numeric,
~ !is.na(.))
This is a implementation of Fisher Yates/Durstenfeld Shuffle, but without actual creation of a array thus reducing space complexity or memory needed, when the pick size is small compared to the number of elements available.
To pick 8 numbers from 100, it is not necessary to create a array of 100 elements.
Assuming a array is created,
rnd
) from 1 to 100 rnd
If a array is not created, A hashMap may be used to remember the actual swapped positions. When the second random number generated is equal to the one of the previously generated numbers, the map provides the current value in that position rather than the actual value.
const getRandom_ = (start, end) => {_x000D_
return Math.floor(Math.random() * (end - start + 1)) + start;_x000D_
};_x000D_
const getRealValue_ = (map, rnd) => {_x000D_
if (map.has(rnd)) {_x000D_
return getRealValue_(map, map.get(rnd));_x000D_
} else {_x000D_
return rnd;_x000D_
}_x000D_
};_x000D_
const getRandomNumbers = (n, start, end) => {_x000D_
const out = new Map();_x000D_
while (n--) {_x000D_
const rnd = getRandom_(start, end--);_x000D_
out.set(getRealValue_(out, rnd), end + 1);_x000D_
}_x000D_
return [...out.keys()];_x000D_
};_x000D_
_x000D_
console.info(getRandomNumbers(8, 1, 100));_x000D_
console.info(getRandomNumbers(8, 1, Math.pow(10, 12)));_x000D_
console.info(getRandomNumbers(800000, 1, Math.pow(10, 15)));
_x000D_
Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine
(e.g. VirtualPathProviderViewEngine
) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.
System.Web.Mvc.WebFormViewEngine
Design Goals:
A view engine that is used to render a Web Forms page to the response.
Pros:
Cons:
Example:
<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
<% foreach(var p in model){%>
<li><%=p.Name%></li>
<%}%>
</ul>
<%}else{%>
<p>No products available</p>
<%}%>
Design Goals:
Pros:
Cons:
Con Example #1 (notice the placement of "string[]..."):
@{
<h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
foreach (var person in teamMembers)
{
<p>@person</p>
}
}
Design goals:
- Respect HTML as first-class language as opposed to treating it as "just text".
- Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML.
- Enforce strict Model-View separation
Design Goals:
The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.
Pros:
Cons:
Example:
<html>
<head>
<title>${title}</title>
</head>
<body>
<p>The following items are in the list:</p>
<ul><%for element in list: output "<li>${element}</li>"%></ul>
<p>I hope that you would like Brail</p>
</body>
</html>
Hasic uses VB.NET's XML literals instead of strings like most other view engines.
Pros:
Cons:
Example:
Protected Overrides Function Body() As XElement
Return _
<body>
<h1>Hello, World</h1>
</body>
End Function
Design Goals:
NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language.
Pros:
WebFormViewEngine
Design Goals:
.NET port of Rails Haml view engine. From the Haml website:
Haml is a markup language that's used to cleanly and simply describe the XHTML of any web document, without the use of inline code... Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content.
Pros:
Cons:
Example:
@type=IEnumerable<Product>
- if(model.Any())
%ul
- foreach (var p in model)
%li= p.Name
- else
%p No products available
NVelocityViewEngine (MvcContrib)
Design Goals:
A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.
Pros:
Cons:
Example:
#foreach ($p in $viewdata.Model)
#beforeall
<ul>
#each
<li>$p.Name</li>
#afterall
</ul>
#nodata
<p>No products available</p>
#end
Design Goals:
SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).
Pros:
Cons:
Example:
<c:if test="${not fn:empty(Page.Tiles)}">
<p class="note">
<fmt:message key="page.tilesSupport"/>
</p>
</c:if>
Design Goals:
The idea is to allow the html to dominate the flow and the code to fit seamlessly.
Pros:
Cons:
Example:
<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
<li each="var p in products">${p.Name}</li>
</ul>
<else>
<p>No products available</p>
</else>
<Form style="background-color:olive;">
<Label For="username" />
<TextBox For="username" />
<ValidationMessage For="username" Message="Please type a valid username." />
</Form>
StringTemplate View Engine MVC
Design Goals:
- Lightweight. No page classes are created.
- Fast. Templates are written to the Response Output stream.
- Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
- Dynamic. Templates can be generated on the fly in code.
- Flexible. Templates can be nested to any level.
- In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.
Pros:
Cons:
Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.
Pros:
Cons:
Design Goals:
Builds views from familiar XSLT
Pros:
Cons:
This is a very generic question and there is a lot of ways it can be answered.
If you want to use JUnit to create the tests, you need to create your testcase class, then create individual test methods that test specific functionality of your class/module under tests (single testcase classes are usually associated with a single "production" class that is being tested) and inside these methods execute various operations and compare the results with what would be correct. It is especially important to try and cover as many corner cases as possible.
In your specific example, you could for example test the following:
To verify the results, you can use various assertXXX methods from the org.junit.Assert class (for convenience, you can do 'import static org.junit.Assert.*'). These methods test a particular condition and fail the test if it does not validate (with a specific message, optionally).
Example testcase class in your case (without the methods contents defined):
import static org.junit.Assert.*;
public class AdditionTests {
@Test
public void testSimpleAddition() { ... }
@Test
public void testPositiveNegativeAddition() { ... }
@Test
public void testNegativePositiveAddition() { ... }
@Test
public void testNegativeAddition() { ... }
@Test
public void testOverflow() { ... }
}
If you are not used to writing unit tests but instead test your code by writing ad-hoc tests that you then validate "visually" (for example, you write a simple main method that accepts arguments entered using the keyboard and then prints out the results - and then you keep entering values and validating yourself if the results are correct), then you can start by writing such tests in the format above and validating the results with the correct assertXXX method instead of doing it manually. This way, you can re-run the test much easier then if you had to do manual tests.
the problem with datagridview is that it select the first row automatically so you want to clear the selection by
grvPackingList.ClearSelection();
dataGridView1.Rows[rowindex].Cells[columnindex].Selected = true;
other wise it will not work
Both Nick and Adam's answers work really well.
I'd like to add a note if you want to allow latin characters like á
and ç
as I wanted to do:
jQuery.validator.addMethod('lettersonly', function(value, element) {
return this.optional(element) || /^[a-z áãâäàéêëèíîïìóõôöòúûüùçñ]+$/i.test(value);
}, "Letters and spaces only please");
summation
and your other functions are defined after they're used in main
, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.
You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.
Either move the function bodies before main
, or include method signatures before main
, e.g.:
#include <stdio.h>
int summation(int *, int *, int *);
int main()
{
// ...
Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:
import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');
describe('myModule', () => {
it('calls the dependency with double the input', () => {
myModule(2);
});
});
And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.
If you want multiplicities, you can put it in map that maps pair to ammount. This way there will only be one pair of given values, but it can represent multiple occurances.
Then if you have lot of repeatet values and want to perform some operation on all values, you can save lot of computations.
You can use these queries:
select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;
Each of these tables have a grantee
column, you can filter on that in the where criteria:
where grantee = 'A'
To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs
, it also has a table_schema
column.
If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs
, user_sys_privs
, user_role_privs
. They can be queried by a normal non-dba user.
You could try:
const obj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
const max = Math.max.apply(null, Object.values(obj));
console.log(max) // 5
I had the same problem. You have to write mysql -u root -p
NOT mysql
or mysql -u root -p root_password
According to this discussion, Promise
has finally been called CompletableFuture
for inclusion in Java 8, and its javadoc explains:
A Future that may be explicitly completed (setting its value and status), and may be used as a CompletionStage, supporting dependent functions and actions that trigger upon its completion.
An example is also given on the list:
f.then((s -> aStringFunction(s)).thenAsync(s -> ...);
Note that the final API is slightly different but allows similar asynchronous execution:
CompletableFuture<String> f = ...;
f.thenApply(this::modifyString).thenAccept(System.out::println);
If you want to create table with data . First create the table :
create table new_table as ( select * from old_table);
and then insert
insert into new_table ( select * from old_table);
If you want to create table without data . You can use :
create table new_table as ( select * from old_table where 1=0);
First, fetch the latest commits from the remote repo. This will not affect your local branch.
git fetch origin
Then checkout the remote tracking branch and do a git log to see the commits
git checkout origin/master
git log
Grab the commit hash of the commit you want to merge up to (or just the first ~5 chars of it) and merge that commit into master
git checkout master
git merge <commit hash>
You don't necessarily need the BouncyCastle library. The following code shows how to do so using the Integer.toHexString function
public static String sha256(String base) {
try{
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(base.getBytes("UTF-8"));
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if(hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
Special thanks to user1452273 from this post: How to hash some string with sha256 in Java?
Keep up the good work !
If you're using Python 3, just execute python3 get-pip.py
. It is just a simple command.
There are several correct ways to display a down-pointing and upward-pointing triangle.
HTML :
▲
▼
HTML :
▲
▼
HTML :
?
?
HTML :
<span class='icon-up'></span>
<span class='icon-down'></span>
CSS :
.icon-up:before {
content: "\25B2";
}
.icon-down:before {
content: "\25BC";
}
Each of these three methods should have the same output. For other symbols, the same three options exist. Some even have a fourth option, allowing you to use a string based reference (eg. ♥
to display ?).
You can use a reference website like Unicode-table.com to find which icons are supported in UNICODE and which codes they correspond with. For example, you find the values for the down-pointing triangle at http://unicode-table.com/en/25BC/.
Note that these methods are sufficient only for icons that are available by default in every browser. For symbols like ?,?,?,?,?,? or ?, this is far less likely to be the case. While it is possible to provide cross-browser support for other UNICODE symbols, the procedure is a bit more complicated.
If you want to know how to add support for less common UNICODE characters, see Create webfont with Unicode Supplementary Multilingual Plane symbols for more info on how to do this.
A totally different strategy is the use of background-images instead of fonts. For optimal performance, it's best to embed the image in your CSS file by base-encoding it, as mentioned by eg. @weasel5i2 and @Obsidian. I would recommend the use of SVG rather than GIF, however, is that's better both for performance and for the sharpness of your symbols.
This following code is the base64 for and SVG version of the icon :
/* size: 0.9kb */
url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz48IURPQ1RZUEUgc3ZnIFBVQkxJQyAiLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4iICJodHRwOi8vd3d3LnczLm9yZy9HcmFwaGljcy9TVkcvMS4xL0RURC9zdmcxMS5kdGQiPjxzdmcgdmVyc2lvbj0iMS4xIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHhtbG5zOnhsaW5rPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5L3hsaW5rIiB3aWR0aD0iMTYiIGhlaWdodD0iMjgiIHZpZXdCb3g9IjAgMCAxNiAyOCI+PGcgaWQ9Imljb21vb24taWdub3JlIj48L2c+PHBhdGggZD0iTTE2IDE3cTAgMC40MDYtMC4yOTcgMC43MDNsLTcgN3EtMC4yOTcgMC4yOTctMC43MDMgMC4yOTd0LTAuNzAzLTAuMjk3bC03LTdxLTAuMjk3LTAuMjk3LTAuMjk3LTAuNzAzdDAuMjk3LTAuNzAzIDAuNzAzLTAuMjk3aDE0cTAuNDA2IDAgMC43MDMgMC4yOTd0MC4yOTcgMC43MDN6TTE2IDExcTAgMC40MDYtMC4yOTcgMC43MDN0LTAuNzAzIDAuMjk3aC0xNHEtMC40MDYgMC0wLjcwMy0wLjI5N3QtMC4yOTctMC43MDMgMC4yOTctMC43MDNsNy03cTAuMjk3LTAuMjk3IDAuNzAzLTAuMjk3dDAuNzAzIDAuMjk3bDcgN3EwLjI5NyAwLjI5NyAwLjI5NyAwLjcwM3oiIGZpbGw9IiMwMDAwMDAiPjwvcGF0aD48L3N2Zz4=
For many use cases, SVG-based background images and icon fonts are largely equivalent with regards to performance and flexibility. To decide which to pick, consider the following differences:
SVG images
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your icon, but you can reference different components of the icon as shapes individually.Icon fonts
color
, font-size
, line-height
, background-color
or other font related styling rules to change the display of your iconPersonally, I would recommend the use of background-images only when you need multiple colors and those color can't be achieved by means of color
, background-color
and other color-related CSS rules for fonts.
The main benefit of using SVG images is that you can give different components of a symbol their own styling. If you embed your SVG XML code in the HTML document, this is very similar to styling the HTML. This would, however, result in a web page that uses both HTML tags and SVG tags, which could significantly reduce the readability of a webpage. It also adds extra bloat if the symbol is repeated across multiple pages and you need to consider that old versions of IE have no or limited support for SVG.
you can make a new object of your class and then assign it's parameters dynamically from the JSON object's parameters.
const employeeData = JSON.parse(employeeString);
let emp:Employee=new Employee();
const keys=Object.keys(employeeData);
keys.forEach(key=>{
emp[key]=employeeData[key];
});
console.log(emp);
now the emp is an object of Employee containing all fields of employeeString's Json object(employeeData);
Another solution:
select * from traintable
where (train, time) in (select train, max(time) from traintable group by train);
You need to give a relative file path of <a href="../index.html">Home</a>
Alternately you can specify a link from the root of your site with
<a href="/pages/en/index.html">Home</a>
..
and .
have special meanings in file paths, ..
means up one directory and .
means current directory.
so <a href="index.html">Home</a>
is the same as <a href="./index.html">Home</a>
The standard ERB templating system may work for your scenario.
def merge_into_string(animal, second_animal, action)
template = 'The <%=animal%> <%=action%> the <%=second_animal%>'
ERB.new(template).result(binding)
end
merge_into_string('tiger', 'deer', 'eats')
=> "The tiger eats the deer"
merge_into_string('bird', 'worm', 'finds')
=> "The bird finds the worm"
This is what I do to get date only:
let isoDate = "2013-03-10T02:00:00Z";_x000D_
_x000D_
alert(isoDate.split("T")[0]);
_x000D_
The error message will include the name of the constraint that was violated (there may be more than one unique constraint on a table). You can use that constraint name to identify the column(s) that the unique constraint is declared on
SELECT column_name, position
FROM all_cons_columns
WHERE constraint_name = <<name of constraint from the error message>>
AND owner = <<owner of the table>>
AND table_name = <<name of the table>>
Once you know what column(s) are affected, you can compare the data you're trying to INSERT
or UPDATE
against the data already in the table to determine why the constraint is being violated.
I was having same problem, i installed latest xamp version and found my site is not working, after research and wasting time i found that.
I need to turn on following tag in php.ini file short_open_tag=On
Make sure to restart apache after doing this.
Hope this helps, most of these problems are related to php.ini file or fresh installation if your site was already running as other people facing similar issue.
the fix for me was to run
npm install
and then unload,then reload the project in visual studio.
If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run
$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run
Alternatively you can do the following (I haven't tried this but one resource online talks about it)
$ export FLASK_APP = hello.py
$ python -m flask run
source: For more
Xcode 10, Swift 4
Wrapping the Text for a label can also be done on Storyboard by selecting the Label, and using Attributes Inspector.
Lines = 0 Linebreak = Word Wrap
Swift 3
@IBOutlet weak var webview: UIWebView!
webview.loadRequest(URLRequest(url: URL(string: "https://www.yourvideo.com")!))
One of my solution, which works for me.
Microsoft recommends to use the "InstallShield Limited Edition for Visual Studio" as replacement for the discontinued "Deployment and Setup Project" - but it is not so nice and nobody else recommends to use it. But for simple setups, and if it is not a problem to relay on commercial third party products, you can use it.
The alternative is to use Windows Installer XML (WiX), but you have to do many things manually that did the Setup-Project by itself.
My issue got resolved with the help of following steps:
For gradle 3.0.0 and above version
No, there is not, see how the "Related XML Attributes" section is missing in the ImageView.setAlpha(int) documentation. The alternative is to use View.setAlpha(float) whose XML counterpart is android:alpha
. It takes a range of 0.0 to 1.0 instead of 0 to 255. Use it e.g. like
<ImageView android:alpha="0.4">
However, the latter in available only since API level 11.
In case it helps someone else, I was able to convert to an array by doing something like this,
JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()
...or you should be able to get the length
((JSONArray) myJsonArray).toArray().length
I think below explanation will help to you..
differentiation between those:
Correlated subquery
is an inner query referenced by main query (outer query) such that inner query considered as being excuted repeatedly.
non-correlated subquery
is a sub query that is an independent of the outer query and it can executed on it's own without relying on main outer query.
plain subquery
is not dependent on the outer query,
C also does a good job at not making anything ambiguous.
Sure the dot could be overloaded to mean both things, but the arrow makes sure that the programmer knows that he's operating on a pointer, just like when the compiler won't let you mix two incompatible types.
Have you thought about creating a view with 'Folder = Show all items without folders', that would get all your documents out of their folders and then perhaps you could create your filter(s) over that view.
This is my solution:
# your test class
class TestingClass(unittest.TestCase):
# This will only run once for all the tests within this class
@classmethod
def setUpClass(cls) -> None:
if len(sys.argv) > 1:
cls.email = sys.argv[1]
def testEmails(self):
assertEqual(self.email, "[email protected]")
if __name__ == "__main__":
unittest.main()
you could have a runner.py
file with something like this:
# your runner.py
loader = unittest.TestLoader()
tests = loader.discover('.') # note that this will find all your tests, you can also provide the name of the package e.g. `loader.discover('tests')
runner = unittest.TextTestRunner(verbose=3)
result = runner.run(tests
with the above code, you should be to run your tests with runner.py [email protected]
Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2
Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'
Click on the 'Google API Console' link.
When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'
Google is your friend: http://docstore.mik.ua/orelly/oracle/prog2/ch06_03.htm
PL/SQL issues an implicit cursor whenever you execute a SQL statement directly in your code, as long as that code does not employ an explicit cursor. It is called an "implicit" cursor because you, the developer, do not explicitly declare a cursor for the SQL statement.
An explicit cursor is a SELECT statement that is explicitly defined in the declaration section of your code and, in the process, assigned a name. There is no such thing as an explicit cursor for UPDATE, DELETE, and INSERT statements.
Here is the link to documentation INSERT ... ON DUPLICATE Statement.
The above methods work when you are connected to a Wi-Fi source or via cell phone data packs. But in case of Wi-Fi connection there are cases when you are further asked to Sign-In like in Cafe. So in that case your application will fail as you are connected to Wi-Fi source but not with the Internet.
This method works fine.
public static boolean isConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null && activeNetwork.isConnected()) {
try {
URL url = new URL("http://www.google.com/");
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setRequestProperty("User-Agent", "test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1000); // mTimeout is in seconds
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
} else {
return false;
}
} catch (IOException e) {
Log.i("warning", "Error checking internet connection", e);
return false;
}
}
return false;
}
Please use this in a separate thread from the main thread as it makes a network call and will throw NetwrokOnMainThreadException if not followed.
And also do not put this method inside onCreate or any other method. Put it inside a class and access it.
I had this occur to me on my Windows machine, turns out the problem was quite different. I had accidentally removed some paths from my %PATH%
variable. Simply restarting the command prompt solved it. It seems as though there was a JS runtime in one of those missing paths.
As the comment stated, this is in C# not Java but the idea is the same. I've researched this issue extensively and ultimately the issue is, FindElement always returns an exception when the element doesn't exist. There isn't an overloaded option that allows you to get null or anything else. Here is why I prefer this solution over others.
It's actually a very simple and elegant once the method is created. By using FindElementSafe instead of FindElement, I don't "see" the ugly try/catch block and I can use a simple Exists method. That would look something like this:
IWebElement myLink = driver.FindElementSafe(By.Id("myId"));
if (myLink.Exists)
{
myLink.Click();
}
Here is how you extend IWebElement & IWebDriver
IWebDriver.FindElementSafe
/// <summary>
/// Same as FindElement only returns null when not found instead of an exception.
/// </summary>
/// <param name="driver">current browser instance</param>
/// <param name="by">The search string for finding element</param>
/// <returns>Returns element or null if not found</returns>
public static IWebElement FindElementSafe(this IWebDriver driver, By by)
{
try
{
return driver.FindElement(by);
}
catch (NoSuchElementException)
{
return null;
}
}
IWebElement.Exists
/// <summary>
/// Requires finding element by FindElementSafe(By).
/// Returns T/F depending on if element is defined or null.
/// </summary>
/// <param name="element">Current element</param>
/// <returns>Returns T/F depending on if element is defined or null.</returns>
public static bool Exists(this IWebElement element)
{
if (element == null)
{ return false; }
return true;
}
You could use polymorphism to modify the IWebDriver class instance of FindElement but that's a bad idea from a maintenance standpoint.
Expanding on the answer provided in https://stackoverflow.com/a/1987215/275388 which fails for database/schema wide rights and database user types you can use:
SELECT
CASE
WHEN dp.class_desc = 'OBJECT_OR_COLUMN' THEN
dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as +
' ON ' + '[' + obj_sch.name + ']' + '.' + '[' + o.name + ']' +
' TO ' + '[' + dpr.name + ']'
WHEN dp.class_desc = 'DATABASE' THEN
dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as +
' TO ' + '[' + dpr.name + ']'
WHEN dp.class_desc = 'SCHEMA' THEN
dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as +
' ON SCHEMA :: ' + '[' + SCHEMA_NAME(dp.major_id) + ']' +
' TO ' + '[' + dpr.name + ']'
WHEN dp.class_desc = 'TYPE' THEN
dp.state_desc + ' ' + dp.permission_name collate Latin1_General_CS_AS +
' ON TYPE :: [' + s_types.name + '].[' + t.name + ']'
+ ' TO [' + dpr.name + ']'
WHEN dp.class_desc = 'CERTIFICATE' THEN
dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as +
' TO ' + '[' + dpr.name + ']'
WHEN dp.class_desc = 'SYMMETRIC_KEYS' THEN
dp.state_desc + ' ' + dp.permission_name collate latin1_general_cs_as +
' TO ' + '[' + dpr.name + ']'
ELSE
'ERROR: Unhandled class_desc: ' + dp.class_desc
END
AS GRANT_STMT
FROM sys.database_permissions AS dp
JOIN sys.database_principals AS dpr ON dp.grantee_principal_id=dpr.principal_id
LEFT JOIN sys.objects AS o ON dp.major_id=o.object_id
LEFT JOIN sys.schemas AS obj_sch ON o.schema_id = obj_sch.schema_id
LEFT JOIN sys.types AS t ON dp.major_id = t.user_type_id
LEFT JOIN sys.schemas AS s_types ON t.schema_id = s_types.schema_id
WHERE
dpr.name NOT IN ('public','guest')
-- AND o.name IN ('My_Procedure') -- Uncomment to filter to specific object(s)
-- AND (o.name NOT IN ('My_Procedure') or o.name is null) -- Uncomment to filter out specific object(s), but include rows with no o.name (VIEW DEFINITION etc.)
-- AND dp.permission_name='EXECUTE' -- Uncomment to filter to just the EXECUTEs
-- AND dpr.name LIKE '%user_name%' -- Uncomment to filter to just matching users
ORDER BY dpr.name, dp.class_desc, dp.permission_name
sqlall
just prints the SQL, it doesn't execute it. syncdb
will create tables that aren't already created, but it won't modify existing tables.
This works for me:
This is a criteria over two fields/columns (9 and 10), this filters rows with values >0 on column 9 and rows with values 4, 7, and 8 on column 10. lastrow
is the number of rows on the data section.
ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=9, Criteria1:=">0", Operator:=xlAnd
ActiveSheet.Range("$A$1:$O$" & lastrow).AutoFilter Field:=10, Criteria1:=Arr("4","7","8"), Operator:=xlFilterValues
You can try this in your Action:
return DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss");
And this in your Ajax success:
success: function (resultDateString) {
var date = new Date(resultDateString);
}
Or this in your View: (Javascript plus C#)
var date = new Date('@DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")');
For Windows 10:
Right-click the taskbar Windows logo, select 'Programs and Features'.
Click 'Turn Windows Features on or off'
In the dialog box that appears, scroll down or resize the window and check the box next to 'Windows Identity Foundation 3.5'
Click OK.
This activates the required DLLs. Apparently Windows 10 keeps all of those features in the windows installation so that it can activate and deactivate them on demand.
This was alluded to in another comment, but you could try something like this.
Sub FilterAndDelete()
Application.DisplayAlerts = False
With Sheet1 'Change this to your sheet name
.AutoFilterMode = False
.Range("A3:K3").AutoFilter
.Range("A3:K3").AutoFilter Field:=5, Criteria1:="none"
.UsedRange.Offset(1, 0).Resize(ActiveSheet.UsedRange.Rows.Count - 1).Rows.Delete
End With
Application.DisplayAlerts = True
End Sub
I haven't tested this and it is from memory, so it may require some tweaking but it should get the job done without looping through thousands of rows. You'll need to remove the 11-Jul so that UsedRange
is correct or change the offset to 2 rows instead of 1 in the .Offset(1,0)
.
Generally, before I do .Delete
I will run the macro with .Select
instead of the Delete that way I can be sure the correct range will be deleted, that may be worth doing to check to ensure the appropriate range is being deleted.
use ilio: (inline io):
just one function call instead of file open(), read(), close().
from ilio import read
content = read('filename')
Here's an example of how to create a ColorList
programmatically in Kotlin:
val colorList = ColorStateList(
arrayOf(
intArrayOf(-android.R.attr.state_enabled), // Disabled
intArrayOf(android.R.attr.state_enabled) // Enabled
),
intArrayOf(
Color.BLACK, // The color for the Disabled state
Color.RED // The color for the Enabled state
)
)
in /usr/bin
type
sudo ln -s -f g++-4.2 g++
sudo ln -s -f gcc-4.2 gcc
That should do it.
Here is how I author custom events:
var event = jQuery.Event('customEventName');
$(element).trigger(event);
Granted, you could simply do
$(element).trigger('eventname');
But the way I wrote allows you to detect whether the user has prevented default or not by doing
var prevented = event.isDefaultPrevented();
This allows you to listen to your end-user's request to stop processing a particular event, such as if you click a button element in a form but do not want to the form to post if there is an error.
I then usually listen to events like so
$(element).off('eventname.namespace').on('eventname.namespace', function () {
...
});
Once again, you could just do
$(element).on('eventname', function () {
...
});
But I've always found this somewhat unsafe, especially if you're working in a team.
There is nothing wrong with the following:
$(element).on('eventname', function () {});
However, assume that I need to unbind this event for whatever reason (imagine a disabled button). I would then have to do
$(element).off('eventname', function () {});
This will remove all eventname
events from $(element)
. You cannot know whether someone in the future will also bind an event to that element, and you'd be inadvertently unbinding that event as well
The safe way to avoid this is to namespace your events by doing
$(element).on('eventname.namespace', function () {});
Lastly, you may have noticed that the first line was
$(element).off('eventname.namespace').on('eventname.namespace', ...)
I personally always unbind an event before binding it just to make sure that the same event handler never gets called multiple times (imagine this was the submit button on a payment form and the event had been bound 5 times)
In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.
All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!
The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.
Ex.(each element has 2 sides so border, margin and padding get multiplied x2)
So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32
Then add all of your element's totaled widths together.
Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24
In this example the width for the "outer" div would be 112.
.outer {_x000D_
/* floats + margins + borders = 270 */_x000D_
max-width: 270px;_x000D_
margin: auto;_x000D_
height: 80px;_x000D_
border: 1px;_x000D_
border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
/* 3 floats x 50px = 150px */_x000D_
width: 50px;_x000D_
/* 6 margins x 10px = 60 */_x000D_
margin: 10px;_x000D_
/* 6 borders x 10px = 60 */_x000D_
border: 10px solid #6B6B6B;_x000D_
float: left;_x000D_
text-align: center;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
<div class="myFloat">Float 1</div>_x000D_
<div class="myFloat">Float 2</div>_x000D_
<div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
In my case, I was in my office proxy which was skipping some of the packages. When I came out of my office proxy and tried to do npm install
it worked. Maybe this helps for someone.
But it took me several hours to identify that was the reason.
Trying to connect to your local computer.try with the hostname "localhost" instead or perhaps ::/ - the last one is ipv6
instead of
self.theTable.tableFooterView = tableFooter;
try
[self.theTable.tableFooterView addSubview:tableFooter];
Swift 3 solution:
let singleTap = UITapGestureRecognizer(target: self, action:#selector(self.singleTapAction(_:)))
singleTap.numberOfTapsRequired = 1
view.addGestureRecognizer(singleTap)
let doubleTap = UITapGestureRecognizer(target: self, action:#selector(self.doubleTapAction(_:)))
doubleTap.numberOfTapsRequired = 2
view.addGestureRecognizer(doubleTap)
singleTap.require(toFail: doubleTap)
In the code line singleTap.require(toFail: doubleTap) we are forcing the single tap to wait and ensure that the tap event is not a double tap.
Working demo http://jsfiddle.net/u9xES/
Good link (Jquery Documentation): http://docs.jquery.com/Main_Page {you can search or read APIs here}
Hope this will help you if you are looking to do it in JQuery.
The alert in the end prompts the array of uncommon element Array i.e. difference between 2 array.
Please lemme know if I missed anything, cheers!
Code
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];
var difference = [];
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) difference.push(el);
});
alert(" the difference is " + difference);? // Changed variable name
Finally found the simplest way:
<button (click)="toggle($event)" class="someclass" id="btn1"></button>
<button (click)="toggle($event)" class="someclass" id="btn2"></button>
toggle(event) {
console.log(event.target.id);
}
I have today similar problem. But weirder.
host pl.archive.ubuntu.com
dig pl.archive.ubuntu.com
, dig @127.0.1.1 pl.archive.ubuntu.com
$ curl -v http://google.com/
* Trying 172.217.18.78...
* Connected to google.com (172.217.18.78) port 80 (#0)
> GET / HTTP/1.1
> Host: google.com
> User-Agent: curl/7.47.0
> Accept: */*
>
< HTTP/1.1 302 Found
< Cache-Control: private
< Content-Type: text/html; charset=UTF-8
< Referrer-Policy: no-referrer
< Location: http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB
< Content-Length: 256
< Date: Thu, 29 Jun 2017 11:08:22 GMT
<
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.pl/?gfe_rd=cr&ei=pt9UWfqXL4uBX_W5n8gB">here</A>.
</BODY></HTML>
* Connection #0 to host google.com left intact
$ curl -v http://pl.archive.ubuntu.com/
* Could not resolve host: pl.archive.ubuntu.com
* Closing connection 0
curl: (6) Could not resolve host: pl.archive.ubuntu.com
Revelation
Eventually I used strace
on curl and found that it was connection to nscd
deamon.
connect(4, {sa_family=AF_LOCAL, sun_path="/var/run/nscd/socket"}, 110) = 0
Solution
I've restarted the nscd service (Name Service Cache Daemon) and it helped to solve this issue!
systemctl restart nscd.service
You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension
In your case, j3evn.jpg.
I'm going to assume you want to build a the regex dynamically to contain other words than part1 and part2, and that you want order not to matter. If so you can use something like this:
((^|, )(part1|part2|part3))+$
Positive matches:
part1
part2, part1
part1, part2, part3
Negative matches:
part1, //with and without trailing spaces.
part3, part2,
otherpart1
https://jsfiddle.net/xk6Ut/256/
One option to dynamically create and update CSS class in JavaScript:
.....
function writeStyles(styleName, cssText) {
var styleElement = document.getElementById(styleName);
if (styleElement)
document.getElementsByTagName('head')[0].removeChild(
styleElement);
styleElement = document.createElement('style');
styleElement.type = 'text/css';
styleElement.id = styleName;
styleElement.innerHTML = cssText;
document.getElementsByTagName('head')[0].appendChild(styleElement);
}
...
var cssText = '.testDIV{ height:' + height + 'px !important; }';
writeStyles('styles_js', cssText)
Simple Answer
The Kernel is the core piece of the operating system. It is not necessarily an operating system in and of itself.
Everything else is built around it.
Ellaborate Definition
ALTER TABLE table_name ADD temp_col INT IDENTITY(1,1)
update
df.iloc[0].head(1)
- First data set only from entire first row.df.iloc[0]
- Entire First row in column./*sorry this is the correct */
public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
{
final ByteBuffer bb ;
bb = ByteBuffer.allocate( sizeofintarray * 4);
for(int k = 0; k < sizeofintarray ; k++)
bb.putInt(k * 4, iar[k]);
return bb.array();
}
I am a git newbie as well. I had the same problem with 'your branch is ahead of origin/master by N commits' messages. Doing the suggested 'git diff origin/master' did show some diffs that I did not care to keep. So ...
Since my git clone was for hosting, and I wanted an exact copy of the master repo, and did not care to keep any local changes, I decided to save off my entire repo, and create a new one:
(on the hosting machine)
mv myrepo myrepo
git clone USER@MASTER_HOST:/REPO_DIR myrepo
For expediency, I used to make changes to the clone on my hosting machine. No more. I will make those changes to the master, git commit there, and do a git pull. Hopefully, this should keep my git clone on the hosting machine in complete sync.
/Nara
I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:
var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";
console.log( JSON.stringify(display) );
This will print:
["none","block","none"]
This is how JSON actually serializes array. However what you want to see is something like:
{"0":"none","1":"block","2":"none"}
To get this format you want to serialize object, not array. So let's rewrite above code like this:
var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";
console.log( JSON.stringify(display2) );
This will print in the format you want.
You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console
Please refer this link[1]. Visual Studio code has mentioned a brief explanation for this error message. I also encountered the same error. Adding the below parameter in the relavant file will fix this issue.
fs.inotify.max_user_watches=524288
The argument to remove()
is a filter document, so passing in an empty document means 'remove all':
db.user.remove({})
However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove()
call vs the drop()
call.
More details in the docs.
here's another one:
Drawable drawable = RoundedBitmapDrawableFactory.create(context.getResources(), bitmap);
The extensions available for each version of Postgresql vary. An easy way to check which extensions are available is, as has been already mentioned:
SELECT * FROM pg_available_extensions;
If the extension that you are looking for is available, you can install it using:
CREATE EXTENSION 'extensionName';
or if you want to drop it use:
DROP EXTENSION 'extensionName';
With psql
you can additionally check if the extension has been successfully installed using \dx
, and find more details about the extension using \dx+ extensioName
. It returns additional information about the extension, like which packages are used with it.
If the extension is not available in your Postgres version, then you need to download the necessary binary files and libraries and locate it them at /usr/share/conrib
Microsoft always ploughs a self-defeating (at least in IE) furrow:
http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/
CORS works with XDomainRequest in IE8. But IE 8 does not support Preflighted or Credentialed Requests while Firefox 3.5+, Safari 4+, and Chrome all support such requests.
Good to see someone's chimed in about Lucene - because I've no idea about that.
Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.
I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.
I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.
for numerical solution, you can use fsolve:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.fsolve.html#scipy.optimize.fsolve
from scipy.optimize import fsolve
import math
def equations(p):
x, y = p
return (x+y**2-4, math.exp(x) + x*y - 3)
x, y = fsolve(equations, (1, 1))
print equations((x, y))
While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.
This can be resolved by specifying a primary key on the @new_super table, as follows:
DECLARE @new_super TABLE (
row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
super_id int
);
This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.
If you want to add your custom headers to ALL requests, you can change the defaults on $httpProvider to always add this header…
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common = {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
};
}]);
@Michiel is correct to create a button but the code for ActionScript 3 it is a little different - where movieClipName is the name of your 'button'.
movieClipName.addEventListener(MouseEvent.CLICK, callLink);
function callLink:void {
var url:String = "http://site";
var request:URLRequest = new URLRequest(url);
try {
navigateToURL(request, '_blank');
} catch (e:Error) {
trace("Error occurred!");
}
}
source: http://scriptplayground.com/tutorials/as/getURL-in-Actionscript-3/
myfunc("string*& val") this itself doesn't make any sense. "string*& val" implies "string val",* and & cancels each other. Finally one can not pas string variable to a function("string val"). Only basic data types can be passed to a function, for other data types need to pass as pointer or reference. You can have either string& val or string* val to a function.
def ruota_orario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento) for elemento in ruota]
def ruota_antiorario(matrix):
ruota=list(zip(*reversed(matrix)))
return[list(elemento)[::-1] for elemento in ruota][::-1]
Overloading is the concept in which you have same signatures or methods with same name but different parameters and overriding, we have same name methods with different parameters also have inheritance is known as overriding.
Technically the answer of zlovelady is preferable, but as I had only to remove items from the navigation, the approach of unsetting the not-needed navigation items in the template was the fastest/easiest way for me:
Just duplicate
app/design/frontend/base/default/template/customer/account/navigation
to
app/design/frontend/YOUR_THEME/default/template/customer/account/navigation
and unset the unneeded navigation items before the get rendered, e.g.:
<?php $_links = $this->getLinks(); ?>
<?php
unset($_links['recurring_profiles']);
?>
I am quite late but any user searching for this can get help from it. Inside the options you can pass a new parameter called chartArea.
var options = {
chartArea:{left:10,top:20,width:"100%",height:"100%"}
};
Left and top options will define the amount of padding from left and top. Hope this will help.
You simply type vim
into the terminal to open it and start a new file.
You can pass a filename as an option and it will open that file, e.g. vim main.c
. You can open multiple files by passing multiple file arguments.
Vim has different modes, unlike most editors you have probably used. You begin in NORMAL
mode, which is where you will spend most of your time once you become familiar with vim.
To return to NORMAL
mode after changing to a different mode, press Esc. It's a good idea to map your Caps Lock key to Esc, as it's closer and nobody really uses the Caps Lock key.
The first mode to try is INSERT
mode, which is entered with a for append after cursor, or i for insert before cursor.
To enter VISUAL
mode, where you can select text, use v. There are many other variants of this mode, which you will discover as you learn more about vim.
To save your file, ensure you're in NORMAL
mode and then enter the command :w
. When you press :
, you will see your command appear in the bottom status bar. To save and exit, use :x
. To quit without saving, use :q
. If you had made a change you wanted to discard, use :q!
.
You can edit your ~/.vimrc
file to configure vim to your liking. It's best to look at a few first (here's mine) and then decide which options suits your style.
This is how mine looks:
To get the file explorer on the left, use NERDTree. For the status bar, use vim-airline. Finally, the color scheme is solarized.
You can use man vim
for some help inside the terminal. Alternatively, run vimtutor
which is a good hands-on starting point.
It's a good idea to print out a Vim Cheatsheet and keep it in front of you while you're learning vim.
Good luck!
You can either use regex, or keep on using str_replace
.
Eg.
$url = parse_url($_SERVER['REQUEST_URI']);
if ($url != '/') {
parse_str($url['query']);
echo $id;
echo $othervar;
}
Output will be: http://www.testing.com/123/123
You just add one additional row before you execute the loop. This row contains your CSV file header name.
schema = ['a','b','c','b']
row = 4
generators = ['A','B','C','D']
with open('test.csv','wb') as csvfile:
writer = csv.writer(csvfile, delimiter=delimiter)
# Gives the header name row into csv
writer.writerow([g for g in schema])
#Data add in csv file
for x in xrange(rows):
writer.writerow([g() for g in generators])
I had the exact same issue on my branch(lets call it branch B) and I followed three simple steps to get make it work
Now you can delete branch B and then rename branch C to branch B.
Hope this helps.
For me, the problem was that I was in recording mode. To exit from recording mode press q. Then Esc worked as expected for me.
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
I went kind of a different route all together, I decided to "De-Nest" them. Maybe someone will find this handy...
var $m1 = $('#Modal1');
var $innermodal = $m1.find(".modal"); //get reference to nested modal
$m1.after($innermodal); // snatch it out of inner modal and put it after.
But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.
Googling for browser reliable detection often results in checking the User agent string. This method is not reliable, because it's trivial to spoof this value.
I've written a method to detect browsers by duck-typing.
Only use the browser detection method if it's truly necessary, such as showing browser-specific instructions to install an extension. Use feature detection when possible.
Demo: https://jsfiddle.net/6spj1059/
// Opera 8.0+
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
// Firefox 1.0+
var isFirefox = typeof InstallTrigger !== 'undefined';
// Safari 3.0+ "[object HTMLElementConstructor]"
var isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification));
// Internet Explorer 6-11
var isIE = /*@cc_on!@*/false || !!document.documentMode;
// Edge 20+
var isEdge = !isIE && !!window.StyleMedia;
// Chrome 1 - 79
var isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);
// Edge (based on chromium) detection
var isEdgeChromium = isChrome && (navigator.userAgent.indexOf("Edg") != -1);
// Blink engine detection
var isBlink = (isChrome || isOpera) && !!window.CSS;
var output = 'Detecting browsers by ducktyping:<hr>';
output += 'isFirefox: ' + isFirefox + '<br>';
output += 'isChrome: ' + isChrome + '<br>';
output += 'isSafari: ' + isSafari + '<br>';
output += 'isOpera: ' + isOpera + '<br>';
output += 'isIE: ' + isIE + '<br>';
output += 'isEdge: ' + isEdge + '<br>';
output += 'isEdgeChromium: ' + isEdgeChromium + '<br>';
output += 'isBlink: ' + isBlink + '<br>';
document.body.innerHTML = output;
_x000D_
The previous method depended on properties of the rendering engine (-moz-box-sizing
and -webkit-transform
) to detect the browser. These prefixes will eventually be dropped, so to make detection even more robust, I switched to browser-specific characteristics:
document.documentMode
.StyleMedia
constructor. Excluding Trident leaves us with Edge.InstallTrigger
chrome
object, containing several properties including a documented chrome.webstore
object.chrome.webstore
is deprecated and undefined in recent versionsSafariRemoteNotification
, which was introduced after version 7.1, to cover all Safaris from 3.0 and upwards.window.opera
has existed for years, but will be dropped when Opera replaces its engine with Blink + V8 (used by Chromium).chrome
object is defined (but chrome.webstore
isn't). Since Opera tries hard to clone Chrome, I use user agent sniffing for this purpose.!!window.opr && opr.addons
can be used to detect Opera 20+ (evergreen).CSS.supports()
was introduced in Blink once Google switched on Chrome 28. It's of course, the same Blink used in Opera.Updated in November 2016 to include detection of Safari browsers from 9.1.3 and upwards
Updated in August 2018 to update the latest successful tests on chrome, firefox IE and edge.
Updated in January 2019 to fix chrome detection (because of the window.chrome.webstore deprecation) and include the latest successful tests on chrome.
Updated in December 2019 to add Edge based on Chromium detection (based on the @Nimesh comment).
Some of the basic data structures in programming languages such as C and C++ are stacks and queues.
The stack data structure follows the "First In Last Out" policy (FILO) where the first element inserted or "pushed" into a stack is the last element that is removed or "popped" from the stack.
Similarly, a queue data structure follows a "First In First Out" policy (as in the case of a normal queue when we stand in line at the counter), where the first element is pushed into the queue or "Enqueued" and the same element when it has to be removed from the queue is "Dequeued".
This is quite similar to push and pop in a stack, but the terms enqueue and dequeue avoid confusion as to whether the data structure in use is a stack or a queue.
Class coders has a simple program to demonstrate the enqueue and dequeue process. You could check it out for reference.
http://classcoders.blogspot.in/2012/01/enque-and-deque-in-c.html
You can USE PyPDF2 package
#install pyDF2
pip install PyPDF2
# importing all the required modules
import PyPDF2
# creating an object
file = open('example.pdf', 'rb')
# creating a pdf reader object
fileReader = PyPDF2.PdfFileReader(file)
# print the number of pages in pdf file
print(fileReader.numPages)
Follow this Documentation http://pythonhosted.org/PyPDF2/
Beware of using string interpolation for SQL queries, since it won't escape the input parameters correctly and will leave your application open to SQL injection vulnerabilities. The difference might seem trivial, but in reality it's huge.
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s" % (param1, param2))
c.execute("SELECT * FROM foo WHERE bar = %s AND baz = %s", (param1, param2))
It adds to the confusion that the modifiers used to bind parameters in a SQL statement varies between different DB API implementations and that the mysql client library uses printf
style syntax instead of the more commonly accepted '?' marker (used by eg. python-sqlite
).
If you are a guava user there is a handy Charsets
class:
String s = "Hello, world!";
byte[] b = s.getBytes(Charsets.US_ASCII);
Apart from not hard-coding arbitrary charset name in your source code it has a much bigger advantage: Charsets.US_ASCII
is of Charset
type (not String
) so you avoid checked UnsupportedEncodingException
thrown only from String.getBytes(String)
, but not from String.getBytes(Charset)
.
In Java 7 there is equivalent StandardCharsets
class.
The ID of the two repos are both localSnap
; that's probably not what you want and it might confuse Maven.
If that's not it: There might be more repository
elements in your POM. Search the output of mvn help:effective-pom
for repository
to make sure the number and place of them is what you expect.
I really like stackPusher's ConvertToLetter function as a solution. However, in working with it I noticed several errors occurring at very specific inputs due to some flaws in the math. For example, inputting 392 returns 'N\', 418 returns 'O\', 444 returns 'P\', etc.
I reworked the function and the result produces the correct output for all input up to 703 (which is the first triple-letter column index, AAA).
Function ConvertToLetter2(iCol As Integer) As String
Dim First As Integer
Dim Second As Integer
Dim FirstChar As String
Dim SecondChar As String
First = Int(iCol / 26)
If First = iCol / 26 Then
First = First - 1
End If
If First = 0 Then
FirstChar = ""
Else
FirstChar = Chr(First + 64)
End If
Second = iCol Mod 26
If Second = 0 Then
SecondChar = Chr(26 + 64)
Else
SecondChar = Chr(Second + 64)
End If
ConvertToLetter2 = FirstChar & SecondChar
End Function
You can use the start command to spawn background processes without launching new windows:
start /b foo.exe
The new process will not be interruptable with CTRL-C; you can kill it only with CTRL-BREAK (or by closing the window, or via Task Manager.)
As per https://stackoverflow.com/a/33859341/446250, having internet connection sharing enabled for my ethernet adapter ended up causing this problem for me. Disabling the sharing fixed the problem
I use File -> Switch Workspace -> Other... and type in my new workspace name.
(EDIT: Added the composite screen shot.)
Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.
from the docs,
the special thing about methods is that the instance object is passed as the first argument of the function. In our example, the call
x.f()
is exactly equivalent toMyClass.f(x)
. In general, calling a method with a list of n arguments is equivalent to calling the corresponding function with an argument list that is created by inserting the method’s instance object before the first argument.
preceding this the related snippet,
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
x = MyClass()
I think you can use smtpjs.com
In most cases you should allow the thread pool to handle this. If you post some code or give more details it might be easier to see if there is some reason the default behavior of the thread pool would not be best.
You can find more information on how this should work here: http://en.wikipedia.org/wiki/Thread_pool_pattern
For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group
from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z")
the grouping factor would be c(1,1,2,3,3)
.
This works
String x = "22/06/2012";
String y = "25/10/2014";
String datestart = x;
String datestop = y;
//DateTimeFormatter format = DateTimeFormat.forPattern("dd/mm/yyyy");
SimpleDateFormat format = new SimpleDateFormat("dd/mm/yyyy");
Date d1 = null;
Date d2 = null;
try {
d1 = format.parse(datestart);
d2 = format.parse(datestop);
DateTime dt1 = new DateTime(d1);
DateTime dt2 = new DateTime(d2);
//Period
period = new Period (dt1,dt2);
//calculate days
int days = Days.daysBetween(dt1, dt2).getDays();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Create an alias for gcc with your favorite includes.
alias mygcc='gcc -I /whatever/'
sed is a much better tool for the job: sed -n '/re/,$p' file
where re is regexp.
Another option is grep's --after-context flag. You need to pass in a number to end at, using wc on the file should give the right value to stop at. Combine this with -n and your match expression.
Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:
function MyController($scope, $http) {
// ...
}
Just add a line after the declaration indicating which objects to inject when the controller is instantiated:
function MyController($scope, $http) {
// ...
}
MyController.$inject = ['$scope', '$http'];
This makes it minification-safe.
I have created a method that helps with getting the stackTrace:
private static String getStackTrace(Exception ex) {
StringBuffer sb = new StringBuffer(500);
StackTraceElement[] st = ex.getStackTrace();
sb.append(ex.getClass().getName() + ": " + ex.getMessage() + "\n");
for (int i = 0; i < st.length; i++) {
sb.append("\t at " + st[i].toString() + "\n");
}
return sb.toString();
}
First, ask the program to tell you what is wrong by checking the errno
, which is set on failure, such as during fseek
or ftell
.
Others (tonio & LatinSuD) have explained the mistake with handling stdin versus checking for a filename. Namely, first check argc
(argument count) to see if there are any command line parameters specified if (argc > 1)
, treating -
as a special case meaning stdin
.
If no parameters are specified, then assume input is (going) to come from stdin
, which is a stream not file, and the fseek
function fails on it.
In the case of a stream, where you cannot use file-on-disk oriented library functions (i.e. fseek
and ftell
), you simply have to count the number of bytes read (including trailing newline characters) until receiving EOF (end-of-file).
For usage with large files you could speed it up by using fgets
to a char array for more efficient reading of the bytes in a (text) file. For a binary file you need to use fopen(const char* filename, "rb")
and use fread
instead of fgetc/fgets
.
You could also check the for feof(stdin)
/ ferror(stdin)
when using the byte-counting method to detect any errors when reading from a stream.
The sample below should be C99 compliant and portable.
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
long getSizeOfInput(FILE *input){
long retvalue = 0;
int c;
if (input != stdin) {
if (-1 == fseek(input, 0L, SEEK_END)) {
fprintf(stderr, "Error seek end: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (-1 == (retvalue = ftell(input))) {
fprintf(stderr, "ftell failed: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
if (-1 == fseek(input, 0L, SEEK_SET)) {
fprintf(stderr, "Error seek start: %s\n", strerror(errno));
exit(EXIT_FAILURE);
}
} else {
/* for stdin, we need to read in the entire stream until EOF */
while (EOF != (c = fgetc(input))) {
retvalue++;
}
}
return retvalue;
}
int main(int argc, char **argv) {
FILE *input;
if (argc > 1) {
if(!strcmp(argv[1],"-")) {
input = stdin;
} else {
input = fopen(argv[1],"r");
if (NULL == input) {
fprintf(stderr, "Unable to open '%s': %s\n",
argv[1], strerror(errno));
exit(EXIT_FAILURE);
}
}
} else {
input = stdin;
}
printf("Size of file: %ld\n", getSizeOfInput(input));
return EXIT_SUCCESS;
}
The cause of the problem was that the server was running PHP using FastCGI.
After changing the config.php to
$config['uri_protocol'] = "REQUEST_URI";
everything worked.
Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
Assigning a class name and applying a CSS style are two different things.
If you mean <img class="someclass">
, and
.someclass {
[cssrule]
}
, then there is no real performance difference between applying the css to the class, or to .column img
EDIT: Per Michael Dillon's answer, SaveAsText does save the commands in a macro without having to go through converting to VBA. I don't know what happened when I tested that, but it didn't produce useful text in the resulting file.
So, I learned something new today!
ORIGINAL POST: To expand the question, I wondered if there was a way to retrieve the contents of a macro from code, and it doesn't appear that there is (at least not in A2003, which is what I'm running).
There are two collections through which you can access stored Macros:
CurrentDB.Containers("Scripts").Documents
CurrentProject.AllMacros
The properties that Intellisense identifies for the two collections are rather different, because the collections are of different types. The first (i.e., traditional, pre-A2000 way) is via a documents collection, and the methods/properties/members of all documents are the same, i.e., not specific to Macros.
Likewise, the All... collections of CurrentProject return collections where the individual items are of type Access Object. The result is that Intellisense gives you methods/properties/members that may not exist for the particular document/object.
So far as I can tell, there is no way to programatically retrieve the contents of a macro.
This would stand to reason, as macros aren't of much use to anyone who would have the capability of writing code to examine them programatically.
But if you just want to evaluate what the macros do, one alternative would be to convert them to VBA, which can be done programmatically thus:
Dim varItem As Variant
Dim strMacroName As String
For Each varItem In CurrentProject.AllMacros
strMacroName = varItem.Name
'Debug.Print strMacroName
DoCmd.SelectObject acMacro, strMacroName, True
DoCmd.RunCommand acCmdConvertMacrosToVisualBasic
Application.SaveAsText acModule, "Converted Macro- " & strMacroName, _
CurrentProject.Path & "\" & "Converted Macro- " & strMacroName & ".txt"
Next varItem
Then you could use the resulting text files for whatever you needed to do.
Note that this has to be run interactively in Access because it uses DoCmd.RunCommand, and you have to click OK for each macro -- tedious for databases with lots of macros, but not too onerous for a normal app, which shouldn't have more than a handful of macros.
Use the valgrind option --track-origins=yes
to have it track the origin of uninitialized values. This will make it slower and take more memory, but can be very helpful if you need to track down the origin of an uninitialized value.
Update: Regarding the point at which the uninitialized value is reported, the valgrind manual states:
It is important to understand that your program can copy around junk (uninitialised) data as much as it likes. Memcheck observes this and keeps track of the data, but does not complain. A complaint is issued only when your program attempts to make use of uninitialised data in a way that might affect your program's externally-visible behaviour.
From the Valgrind FAQ:
As for eager reporting of copies of uninitialised memory values, this has been suggested multiple times. Unfortunately, almost all programs legitimately copy uninitialised memory values around (because compilers pad structs to preserve alignment) and eager checking leads to hundreds of false positives. Therefore Memcheck does not support eager checking at this time.
The pytz
module is one option, and there is another python-dateutil
, which although is also third party package, may already be available depending on your other dependencies and operating system.
I just wanted to include this methodology for reference- if you've already installed python-dateutil
for other purposes, you can use its tzinfo
instead of duplicating with pytz
import datetime
import dateutil.tz
# Get the UTC time with datetime.now:
utcdt = datetime.datetime.now(dateutil.tz.tzutc())
# Get the UTC time with datetime.utcnow:
utcdt = datetime.datetime.utcnow()
utcdt = utcdt.replace(tzinfo=dateutil.tz.tzutc())
# For fun- get the local time
localdt = datetime.datetime.now(dateutil.tz.tzlocal())
I tend to agree that calls to utcnow
should include the UTC timezone information. I suspect that this is not included because the native datetime library defaults to naive datetimes for cross compatibility.
values timestampdiff (16, char(
timestamp(current timestamp + 1 year + 2 month - 3 day)-
timestamp(current timestamp)))
1
=
422
values timestampdiff (16, char(
timestamp('2012-03-08-00.00.00')-
timestamp('2011-12-08-00.00.00')))
1
=
90
---------- EDIT BY galador
SELECT TIMESTAMPDIFF(16, CHAR(CURRENT TIMESTAMP - TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD'))
FROM CHCART00
WHERE CHSTAT = '05'
EDIT
As it has been pointed out by X-Zero, this function returns only an estimate. This is true. For accurate results I would use the following to get the difference in days between two dates a and b:
SELECT days (current date) - days (date(TIMESTAMP_FORMAT(CHDLM, 'YYYYMMDD')))
FROM CHCART00
WHERE CHSTAT = '05';
I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.
Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:
HTML:
<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>
Javascript:
function maxLength(el) {
if (!('maxLength' in el)) {
var max = el.attributes.maxLength.value;
el.onkeypress = function () {
if (this.value.length >= max) return false;
};
}
}
maxLength(document.getElementById("text"));
There is no such thing as a minlength
attribute in HTML5.
For the following input types: number
, range
, date
, datetime
, datetime-local
, month
, time
, and week
(which aren't fully supported yet) use the min
and max
attributes.
I noticed some caching issues with service calls when repeating the same service call (long polling). Adding metadata didn't help. One solution is to pass a timestamp
to ensure ie
thinks it's a different http
service request. That worked for me, so adding a server side scripting code snippet to automatically update this tag wouldn't hurt:
<meta http-equiv="expires" content="timestamp">
In-case if someone wants a little dynamic search.
let searchInArray=(searchQuery, array, objectKey=null)=>{
return array.filter(d=>{
let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
let matchingWords = searchWords.filter(word=>dataWords.includes(word))
return matchingWords.length
})
}
For an Array of strings:
let arrayOfStr = [
"Search for words",
"inside an array",
"dynamic searching",
"match rate 90%"
]
searchInArray("dynamic search", arrayOfStr)
//Results: [ "Search for words", "dynamic searching" ]
For an Array of Objects:
let arrayOfObject = [
{
"address": "Karachi Pakistan"
},
{
"address": "UK London"
},
{
"address": "Pakistan Lahore"
}
]
searchInArray("Pakistan", arrayOfObject,"address")
//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]
You can use Phantomjs. Download here and use the following example to test the html->pdf conversion feature https://github.com/ariya/phantomjs/blob/master/examples/rasterize.js
Example code:
phantomjs.exe examples/rasterize.js http://www.w3.org/Style/CSS/Test/CSS3/Selectors/current/xhtml/index.html sample.pdf
Try this:
add in html following
<input type="text" id="datepicker"/>
Add in js file
$(function() {
$( "#datepicker" ).datepicker({dateFormat: 'yy', changeYear: true, changeMonth: false});
});
Add in css
.ui-datepicker-calendar {
display: none;
}
.ui-datepicker-month {
display: none;
}
.ui-datepicker-prev{
display: none;
}
.ui-datepicker-next{
display: none;
}
Your query would work already - except that you are running into naming conflicts or just confusing the output column (the CASE
expression) with source column result
, which has different content.
...
GROUP BY model.name, attempt.type, attempt.result
...
You need to GROUP BY
your CASE
expression instead of your source column:
...
GROUP BY model.name, attempt.type
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END
...
Or provide a column alias that's different from any column name in the FROM
list - or else that column takes precedence:
SELECT ...
, CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END AS result1
...
GROUP BY model.name, attempt.type, result1
...
The SQL standard is rather peculiar in this respect. Quoting the manual here:
An output column's name can be used to refer to the column's value in
ORDER BY
andGROUP BY
clauses, but not in theWHERE
orHAVING
clauses; there you must write out the expression instead.
And:
If an
ORDER BY
expression is a simple name that matches both an output column name and an input column name,ORDER BY
will interpret it as the output column name. This is the opposite of the choice thatGROUP BY
will make in the same situation. This inconsistency is made to be compatible with the SQL standard.
Bold emphasis mine.
These conflicts can be avoided by using positional references (ordinal numbers) in GROUP BY
and ORDER BY
, referencing items in the SELECT
list from left to right. See solution below.
The drawback is, that this may be harder to read and vulnerable to edits in the SELECT
list (one might forget to adapt positional references accordingly).
But you do not have to add the column day
to the GROUP BY
clause, as long as it holds a constant value (CURRENT_DATE-1
).
Rewritten and simplified with proper JOIN syntax and positional references it could look like this:
SELECT m.name
, a.type
, CASE WHEN a.result = 0 THEN 0 ELSE 1 END AS result
, CURRENT_DATE - 1 AS day
, count(*) AS ct
FROM attempt a
JOIN prod_hw_id p USING (hard_id)
JOIN model m USING (model_id)
WHERE ts >= '2013-11-06 00:00:00'
AND ts < '2013-11-07 00:00:00'
GROUP BY 1,2,3
ORDER BY 1,2,3;
Also note that I am avoiding the column name time
. That's a reserved word and should never be used as identifier. Besides, your "time" obviously is a timestamp
or date
, so that is rather misleading.
Just as addition to the other answers: If you don't even want to write the commit message with the issue number and happen to use Eclipse for development, then you can install the eGit and Mylyn plugins as well as the GitHub connector for Mylyn. Eclipse can then automatically track which issue you are working on and automatically fill the commit message, including the issue number as shown in all the other answers.
For more details about that setup see http://wiki.eclipse.org/EGit/GitHub/UserGuide
Member in base class : Private Protected Public
Inheritance type : Object inherited as:
Private : Inaccessible Private Private
Protected : Inaccessible Protected Protected
Public : Inaccessible Protected Public
Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).
Thanks to user1354692 I could made it more easy, with only one line! the one he has commented:
try {
File file = new File(Environment.getExternalStorageDirectory(), String.valueOf(System.currentTimeMillis()));
Runtime.getRuntime().exec("logcat -d -v time -f " + file.getAbsolutePath());}catch (IOException e){}
From, Session 703 WWDC 2015:
You can continue to use URL schemes when you build your app for iOS 9 and you want to call URL schemes, you will now need to declare them in your apps Info.plist. There is a new key,
LSApplicationQueriesSchemes
, and here you will need to add the list of schemes you want to are canOpenURL on.
It's very important for accessibility reasons that you always specify value of the submit even if you are hiding this text, or if you use <input type="image" .../>
to always specify alt=""
attribute for this input field.
Blind people don't know what button will do if it doesn't contain meaningful alt=""
or value=""
.
Specifications:
Articles:
Tutorial:
Libraries:
sed
is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.
The s,%,$,g
part of the command line is the sed
command to execute. The s
stands for substitute, the ,
characters are delimiters (other characters can be used; /
, :
and @
are popular). The %
is the pattern to match (here a literal percent sign) and the $
is the second pattern to match (here a literal dollar sign). The g
at the end means to g
lobally replace on each line (otherwise it would only update the first match).
Update 2020
Products are located mainly in the following tables:
wp_posts
table with post_type
like product
(or product_variation
),
wp_postmeta
table with post_id
as relational index (the product ID).
wp_wc_product_meta_lookup
table with product_id
as relational index (the post ID) | Allow fast queries on specific product data (since WooCommerce 3.7)
wp_wc_order_product_lookup
table with product_id
as relational index (the post ID) | Allow fast queries to retrieve products on orders (since WooCommerce 3.7)
Product types, categories, subcategories, tags, attributes and all other custom taxonomies are located in the following tables:
wp_terms
wp_termmeta
wp_term_taxonomy
wp_term_relationships
- column object_id
as relational index (the product ID)
wp_woocommerce_termmeta
wp_woocommerce_attribute_taxonomies
(for product attributes only)
wp_wc_category_lookup
(for product categories hierarchy only since WooCommerce 3.7)
Product types are handled by custom taxonomy product_type
with the following default terms:
simple
grouped
variable
external
Some other product types for Subscriptions and Bookings plugins:
subscription
variable-subscription
booking
Since Woocommerce 3+ a new custom taxonomy named product_visibility
handle:
exclude-from-search
and exclude-from-catalog
featured
outofstock
rated-1
to rated-5
Particular feature: Each product attribute is a custom taxonomy…
References:
The below code should apply different CSS classes based on your Model's CanEdit
Property value .
<div class="@(Model.CanEdit?"visible-item":"hidden-item")">Some links</div>
But if it is something important like Edit/Delete links, you shouldn't be simply hiding,because people can update the css class/HTML markup in their browser and get access to your important link. Instead you should be simply not Rendering the important stuff to the browser.
@if(Model.CanEdit)
{
<div>Edit/Delete link goes here</div>
}
X returns (value +3), while Y returns (value*2)
Given a value of 4, this means (4+3) * (4*2) = 7 * 8 = 56
.
Although functions are not limited in scope (which means that you can safely 'nest' function definitions), this particular example is prone to errors:
1) You can't call y()
before calling x()
, because function y()
won't actually be defined until x()
has executed once.
2) Calling x()
twice will cause PHP to redeclare function y()
, leading to a fatal error:
Fatal error: Cannot redeclare y()
The solution to both would be to split the code, so that both functions are declared independent of each other:
function x ($y)
{
return($y+3);
}
function y ($z)
{
return ($z*2);
}
This is also a lot more readable.
A TextBlock does not actually inherit from Control so it does not have properties that you would generally associate with a Control. Your best bet for adding a border in a style is to replace the TextBlock with a Label
See this link for more on the differences between a TextBlock and other Controls
REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.
Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.
HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.
Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.
The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.
(Updated to cover implications of making the connection SSL-only.)
You are binding the click
event to anchors with an href attribute with value sign_new
.
Either bind anchors with class sign_new
or bind anchors with href value #sign_up
. I would prefer the former.
You can use the following code:
return RedirectToAction("Index", "Home");
See RedirectToAction
In this document it states:
There is (intentionally) no direct declarative way to define either prototype data properties (other than methods) class properties, or instance property
This means that it is intentionally like this.
Maybe you can define a variable in the constructor?
constructor(){
this.key = value
}
As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:
var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da
For Node.js v5.11.1 and below
Construct a new Buffer
and pass 'base64'
as the second argument:
var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da
If you want to be clean, you can check whether from
exists :
if (typeof Buffer.from === "function") {
// Node 5.10+
buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
// older Node versions, now deprecated
buf = new Buffer(b64string, 'base64'); // Ta-da
}
eloone did it file by file with
git checkout <commit-hash> <filename>
but you could checkout all files more easily by doing
git checkout <commit-hash> .
UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')
OK, I found it.
apt-cache policy <package name>
will show the version details.
It also shows which version is currently installed and which versions are available to install.
For example, apt-cache policy hylafax+
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match("Tryit")
{
alert("Field says Tryit");
return false;
}
else
{
return true;
}
}
Use this for expressing things
I had the same issue with a dll yesterday and all it referenced was System, System.Data, and System.Xml. Turns out the build configuration for the Platform type didn't line up. The dll was build for x86 and the program using it was "Any CPU" and since I am running a x64 machine, it ran the program as x64 and had issues with the x86 dll. I don't know if this is your issue or not, just thought that I would mention it as something else to check.
For me, it was trying to find a DLL in a path that used to contain the Project, but we'd moved it to a new directory. The Solution had the correct path to the Project, but Visual Studio somehow kept looking in the old location.
Solution: Rename each problem Project - just add a character or whatever - then rename it back to its original name.
This must reset some global cache of some kind in Visual Studio, because this clears both this issue up and several like it, while things like Clean do not.
I think the approach to using UITableViewController might be a little bit different from what you have done before. It has worked for me, but you might not be a fan of it. What I have done is have a view controller with a container view that points to my UItableViewController. This way I am able to use the TopLayoutGuide provided to my in storyboard. Just add the constraint to the container view and you should be taken care of for both iOS7 and iOS6.
To parse a Date from a String you can choose which format you would like it to have. For example:
public Date StringToDate(String s){
Date result = null;
try{
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
result = dateFormat.parse(s);
}
catch(ParseException e){
e.printStackTrace();
}
return result ;
}
If you would like to use this method now, you will have to use something like this
Date date = StringToDate("2015-12-06 17:03:00");
For more explanation you should check out http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Beside radius
, there are some property to round corner like topRightRadius
, topLeftRadius
, bottomRightRadius
, bottomLeftRadius
Example TextView
with red
border with corner and gray
background
bg_rounded.xml (in the drawables folder)
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke
android:width="10dp"
android:color="#f00" />
<solid android:color="#aaa" />
<corners
android:radius="5dp"
android:topRightRadius="100dp" />
</shape>
TextView
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@drawable/bg_rounded"
android:text="Text"
android:padding="20dp"
android:layout_margin="10dp"
/>
Result
$url='Your url'; // Specify your url
$data= array('parameterkey1'=>value,'parameterkey2'=>value); // Add parameters in key value
$ch = curl_init(); // Initialize cURL
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
If the users enter an incorrect value, apply a 1px red color border to the input field:
document.getElementById('fName').style.border ="1px solid red";
If the user enters a correct value, remove the border from the input field:
document.getElementById('fName').style.border ="";
you need to enable the Show Assistant Editor:
What's missing from all the explanations is the fact that Java has a strict rule of class name = file name. Meaning if you have a class "Person", is must be in a file named "Person.java". Therefore, if one class tries to access "Person" the filename is not necessary, because it has got to be "Person.java".
Coming for C/C++, I have exact same issue. The answer is to create a new class (in a new file matching class name) and create a public string. This will be your "header" file. Then use that in your main file by using "extends" keyword.
Here is your answer:
Create a file called Include.java. In this file, add this:
public class Include {
public static String MyLongString= "abcdef";
}
Create another file, say, User.java. In this file, put:
import java.io.*;
public class User extends Include {
System.out.println(Include.MyLongString);
}
Windows communication Fundation(WCF) is used for connecting different applications and passing the data's between them using endpoints.
Windows Presentation Foundation is used for designing rich internet applications in the format of xaml.
Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:
<script type="text/javascript"> $(function() { //jQuery trick to say after all the HTML is parsed. $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); }); </script>
EDIT: This code works for me
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body> <strong>Choose a base package:</strong> <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942 <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313 <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829 <strong>Choose an add on:</strong> <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0 <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146) <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455) <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764) <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073) <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382) <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691) <strong>Your total is:</strong> <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" /> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"> $("input[type=radio]").click(function() { var total = 0; $("input[type=radio]:checked").each(function() { total += parseFloat($(this).val()); }); $("#totalSum").val(total); }); </script> </body> </html>
You can use:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).
The other two ways that spring to mind are to blat the contents if they're fixed:
GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));
or provide a function that looks like your initialisation code anyway:
void setCoords (float *p0, float p1, ..., float p8) {
p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);
keeping in mind those ellipses (...
) are placeholders, not things to literally insert in the code.
The problem with Yahoo and Google data is that it violates terms of service if you're using it for commercial use. When your site/app is still small it's not biggie, but as soon as you grow a little you start getting cease and desists from the exchanges. A licensed solution example is FinancialContent: http://www.financialcontent.com/json.php or Xignite
It's not a good way, but for me it seems the most simplest.
Add an anchor tag which contains the modal data-target and data-toggle, have an id associated with it. (Can be added mostly anywhere in the html view)
<a href="" data-toggle="modal" data-target="#myModal" id="myModalShower"></a>
Now,
Inside the angular controller, from where you want to trigger the modal just use
angular.element('#myModalShower').trigger('click');
This will mimic a click to the button based on the angular code and the modal will appear.
If you dont want to modify the xtick labels, you can just use:
plt.xticks(rotation=45)
Try this.
string path = @"E:\AppServ\Example.txt";
if (!File.Exists(path))
{
using (var txtFile = File.AppendText(path))
{
txtFile.WriteLine("The very first line!");
}
}
else if (File.Exists(path))
{
using (var txtFile = File.AppendText(path))
{
txtFile.WriteLine("The next line!");
}
}
I like the answer of Patrick Cuff. What I like to add is the distinction between a test level and a test type which was for me an eye opener.
Test level is easy to explain using V-model, an example: Each test level has its corresponding development level. It has a typical time characteristic, they're executed at certain phase in the development life cycle.
A test type is a characteristics, it focuses on a specific test objective. Test types emphasize your quality aspects, also known as technical or non-functional aspects. Test types can be executed at any test level. I like to use as test types the quality characteristics mentioned in ISO/IEC 25010:2011.
To make it complete. There's also something called regression testing. This an extra classification next to test level and test type. A regression test is a test you want to repeat because it touches something critical in your product. It's in fact a subset of tests you defined for each test level. If a there's a small bug fix in your product, one doesn't always have the time to repeat all tests. Regression testing is an answer to that.
The easiest way is to have
if (document.location.search.indexOf('yourtext=') >= 0) {
// your code
} else {
// what happens?
}
The indexOf(text)
function returns
document.location.search
.document.location.search
.I hope this was useful, @gumbo
var pause_menu = {
pause_button : { someProperty : "prop1", someOther : "prop2" },
resume_button : { resumeProp : "prop", resumeProp2 : false },
quit_button : false
};
then:
pause_menu.pause_button.someProperty //evaluates to "prop1"
etc etc.
Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html
That will get you up and running in about 10 minutes.
There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229
Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.
Basically you need apache / php running.
In my scenario, there was no process blocking the database under sp_who2. However, we discovered because the database is much larger than our other databases that pending processes were still running which is why the database under the availability group still displayed as red/offline after we tried to 'resume data'by right clicking the paused database.
To check if you still have processes running just execute this command: select percent complete from sys.dm_exec_requests where percent_complete > 0
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
With this method you evoke the flush process. This process synchronizes the state of your database with state of your session by detecting state changes and executing the respective SQL statements.
Swift 4.2
write this in viewDidLoad
// to detect if TextField changed
TextField.addTarget(self, action: #selector(textFieldDidChange(_:)),
for: UIControl.Event.editingChanged)
write this outside viewDidLoad
@objc func textFieldDidChange(_ textField: UITextField) {
// do something
}
You could change the event by UIControl.Event.editingDidBegin or what ever you want to detect.
In reference to answer 2, when discussing envsubst, you asked:
How can I make it work with the variables that are declared in my .sh script?
The answer is you simply need to export your variables before calling envsubst
.
You can also limit the variable strings you want to replace in the input using the envsubst
SHELL_FORMAT
argument (avoiding the unintended replacement of a string in the input with a common shell variable value - e.g. $HOME
).
For instance:
export VAR1='somevalue' VAR2='someothervalue'
MYVARS='$VAR1:$VAR2'
envsubst "$MYVARS" <source.txt >destination.txt
Will replace all instances of $VAR1
and $VAR2
(and only VAR1
and VAR2
) in source.txt
with 'somevalue'
and 'someothervalue'
respectively.
You are ready to do with php zip lib, and can use zend zip lib too,
<?PHP
// create object
$zip = new ZipArchive();
// open archive
if ($zip->open('app-0.09.zip') !== TRUE) {
die ("Could not open archive");
}
// get number of files in archive
$numFiles = $zip->numFiles;
// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
$file = $zip->statIndex($x);
printf("%s (%d bytes)", $file['name'], $file['size']);
print "
";
}
// close archive
$zip->close();
?>
http://devzone.zend.com/985/dynamically-creating-compressed-zip-archives-with-php/
and there is also php pear lib for this http://www.php.net/manual/en/class.ziparchive.php
library(tidyverse)
x <- data.frame(Category= c('First', 'First', 'First', 'Second', 'Third', 'Third', 'Second'),
Frequency = c(10, 15, 5, 2, 14, 20, 3))
count(x, Category, wt = Frequency)
You simply need to make cab
a string:
cab = '6176'
As the error message states, you cannot do <int> in <string>
:
>>> 1 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not int
>>>
because integers and strings are two totally different things and Python does not embrace implicit type conversion ("Explicit is better than implicit.").
In fact, Python only allows you to use the in
operator with a right operand of type string if the left operand is also of type string:
>>> '1' in '123' # Works!
True
>>>
>>> [] in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not list
>>>
>>> 1.0 in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not float
>>>
>>> {} in '123'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'in <string>' requires string as left operand, not dict
>>>
This is the case from the question because the OP wants to commit to a new branch and also applies if your changes are compatible with the target branch without triggering an overwrite.
As in the accepted answer by John Brodie, you can simply checkout the new branch and commit the work:
git checkout -b branch_name
git add <files>
git commit -m "message"
If you get the error:
error: Your local changes to the following files would be overwritten by checkout:
...
Please commit your changes or stash them before you switch branches
Then you can stash your work, create a new branch, then pop your stash changes, and resolve the conflicts:
git stash
git checkout -b branch_name
git stash pop
It will be as if you had made those changes after creating the new branch. Then you can commit as usual:
git add <files>
git commit -m "message"
See the answer by Carl Norum with cherry-picking, which is the right tool in this case:
git checkout <target name>
git cherry-pick <original branch>
See the answer by joeytwiddle on this potential duplicate. Follow any of the above steps as appropriate, then roll back the original branch:
git branch -f <original branch> <earlier commit id>
If you have pushed your changes to a shared remote like GitHub, you should not attempt this roll-back unless you know what you are doing.
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub