Just use indexOf
:
haystack.indexOf(needle) >= 0
If you want to support old Internet Explorers (< IE9), you'll have to include your current code as a workaround though.
Unless your list is sorted, you need to compare every value to the needle. Therefore, both your solution and indexOf
will have to execute n/2
comparisons on average. However, since indexOf
is a built-in method, it may use additional optimizations and will be slightly faster in practice. Note that unless your application searches in lists extremely often (say a 1000 times per second) or the lists are huge (say 100k entries), the speed difference will not matter.
Just check the PATH environment variable. In My Computer - > Properties -> Advanced System settings -> Environment Variables -> (left upper window "User Variables for "some name of PC"" ) just check the PATH variable. If it doesn't exist create it with the following -- > C:\Program Files (x86)\Java\jre7\bin <--
I was faced with the same problem after had updated my Eclipse. I've found that the path asked 64-bit version, but I had the 32-bit in dif path. It was helpful for me. P.S.: I have a 64-bit OS, 32-bit JRE and 32-bit Eclipse. All works fine :)
Part 1 of your question:
var allChecked = true;
$("input.abc").each(function(index, element){
if(!element.checked){
allChecked = false;
return false;
}
});
EDIT:
The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.
Many of these answers will only give you new records and not updates and/or are extremely ineffecient
The only reliable, performant way to do this is to create a tailable cursor on local db: oplog.rs collection to get ALL changes to MongoDB and do with it what you will. (MongoDB even does this internally more or less to support replication!)
Explanation of what the oplog contains: https://www.compose.com/articles/the-mongodb-oplog-and-node-js/
Example of a Node.js library that provides an API around what is available to be done with the oplog: https://github.com/cayasso/mongo-oplog
You should be able to use forward slashes in Java to refer to file locations.
The BufferedReader class is used for wrapping other file readers whos read method may not be very efficient. A more detailed description can be found in the Java APIs.
Toolkit's use of BufferedReader is probably what you need.
Two options:
Install Oracle client on the PC you want to run your program on
Use Oracle.ManagedDataAccess.dll
You can get it on NuGet (search 'oracle managed') or download ODP.NET_Managed.zip (link is to a beta version, but points you in the right direction)
I use this so that the computers I deploy onto don't need Oracle client installed.
N.B. in my opinion this is good for console apps but annoying if you intend to install your application, so I install the client in that case.
fscanf
- "On success, the function returns the number of items successfully read. This count can match the expected number of readings or be less -even zero- in the case of a matching failure.
In the case of an input failure before any data could be successfully read, EOF is returned."
So, instead of doing nothing with the return value like you are right now, you can check to see if it is == EOF
.
You should check for EOF when you call fscanf
, not check the array slot for EOF.
The previous answer is pretty good, but I also wanted to mention that there is a fixed layout equivalent for grids, you just need to write minmax(0, 1fr)
instead of 1fr
as your track size.
What you want to see is the list of outgoing commits. You can do this using
git log master..branchName
or
git log master..branchName --oneline
Where I assume that "branchName" was created as a tracking branch of "master".
Similarly, to see the incoming changes you can use:
git log branchName..master
By default, git will update execute file permissions if you change them. It will not change or track any other permissions.
If you don't see any changes when modifying execute permission, you probably have a configuration in git which ignore file mode.
Look into your project, in the .git
folder for the config
file and you should see something like this:
[core]
filemode = false
You can either change it to true
in your favorite text editor, or run:
git config core.filemode true
Then, you should be able to commit normally your files. It will only commit the permission changes.
Download the plugin, extract it inside eclipse/dropins folder and restart your Eclipse IDE. You may require to pass --clean along with eclipse command
Just load the image in a hidden <img>
tag (style = "display none"
), listen to the load event firing with jQuery, create a new Image()
with JavaScript, set the source to the invisible image, and get the size like above.
After installing git-extentions (http://gitextensions.github.io/) you can run .sh file from the command prompt. (No ./script.sh required, just run it like a bat/cmd file) Or you can run them in a "full" bash environment by using the MinGW Git bash shell.
I am not a great fan of Cygwin (yes I am sure it's really powerful), so running bash scripts on windows without having to install it perfect for me.
There is a bunch on here:
http://www.webservicex.net/WS/wscatlist.aspx
Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.
Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.
I was also having problem with starting MySql server but run command as mention right mark in picture . Its working fine .
This will work but it is suggested to take backup of your database first.
The running the impdp command to produce an sqlfile, you will need to run it as a user which has the DATAPUMP_IMP_FULL_DATABASE role.
Or... run it as a low privileged user and use the MASTER_ONLY=YES option, then inspect the master table. e.g.
select value_t
from SYS_IMPORT_TABLE_01
where name = 'CLIENT_COMMAND'
and process_order = -59;
col object_name for a30
col processing_status head STATUS for a6
col processing_state head STATE for a5
select distinct
object_schema,
object_name,
object_type,
object_tablespace,
process_order,
duplicate,
processing_status,
processing_state
from sys_import_table_01
where process_order > 0
and object_name is not null
order by object_schema, object_name
/
You can do this using Input.setSelectionRange
, part of the Range API for interacting with text selections and the text cursor:
var searchInput = $('#Search');
// Multiply by 2 to ensure the cursor always ends up at the end;
// Opera sometimes sees a carriage return as 2 characters.
var strLength = searchInput.val().length * 2;
searchInput.focus();
searchInput[0].setSelectionRange(strLength, strLength);
Demo: Fiddle
While using simplified tags with AndroidX consider using HtmlCompat.fromHtml()
String s = "<b>Bolded text</b>, <i>italic text</i>, even <u>underlined</u>!"
TextView tv = (TextView)findViewById(R.id.THE_TEXTVIEW_ID);
tv.setText(HtmlCompat.fromHtml(s, FROM_HTML_MODE_LEGACY));
This is unappealing as it requires I assign
df
to a variable before being able to filter on its values.
df[df["column_name"] != 5].groupby("other_column_name")
seems to work: you can nest the []
operator as well. Maybe they added it since you asked the question.
Surely using array_map
and if using a container implementing ArrayAccess
to derive objects is just a smarter, semantic way to go about this?
Array map semantics are similar across most languages and implementations that I've seen. It's designed to return a modified array based upon input array element (high level ignoring language compile/runtime type preference); a loop is meant to perform more logic.
For retrieving objects by ID / PK, depending upon if you are using SQL or not (it seems suggested), I'd use a filter to ensure I get an array of valid PK's, then implode with comma and place into an SQL IN()
clause to return the result-set. It makes one call instead of several via SQL, optimising a bit of the call->wait
cycle. Most importantly my code would read well to someone from any language with a degree of competence and we don't run into mutability problems.
<?php
$arr = [0,1,2,3,4];
$arr2 = array_map(function($value) { return is_int($value) ? $value*2 : $value; }, $arr);
var_dump($arr);
var_dump($arr2);
vs
<?php
$arr = [0,1,2,3,4];
foreach($arr as $i => $item) {
$arr[$i] = is_int($item) ? $item * 2 : $item;
}
var_dump($arr);
If you know what you are doing will never have mutability problems (bearing in mind if you intend upon overwriting $arr
you could always $arr = array_map
and be explicit.
The former answer is now superseded by .iloc
:
>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
date
17 10
18 18
19 26
20 34
21 42
22 50
23 58
>>> df["date"].iloc[0]
10
>>> df["date"].iloc[-1]
58
The shortest way I can think of uses .iget()
:
>>> df = pd.DataFrame({"date": range(10, 64, 8)})
>>> df.index += 17
>>> df
date
17 10
18 18
19 26
20 34
21 42
22 50
23 58
>>> df['date'].iget(0)
10
>>> df['date'].iget(-1)
58
Alternatively:
>>> df['date'][df.index[0]]
10
>>> df['date'][df.index[-1]]
58
There's also .first_valid_index()
and .last_valid_index()
, but depending on whether or not you want to rule out NaN
s they might not be what you want.
Remember that df.ix[0]
doesn't give you the first, but the one indexed by 0. For example, in the above case, df.ix[0]
would produce
>>> df.ix[0]
Traceback (most recent call last):
File "<ipython-input-489-494245247e87>", line 1, in <module>
df.ix[0]
[...]
KeyError: 0
You may have started your docker with dns options --dns 172.x.x.x
I had the same error and removed the options from /etc/default/docker
The lines:
# Use DOCKER_OPTS to modify the daemon startup options.
DOCKER_OPTS="--dns 172.x.x.x"
I know this is an old post, but I thought the tracking of mouse button using mouse up/down felt a bit clunky, so I found an alternative that may appeal to some.
<style>
div.myDiv:active {
cursor: default;
}
</style>
<script>
function handleMove( div ) {
var style = getComputedStyle( div );
if (style.getPropertyValue('cursor') == 'default')
{
// You're down and moving here!
}
}
</script>
<div class='myDiv' onmousemove='handleMove(this);'>Click and drag me!</div>
The :active selector handles the mouse click much better than mouse up/down, you just need a way of reading that state in the onmousemove event. For that I needed to cheat and relied on the fact that the default cursor is "auto" and I just change it to "default", which is what auto selects by default.
You can use anything in the object that is returned by getComputedStyle that you can use as a flag without upsetting the look of your page e.g. border-color.
I would have liked to set my own user defined style in the :active section, but I couldn't get that to work. It would be better if it's possible.
For Select2 v4:
Use dropdownParent
to attach the dropdown to the modal dialog, rather than the HTML body.
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
<select id="select2insidemodal" multiple="multiple">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#select2insidemodal").select2({
dropdownParent: $("#myModal")
});
});
</script>
This will attach the Select2 dropdown so it falls within the DOM of the modal rather than to the HTML body (the default). See https://select2.org/dropdown#dropdown-placement
AndroidManifest.xml
Include launchMode="singleTop"
<activity android:name=".MessagesDetailsActivity"
android:launchMode="singleTop"
android:excludeFromRecents="true"
/>
SMSReceiver.java
Set the flags for the Intent and PendingIntent
Intent intent = new Intent(context, MessagesDetailsActivity.class);
intent.putExtra("smsMsg", smsObject.getMsg());
intent.putExtra("smsAddress", smsObject.getAddress());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MessageDetailsActivity.java
onResume() - gets called everytime, load the extras.
Intent intent = getIntent();
String extraAddress = intent.getStringExtra("smsAddress");
String extraBody = intent.getStringExtra("smsMsg");
Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.
An alternative approach, without searching for the field html:
var $form = $('#' + DynamicValueAssignedHere).find('form');
var formData = $form.serializeArray();
var myFieldName = 'FirstName';
var myFieldFilter = function (field) {
return field.name == myFieldName;
}
var value = formData.filter(myFieldFilter)[0].value;
A simple, newbie friendly way for looking into a file:
git gui browser <branch>
which lets you explore the contents of any file.
It's also there in the File menu of git gui
. Most other -more advanced- GUI wrappers (Qgit, Egit, etc..) offer browsing/opening files as well.
Assume that foo.jsp is your jsp file. and following code is the button that you want do redirect.
<h:commandButton value="Redirect" action="#{trial.enter }"/>
And now we'll check the method for directing in your java (service) class
public String enter() {
if (userName.equals("xyz") && password.equals("123")) {
return "enter";
} else {
return null;
}
}
and now this is a part of faces-config.xml file
<managed-bean>
<managed-bean-name>'class_name'</managed-bean-name>
<managed-bean-class>'package_name'</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-case>
<from-outcome>enter</from-outcome>
<to-view-id>/foo.jsp</to-view-id>
<redirect />
</navigation-case>
Something like this:
$.getJSON("http://mywebsite.com/json/get.php?cid=15",
function(data){
$.each(data.products, function(i,product){
content = '<p>' + product.product_title + '</p>';
content += '<p>' + product.product_short_description + '</p>';
content += '<img src="' + product.product_thumbnail_src + '"/>';
content += '<br/>';
$(content).appendTo("#product_list");
});
});
Would take a json object made from a PHP array returned with the key of products. e.g:
Array('products' => Array(0 => Array('product_title' => 'Product 1',
'product_short_description' => 'Product 1 is a useful product',
'product_thumbnail_src' => '/images/15/1.jpg'
)
1 => Array('product_title' => 'Product 2',
'product_short_description' => 'Product 2 is a not so useful product',
'product_thumbnail_src' => '/images/15/2.jpg'
)
)
)
To reload the list you would simply do:
$("#product_list").empty();
And then call getJSON again with new parameters.
You might also be interested in the unit testing framework that is part of qooxdoo, an open source RIA framework similar to Dojo, ExtJS, etc. but with quite a comprehensive tool chain.
Try the online version of the testrunner. Hint: hit the gray arrow at the top left (should be made more obvious). It's a "play" button that runs the selected tests.
To find out more about the JS classes that let you define your unit tests, see the online API viewer.
For automated UI testing (based on Selenium RC), check out the Simulator project.
In order to hande naming conflict between logins, roles, users etc. you should check the type
column according to Microsoft sys.database_principals documentation
In order to handle special chacters in usernames etc, use N'<name>'
and [<name>]
accordingly.
USE MASTER
IF NOT EXISTS (SELECT 1 FROM master.sys.server_principals WHERE
[name] = N'<loginname>' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
CREATE LOGIN [<loginname>] <further parameters>
USE [<databasename>]
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE
[name] = N'<username>' and [type] IN ('C','E', 'G', 'K', 'S', 'U'))
CREATE USER [<username>] FOR LOGIN [<loginname>]
USE [<databasename>]
IF NOT EXISTS (SELECT 1 FROM sys.database_principals WHERE
[name] = N'<rolename>' and Type = 'R')
CREATE ROLE [<rolename>]
USE [<databasename>]
EXEC sp_addrolemember N'<rolename>', N'<username>'
USE [<databasename>]
GRANT SELECT ON [<tablename>] TO [<rolename>]
GRANT UPDATE ON [<tablename>] ([<columnname>]) TO [<rolename>]
GRANT EXECUTE ON [<procedurename>] TO [<rolename>]
The SQL is tested on SQL Server 2005, 2008, 2008 R2, 2014, 2016, 2017, 2019
The JavaDoc explains it very well:
With this option set to a non-zero timeout, a read() call on the InputStream associated with this Socket will block for only this amount of time. If the timeout expires, a java.net.SocketTimeoutException is raised, though the Socket is still valid. The option must be enabled prior to entering the blocking operation to have effect. The timeout must be > 0. A timeout of zero is interpreted as an infinite timeout.
SO_TIMEOUT
is the timeout that a read()
call will block. If the timeout is reached, a java.net.SocketTimeoutException will be thrown. If you want to block forever put this option to zero (the default value), then the read()
call will block until at least 1 byte could be read.
protected void Application_Start(object sender, EventArgs e)
{
string path = Server.MapPath("/");
//or
string path2 = Server.MapPath("~");
//depends on your application needs
}
For an example data in your table such as combinations of
''
, null
and as well as actual value
than if you want to only actual value
and replace to ''
and null
value by #
symbol than execute this query
SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull
function but here only i am mentioning IIF
function
SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name
SELECT IIF(Column_Name = '', '#', Column_Name) FROM Table_Name
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
If you want to submit a POST request
Content-Type
” and “value” = “application/x-www-form-urlencoded
”name=mynamehere&title=TA
” in the “request body” text area fieldOne point from me. I used a mutual cert authentication with spring-boot microservices. The following is working for me, key points here are
keyManagerFactory.init(...)
and sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom())
lines of code without them, at least for me, things did not work. Certificates are packaged by PKCS12.
@Value("${server.ssl.key-store-password}")
private String keyStorePassword;
@Value("${server.ssl.key-store-type}")
private String keyStoreType;
@Value("${server.ssl.key-store}")
private Resource resource;
private RestTemplate getRestTemplate() throws Exception {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() throws Exception {
return new HttpComponentsClientHttpRequestFactory(httpClient());
}
private HttpClient httpClient() throws Exception {
KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
KeyStore trustStore = KeyStore.getInstance(keyStoreType);
if (resource.exists()) {
InputStream inputStream = resource.getInputStream();
try {
if (inputStream != null) {
trustStore.load(inputStream, keyStorePassword.toCharArray());
keyManagerFactory.init(trustStore, keyStorePassword.toCharArray());
}
} finally {
if (inputStream != null) {
inputStream.close();
}
}
} else {
throw new RuntimeException("Cannot find resource: " + resource.getFilename());
}
SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
sslcontext.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslcontext, new String[]{"TLSv1.2"}, null, getDefaultHostnameVerifier());
return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
}
you can use:
df.plot(x='Date',y='adj_close')
Or you can set the index to be Date
beforehand, then it's easy to plot the column you want:
df.set_index('Date', inplace=True)
df['adj_close'].plot()
ticker
on itYou need to groupby before:
df.set_index('Date', inplace=True)
df.groupby('ticker')['adj_close'].plot(legend=True)
grouped = df.groupby('ticker')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,4), sharey=True)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
I got similar task: to rsync all files modified after given date, but excluding some directories. It was difficult to build one liner all-in-one style, so I dived problem into smaller pieces. Final solution:
find ~/sourceDIR -type f -newermt "DD MMM YYYY HH:MM:SS" | egrep -v "/\..|Downloads|FOO" > FileList.txt
rsync -v --files-from=FileList.txt ~/sourceDIR /Destination
First I use find -L ~/sourceDIR -type f -newermt "DD MMM YYYY HH:MM:SS"
. I tried to add regex
to find
line to exclude name patterns, however my flavor of Linux (Mint) seams not to understand negate regex in find
. Tried number of regex flavors - non work as desired.
So I end up with egrep -v
- option that excludes pattern easy way. My rsync
is not copying directories like /.cache or /.config plus some other I explicitly named.
I'm using Java 8 and this worked for me.
Add the dependency on pom.xml
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
<version>2.4.0</version>
</dependency>
and add JodaModule on your ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());
To pass a pointer to an int it should be void Fun(int* pointer)
.
Passing a reference to an int would look like this...
void Fun(int& ref) {
ref = 10;
}
int main() {
int test = 5;
cout << test << endl; // prints 5
Fun(test);
cout << test << endl; // prints 10 because Fun modified the value
return 1;
}
You should try using isinstance()
if isinstance(object, list):
## DO what you want
In your case
if isinstance(tmpDict[key], list):
## DO SOMETHING
To elaborate:
x = [1,2,3]
if type(x) == list():
print "This wont work"
if type(x) == list: ## one of the way to see if it's list
print "this will work"
if type(x) == type(list()):
print "lets see if this works"
if isinstance(x, list): ## most preferred way to check if it's list
print "This should work just fine"
The difference between isinstance()
and type()
though both seems to do the same job is that isinstance()
checks for subclasses in addition, while type()
doesn’t.
var refreshAlert = UIAlertController(title: "Log Out", message: "Are You Sure to Log Out ? ", preferredStyle: UIAlertControllerStyle.Alert)
refreshAlert.addAction(UIAlertAction(title: "Confirm", style: .Default, handler: { (action: UIAlertAction!) in
self.navigationController?.popToRootViewControllerAnimated(true)
}))
refreshAlert.addAction(UIAlertAction(title: "Cancel", style: .Default, handler: { (action: UIAlertAction!) in
refreshAlert .dismissViewControllerAnimated(true, completion: nil)
}))
presentViewController(refreshAlert, animated: true, completion: nil)
Here is my solution:
chrome.runtime.onMessage.addListener(function(request, sender) {
if (request.action == "getSource") {
this.pageSource = request.source;
var title = this.pageSource.match(/<title[^>]*>([^<]+)<\/title>/)[1];
alert(title)
}
});
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
chrome.tabs.executeScript(
tabs[0].id,
{ code: 'var s = document.documentElement.outerHTML; chrome.runtime.sendMessage({action: "getSource", source: s});' }
);
});
There are many quirks in the way browsers handle XMLHttpRequest, this JS code will work across all browsers:
https://github.com/ilinsky/xmlhttprequest
This JS code converts XML into easy to use JavaScript objects:
http://www.terracoder.com/index.php/xml-objectifier
The JS code above can be included in the page to meet your no external library requirement.
var symbol = "MSFT";
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "http://www.webservicex.net/stockquote.asmx?op=GetQuote",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseText);
// http://www.terracoder.com convert XML to JSON
var json = XMLObjectifier.xmlToJSON(xmlhttp.responseXML);
var result = json.Body[0].GetQuoteResponse[0].GetQuoteResult[0].Text;
// Result text is escaped XML string, convert string to XML object then convert to JSON object
json = XMLObjectifier.xmlToJSON(XMLObjectifier.textToXML(result));
alert(symbol + ' Stock Quote: $' + json.Stock[0].Last[0].Text);
}
}
xmlhttp.setRequestHeader("SOAPAction", "http://www.webserviceX.NET/GetQuote");
xmlhttp.setRequestHeader("Content-Type", "text/xml");
var xml = '<?xml version="1.0" encoding="utf-8"?>' +
'<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" ' +
'xmlns:xsd="http://www.w3.org/2001/XMLSchema" ' +
'xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">' +
'<soap:Body> ' +
'<GetQuote xmlns="http://www.webserviceX.NET/"> ' +
'<symbol>' + symbol + '</symbol> ' +
'</GetQuote> ' +
'</soap:Body> ' +
'</soap:Envelope>';
xmlhttp.send(xml);
// ...Include Google and Terracoder JS code here...
Two other options:
JavaScript SOAP client:
http://www.guru4.net/articoli/javascript-soap-client/en/
Generate JavaScript from a WSDL:
https://cwiki.apache.org/confluence/display/CXF20DOC/WSDL+to+Javascript
Actually, you can achieve this pretty easy. Simply specify the line height as a number:
<p style="line-height:1.5">
<span style="font-size:12pt">The quick brown fox jumps over the lazy dog.</span><br />
<span style="font-size:24pt">The quick brown fox jumps over the lazy dog.</span>
</p>
The difference between number and percentage in the context of the line-height CSS property is that the number value is inherited by the descendant elements, but the percentage value is first computed for the current element using its font size and then this computed value is inherited by the descendant elements.
For more information about the line-height property, which indeed is far more complex than it looks like at first glance, I recommend you take a look at this online presentation.
The easiest way I have found to pass data between routeHandlers to use next()
no need to mess with redirect or sessions.
Optionally you could just call your homeCtrl(req,res)
instead of next()
and just pass the req
and res
var express = require('express');
var jade = require('jade');
var http = require("http");
var app = express();
var server = http.createServer(app);
/////////////
// Routing //
/////////////
// Move route middleware into named
// functions
function homeCtrl(req, res) {
// Prepare the context
var context = req.dataProcessed;
res.render('home.jade', context);
}
function categoryCtrl(req, res, next) {
// Process the data received in req.body
// instead of res.redirect('/');
req.dataProcessed = somethingYouDid;
return next();
// optionally - Same effect
// accept no need to define homeCtrl
// as the last piece of middleware
// return homeCtrl(req, res, next);
}
app.get('/', homeCtrl);
app.post('/category', categoryCtrl, homeCtrl);
As an addition to other answers, unix considers everything as a file system. Your keyboard is a file that is read only from the perspective of the kernel. The screen is a write only file. Similarly, folders, input-output devices etc are also considered to be files. Whenever a file is opened, say when the device drivers[for device files] requests an open(), or a process opens an user file the kernel allocates a file descriptor, an integer that specifies the access to that file such it being read only, write only etc. [for reference : https://en.wikipedia.org/wiki/Everything_is_a_file ]
According to the documentation since Symfony 2.1 simply use this shortcut :
$user = $this->getUser();
The above is still working on Symfony 3.2 and is a shortcut for this :
$user = $this->get('security.token_storage')->getToken()->getUser();
The
security.token_storage
service was introduced in Symfony 2.6. Prior to Symfony 2.6, you had to use thegetToken()
method of thesecurity.context
service.
Example : And if you want directly the username :
$username = $this->getUser()->getUsername();
The user will be an object and the class of that object will depend on your user provider.
You are probably using a locale where the month names are not "January", "February", etc. but some other words in your local language.
Try specifying the locale you wish to use, for example Locale.US
:
DateFormat fmt = new SimpleDateFormat("MMMM dd, yyyy", Locale.US);
Date d = fmt.parse("June 27, 2007");
Also, you have an extra space in the date string, but actually this has no effect on the result. It works either way.
Use NodePort:
$ kubectl run user-login --replicas=2 --labels="run=user-login" --image=kingslayerr/teamproject:version2 --port=5000
$ kubectl expose deployment user-login --type=NodePort --name=user-login-service
$ kubectl describe services user-login-service
(Note down the port)
$ kubectl cluster-info
(IP-> Get The IP where master is running)
Your service is accessible at (IP):(port)
Use require('child_process').exec
instead of spawn for a more specific error message!
for example:
var exec = require('child_process').exec;
var commandStr = 'java -jar something.jar';
exec(commandStr, function(error, stdout, stderr) {
if(error || stderr) console.log(error || stderr);
else console.log(stdout);
});
INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;
does the later approach save computation time and memory?
There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg
Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:
output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.
Excerpt:
Return true if
class
is a subclass (direct, indirect or virtual) ofclassinfo
.
Add ID current
for active/current page:
<div class="menuBar">
<ul>
<li id="current"><a href="index.php">HOME</a></li>
<li><a href="two.php">PORTFOLIO</a></li>
<li><a href="three.php">ABOUT</a></li>
<li><a href="four.php">CONTACT</a></li>
<li><a href="five.php">SHOP</a></li>
</ul>
#current a { color: #ff0000; }
VideoView can only Stream 3gp videos I recommend this code to stream your video or try a higher version of android. Try Video Online Streaming.
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
String videourl = "http://something.com/blah.mp4";
Uri uri = Uri.parse(videourl);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.setDataAndType(uri, "video/mp4");
startActivity(intent);
}
input(char_val, date9.);
You can consider to convert it to word format using input(char_val, worddate.)
You can get a lot in this page http://v8doc.sas.com/sashtml/lrcon/zenid-63.htm
IF EXISTS (SELECT 1 FROM Table WHERE FieldValue='')
BEGIN
SELECT TableID FROM Table WHERE FieldValue=''
END
ELSE
BEGIN
INSERT INTO TABLE(FieldValue) VALUES('')
SELECT SCOPE_IDENTITY() AS TableID
END
See here for more information on IF ELSE
Note: written without a SQL Server install handy to double check this but I think it is correct
Also, I've changed the EXISTS bit to do SELECT 1 rather than SELECT * as you don't care what is returned within an EXISTS, as long as something is I've also changed the SCOPE_IDENTITY() bit to return just the identity assuming that TableID is the identity column
import sys
import time
a = 0
for x in range (0,3):
a = a + 1
b = ("Loading" + "." * a)
# \r prints a carriage return first, so `b` is printed on top of the previous line.
sys.stdout.write('\r'+b)
time.sleep(0.5)
print (a)
Note that you might have to run sys.stdout.flush()
right after sys.stdout.write('\r'+b)
depending on which console you are doing the printing to have the results printed when requested without any buffering.
I write below code to remove the blank value in the array string.
string[] test={"1","","2","","3"};
test= test.Except(new List<string> { string.Empty }).ToArray();
Each row in /proc/$PID/maps
describes a region of contiguous virtual memory in a process or thread. Each row has the following fields:
address perms offset dev inode pathname
08048000-08056000 r-xp 00000000 03:0c 64593 /usr/sbin/gpm
-
will appear instead of the r
/w
/x
. If a region is not shared, it is private, so a p
will appear instead of an s
. If the process attempts to access memory in a way that is not permitted, a segmentation fault is generated. Permissions can be changed using the mprotect
system call.mmap
), this is the offset in the file where the mapping begins. If the memory was not mapped from a file, it's just 0.[heap]
, [stack]
, or [vdso]
. [vdso]
stands for virtual dynamic shared object. It's used by system calls to switch to kernel mode. Here's a good article about it: "What is linux-gate.so.1?"You might notice a lot of anonymous regions. These are usually created by mmap
but are not attached to any file. They are used for a lot of miscellaneous things like shared memory or buffers not allocated on the heap. For instance, I think the pthread library uses anonymous mapped regions as stacks for new threads.
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
babel-polyfill
(deprecated as of Babel 7.4) is required. You must also install it in order to get async/await working.
npm i -D babel-core babel-polyfill babel-preset-es2015 babel-preset-stage-0 babel-loader
package.json
"devDependencies": {
"babel-core": "^6.0.20",
"babel-polyfill": "^6.0.16",
"babel-preset-es2015": "^6.0.15",
"babel-preset-stage-0": "^6.0.15"
}
.babelrc
{
"presets": [ "es2015", "stage-0" ]
}
.js with async/await (sample code)
"use strict";
export default async function foo() {
var s = await bar();
console.log(s);
}
function bar() {
return "bar";
}
In the startup file
require("babel-core/register");
require("babel-polyfill");
If you are using webpack you need to put it as the first value of your entry
array in your webpack configuration file (usually webpack.config.js
), as per @Cemen comment:
module.exports = {
entry: ['babel-polyfill', './test.js'],
output: {
filename: 'bundle.js'
},
module: {
loaders: [
{ test: /\.jsx?$/, loader: 'babel', }
]
}
};
If you want to run tests with babel then use:
mocha --compilers js:babel-core/register --require babel-polyfill
As others have mentioned, the right mouse button can be detected through the usual mouse events (mousedown, mouseup, click). However, if you're looking for a firing event when the right-click menu is brought up, you're looking in the wrong place. The right-click/context menu is also accessible via the keyboard (shift+F10 or context menu key on Windows and some Linux). In this situation, the event that you're looking for is oncontextmenu
:
window.oncontextmenu = function ()
{
showCustomMenu();
return false; // cancel default menu
}
As for the mouse events themselves, browsers set a property to the event object that is accessible from the event handling function:
document.body.onclick = function (e) {
var isRightMB;
e = e || window.event;
if ("which" in e) // Gecko (Firefox), WebKit (Safari/Chrome) & Opera
isRightMB = e.which == 3;
else if ("button" in e) // IE, Opera
isRightMB = e.button == 2;
alert("Right mouse button " + (isRightMB ? "" : " was not") + "clicked!");
}
(For future references)
I think it's because there's differences in Application Context and Activity Context, as explained here: http://www.doubleencore.com/2013/06/context/
Which means that we can't show dialog using Application Context. That's it.
Try Shift + Delete. Did 24.000 files in 2 minutes for me.
In mac osx , you can use the following command:
system_profiler SPUSBDataType
You should be using Maven, as the structure is standardized. To do that (Once you have created your Maven project in Netbeans, just
As long as the project has no errors, I usually get none transferring to eclipse. This works for Maven web projects and regular projects.
Just remove the white space from the string before you split it.
mylist = my_string.replace(' ','').split(',')
Just code it like this:
function example($anon) {
$anon();
}
example(function(){
// some codes here
});
it would be great if you could invent something like this (inspired by Laravel Illuminate):
Object::method("param_1", function($param){
$param->something();
});
<?php
$a= array("1","2","3");
print_r($a);
$b=serialize($a);
echo $b;
$c=unserialize($b);
print_r($c);
Run this program its echo the output
a:3:{i:0;s:1:"1";i:1;s:1:"2";i:2;s:1:"3";}
you can use serialize to store array of data in database
and can retrieve and UN-serialize data to use.
The path /usr/local/bin/composer
is not in your PATH, executables in that folder won't be found.
Delete the folder /usr/local/bin/composer
, then run
$ mv composer.phar /usr/local/bin/composer
This moves composer.phar
into /usr/local/bin/
and renames it into composer
(which is still an executable, not a folder).
Then just use it like:
$ composer ...
There is a similar call, isUserAMonkey()
, that returns true if the MonkeyRunner tool is being used. The SDK explanation is just as curious as this one.
public static boolean isUserAMonkey(){}
Returns
true
if the user interface is currently being messed with by a monkey.
Here is the source.
I expect that this was added in anticipation of a new SDK tool named something with a goat and will actually be functional to test for the presence of that tool.
Also see a similar question, Strange function in ActivityManager: isUserAMonkey. What does this mean, what is its use?.
DirectoryInfo dirInfo = new DirectoryInfo(@strDirPath);
long dirSize = await Task.Run(() => dirInfo.EnumerateFiles( "*", SearchOption.AllDirectories).Sum(file => file.Length));
I have just copied and moved a Magento site to a local area so I could work on it offline and had the same problem.
But in the end I found out Magento was forcing a redirect from http to https and I didn't have a SSL setup. So this solved my problem http://www.magentocommerce.com/wiki/recover/ssl_access_with_phpmyadmin
It pretty much says set web/secure/use_in_adminhtml value from 1 to 0 in the core_config_data to allow non-secure access to the admin area
What you were missing was the float: left; here is an example just done in the HTML
<div id="form">
<form action="" method="post" name="registration" class="register">
<fieldset>
<label for="Student" style="float: left">Name:</label>
<input name="Student" />
<label for="Matric_no" style="float: left">Matric number:</label>
<input name="Matric_no" />
<label for="Email" style="float: left">Email:</label>
<input name="Email" />
<label for="Username" style="float: left">Username:</label>
<input name="Username" />
<label for="Password" style="float: left">Password:</label>
<input name="Password" type="password" />
<input name="regbutton" type="button" class="button" value="Register" />
</fieldset>
</form>
The more efficient way to do this is to add a class to the labels and set the float: left; to the class in CSS
Why Not Use an Inner Class (Nesting)
class A extends B {
private class C extends D {
//Classes A , B , C , D accessible here
}
}
Add android:noHistory="true" in manifest file .
<manifest >
<activity
android:name="UI"
android:noHistory="true"/>
</manifest>
This tutorial should help you:
Getting Started with Oracle SQL Developer
See the prerequisites:
Unlock the HR user. Login to SQL*Plus as the SYS user and execute the following command:
alter user hr identified by hr account unlock;
Download and unzip the sqldev_mngdb.zip file that contains all the files you need to perform this tutorial.
Another version from May 2011: Getting Started with Oracle SQL Developer
For more info check this related question:
How to create a new database after initally installing oracle database 11g Express Edition?
To put text, use .text('text')
If you want to use .html(SomeValue)
, SomeValue should have html tags that can be inside a div it must work too.
Just check your script location, as farzad said.
In a .git directory in the root of the project. Unlike some other version control systems, notably CVS, there are no additional directories in any of the subdirectories.
Its faster with MUTT command
echo "Body Of the Email" | mutt -a "File_Attachment.csv" -s "Daily Report for $(date)" -c [email protected] [email protected] -y
String source = "24/10/17";
String[] sourceSplit= source.split("/");
int anno= Integer.parseInt(sourceSplit[2]);
int mese= Integer.parseInt(sourceSplit[1]);
int giorno= Integer.parseInt(sourceSplit[0]);
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(anno,mese-1,giorno);
Date data1= calendar.getTime();
SimpleDateFormat myFormat = new SimpleDateFormat("20yy-MM-dd");
String dayFormatted= myFormat.format(data1);
System.out.println("data formattata,-->"+dayFormatted);
Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();
. However, you have updated your code to use the List.isEmpty()
method to properly check if the list is empty.
The problem now is that you are never actually sending an empty list to giveList()
. In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.
do {
number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
/* Change this line */
if (number != -1) numbers.add(number);
} while (number != -1);
You can create your own method Equivalent to
String.IsNullOrWhiteSpace(value)
function IsNullOrWhiteSpace( value) {
if (value== null) return true;
return value.replace(/\s/g, '').length == 0;
}
If you want to use jQuery, the .load() function is the correct function you are after;
But you are missing the #
from the div1 id selector in the example 2)
This should work:
$("#div1").load("file2.html");
In Chrome, go to options (Customize and Control, the 3 dots/bars at top right) ---> More Tools ---> save page as
save page as
filename : any_name.html
save as type : webpage complete.
Then you will get any_name.html
and any_name folder
.
Compound checking:
if (thing.foo && thing.foo.bar) {
... thing.foor.bar exists;
}
Yes, it is possible.
try:
...
except FirstException:
handle_first_one()
except SecondException:
handle_second_one()
except (ThirdException, FourthException, FifthException) as e:
handle_either_of_3rd_4th_or_5th()
except Exception:
handle_all_other_exceptions()
See: http://docs.python.org/tutorial/errors.html
The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)
It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:
A = matrix( [[1,2,3],[11,12,13],[21,22,23]])
By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanation does not do that. In fact just looking at the inverse gives a clue that the inversion did not work correctly. Look at the magnitude of the individual terms - they are very, very big compared with the terms of the original A matrix...
It is remarkable that the humans when picking an example of a matrix so often manage to pick a singular matrix!
I did have a problem with the solution, so looked into it further. On the ubuntu-kubuntu platform, the debian package numpy does not have the matrix and the linalg sub-packages, so in addition to import of numpy, scipy needs to be imported also.
If the diagonal terms of A are multiplied by a large enough factor, say 2, the matrix will most likely cease to be singular or near singular. So
A = matrix( [[2,2,3],[11,24,13],[21,22,46]])
becomes neither singular nor nearly singular and the example gives meaningful results... When dealing with floating numbers one must be watchful for the effects of inavoidable round off errors.
Thanks for your contribution,
OldAl.
Just move to the new branch. The uncommited changes get carried over.
git checkout -b ABC_1
git commit -m <message>
I would tend to prefer using NULL for the clarity of what is required and what is optional. One word of warning about using default values that depend on other arguments, as suggested by Jthorpe. The value is not set when the function is called, but when the argument is first referenced! For instance:
foo <- function(x,y=length(x)){
x <- x[1:10]
print(y)
}
foo(1:20)
#[1] 10
On the other hand, if you reference y before changing x:
foo <- function(x,y=length(x)){
print(y)
x <- x[1:10]
}
foo(1:20)
#[1] 20
This is a bit dangerous, because it makes it hard to keep track of what "y" is being initialized as if it's not called early on in the function.
You can run the client like this ...
puppet agent --test --debug --noop
with that command you get all the output you can get.
excerpt puppet agent help* --test:
Enable the most common options used for testing. These are 'onetime',
'verbose', 'ignorecache', 'no-daemonize', 'no-usecacheonfailure',
'detailed-exitcodes', 'no-splay', and 'show_diff'.
NOTE: No need to include --verbose
when you use the --test|-t
switch, it implies the --verbose
as well.
Just think of it as the keyword params
in C#, if you are coming from that background :)
this post was made a while ago, but it provides an answer that did not solve the problem regarding reaching the limit of requests in an iteration for me, so I publish this, to help who else has not served.
My environment happened in Ionic 3.
Instead of making a "pause" in the iteration, I ocurred the idea of ??iterating with a timer
, this timer has the particularity of executing the code that would go in the iteration, but will run every so often until it is reached the maximum count of the "Array" in which we want to iterate.
In other words, we will consult the Google API in a certain time so that it does not exceed the limit allowed in milliseconds.
// Code to start the timer
this.count= 0;
let loading = this.loadingCtrl.create({
content: 'Buscando los mejores servicios...'
});
loading.present();
this.interval = setInterval(() => this.getDistancias(loading), 40);
// Function that runs the timer, that is, query Google API
getDistancias(loading){
if(this.count>= this.datos.length){
clearInterval(this.interval);
} else {
var sucursal = this.datos[this.count];
this.calcularDistancia(this.posicion, new LatLng(parseFloat(sucursal.position.latitude),parseFloat(sucursal.position.longitude)),sucursal.codigo).then(distancia => {
}).catch(error => {
console.log('error');
console.log(error);
});
}
this.count += 1;
}
calcularDistancia(miPosicion, markerPosicion, codigo){
return new Promise(async (resolve,reject) => {
var service = new google.maps.DistanceMatrixService;
var distance;
var duration;
service.getDistanceMatrix({
origins: [miPosicion, 'salida'],
destinations: [markerPosicion, 'llegada'],
travelMode: 'DRIVING',
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function(response, status){
if (status == 'OK') {
var originList = response.originAddresses;
var destinationList = response.destinationAddresses;
try{
if(response != null && response != undefined){
distance = response.rows[0].elements[0].distance.value;
duration = response.rows[0].elements[0].duration.text;
resolve(distance);
}
}catch(error){
console.log("ERROR GOOGLE");
console.log(status);
}
}
});
});
}
I hope this helps!
I'm sorry for my English, I hope it's not an inconvenience, I had to use the Google translator.
Regards, Leandro.
You can try to use CDATA to put all your symbols that don't work.
An example of something that will work in XML:
<![CDATA[
function matchwo(a,b) {
if (a < b && a < 0) {
return 1;
} else {
return 0;
}
}
]]>
And of course you can use <
and >
.
git rev-parse
Also works for getting the current branch name using the --abbrev-ref flag like:
git rev-parse --abbrev-ref HEAD
Interface is like an abstraction that is not providing any functionality. Hence It does not 'implement' but extend the other abstractions or interfaces.
declare
x number;
begin
x := myfunc(myargs);
end;
Alternatively:
select myfunc(myargs) from dual;
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
To set the use of scientific notation in your entire R session, you can use the scipen
option. From the documentation (?options
):
‘scipen’: integer. A penalty to be applied when deciding to print
numeric values in fixed or exponential notation. Positive
values bias towards fixed and negative towards scientific
notation: fixed notation will be preferred unless it is more
than ‘scipen’ digits wider.
So in essence this value determines how likely it is that scientific notation will be triggered. So to prevent scientific notation, simply use a large positive value like 999
:
options(scipen=999)
Similar to Lukazoid's answer I've created an extension for IQueryable.
public static IEnumerable<IEnumerable<T>> PageIterator<T>(this IQueryable<T> source, int pageSize)
{
Contract.Requires(source != null);
Contract.Requires(pageSize > 0);
Contract.Ensures(Contract.Result<IEnumerable<IQueryable<T>>>() != null);
using (var enumerator = source.GetEnumerator())
{
while (enumerator.MoveNext())
{
var currentPage = new List<T>(pageSize)
{
enumerator.Current
};
while (currentPage.Count < pageSize && enumerator.MoveNext())
{
currentPage.Add(enumerator.Current);
}
yield return new ReadOnlyCollection<T>(currentPage);
}
}
}
It is useful if Skip or Take are not supported.
Yes, it is sufficient. The way injection type attacks work, is by somehow getting an interpreter (The database) to evaluate something, that should have been data, as if it was code. This is only possible if you mix code and data in the same medium (Eg. when you construct a query as a string).
Parameterised queries work by sending the code and the data separately, so it would never be possible to find a hole in that.
You can still be vulnerable to other injection-type attacks though. For example, if you use the data in a HTML-page, you could be subject to XSS type attacks.
I prefer to solve this in the classic way, creating a new array of my desired data type:
List<MyNewType> newArray = new ArrayList<>();
myOldArray.forEach(info -> newArray.add(objectMapper.convertValue(info, MyNewType.class)));
The accepted answer works, and may be faster, but SQL 2012 and above have a more easily understood method:
SELECT cast(format(GETDATE(), 'yyyy-MM-01') as Date)
Please find attached my dynamic solution if you want to increase the size of an array dynamically after clicking on a button (This is how I got to this question).
Allocation of necessary variables:
array = [1];
arraySize: number;
Declare the function that adds an element to the array:
increaseArrayElement() {
this.arraySize = this.array[this.array.length - 1 ];
this.arraySize += 1;
this.array.push(this.arraySize);
console.log(this.arraySize);
}
Invoke the function in html
<button md-button (click)="increaseArrayElement()" >
Add element to array
</button>
Iterate through array with ngFor:
<div *ngFor="let i of array" >
iterateThroughArray: {{ i }}
</div>
Use Load()
method instead, it will solve the problem. See more
You also can set the width of a audio tag by JavaScript:
audio = document.getElementById('audio-id');
audio.style.width = '200px';
Have a read of the urllib Missing Manual. Pulled from there is the following simple example of a POST request.
url = 'http://myserver/post_service'
data = urllib.urlencode({'name' : 'joe', 'age' : '10'})
req = urllib2.Request(url, data)
response = urllib2.urlopen(req)
print response.read()
As suggested by @Michael Kent do consider requests, it's great.
EDIT: This said, I do not know why passing data to urlopen() does not result in a POST request; It should. I suspect your server is redirecting, or misbehaving.
The most simple way:
>>> import re
>>> string = 'This is a string, with words!'
>>> re.findall(r'\w+', string)
['This', 'is', 'a', 'string', 'with', 'words']
I am now returning to setters and getters but I am also putting the getters and setters in the magic methos __get and __set. This way I have a default behavior when I do this
$class->var;
This will just call the getter I have set in the __get. Normally I will just use the getter directly but there are still some instances where this is just simpler.
I use Gmail as my SMTP server for Django. Much easier than dealing with postfix or whatever other server. I'm not in the business of managing email servers.
In settings.py:
EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '[email protected]'
EMAIL_HOST_PASSWORD = 'password'
NOTE: In 2016 Gmail is not allowing this anymore by default. You can either use an external service like Sendgrid, or you can follow this tutorial from Google to reduce security but allow this option: https://support.google.com/accounts/answer/6010255
In js you can change zoom by
document.body.style.zoom="90%"
But it doesn't work in FF http://caniuse.com/#search=zoom
For ff you can try
-moz-transform: scale(0.9);
And check next topic How can I zoom an HTML element in Firefox and Opera?
I'll add one more possible solution, if you're running this on a virtual machine (vmware, etc.) , some other process on the host or other VM could already have the port you're trying to connect with. Either stop that other process or choose another port.
One of the disadvantages of using HTML for labels is when you need to write a localizable program (which should work in several languages). You will have issues to change just the translatable text. Or you will have to put the whole HTML code into your translations which is very awkward, I would even say absurd :)
gui_en.properties:
title.text=<html>Text color: <font color='red'>red</font></html>
gui_fr.properties:
title.text=<html>Couleur du texte: <font color='red'>rouge</font></html>
gui_ru.properties:
title.text=<html>???? ??????: <font color='red'>???????</font></html>
You can use the react-moment package
-> https://www.npmjs.com/package/react-moment
Put in your file the next line:
import moment from "moment";
date_create: moment().format("DD-MM-YYYY hh:mm:ss")
First one is for Javadoc you define on the top of classes, interfaces, methods etc. You can use Javadoc as the name suggest to document your code on what the class does or what method does etc and generate report on it.
Second one is code block comment. Say for example you have some code block which you do not want compiler to interpret then you use code block comment.
another one is // this you use on statement level to specify what the proceeding lines of codes are supposed to do.
There are some other also like //TODO, this will mark that you want to do something later on that place
//FIXME you can use when you have some temporary solution but you want to visit later and make it better.
Hope this helps
is
compares identity. A string will never be identical to a not-string.
==
is equality. But a string will never be equal to either True
or False
.
You want neither.
path = '/bla/bla/bla'
if path:
print "True"
else:
print "False"
document.add(new Paragraph(""))
It is ineffective above,must add a blank string, like this:
document.add(new Paragraph(" "));
The link posted by Jose has been updated and pylab now has a tight_layout()
function that does this automatically (in matplotlib version 1.1.0).
http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout
http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout
Not quite answering the question, but rather than having
if (error condition that would break you out of this) {
break; // leaves looping structure
}
You should probably have
while(condition && !error_condition)
Also, I'd go with a Timer
.
This code detects left and right swipes, avoids deprecated API calls, and has other miscellaneous improvements over earlier answers.
/**
* Detects left and right swipes across a view.
*/
public class OnSwipeTouchListener implements OnTouchListener {
private final GestureDetector gestureDetector;
public OnSwipeTouchListener(Context context) {
gestureDetector = new GestureDetector(context, new GestureListener());
}
public void onSwipeLeft() {
}
public void onSwipeRight() {
}
public boolean onTouch(View v, MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
private final class GestureListener extends SimpleOnGestureListener {
private static final int SWIPE_DISTANCE_THRESHOLD = 100;
private static final int SWIPE_VELOCITY_THRESHOLD = 100;
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
float distanceX = e2.getX() - e1.getX();
float distanceY = e2.getY() - e1.getY();
if (Math.abs(distanceX) > Math.abs(distanceY) && Math.abs(distanceX) > SWIPE_DISTANCE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
if (distanceX > 0)
onSwipeRight();
else
onSwipeLeft();
return true;
}
return false;
}
}
}
Use it like this:
view.setOnTouchListener(new OnSwipeTouchListener(context) {
@Override
public void onSwipeLeft() {
// Whatever
}
});
The good folks at HubSpot have a resource where you can find pure Javascript methodologies for achieving a lot of jQuery goodness - including ready
http://youmightnotneedjquery.com/#ready
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', fn);
} else {
document.attachEvent('onreadystatechange', function() {
if (document.readyState != 'loading')
fn();
});
}
}
example inline usage:
ready(function() { alert('hello'); });
Did you omit O, 0, and i on purpose?
I just created a PHP class based on Ryan's solution.
<?php
$shorty = new App_Shorty();
echo 'ID: ' . 1000;
echo '<br/> Short link: ' . $shorty->encode(1000);
echo '<br/> Decoded Short Link: ' . $shorty->decode($shorty->encode(1000));
/**
* A nice shorting class based on Ryan Charmley's suggestion see the link on Stack Overflow below.
* @author Svetoslav Marinov (Slavi) | http://WebWeb.ca
* @see http://stackoverflow.com/questions/742013/how-to-code-a-url-shortener/10386945#10386945
*/
class App_Shorty {
/**
* Explicitly omitted: i, o, 1, 0 because they are confusing. Also use only lowercase ... as
* dictating this over the phone might be tough.
* @var string
*/
private $dictionary = "abcdfghjklmnpqrstvwxyz23456789";
private $dictionary_array = array();
public function __construct() {
$this->dictionary_array = str_split($this->dictionary);
}
/**
* Gets ID and converts it into a string.
* @param int $id
*/
public function encode($id) {
$str_id = '';
$base = count($this->dictionary_array);
while ($id > 0) {
$rem = $id % $base;
$id = ($id - $rem) / $base;
$str_id .= $this->dictionary_array[$rem];
}
return $str_id;
}
/**
* Converts /abc into an integer ID
* @param string
* @return int $id
*/
public function decode($str_id) {
$id = 0;
$id_ar = str_split($str_id);
$base = count($this->dictionary_array);
for ($i = count($id_ar); $i > 0; $i--) {
$id += array_search($id_ar[$i - 1], $this->dictionary_array) * pow($base, $i - 1);
}
return $id;
}
}
?>
I had the same problem. The offset appeared after UpdatePanel refresh. The solution was to add an empty tag before the UpdatePanel like this:
<div></div>
...
fyi The code I ended up with:
IF UPDATE (QtyToRepair)
begin
INSERT INTO tmpQtyToRepairChanges (OrderNo, PartNumber, ModifiedDate, ModifiedUser, ModifiedHost, QtyToRepairOld, QtyToRepairNew)
SELECT S.OrderNo, S.PartNumber, GETDATE(), SUSER_NAME(), HOST_NAME(), D.QtyToRepair, I.QtyToRepair FROM SCHEDULE S
INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber
WHERE I.QtyToRepair <> D.QtyToRepair
end
var css_link = $("<link>", {
rel: "stylesheet",
type: "text/css",
href: "yourcustomaddress/bundles/andreistatistics/css/like.css"
});
css_link.appendTo('head');
The correct version of your script is as follows;
FILE="cat test"
$FILE | \
while read CMD; do
echo $CMD
done
However this kind of indirection --putting your command in a variable named FILE-- is unnecessary. Use one of the solutions already provided. I just wanted to point out your mistake.
After migrating from Turbo Pascal to C++ back in the day, I used to do this in order to have an equivalent for the Turbo Pascal "inherited" keyword, which works the same way. However, after programming in C++ for a few years I stopped doing it. I found I just didn't need it very much.
* {_x000D_
padding: 0;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
ul {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
li {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
align-items: center;_x000D_
background: silver;_x000D_
width: 100%;_x000D_
height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
<li>This is the text</li>_x000D_
</ul>
_x000D_
You're so close!
Change
plot "print_1012720" using 1:2 title "Flow 1", \
plot "print_1058167" using 1:2 title "Flow 2", \
plot "print_193548" using 1:2 title "Flow 3", \
plot "print_401125" using 1:2 title "Flow 4", \
plot "print_401275" using 1:2 title "Flow 5", \
plot "print_401276" using 1:2 title "Flow 6"
to
plot "print_1012720" using 1:2 title "Flow 1", \
"print_1058167" using 1:2 title "Flow 2", \
"print_193548" using 1:2 title "Flow 3", \
"print_401125" using 1:2 title "Flow 4", \
"print_401275" using 1:2 title "Flow 5", \
"print_401276" using 1:2 title "Flow 6"
The error arises because gnuplot is trying to interpret the word "plot" as the filename to plot, but you haven't assigned any strings to a variable named "plot" (which is good – that would be super confusing).
See also:
for Microsoft Visual C:
http://msdn.microsoft.com/en-us/library/2e70t5y1%28v=vs.80%29.aspx
and GCC claim compatibility with Microsoft's compiler.:
http://gcc.gnu.org/onlinedocs/gcc/Structure_002dPacking-Pragmas.html
In addition to the previous answers, please note that regardless the packaging, there is no members-order-guarantee in C++. Compilers may (and certainly do) add virtual table pointer and base structures' members to the structure. Even the existence of virtual table is not ensured by the standard (virtual mechanism implementation is not specified) and therefore one can conclude that such guarantee is just impossible.
I'm quite sure member-order is guaranteed in C, but I wouldn't count on it, when writing a cross-platform or cross-compiler program.
Those are called spreads. Just as the name implies. It means it's putting whatever the value of it in those array or objects.
Such as :
let a = [1, 2, 3];
let b = [...a, 4, 5, 6];
console.log(b);
> [1, 2, 3, 4, 5, 6]
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
You can instantiate a Process instance once for the process you want and keep on tracking the process using that .NET Process object (it will keep on tracking till you call Close on that .NET object explicitly, even if the process it was tracking has died [this is to be able to give you time of process close, aka ExitTime etc.])
Quoting http://msdn.microsoft.com/en-us/library/fb4aw7b8.aspx:
When an associated process exits (that is, when it is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called WaitForExit. The Process component can then access the information, which includes the ExitTime, by using the Handle to the exited process.
Because the associated process has exited, the Handle property of the component no longer points to an existing process resource. Instead, the handle can be used only to access the operating system’s information about the process resource. The system is aware of handles to exited processes that have not been released by Process components, so it keeps the ExitTime and Handle information in memory until the Process component specifically frees the resources. For this reason, any time you call Start for a Process instance, call Close when the associated process has terminated and you no longer need any administrative information about it. Close frees the memory allocated to the exited process.
In my case I had a solution with VB Web Forms project that referenced a C# UserControl. Both the VB project and the CS project had a Service Reference to the same service. The reference appeared under Service References in the VB project and under the Connected Services grouping in the CS (framework) project.
In order to update the service reference (ie, get the Reference.vb file to not be empty) in the VB web forms project, I needed to REMOVE THE CS PROJECT, then update the VB Service Reference, then add the CS project back into the solution.
Use the pointtype
and pointsize
options, e.g.
plot "./points.dat" using 1:2 pt 7 ps 10
where pt 7
gives you a filled circle and ps 10
is the size.
See: Plotting data.
LIST="some string with a substring you want to match"
SOURCE="substring"
if echo "$LIST" | grep -q "$SOURCE"; then
echo "matched";
else
echo "no match";
fi
Its simple way
>>import json
>>from collection import OrderedDict
>>json.dumps(dict(OrderedDict([('method', 'constant'), ('data', '1.225')])))
try the following program
using System;
using System.Data;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
System.Data.OleDb.OleDbConnection MyConnection;
System.Data.DataSet DtSet;
System.Data.OleDb.OleDbDataAdapter MyCommand;
MyConnection = new System.Data.OleDb.OleDbConnection(@"provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\csharp.net-informations.xls';Extended Properties=Excel 8.0;");
MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", MyConnection);
MyCommand.TableMappings.Add("Table", "Net-informations.com");
DtSet = new System.Data.DataSet();
MyCommand.Fill(DtSet);
dataGridView1.DataSource = DtSet.Tables[0];
MyConnection.Close();
}
}
}
Well you can hide the close button by changing the FormBorderStyle from the properties section or programmatically in the constructor using:
public Form1()
{
InitializeComponent();
this.FormBorderStyle = FormBorderStyle.None;
}
then you create a menu strip item to exit the application.
cheers
Whenever there are issues of mismatched axis limits, the right tool in base
graphics is to use matplot
. The key is to leverage the from
and to
arguments to density.default
. It's a bit hackish, but fairly straightforward to roll yourself:
set.seed(102349)
x1 = rnorm(1000, mean = 5, sd = 3)
x2 = rnorm(5000, mean = 2, sd = 8)
xrng = range(x1, x2)
#force the x values at which density is
# evaluated to be the same between 'density'
# calls by specifying 'from' and 'to'
# (and possibly 'n', if you'd like)
kde1 = density(x1, from = xrng[1L], to = xrng[2L])
kde2 = density(x2, from = xrng[1L], to = xrng[2L])
matplot(kde1$x, cbind(kde1$y, kde2$y))
Add bells and whistles as desired (matplot
accepts all the standard plot
/par
arguments, e.g. lty
, type
, col
, lwd
, ...).
I like PodTech.io's answer to achieve this without additional tools. For me, it did not run out of the box, so I had to slightly change it. I am not sure if the command wScript.Sleep 12000
(12 sec delay) in the original script is required or not, so I kept it.
Here's the modified script Zip.cmd
based on his answer, which works fine on my end:
@echo off
if "%1"=="" goto end
setlocal
set TEMPDIR=%TEMP%\ZIP
set FILETOZIP=%1
set OUTPUTZIP=%2.zip
if "%2"=="" set OUTPUTZIP=%1.zip
:: preparing VBS script
echo Set objArgs = WScript.Arguments > _zipIt.vbs
echo InputFolder = objArgs(0) >> _zipIt.vbs
echo ZipFile = objArgs(1) >> _zipIt.vbs
echo Set fso = WScript.CreateObject("Scripting.FileSystemObject") >> _zipIt.vbs
echo Set objZipFile = fso.CreateTextFile(ZipFile, True) >> _zipIt.vbs
echo objZipFile.Write "PK" ^& Chr(5) ^& Chr(6) ^& String(18, vbNullChar) >> _zipIt.vbs
echo objZipFile.Close >> _zipIt.vbs
echo Set objShell = WScript.CreateObject("Shell.Application") >> _zipIt.vbs
echo Set source = objShell.NameSpace(InputFolder).Items >> _zipIt.vbs
echo Set objZip = objShell.NameSpace(fso.GetAbsolutePathName(ZipFile)) >> _zipIt.vbs
echo if not (objZip is nothing) then >> _zipIt.vbs
echo objZip.CopyHere(source) >> _zipIt.vbs
echo wScript.Sleep 12000 >> _zipIt.vbs
echo end if >> _zipIt.vbs
@ECHO Zipping, please wait...
mkdir %TEMPDIR%
xcopy /y /s %FILETOZIP% %TEMPDIR%
WScript _zipIt.vbs %TEMPDIR% %OUTPUTZIP%
del _zipIt.vbs
rmdir /s /q %TEMPDIR%
@ECHO ZIP Completed.
:end
Usage:
One parameter (no wildcards allowed here):
Zip FileToZip.txt
will create FileToZip.txt.zip
in the same folder containing the zipped file FileToZip.txt
.
Two parameters (optionally with wildcards for the first parameter), e.g.
Zip *.cmd Scripts
creates Scripts.zip
in the same folder containing all matching *.cmd
files.
Note: If you want to debug the VBS script, check out this hint, it describes how to activate the debugger to go through it step by step.
A simple and cross-platform solution would be to use either the cls
command on Windows, or clear
on Unix systems. Used with os.system
, this makes a nice one-liner:
import os
os.system('cls' if os.name == 'nt' else 'clear')
For New version of Java JavaPath folder is located
64 bit OS
"C:\Program Files \Common Files\Oracle\Java\javapath\"
X86
"C:\Program Files(x86) \Common Files\Oracle\Java\javapath\"
This is answered in the Protractor FAQ: https://github.com/angular/protractor/blob/master/docs/faq.md#the-result-of-gettext-from-an-input-element-is-always-empty
The result of getText from an input element is always empty
This is a webdriver quirk. and elements always have empty getText values. Instead, try:
element.getAttribute('value')
As for question 2, yes, you should be able to use a fully qualified name for by.binding. I suspect that your template does not actually having an element that is bound to risk.name via {{}} or ng-bind.
First of all you should fix modal HTML structure. Now it's not correct, you don't need class .hide
:
<div id="edit-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body edit-content">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
Then links should point to this modal via data-target
attribute:
<a href="#myModal" data-toggle="modal" id="1" data-target="#edit-modal">Edit 1</a>
Finally Js part becomes very simple:
$('#edit-modal').on('show.bs.modal', function(e) {
var $modal = $(this),
esseyId = e.relatedTarget.id;
$.ajax({
cache: false,
type: 'POST',
url: 'backend.php',
data: 'EID=' + essayId,
success: function(data) {
$modal.find('.edit-content').html(data);
}
});
})
echo '<span style="Your CSS Styles">' . $ip['cityName'] . '</span>';
The search query
model lives in the scope defined by the ng-controller="whatever"
directive. So if you want to bind the query model to <title>
, you have to move the ngController
declaration to an HTML element that is a common parent to both the body and title elements:
<html ng-app="phonecatApp" ng-controller="PhoneListCtrl">
From the documentation of the DBNull class:
Do not confuse the notion of null in an object-oriented programming language with a DBNull object. In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column.
Be aware that when you do press your <leader>
key you have only 1000ms (by default) to enter the command following it.
This is exacerbated because there is no visual feedback (by default) that you have pressed your <leader>
key and vim is awaiting the command; and so there is also no visual way to know when this time out has happened.
If you add set showcmd
to your vimrc
then you will see your <leader>
key appear in the bottom right hand corner of vim (to the left of the cursor location) and perhaps more importantly you will see it disappear when the time out happens.
The length of the timeout can also be set in your vimrc
, see :help timeoutlen
for more information.
The behavior of Excel when opening CSV files heavily depends on your local settings and the selected list separator under Region and language » Formats » Advanced. By default Excel will assume every CSV was saved with that separator. Which is true as long as the CSV doesn't come from another country!
If your customers are in other countries, they may see other results then you think.
For example, here you see that a German Excel will use semicolon instead of comma like in the U.S.
import java.util.Arrays;
public class Main {
public static void main(String[] args)
{
double[][] test = { {100}, {200}, {300}, {400}, {500}, {600}, {700}, {800}, {900}, {1000}};
int [][] removeRow = { {0}, {1}, {3}, {4}, };
double[][] newTest = new double[test.length - removeRow.length][test[0].length];
for (int i = 0, j = 0, k = 0; i < test.length; i++) {
if (j < removeRow.length) {
if (i == removeRow[j][0]) {
j++;
continue;
}
}
newTest[k][0] = test[i][0];
k++;
}
System.out.println(Arrays.deepToString(newTest));
}
}
This is, in effect, a way to check whether the expression e can be evaluated to be 0, and if not, to fail the build.
The macro is somewhat misnamed; it should be something more like BUILD_BUG_OR_ZERO
, rather than ...ON_ZERO
. (There have been occasional discussions about whether this is a confusing name.)
You should read the expression like this:
sizeof(struct { int: -!!(e); }))
(e)
: Compute expression e
.
!!(e)
: Logically negate twice: 0
if e == 0
; otherwise 1
.
-!!(e)
: Numerically negate the expression from step 2: 0
if it was 0
; otherwise -1
.
struct{int: -!!(0);} --> struct{int: 0;}
: If it was zero, then we declare a struct with an anonymous integer bitfield that has width zero. Everything is fine and we proceed as normal.
struct{int: -!!(1);} --> struct{int: -1;}
: On the other hand, if it isn't zero, then it will be some negative number. Declaring any bitfield with negative width is a compilation error.
So we'll either wind up with a bitfield that has width 0 in a struct, which is fine, or a bitfield with negative width, which is a compilation error. Then we take sizeof
that field, so we get a size_t
with the appropriate width (which will be zero in the case where e
is zero).
Some people have asked: Why not just use an assert
?
keithmo's answer here has a good response:
These macros implement a compile-time test, while assert() is a run-time test.
Exactly right. You don't want to detect problems in your kernel at runtime that could have been caught earlier! It's a critical piece of the operating system. To whatever extent problems can be detected at compile time, so much the better.
Use an image editor to cut out a portion of the background, then apply CSS's background-repeat property to make the small image fill the area where it is used.
In some cases, background-repeat creates seams where the image repeats. A solution is to use an image editor as follows: starting with the background image, copy the image, flip (mirror, not rotate) the copy left-to-right, and paste it to the right edge of the original, overlapping 1 pixel. Crop to remove 1 pixel from the right edge of the combined image. Now repeat for the vertical: copy the combined image, flip the copy top-to-bottom, paste it to the bottom of the combined, overlapping one pixel. Crop to remove 1 pixel from the bottom. The resulting image should be seam-free.
You can use Phantombuster. Instagram has set some rate limit, so you will have to use either multiple accounts or wait for 15 minutes for the next run.
var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
conn.Open();
var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
using (var cmd = conn.CreateCommand())
{
cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";
var adapter = new OleDbDataAdapter(cmd);
var ds = new DataSet();
adapter.Fill(ds);
}
}
Apple recommends against relying on the fileExistAtPath: method. It's often better to just try to open a file and deal with the error if the file does not exist.
NSFileManager Class Reference
Note: Attempting to predicate behavior based on the current state of the file system or a particular file on the file system is not recommended. Doing so can cause odd behavior or race conditions. It's far better to attempt an operation (such as loading a file or creating a directory), check for errors, and handle those errors gracefully than it is to try to figure out ahead of time whether the operation will succeed. For more information on file system race conditions, see “Race Conditions and Secure File Operations” in Secure Coding Guide.
Source: Apple Developer API Reference
From the secure coding guide.
To prevent this, programs often check to make sure a temporary file with a specific name does not already exist in the target directory. If such a file exists, the application deletes it or chooses a new name for the temporary file to avoid conflict. If the file does not exist, the application opens the file for writing, because the system routine that opens a file for writing automatically creates a new file if none exists. An attacker, by continuously running a program that creates a new temporary file with the appropriate name, can (with a little persistence and some luck) create the file in the gap between when the application checked to make sure the temporary file didn’t exist and when it opens it for writing. The application then opens the attacker’s file and writes to it (remember, the system routine opens an existing file if there is one, and creates a new file only if there is no existing file). The attacker’s file might have different access permissions than the application’s temporary file, so the attacker can then read the contents. Alternatively, the attacker might have the file already open. The attacker could replace the file with a hard link or symbolic link to some other file (either one owned by the attacker or an existing system file). For example, the attacker could replace the file with a symbolic link to the system password file, so that after the attack, the system passwords have been corrupted to the point that no one, including the system administrator, can log in.
In case anyone else finds this thread with my problem -- I was using an "integer" column type in MySQL. The row I was attempting to insert had a primary key with a value larger than allowed by integer. Switching to "bigint" fixed the problem.
I'd suggest using such extension method:
public static class DataColumnCollectionExtensions
{
public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
{
return source.Cast<DataColumn>();
}
}
And therefore:
string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();
You may also implement one more extension method for DataTable
class to reduce code:
public static class DataTableExtensions
{
public static IEnumerable<DataColumn> GetColumns(this DataTable source)
{
return source.Columns.AsEnumerable();
}
}
And use it as follows:
string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();
Removing hashCode()
and equals()
solved my issue. In my case, I used Apache's commons-lang hash code and equals builders for creating non-static classes manually, so the compiler didn't throw any exception. But at runtime it caused the invocation exception.
You can do something like this, without using any external libraries.
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.txt");
https.get("https://www.w3.org/TR/PNG/iso_8859-1.txt", response => {
var stream = response.pipe(file);
stream.on("finish", function() {
console.log("done");
});
});
Other posters have already explained why the :focus
pseudo class is insufficient, but finally there is a CSS-based standard solution.
CSS Selectors Level 4 defines a new pseudo class:
From MDN:
The
:focus-within
CSS pseudo-class matches any element that the:focus
pseudo-class matches or that has a descendant that the:focus
pseudo-class matches. (This includes descendants in shadow trees.)
So now with the :focus-within
pseudo class - styling the outer div when the textarea
gets clicked becomes trivial.
.box:focus-within {
border: thin solid black;
}
.box {_x000D_
width: 300px;_x000D_
height: 300px;_x000D_
border: 5px dashed red;_x000D_
}_x000D_
_x000D_
.box:focus-within {_x000D_
border: 5px solid green;_x000D_
}
_x000D_
<p>The outer box border changes when the textarea gets focus.</p>_x000D_
<div class="box">_x000D_
<textarea rows="10" cols="25"></textarea>_x000D_
</div>
_x000D_
NB: Browser Support : Chrome (60+), Firefox and Safari
I cross over the same problem
I put the following code in the folder ~/.gvimrc
and it works.
set guifont=Monaco:h20
Pressing ESC quits from insert mode to normal mode, where you can press : to type in a command. Press i again to back to insert mode, and you are good to go.
I'm not a Vim guru, so someone else can be more experienced and give you other options.
For reference from SQL Server 2016 SP1+
you could use CREATE OR ALTER VIEW
syntax.
CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ]
OR ALTER
Conditionally alters the view only if it already exists.
Git has three modes of how it treats line endings:
$ git config core.autocrlf
# that command will print "true" or "false" or "input"
You can set the mode to use by adding an additional parameter of true
or false
to the above command line.
If core.autocrlf
is set to true, that means that any time you add a file to the git repo that git thinks is a text file, it will turn all CRLF line endings to just LF before it stores it in the commit. Whenever you git checkout
something, all text files automatically will have their LF line endings converted to CRLF endings. This allows development of a project across platforms that use different line-ending styles without commits being very noisy because each editor changes the line ending style as the line ending style is always consistently LF.
The side-effect of this convenient conversion, and this is what the warning you're seeing is about, is that if a text file you authored originally had LF endings instead of CRLF, it will be stored with LF as usual, but when checked out later it will have CRLF endings. For normal text files this is usually just fine. The warning is a "for your information" in this case, but in case git incorrectly assesses a binary file to be a text file, it is an important warning because git would then be corrupting your binary file.
If core.autocrlf
is set to false, no line-ending conversion is ever performed, so text files are checked in as-is. This usually works ok, as long as all your developers are either on Linux or all on Windows. But in my experience I still tend to get text files with mixed line endings that end up causing problems.
My personal preference is to leave the setting turned ON, as a Windows developer.
See http://kernel.org/pub/software/scm/git/docs/git-config.html for updated info that includes the "input" value.
Just say: $("#divID").html($('').html($("#divID").html()));
You're declaring a virtual
function and not defining it:
virtual void calculateCredits();
Either define it or declare it as:
virtual void calculateCredits() = 0;
Or simply:
virtual void calculateCredits() { };
Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
Simple and thorough:
function isNumber(x) {
return parseFloat(x) == x
};
Test cases:
console.log('***TRUE CASES***');
console.log(isNumber(0));
console.log(isNumber(-1));
console.log(isNumber(-500));
console.log(isNumber(15000));
console.log(isNumber(0.35));
console.log(isNumber(-10.35));
console.log(isNumber(2.534e25));
console.log(isNumber('2.534e25'));
console.log(isNumber('52334'));
console.log(isNumber('-234'));
console.log(isNumber(Infinity));
console.log(isNumber(-Infinity));
console.log(isNumber('Infinity'));
console.log(isNumber('-Infinity'));
console.log('***FALSE CASES***');
console.log(isNumber(NaN));
console.log(isNumber({}));
console.log(isNumber([]));
console.log(isNumber(''));
console.log(isNumber('one'));
console.log(isNumber(true));
console.log(isNumber(false));
console.log(isNumber());
console.log(isNumber(undefined));
console.log(isNumber(null));
console.log(isNumber('-234aa'));
Two options: 1, add css inline like style="background:black" Or 2. In the head include the css as a style tag block.
var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
The answers above me works. But, I'd like to contribute a method on how to perform it using GET
on your html/php page
$File = 'some/dir/file.jpg';
<a href="<?php echo '../sumdir/download.php?f='.$File; ?>" target="_blank">Download</a>
and download.php
contains
$file = $_GET['f'];
header("Expires: 0");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-store, no-cache, must-revalidate");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
$ext = pathinfo($file, PATHINFO_EXTENSION);
$basename = pathinfo($file, PATHINFO_BASENAME);
header("Content-type: application/".$ext);
header('Content-length: '.filesize($file));
header("Content-Disposition: attachment; filename=\"$basename\"");
ob_clean();
flush();
readfile($file);
exit;
this should work on any file types. this is not tested using POST, but it could work.
public ActionResult Index()
{
List<CustomerOrder_Result> obj = new List<CustomerOrder_Result>();
var orderlist = (from a in db.OrderMasters
join b in db.Customers on a.CustomerId equals b.Id
join c in db.CustomerAddresses on b.Id equals c.CustomerId
where a.Status == "Pending"
select new
{
Customername = b.Customername,
Phone = b.Phone,
OrderId = a.OrderId,
OrderDate = a.OrderDate,
NoOfItems = a.NoOfItems,
Order_amt = a.Order_amt,
dis_amt = a.Dis_amt,
net_amt = a.Net_amt,
status=a.Status,
address = c.address,
City = c.City,
State = c.State,
Pin = c.Pin
}) ;
foreach (var item in orderlist)
{
CustomerOrder_Result clr = new CustomerOrder_Result();
clr.Customername=item.Customername;
clr.Phone = item.Phone;
clr.OrderId = item.OrderId;
clr.OrderDate = item.OrderDate;
clr.NoOfItems = item.NoOfItems;
clr.Order_amt = item.Order_amt;
clr.net_amt = item.net_amt;
clr.address = item.address;
clr.City = item.City;
clr.State = item.State;
clr.Pin = item.Pin;
clr.status = item.status;
obj.Add(clr);
}
From plt.imshow()
official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 10000, 0, 10], aspect = 1000)
Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.
plt.imshow(data, origin = 'lower', extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')
To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1]
and y_max - y_min = y_res * data.shape[0]
, where extent = [x_min, x_max, y_min, y_max]
. By default, aspect = 1
, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower', extent = [0, 5, 0, 5])
The aspect of color pixel is x_res / y_res
. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])
) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.5)
The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.
plt.imshow(data, origin = 'lower', extent = [0, 15, 0, 10], aspect = 1.2)
Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.
A good approach is to have a common base class for all your entities. In this base class, you can have your id property if it is commonly named in all your entities (a common design), your creation and last update date properties.
For the creation date, you simply keep a java.util.Date property. Be sure, to always initialize it with new Date().
For the last update field, you can use a Timestamp property, you need to map it with @Version. With this Annotation the property will get updated automatically by Hibernate. Beware that Hibernate will also apply optimistic locking (it's a good thing).
I was having the same problem. When I initially created the java project in Eclipse I specified JRE 8. When I went into the project's build path and edited the JRE System Library, the Java 8 execution environment was selected. When I chose to use an "Alernate JRE" (still java 8) it fixed the error for me.
Username you get like this:
var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;
How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...
To delete all stashes older than 40 days, use:
git reflog expire --expire-unreachable=40.days refs/stash
Add --dry-run
to see which stashes are deleted.
See https://stackoverflow.com/a/44829516/946850 for an explanation and much more detail.
Haven't seen this solution yet so here's how I did it without using read_csv:
df.rename(columns={'A':'','B':''})
If you rename all your column names to empty strings your table will return without a header.
And if you have a lot of columns in your table you can just create a dictionary first instead of renaming manually:
df_dict = dict.fromkeys(df.columns, '')
df.rename(columns = df_dict)
Example:
$ svn propset svn:ignore -F .cvsignore .
property 'svn:ignore' set on '.'
You can read a group of txt files in a folder and echo the contents like this.
<?php
$directory = "folder/";
$dir = opendir($directory);
$filenames = [];
while (($file = readdir($dir)) !== false) {
$filename = $directory . $file;
$type = filetype($filename);
if($type !== 'file') continue;
$filenames[] = $filename;
}
closedir($dir);
?>
The POSIX standard mandates that multiple /
are treated as a single /
in a file name. Thus
//dir///subdir////file
is the same as /dir/subdir/file
.
As such concatenating a two strings to build a complete path is a simple as:
full_path="$part1/$part2"
Here is the content of the file MessageBoxManager.cs
#pragma warning disable 0618
using System;
using System.Text;
using System.Runtime.InteropServices;
using System.Security.Permissions;
[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true)]
namespace System.Windows.Forms
{
public class MessageBoxManager
{
private delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);
private delegate bool EnumChildProc(IntPtr hWnd, IntPtr lParam);
private const int WH_CALLWNDPROCRET = 12;
private const int WM_DESTROY = 0x0002;
private const int WM_INITDIALOG = 0x0110;
private const int WM_TIMER = 0x0113;
private const int WM_USER = 0x400;
private const int DM_GETDEFID = WM_USER + 0;
private const int MBOK = 1;
private const int MBCancel = 2;
private const int MBAbort = 3;
private const int MBRetry = 4;
private const int MBIgnore = 5;
private const int MBYes = 6;
private const int MBNo = 7;
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(IntPtr hWnd, int Msg, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll")]
private static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);
[DllImport("user32.dll")]
private static extern int UnhookWindowsHookEx(IntPtr idHook);
[DllImport("user32.dll")]
private static extern IntPtr CallNextHookEx(IntPtr idHook, int nCode, IntPtr wParam, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetWindowTextLengthW", CharSet = CharSet.Unicode)]
private static extern int GetWindowTextLength(IntPtr hWnd);
[DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)]
private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxLength);
[DllImport("user32.dll")]
private static extern int EndDialog(IntPtr hDlg, IntPtr nResult);
[DllImport("user32.dll")]
private static extern bool EnumChildWindows(IntPtr hWndParent, EnumChildProc lpEnumFunc, IntPtr lParam);
[DllImport("user32.dll", EntryPoint = "GetClassNameW", CharSet = CharSet.Unicode)]
private static extern int GetClassName(IntPtr hWnd, StringBuilder lpClassName, int nMaxCount);
[DllImport("user32.dll")]
private static extern int GetDlgCtrlID(IntPtr hwndCtl);
[DllImport("user32.dll")]
private static extern IntPtr GetDlgItem(IntPtr hDlg, int nIDDlgItem);
[DllImport("user32.dll", EntryPoint = "SetWindowTextW", CharSet = CharSet.Unicode)]
private static extern bool SetWindowText(IntPtr hWnd, string lpString);
[StructLayout(LayoutKind.Sequential)]
public struct CWPRETSTRUCT
{
public IntPtr lResult;
public IntPtr lParam;
public IntPtr wParam;
public uint message;
public IntPtr hwnd;
};
private static HookProc hookProc;
private static EnumChildProc enumProc;
[ThreadStatic]
private static IntPtr hHook;
[ThreadStatic]
private static int nButton;
/// <summary>
/// OK text
/// </summary>
public static string OK = "&OK";
/// <summary>
/// Cancel text
/// </summary>
public static string Cancel = "&Cancel";
/// <summary>
/// Abort text
/// </summary>
public static string Abort = "&Abort";
/// <summary>
/// Retry text
/// </summary>
public static string Retry = "&Retry";
/// <summary>
/// Ignore text
/// </summary>
public static string Ignore = "&Ignore";
/// <summary>
/// Yes text
/// </summary>
public static string Yes = "&Yes";
/// <summary>
/// No text
/// </summary>
public static string No = "&No";
static MessageBoxManager()
{
hookProc = new HookProc(MessageBoxHookProc);
enumProc = new EnumChildProc(MessageBoxEnumProc);
hHook = IntPtr.Zero;
}
/// <summary>
/// Enables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// MessageBoxManager functionality is enabled on current thread only.
/// Each thread that needs MessageBoxManager functionality has to call this method.
/// </remarks>
public static void Register()
{
if (hHook != IntPtr.Zero)
throw new NotSupportedException("One hook per thread allowed.");
hHook = SetWindowsHookEx(WH_CALLWNDPROCRET, hookProc, IntPtr.Zero, AppDomain.GetCurrentThreadId());
}
/// <summary>
/// Disables MessageBoxManager functionality
/// </summary>
/// <remarks>
/// Disables MessageBoxManager functionality on current thread only.
/// </remarks>
public static void Unregister()
{
if (hHook != IntPtr.Zero)
{
UnhookWindowsHookEx(hHook);
hHook = IntPtr.Zero;
}
}
private static IntPtr MessageBoxHookProc(int nCode, IntPtr wParam, IntPtr lParam)
{
if (nCode < 0)
return CallNextHookEx(hHook, nCode, wParam, lParam);
CWPRETSTRUCT msg = (CWPRETSTRUCT)Marshal.PtrToStructure(lParam, typeof(CWPRETSTRUCT));
IntPtr hook = hHook;
if (msg.message == WM_INITDIALOG)
{
int nLength = GetWindowTextLength(msg.hwnd);
StringBuilder className = new StringBuilder(10);
GetClassName(msg.hwnd, className, className.Capacity);
if (className.ToString() == "#32770")
{
nButton = 0;
EnumChildWindows(msg.hwnd, enumProc, IntPtr.Zero);
if (nButton == 1)
{
IntPtr hButton = GetDlgItem(msg.hwnd, MBCancel);
if (hButton != IntPtr.Zero)
SetWindowText(hButton, OK);
}
}
}
return CallNextHookEx(hook, nCode, wParam, lParam);
}
private static bool MessageBoxEnumProc(IntPtr hWnd, IntPtr lParam)
{
StringBuilder className = new StringBuilder(10);
GetClassName(hWnd, className, className.Capacity);
if (className.ToString() == "Button")
{
int ctlId = GetDlgCtrlID(hWnd);
switch (ctlId)
{
case MBOK:
SetWindowText(hWnd, OK);
break;
case MBCancel:
SetWindowText(hWnd, Cancel);
break;
case MBAbort:
SetWindowText(hWnd, Abort);
break;
case MBRetry:
SetWindowText(hWnd, Retry);
break;
case MBIgnore:
SetWindowText(hWnd, Ignore);
break;
case MBYes:
SetWindowText(hWnd, Yes);
break;
case MBNo:
SetWindowText(hWnd, No);
break;
}
nButton++;
}
return true;
}
}
}
def round_to_next5(n):
return n + (5 - n) % 5
using System.Diagnostics;
class Program
{
static void Main()
{
Process.Start("C:\\");
}
}
If your application needs cmd arguments, use something like this:
using System.Diagnostics;
class Program
{
static void Main()
{
LaunchCommandLineApp();
}
/// <summary>
/// Launch the application with some options set.
/// </summary>
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
}
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>
, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
A good resource start off point would be MSDN as your looking into a microsoft product
Use DATE(NOW())
to compare dates
DATE(NOW())
will give you the date part of current date and DATE(duedate)
will give you the date part of the due date. then you can easily compare the dates
So you can compare it like
DATE(NOW()) = DATE(duedate)
OR
DATE(duedate) = CURDATE()
See here
You can configure your build.gradle file for proguard implementation. It can be at module level or the project level.
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
The configuration shown is for debug level but you can write you own build flavors like shown below inside buildTypes:
myproductionbuild{
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
Better to have your debug with minifyEnabled false
and productionbuild and other builds as minifyEnabled true
.
Copy your proguard-rules.txt file in the root of your module or project folder like
$YOUR_PROJECT_DIR\YoutProject\yourmodule\proguard-rules.txt
You can change the name of your file as you want. After configuration use one of the three options available to generate your build as per the buildType
Go to gradle task in right panel and search for assembleRelease/assemble(#your_defined_buildtype)
under module tasks
Go to Build Variant in Left Panel and select the build from drop down
Go to project root directory in File Explorer and open cmd/terminal and run
Linux ./gradlew assembleRelease or assemble(#your_defined_buildtype)
Windows gradlew assembleRelease or assemble(#your_defined_buildtype)
You can find apk in your module/build directory.
More about the configuration and proguard files location is available at the link
http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Running-ProGuard
Simply speaking Unicode
is a standard which assigned one number (called code point) to all characters of the world (Its still work in progress).
Now you need to represent this code points using bytes, thats called character encoding
. UTF-8, UTF-16, UTF-6
are ways of representing those characters.
UTF-8
is multibyte character encoding. Characters can have 1 to 6 bytes (some of them may be not required right now).
UTF-32
each characters have 4 bytes a characters.
UTF-16
uses 16 bits for each character and it represents only part of Unicode characters called BMP (for all practical purposes its enough). Java uses this encoding in its strings.
The Python package drawnow allows to update a plot in real time in a non blocking way.
It also works with a webcam and OpenCV for example to plot measures for each frame.
See the original post.
You can't. and the reason is that they do not "live" in the same time. The Razor variables are "Server side variables" and they don't exist anymore after the page was sent to the "Client side".
When the server get a request for a view, it creates the view with only HTML, CSS and Javascript code. No C# code is left, it's all get "translated" to the client side languages.
The Javascript code DOES exist when the view is still on the server, but it's meaningless and will be executed by the browser only (Client side again).
This is why you can use Razor variables to change the HTML and Javascript but not vice versa. Try to look at your page source code (CTRL+U in most browsers), there will be no sign of C# code there.
In short:
The server gets a request.
The server creates or "takes" the view, then computes and translates all the C# code that was embedded in the view to CSS, Javascript, and HTML.
The server returns the client side version of the view to the browser as a response to the request. (there is no C# at this point anymore)
the browser renders the page and executes all the Javascript