Try this, It worked for me
SELECT * FROM (
SELECT
[Code],
[Name],
[CategoryCode],
[CreatedDate],
[ModifiedDate],
[CreatedBy],
[ModifiedBy],
[IsActive],
ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
FROM MasterTable
) a
WHERE rownumber = 1
Lists are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.
Tuples are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.
Dictionaries are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - tare similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book.
Python is only a language, to get GET and POST data, you need a web framework or toolkit written in Python. Django is one, as Charlie points out, the cgi and urllib standard modules are others. Also available are Turbogears, Pylons, CherryPy, web.py, mod_python, fastcgi, etc, etc.
In Django, your view functions receive a request argument which has request.GET and request.POST. Other frameworks will do it differently.
I don't think there's any reason to add this function to JQuery's namespace. Why not just define the method by itself:
function showMessage(msg) {
alert(msg);
};
<input type="button" value="ahaha" onclick="showMessage('msg');" />
UPDATE: With a small change to how your method is defined I can get it to work:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="javascript">
// define the function within the global scope
$.fn.MessageBox = function(msg) {
alert(msg);
};
// or, if you want to encapsulate variables within the plugin
(function($) {
$.fn.MessageBoxScoped = function(msg) {
alert(msg);
};
})(jQuery); //<-- make sure you pass jQuery into the $ parameter
</script>
</head>
<body>
<div class="Title">Welcome!</div>
<input type="button" value="ahaha" id="test" onClick="$(this).MessageBox('msg');" />
</body>
</html>
requireContext() method is the simplest option
requireContext()
Example
MyDatabase(requireContext())
There are two options I'd like to present:
1: Add getSupportActionBar().hide(); to your onCreate method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
}
2: Another option is to change the style of your Application. Check out the styles.xml in "app->res->values" and change
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Came across this question just now and have something to add
To go to the most recent commit:
git checkout $(git log --branches -1 --pretty=format:"%H")
Explanation:
git log --branches
shows log of commits from all local branches
-1
limit to one commit → most recent commit
--pretty=format:"%H"
format to only show commit hash
git checkout $(...)
use output of subshell as argument for checkout
Note:
This will result in a detached head though (because we checkout directly to the commit). This can be avoided by extracting the branch name using sed
, explained below.
To go to the branch of the most recent commit:
git checkout $(git log --branches -1 --pretty=format:'%D' | sed 's/.*, //g')
Explanation:
git log --branches
shows log of commits from all local branches
-1
limit to one commit → most recent commit
--pretty=format:"%D"
format to only show ref names
| sed 's/.*, //g'
ignore all but the last of multiple refs (*)
git checkout $(...)
use output of subshell as argument for checkout
*) HEAD and remote branches are listed first, local branches are listed last in alphabetically descending order, so the one remaining will be the alphabetically first branch name
Note:
This will always only use the (alphabetically) first branch name if there are multiple for that commit.
Anyway, I think the best solution would just be to display the ref names for the most recent commit to know where to checkout to:
git log --branches -1 --pretty=format:'%D'
E.g. create the alias git top
for that command.
Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)
import numpy as np
a = np.array([(1,2,3), (4,5,6)])
b = a.transpose()
git checkout master
git pull origin master
# Merge branch test into master
git merge test
After merging, if the file is changed, then when you merge it will through error of "Resolve Conflict"
So then you need to first resolve all your conflicts then, you have to again commit all your changes and then push
git push origin master
This is better do who has done changes in test branch, because he knew what changes he has done.
There are 2 things you must accomplish to serve the assets in production:
1) In order to precompile the assets, you have several choices.
You can run rake assets:precompile
on your local machine, commit it to source code control (git), then run the deployment program, for example capistrano. This is not a good way to commit precompiled assets to SCM.
You can write a rake task that run RAILS_ENV=production rake assets:precompile
on the target servers each time you deploy your Rails app to production, before you restart the server.
Code in a task for capistrano will look similar to this:
on roles(:app) do
if DEPLOY_ENV == 'production'
execute("cd #{DEPLOY_TO_DIR}/current && RAILS_ENV=production rvm #{ruby_string} do rake assets:precompile")
end
end
2) Now, you have the assets on production servers, you need to serve them to browser.
Again, you have several choices.
Turn on Rails static file serving in config/environments/production.rb
config.serve_static_assets = true # old or config.serve_static_files = true # new
Using Rails to serve static files will kill your Rails app performance.
Configure nginx (or Apache) to serve static files.
For example, my nginx that was configured to work with Puma looks like this:
location ~ ^/(assets|images|fonts)/(.*)$ {
alias /var/www/foster_care/current/public/$1/$2;
gzip on;
expires max;
add_header Cache-Control public;
}
The sane way to do this is to use zip()
and a List Comprehension / Generator Expression:
filtered = (
(email, other)
for email, other in zip(emails, other_list)
if email == '[email protected]')
new_emails, new_other_list = zip(*filtered)
Also, if your'e not using array.array()
or numpy.array()
, then most likely you are using []
or list()
, which give you Lists, not Arrays. Not the same thing.
class Rectangle : public Area<int> {
};
package main
import (
"fmt"
"time"
)
func main() {
v , _ := time.Now().UTC().MarshalText()
fmt.Println(string(v))
}
Output : 2009-11-10T23:00:00Z
You can also add an extension method to the Enum type rather than an instance of the Enum:
/// <summary> Enum Extension Methods </summary>
/// <typeparam name="T"> type of Enum </typeparam>
public class Enum<T> where T : struct, IConvertible
{
public static int Count
{
get
{
if (!typeof(T).IsEnum)
throw new ArgumentException("T must be an enumerated type");
return Enum.GetNames(typeof(T)).Length;
}
}
}
You can invoke the extension method above by doing:
var result = Enum<Duration>.Count;
It's not a true extension method. It only works because Enum<> is a different type than System.Enum.
The simple answer is to use the HttpRequest.UserHostAddress property.
Example: From within a Controller:
using System;
using System.Web.Mvc;
namespace Mvc.Controllers
{
public class HomeController : ClientController
{
public ActionResult Index()
{
string ip = Request.UserHostAddress;
...
}
}
}
Example: From within a helper class:
using System.Web;
namespace Mvc.Helpers
{
public static class HelperClass
{
public static string GetIPHelper()
{
string ip = HttpContext.Current.Request.UserHostAddress;
..
}
}
}
BUT, if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.
Proxy servers MAY use the de facto standard of placing the client's IP address in the X-Forwarded-For HTTP header. Aside from there is no guarantee that a request has a X-Forwarded-For header, there is also no guarantee that the X-Forwarded-For hasn't been SPOOFED.
Original Answer
Request.UserHostAddress
The above code provides the Client's IP address without resorting to looking up a collection. The Request property is available within Controllers (or Views). Therefore instead of passing a Page class to your function you can pass a Request object to get the same result:
public static string getIPAddress(HttpRequestBase request)
{
string szRemoteAddr = request.UserHostAddress;
string szXForwardedFor = request.ServerVariables["X_FORWARDED_FOR"];
string szIP = "";
if (szXForwardedFor == null)
{
szIP = szRemoteAddr;
}
else
{
szIP = szXForwardedFor;
if (szIP.IndexOf(",") > 0)
{
string [] arIPs = szIP.Split(',');
foreach (string item in arIPs)
{
if (!isPrivateIP(item))
{
return item;
}
}
}
}
return szIP;
}
I would suggest not to use list-style-image
, as it behaves quite differently in different browsers, especially the image position
instead, you can use something like this
ol.widgets,
ol.widgets li { list-style: none; }
ol.widgets li { padding-left: 20px; backgroud: transparent ("image") no-repeat x y; }
it works in all browsers and would give you the identical result in different browsers.
Both
-Djavax.net.ssl.trustStore=path/to/trustStore.jks
and
System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");
do the same thing and have no difference working wise. In your case you just have a typo. You have misspelled trustStore
in javax.net.ssl.trustStore.
This is the best option to cast/convert list of generic object to list of string.
object valueList;
List<string> list = ((IList)valueList).Cast<object>().Select(o => o.ToString()).ToList();
That is a pretty standard use case for apply()
:
R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
start end newcol
1 1 2 1.5
2 3 6 4.5
3 5 7 6.0
4 7 9 8.0
R>
You can also use plyr
if you prefer but here is no real need to go beyond functions from base R.
The combination of both answers. Also prints a method name:
Class thisClass = new Object(){}.getClass();
String className = thisClass.getEnclosingClass().getSimpleName();
String methodName = thisClass.getEnclosingMethod().getName();
Log.d("app", className + ":" + methodName);
This might help:
If the adb connection is ever lost:
Make sure that your host is still connected to the same Wi-Fi network your Android device is.
Reconnect by executing the "adb connect IP" step. (IP is obviously different when you change location.)
Or if that doesn't work, reset your adb host:
adb kill-server
and then start over from the beginning.
In npm 6.x you can use
npm i --package-lock-only
According to https://docs.npmjs.com/cli/install.html
The --package-lock-only argument will only update the package-lock.json, instead of checking node_modules and downloading dependencies.
In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().
Using ForEach:
List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
if(eachCategory.toString().equals("3")){
String name = eachCategory.name();
}
});
Or, using Filter:
When you want to find with code:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
When you want to find with name:
List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);
System.out.println(category.toString() + " " + category.name());
Hope it helps! I know this is a very old post, but someone can get help.
In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .
i hope this will resolve your problem
It means it’ll do nothing. It’s an attempt to have the link not ‘navigate’ anywhere. But it’s not the right way.
You should actually just return false
in the onclick
event, like so:
<a href="#" onclick="return false;">hello</a>
Typically it’s used if the link is doing some ‘JavaScript-y’ thing. Like posting an AJAX form, or swapping an image, or whatever. In that case you just make whatever function is being called return false
.
To make your website completely awesome, however, generally you’ll include a link that does the same action, if the person browsing it chooses not to run JavaScript.
<a href="backup_page_displaying_image.aspx"
onclick="return coolImageDisplayFunction();">hello</a>
I think the Key and IV used for encryption using command line and decryption using your program are not same.
Please note that when you use the "-k" (different from "-K"), the input given is considered as a password from which the key is derived. Generally in this case, there is no need for the "-iv" option as both key and password will be derived from the input given with "-k" option.
It is not clear from your question, how you are ensuring that the Key and IV are same between encryption and decryption.
In my suggestion, better use "-K" and "-iv" option to explicitly specify the Key and IV during encryption and use the same for decryption. If you need to use "-k", then use the "-p" option to print the key and iv used for encryption and use the same in your decryption program.
More details can be obtained at https://www.openssl.org/docs/manmaster/apps/enc.html
It's difficult to tell what you're actually trying to do and if this is what you really need but you might also use a callback:
function myFunction(value1,callback)
{
//Do stuff and
if(typeof callback == 'function'){
callback(somevalue2,somevalue3);
}
}
myFunction("1", function(value2, value3){
if(value2 && value3)
{
//Do some stuff
}
});
To expand on @PhiLho answer, you can center a very large image (or any size image) on a page with:
{
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
Or you could use a smaller image with a background color that matches the background of the image (if it is a solid color). This may or may not suit your purposes.
{
background-color: green;
background-image: url(_images/home.jpg);
background-repeat:no-repeat;
background-position:center;
}
It's simple-
SELECT empname,
empid,
(SELECT COUNT (profileid)
FROM profile
WHERE profile.empid = employee.empid)
AS number_of_profiles
FROM employee;
It is even simpler when you use a table join like this:
SELECT e.empname, e.empid, COUNT (p.profileid) AS number_of_profiles
FROM employee e LEFT JOIN profile p ON e.empid = p.empid
GROUP BY e.empname, e.empid;
Explanation for the subquery:
Essentially, a subquery in a select
gets a scalar value and passes it to the main query. A subquery in select
is not allowed to pass more than one row and more than one column, which is a restriction. Here, we are passing a count
to the main query, which, as we know, would always be only a number- a scalar value. If a value is not found, the subquery returns null
to the main query. Moreover, a subquery can access columns from the from
clause of the main query, as shown in my query where employee.empid
is passed from the outer query to the inner query.
Edit:
When you use a subquery in a select
clause, Oracle essentially treats it as a left join (you can see this in the explain plan for your query), with the cardinality of the rows being just one on the right for every row in the left.
Explanation for the left join
A left join is very handy, especially when you want to replace the select
subquery due to its restrictions. There are no restrictions here on the number of rows of the tables in either side of the LEFT JOIN
keyword.
For more information read Oracle Docs on subqueries and left join or left outer join.
This should work.
app = angular.module('plunker', [])
app.controller 'MainCtrl', ($scope) ->
$scope.users = ['bob', 'sean', 'rocky', 'john']
$scope.test = ->
console.log $scope.users
HTML:
<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />
I used it like this:
@media (max-width: 450px) {
br {
display: none;
}
}
nb: media query via Foundation
nb2: this is useful if one of the editor intend to use
tags in his/her copy and you need to deal with it specifically under some conditions—on mobile for example.
Use ON DUPLICATE KEY UPDATE ...
,
Negative : because the UPDATE
uses resources for the second action.
Use INSERT IGNORE ...
,
Negative : MySQL will not show any errors if something goes wrong, so you cannot handle the errors. Use it only if you don’t care about the query.
I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:
var namesCount = (int)MyEnum.Length;
Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.
No, they are not always.
It depends on whether you allow user input to be placed within the query itself. For example:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
would be vulnerable to SQL injections and using prepared statements in this example won't work, because the user input is used as an identifier, not as data. The right answer here would be to use some sort of filtering/validation like:
$dbh = new PDO("blahblah");
$tableToUse = $_GET['userTable'];
$allowedTables = array('users','admins','moderators');
if (!in_array($tableToUse,$allowedTables))
$tableToUse = 'users';
$stmt = $dbh->prepare('SELECT * FROM ' . $tableToUse . ' where username = :username');
$stmt->execute( array(':username' => $_REQUEST['username']) );
Note: you can't use PDO to bind data that goes outside of DDL (Data Definition Language), i.e. this does not work:
$stmt = $dbh->prepare('SELECT * FROM foo ORDER BY :userSuppliedData');
The reason why the above does not work is because DESC
and ASC
are not data. PDO can only escape for data. Secondly, you can't even put '
quotes around it. The only way to allow user chosen sorting is to manually filter and check that it's either DESC
or ASC
.
Before i was running this command
npm install typescript -g
after changing the command it worked perfectly.
npm install -g typescript
Some years later, looking for the same requirement, I found a CSS option using background-size.
It is supposed to work in modern browsers (IE9+).
<div id="container" style="background-image:url(myimage.png)">
</div>
And the style:
#container
{
width: 100px; /*or 70%, or what you want*/
height: 200px; /*or 70%, or what you want*/
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
The reference: http://www.w3schools.com/cssref/css3_pr_background-size.asp
And the demo: http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size
It's also worth noting that ActiveX controls only work in Windows, whereas Form Controls will work on both Windows and MacOS versions of Excel.
I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.
Just add
::-webkit-scrollbar {display:none;}
To your id or class of the div you're using the scroll bar with.
Here is a helpful link Custom Scroll Bar in Webkit
It CAN be done cross browser; it just takes some custom programming. Please see my fiddle at http://jsfiddle.net/sablefoste/YVMzt/6/. It was tested to work in Chrome, Firefox, Internet Explorer, and Safari.
In short, I have a hidden field, #optionstore
, which stores the array sequentially (since you can't have Associative Arrays in JavaScript). Then when you change the category, it parses the existing options (first time through only) writes them to #optionstore
, erases everything, and puts back only the ones associated with the category.
NOTE: I created this to allow different option values from the text displayed to the user, so it is highly flexible.
The HTML:
<p id="choosetype">
<div>
Food Category:
</div>
<select name="category" id="category" title="OPTIONAL - Choose a Category to Limit Food Types" size="1">
<option value="">All Food</option>
<option value="Food1">Fruit</option>
<option value="Food2">Veggies</option>
<option value="Food3">Meat</option>
<option value="Food4">Dairy</option>
<option value="Food5">Bread</option>
</select>
<div>
Food Selection
</div>
<select name="foodType" id="foodType" size="1">
<option value="Fruit1" class="sub-Food1">Apples</option>
<option value="Fruit2" class="sub-Food1">Pears</option>
<option value="Fruit3" class="sub-Food1">Bananas</option>
<option value="Fruit4" class="sub-Food1">Oranges</option>
<option value="Veg1" class="sub-Food2">Peas</option>
<option value="Veg2" class="sub-Food2">Carrots</option>
<option value="Veg3" class="sub-Food2">Broccoli</option>
<option value="Veg4" class="sub-Food2">Lettuce</option>
<option value="Meat1" class="sub-Food3">Steak</option>
<option value="Meat2" class="sub-Food3">Chicken</option>
<option value="Meat3" class="sub-Food3">Salmon</option>
<option value="Meat4" class="sub-Food3">Shrimp</option>
<option value="Meat5" class="sub-Food3">Tuna</option>
<option value="Meat6" class="sub-Food3">Pork</option>
<option value="Dairy1" class="sub-Food4">Milk</option>
<option value="Dairy2" class="sub-Food4">Cheese</option>
<option value="Dairy3" class="sub-Food4">Ice Cream</option>
<option value="Dairy4" class="sub-Food4">Yogurt</option>
<option value="Bread1" class="sub-Food5">White Bread</option>
<option value="Bread2" class="sub-Food5">Panini</option>
</select>
<span id="optionstore" style="display:none;"></span>
</p>
The JavaScript/jQuery:
$(document).ready(function() {
$('#category').on("change", function() {
var cattype = $(this).val();
optionswitch(cattype);
});
});
function optionswitch(myfilter) {
//Populate the optionstore if the first time through
if ($('#optionstore').text() == "") {
$('option[class^="sub-"]').each(function() {
var optvalue = $(this).val();
var optclass = $(this).prop('class');
var opttext = $(this).text();
optionlist = $('#optionstore').text() + "@%" + optvalue + "@%" + optclass + "@%" + opttext;
$('#optionstore').text(optionlist);
});
}
//Delete everything
$('option[class^="sub-"]').remove();
// Put the filtered stuff back
populateoption = rewriteoption(myfilter);
$('#foodType').html(populateoption);
}
function rewriteoption(myfilter) {
//Rewrite only the filtered stuff back into the option
var options = $('#optionstore').text().split('@%');
var resultgood = false;
var myfilterclass = "sub-" + myfilter;
var optionlisting = "";
myfilterclass = (myfilter != "")?myfilterclass:"all";
//First variable is always the value, second is always the class, third is always the text
for (var i = 3; i < options.length; i = i + 3) {
if (options[i - 1] == myfilterclass || myfilterclass == "all") {
optionlisting = optionlisting + '<option value="' + options[i - 2] + '" class="' + options[i - 1] + '">' + options[i] + '</option>';
resultgood = true;
}
}
if (resultgood) {
return optionlisting;
}
}
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
The answer that has 50 votes doesn't check for date in only checks for months. That answer is not correct. The code below works.
var dateFrom = "01/08/2017";
var dateTo = "01/10/2017";
var dateCheck = "05/09/2017";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1); // -1 because months are from 0 to 11
var to = new Date(d2);
var check = new Date(c);
alert(check > from && check < to);
This is the code posted in another answer and I have changed the dates and that's how I noticed it doesn't work
var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "07/07/2013";
var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");
var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]); // -1 because months are from 0 to 11
var to = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);
alert(check > from && check < to);
Remember that you can apply multiple classes to an element by separating each class with a space within its class attribute. For example:
<img class="class1 class2">
Try this too in addition to MahmoudS comments. Change the maven compiler source and target in your pom.xml to the java version which you are using. Say 1.7 for jdk7
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
Since the OP asked for the list of the tensors instead of the list of operations/nodes, the code should be slightly different:
graph = tf.get_default_graph()
tensors_per_node = [node.values() for node in graph.get_operations()]
tensor_names = [tensor.name for tensors in tensors_per_node for tensor in tensors]
Try:
String words[]=temp.split("\\.");
The method is:
String[] split(String regex)
"." is a reserved char in regex
I created a plugin which allows you to drop some files onto a given area. This plugin currently works in Firefox, Safari and Chrome.
Eric Sink, who appeared on SO podcast#36 in January 2009, wrote an excellent series of articles under the title Source Control How-to.
(Eric is the founder of SourceGear who market a plug-compatible version of SourceSafe, but without the horribleness.)
Delete node_modules
rm -r node_modules
install packages again
npm install
The above error run the commend line\
please change the command $ node server it's working and server is started
For more complex tasks there is expect
( http://en.wikipedia.org/wiki/Expect ).
It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.
This also works in cases like ssh
that prohibits piping passwords to it.
With the release of Docker 19.03, you can skip creating the container and even building an image. There's an option with BuildKit based builds to change the output destination. You can use this to write the results of the build to your local directory rather than into an image. E.g. here's a build of a go binary:
$ ls
Dockerfile go.mod main.go
$ cat Dockerfile
FROM golang:1.12-alpine as dev
RUN apk add --no-cache git ca-certificates
RUN adduser -D appuser
WORKDIR /src
COPY . /src/
CMD CGO_ENABLED=0 go build -o app . && ./app
FROM dev as build
RUN CGO_ENABLED=0 go build -o app .
USER appuser
CMD [ "./app" ]
FROM scratch as release
COPY --from=build /etc/passwd /etc/group /etc/
COPY --from=build /src/app /app
USER appuser
CMD [ "/app" ]
FROM scratch as artifact
COPY --from=build /src/app /app
FROM release
From the above Dockerfile, I'm building the artifact
stage that only includes the files I want to export. And the newly introduced --output
flag lets me write those to a local directory instead of an image. This needs to be performed with the BuildKit engine that ships with 19.03:
$ DOCKER_BUILDKIT=1 docker build --target artifact --output type=local,dest=. .
[+] Building 43.5s (12/12) FINISHED
=> [internal] load build definition from Dockerfile 0.7s
=> => transferring dockerfile: 572B 0.0s
=> [internal] load .dockerignore 0.5s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/golang:1.12-alpine 0.9s
=> [dev 1/5] FROM docker.io/library/golang:1.12-alpine@sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 22.5s
=> => resolve docker.io/library/golang:1.12-alpine@sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 0.0s
=> => sha256:1ec62c064901392a6722bb47a377c01a381f4482b1ce094b6d28682b6b6279fd 155B / 155B 0.3s
=> => sha256:50deab916cce57a792cd88af3479d127a9ec571692a1a9c22109532c0d0499a0 1.65kB / 1.65kB 0.0s
=> => sha256:2ecd820bec717ec5a8cdc2a1ae04887ed9b46c996f515abc481cac43a12628da 1.36kB / 1.36kB 0.0s
=> => sha256:6a17089e5a3afc489e5b6c118cd46eda66b2d5361f309d8d4b0dcac268a47b13 3.81kB / 3.81kB 0.0s
=> => sha256:89d9c30c1d48bac627e5c6cb0d1ed1eec28e7dbdfbcc04712e4c79c0f83faf17 2.79MB / 2.79MB 0.6s
=> => sha256:8ef94372a977c02d425f12c8cbda5416e372b7a869a6c2b20342c589dba3eae5 301.72kB / 301.72kB 0.4s
=> => sha256:025f14a3d97f92c07a07446e7ea8933b86068d00da9e252cf3277e9347b6fe69 125.33MB / 125.33MB 13.7s
=> => sha256:7047deb9704134ff71c99791be3f6474bb45bc3971dde9257ef9186d7cb156db 125B / 125B 0.8s
=> => extracting sha256:89d9c30c1d48bac627e5c6cb0d1ed1eec28e7dbdfbcc04712e4c79c0f83faf17 0.2s
=> => extracting sha256:8ef94372a977c02d425f12c8cbda5416e372b7a869a6c2b20342c589dba3eae5 0.1s
=> => extracting sha256:1ec62c064901392a6722bb47a377c01a381f4482b1ce094b6d28682b6b6279fd 0.0s
=> => extracting sha256:025f14a3d97f92c07a07446e7ea8933b86068d00da9e252cf3277e9347b6fe69 5.2s
=> => extracting sha256:7047deb9704134ff71c99791be3f6474bb45bc3971dde9257ef9186d7cb156db 0.0s
=> [internal] load build context 0.3s
=> => transferring context: 2.11kB 0.0s
=> [dev 2/5] RUN apk add --no-cache git ca-certificates 3.8s
=> [dev 3/5] RUN adduser -D appuser 1.7s
=> [dev 4/5] WORKDIR /src 0.5s
=> [dev 5/5] COPY . /src/ 0.4s
=> [build 1/1] RUN CGO_ENABLED=0 go build -o app . 11.6s
=> [artifact 1/1] COPY --from=build /src/app /app 0.5s
=> exporting to client 0.1s
=> => copying files 10.00MB 0.1s
After the build was complete the app
binary was exported:
$ ls
Dockerfile app go.mod main.go
$ ./app
Ready to receive requests on port 8080
Docker has other options to the --output
flag documented in their upstream BuildKit repo: https://github.com/moby/buildkit#output
After 1.13.0, Docker includes a new command docker system df
to show docker disk usage.
$ docker system df
TYPE TOTAL ACTIVE SIZE RECLAIMABLE
Images 5 1 2.777 GB 2.647 GB (95%)
Containers 1 1 0 B 0B
Local Volumes 4 1 3.207 GB 2.261 (70%)
To show more detailed information on space usage:
$ docker system df --verbose
please open your android sdk installed directory then,
in my path :
E:\Android\sdk\extras\android\support\v7\appcompat
then you can see " project.properties" file
open it and change target "target=android-19" to "target=android-23"
its worked for me.
Google's libs-for-android has a nice libraries for managing image and file cache.
found the solution with AND condition:
$trainstrength = "UPDATE user_character SET strength_trains = strength_trains + 1, trained_strength = trained_strength +1, character_gold = character_gold - $gold_to_next_strength WHERE ID = $currentUser AND character_gold > $gold_to_next_strength";
You are close you want to use @Html.Raw(str)
@Html.Encode
takes strings and ensures that all the special characters are handled properly. These include characters like spaces.
If you want to retain the exact commit history of the second repository and therefore also retain the ability to easily merge upstream changes in the future then here is the method you want. It results in unmodified history of the subtree being imported into your repo plus one merge commit to move the merged repository to the subdirectory.
git remote add XXX_remote <path-or-url-to-XXX-repo>
git fetch XXX_remote
git merge -s ours --no-commit --allow-unrelated-histories XXX_remote/master
git read-tree --prefix=ZZZ/ -u XXX_remote/master
git commit -m "Imported XXX as a subtree."
You can track upstream changes like so:
git pull -s subtree XXX_remote master
Git figures out on its own where the roots are before doing the merge, so you don't need to specify the prefix on subsequent merges.
The downside is that in the merged history the files are unprefixed (not in a subdirectory). As a result git log ZZZ/a
will show you all the changes (if any) except those in the merged history. You can do:
git log --follow -- a
but that won't show the changes other then in the merged history.
In other words, if you don't change ZZZ
's files in repository XXX
, then you need to specify --follow
and an unprefixed path. If you change them in both repositories, then you have 2 commands, none of which shows all the changes.
Git versions before 2.9: You don’t need to pass the --allow-unrelated-histories
option to git merge
.
The method in the other answer that uses read-tree
and skips the merge -s ours
step is effectively no different than copying the files with cp and committing the result.
Original source was from github's "Subtree Merge" help article. And another useful link.
You can use the following option to check for the files:
wget --delete-after URL
VisualSVN (not-free)
I personally prefer this over AnkhSVN since its not an SCC provider and doesn't add extra files to my repository.
You will soon be able to use Adobe Flash CS 5
to create Apps for the iPhone
on Windows
:
I SSH'ed into my AWS Lightsail wordpress instance, the following worked: sudo /opt/bitnami/ctlscript.sh restart mysql I learnt this here: https://docs.bitnami.com/aws/infrastructure/mysql/administration/control-services/
The answer will vary slightly depending on whether the application or applet is using AWT or Swing.
(Basically, classes that start with J
such as JApplet
and JFrame
are Swing, and Applet
and Frame
are AWT.)
In either case, the basic steps would be:
Image
object.Component
you want to draw the background in.Step 1. Loading the image can be either by using the Toolkit
class or by the ImageIO
class.
The Toolkit.createImage
method can be used to load an Image
from a location specified in a String
:
Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");
Similarly, ImageIO
can be used:
Image img = ImageIO.read(new File("background.jpg");
Step 2. The painting method for the Component
that should get the background will need to be overridden and paint the Image
onto the component.
For AWT, the method to override is the paint
method, and use the drawImage
method of the Graphics
object that is handed into the paint
method:
public void paint(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
For Swing, the method to override is the paintComponent
method of the JComponent
, and draw the Image
as with what was done in AWT.
public void paintComponent(Graphics g)
{
// Draw the previously loaded image to Component.
g.drawImage(img, 0, 0, null);
// Draw sprites, and other things.
// ....
}
Simple Component Example
Here's a Panel
which loads an image file when instantiated, and draws that image on itself:
class BackgroundPanel extends Panel
{
// The Image to store the background image in.
Image img;
public BackgroundPanel()
{
// Loads the background image and stores in img object.
img = Toolkit.getDefaultToolkit().createImage("background.jpg");
}
public void paint(Graphics g)
{
// Draws the img to the BackgroundPanel.
g.drawImage(img, 0, 0, null);
}
}
For more information on painting:
With c++14 you can do this:
std::sort(numbers.begin(), numbers.end(), std::greater<>());
Depends on what you need, you have a couple of choices, you can do:
// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");
// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);
// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");
This will do it in Delphi. Note the use of the BitBlt function, which is a Windows API call, not something specific to Delphi.
Edit: Added example usage
function TForm1.GetScreenShot(OnlyActiveWindow: boolean) : TBitmap;
var
w,h : integer;
DC : HDC;
hWin : Cardinal;
r : TRect;
begin
//take a screenshot and return it as a TBitmap.
//if they specify "OnlyActiveWindow", then restrict the screenshot to the
//currently focused window (same as alt-prtscrn)
//Otherwise, get a normal screenshot (same as prtscrn)
Result := TBitmap.Create;
if OnlyActiveWindow then begin
hWin := GetForegroundWindow;
dc := GetWindowDC(hWin);
GetWindowRect(hWin,r);
w := r.Right - r.Left;
h := r.Bottom - r.Top;
end //if active window only
else begin
hWin := GetDesktopWindow;
dc := GetDC(hWin);
w := GetDeviceCaps(DC,HORZRES);
h := GetDeviceCaps(DC,VERTRES);
end; //else entire desktop
try
Result.Width := w;
Result.Height := h;
BitBlt(Result.Canvas.Handle,0,0,Result.Width,Result.Height,DC,0,0,SRCCOPY);
finally
ReleaseDC(hWin, DC) ;
end; //try-finally
end;
procedure TForm1.btnSaveScreenshotClick(Sender: TObject);
var
bmp : TBitmap;
savdlg : TSaveDialog;
begin
//take a screenshot, prompt for where to save it
savdlg := TSaveDialog.Create(Self);
bmp := GetScreenshot(False);
try
if savdlg.Execute then begin
bmp.SaveToFile(savdlg.FileName);
end;
finally
FreeAndNil(bmp);
FreeAndNil(savdlg);
end; //try-finally
end;
When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution. My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.
(1) open a new command window, then open a new jupyter notebook. try to save again in the old notebook, this time ,the error is 'fail: forbidden'
(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.
(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list' copy the code after 'token=' and before :: to the box you just saw. You can save this time. If it fails, you can try another token in the list
Add FormsModule
in Imports Array.
i.e
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
Or this can be done without using [(ngModel)]
by using
<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">
instead of
<input [(ngModel)]="hero.name" placeholder="Name">
I would probably go with Joran's suggestion of replacing 0's with NAs and then using the built in functions you mentioned. If you can't/don't want to do that, one approach is to use any()
to find rows that contain 0's and subset those out:
set.seed(42)
#Fake data
x <- data.frame(a = sample(0:2, 5, TRUE), b = sample(0:2, 5, TRUE))
> x
a b
1 2 1
2 2 2
3 0 0
4 2 1
5 1 2
#Subset out any rows with a 0 in them
#Note the negation with ! around the apply function
x[!(apply(x, 1, function(y) any(y == 0))),]
a b
1 2 1
2 2 2
4 2 1
5 1 2
To implement Joran's method, something like this should get you started:
x[x==0] <- NA
Getters and setters coming from data hiding. Data Hiding means We are hiding data from outsiders or outside person/thing cannot access our data.This is a useful feature in OOP.
As a example:
If you create a public variable, you can access that variable and change value in anywhere(any class). But if you create as private that variable cannot see/access in any class except declared class.
public
andprivate
are access modifiers.
So how can we access that variable outside:
This is the place getters and setters coming from. You can declare variable as private then you can implement getter and setter for that variable.
Example(Java):
private String name;
public String getName(){
return this.name;
}
public void setName(String name){
this.name= name;
}
Advantage:
When anyone want to access or change/set value to balance
variable, he/she must have permision.
//assume we have person1 object
//to give permission to check balance
person1.getName()
//to give permission to set balance
person1.setName()
You can set value in constructor also but when later on when you want to update/change value, you have to implement setter method.
Scanner scan = new Scanner (System.in);
for (int i=0; i<=4, i++){
System.out.printf("Enter value at index"+i+" :");
anArray[i]=scan.nextInt();
}
As with anything: if used with care, it can be an elegant tool.
However, I think the drawbacks more than justify not to use it, and finally not to allow it anymore (C#). Among the problems are:
Good use of a switch/case fall-through:
switch (x)
{
case 1:
case 2:
case 3:
Do something
break;
}
Baaaaad use of a switch/case fall-through:
switch (x)
{
case 1:
Some code
case 2:
Some more code
case 3:
Even more code
break;
}
This can be rewritten using if/else constructs with no loss at all in my opinion.
My final word: stay away from fall-through case labels as in the bad example, unless you are maintaining legacy code where this style is used and well understood.
You asked for a combination of quick, nice, no use of a boolean, no use of goto, and C#. You've ruled out all possible ways of doing what you want.
The most quick and least ugly way is to use a goto.
If the above solution does not work for you it is may be possible to obtain the same result with the following pure nodejs code. The above did not work for me and resulted in a compilation exception when running 'npm install iconv' on OSX:
npm install iconv
npm WARN package.json [email protected] No README.md file found!
npm http GET https://registry.npmjs.org/iconv
npm http 200 https://registry.npmjs.org/iconv
npm http GET https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
npm http 200 https://registry.npmjs.org/iconv/-/iconv-2.0.4.tgz
> [email protected] install /Users/markboyd/git/portal/app/node_modules/iconv
> node-gyp rebuild
gyp http GET http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
gyp http 200 http://nodejs.org/dist/v0.10.1/node-v0.10.1.tar.gz
xcode-select: Error: No Xcode is selected. Use xcode-select -switch <path-to-xcode>, or see the xcode-select manpage (man xcode-select) for further information.
fs.readFileSync() returns a Buffer if no encoding is specified. And Buffer has a toString() method that will convert to UTF8 if no encoding is specified giving you the file's contents. See the nodejs documentation. This worked for me.
String path = "C:\\Documents and Settings\\Manoj\\Desktop";
String javaPath = path.replace("\\", "/"); // Create a new variable
or
path = path.replace("\\", "/"); // Just use the existing variable
String
s are immutable. Once they are created, you can't change them. This means replace
returns a new String where the target("\\"
) is replaced by the replacement("/"
). Simply calling replace
will not change path
.
The difference between replaceAll
and replace
is that replaceAll will search for a regex, replace doesn't.
The problem is that you're calling List<T>.Reverse()
which returns void
.
You could either do:
List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();
or:
IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();
The latter is more expensive, as reversing an arbitrary IEnumerable<T>
involves buffering all of the data and then yielding it all - whereas List<T>
can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>()
extension method, instead of the List<T>.Reverse()
instance method.)
More efficient yet, you could use:
string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();
This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.
We can use params
, new feature of the UI-Router:
API Reference / ui.router.state / $stateProvider
params
A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.
See the part: "...or defines additional non-url parameters..."
So the state def would be:
$stateProvider
.state('home', {
url: "/home",
templateUrl: 'tpl.html',
params: { hiddenOne: null, }
})
Few examples form the doc mentioned above:
// define a parameter's default value
params: {
param1: { value: "defaultValue" }
}
// shorthand default values
params: {
param1: "defaultValue",
param2: "param2Default"
}
// param will be array []
params: {
param1: { array: true }
}
// handling the default value in url:
params: {
param1: {
value: "defaultId",
squash: true
} }
// squash "defaultValue" to "~"
params: {
param1: {
value: "defaultValue",
squash: "~"
} }
EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info
Here is an example of a state definition:
$stateProvider
.state('home', {
url: "/home",
params : { veryLongParamHome: null, },
...
})
.state('parent', {
url: "/parent",
params : { veryLongParamParent: null, },
...
})
.state('parent.child', {
url: "/child",
params : { veryLongParamChild: null, },
...
})
This could be a call using ui-sref:
<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
})">home</a>
<a ui-sref="parent({
veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
})">parent</a>
<a ui-sref="parent.child({
veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',
veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
})">parent.child</a>
Check the example here
They're there to allow for different levels of encapsulation
rows = a.shape[0] # 2
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4
I use iterator and a while loop to store the various window handles and then switch back and forth.
//Click your link
driver.findElement(By.xpath("xpath")).click();
//Get all the window handles in a set
Set <String> handles =driver.getWindowHandles();
Iterator<String> it = handles.iterator();
//iterate through your windows
while (it.hasNext()){
String parent = it.next();
String newwin = it.next();
driver.switchTo().window(newwin);
//perform actions on new window
driver.close();
driver.switchTo().window(parent);
}
This issue came for me due to the fact that .. i was running server with selenium-server-standalone-2.32.0 and client registered with selenium-server-standalone-2.37.0 .. When i made both selenium-server-standalone-2.32.0 and ran then things worked fine
We recently addressed a similar issue with an embedded video and found that the autoplay and muted attributes were not sufficient for our implementation.
We added a third "playsinline" attribute to the code and it fixed the issue for iOS users.
This fix is specific to videos that are to be played inline. From https://webkit.org/blog/6784/new-video-policies-for-ios/ :
On iPhone, elements will now be allowed to play inline, and will not automatically enter fullscreen mode when playback begins. elements without playsinline attributes will continue to require fullscreen mode for playback on iPhone. When exiting fullscreen with a pinch gesture, elements without playsinline will continue to play inline.
Use can use one of below this
history.back(); // equivalent to clicking back button
history.go(-1); // equivalent to history.back();
I am using as below for back button
<a class="btn btn-info float-right" onclick="history.back();" >Back</a>
J.Random Coder's answer and initialize version field.
private string version = "10.4';
As shown in the latest edit, the password is valid until 1970, which means it's currently invalid. This explains the error message which is the same as if the password was incorrect.
Reset the validity with:
ALTER USER postgres VALID UNTIL 'infinity';
In a recent question, another user had the same problem with user accounts and PG-9.2:
PostgreSQL - Password authentication fail after adding group roles
So apparently there is a way to unintentionally set a bogus password validity to the Unix epoch (1st Jan, 1970, the minimum possible value for the abstime
type). Possibly, there's a bug in PG itself or in some client tool that would create this situation.
EDIT: it turns out to be a pgadmin bug. See https://dba.stackexchange.com/questions/36137/
Edit: Sorry, this won't work for you. I just remembered the line color thing is in 4.2. I ran into this problem in the past and my fix was to upgrade gnuplot.
You can control the color with set style line as well. "lt 3" will give you a dashed line while "lt 1" will give you a solid line. To add color, you can use "lc rgb 'color'". This should do what you need:
set style line 1 lt 1 lw 3 pt 3 lc rgb "red"
set style line 2 lt 3 lw 3 pt 3 lc rgb "red"
set style line 3 lt 1 lw 3 pt 3 lc rgb "blue"
set style line 4 lt 3 lw 3 pt 3 lc rgb "blue"
This works for me (Excel 2013):
Public Sub StartExeWithArgument()
Dim strProgramName As String
Dim strArgument As String
strProgramName = "C:\Program Files\Test\foobar.exe"
strArgument = "/G"
Call Shell("""" & strProgramName & """ """ & strArgument & """", vbNormalFocus)
End Sub
With inspiration from here https://stackoverflow.com/a/3448682.
For users on mac, I solved an issue similar to this by modifying my zshrc file and adding the following (although your java_home might be configured differently) :
export JAVA_HOME=$(/usr/libexec/java_home)
export ANDROID_HOME=/Users/YOURUSER/Library/Android/sdk
export PATH=$PATH:/Users/YOURUSER/Library/Android/sdk/tools
export PATH=$PATH:%ANDROID_HOME%\tools
export PATH=$PATH:/Users/YOURUSER/Library/Android/sdk
There's a more convenient way to store passwords in a script but you will have to encrypt and obfuscate the script so that it cannot be read. In order to successfully encrypt and obfuscate a shell script and actually have that script be executable, try copying and pasting it here:
http://www.kinglazy.com/shell-script-encryption-kinglazy-shieldx.htm
On the above page, all you have to do is submit your script and give the script a proper name, then hit the download button. A zip file will be generated for you. Right click on the download link and copy the URL you're provided. Then, go to your UNIX box and perform the following steps.
Installation:
1. wget link-to-the-zip-file
2. unzip the-newly-downloaded-zip-file
3. cd /tmp/KingLazySHIELD
4. ./install.sh /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force
What the above install command will do for you is:
NOTE:
This does not work for interactive scripts that prompts and waits on the user for a response. The values that are expected from the user should be hard-coded into the script. The encryption ensures no one can actually see those values so you need not worry about that.
RELATION:
The solution provided in this post answers your problem in the sense that it encrypts the actual script containing the password that you wanted to have encrypted. You get to leave the password as is (unencrypted) but the script that the password is in is so deeply obfuscated and encrypted that you can rest assured no one will be able to see it. And if attempts are made to try to pry into the script, you will receive email notifications about them.
You need to save the PID of the background process at the time you start it:
foo &
FOO_PID=$!
# do other stuff
kill $FOO_PID
You cannot use job control, since that is an interactive feature and tied to a controlling terminal. A script will not necessarily have a terminal attached at all so job control will not necessarily be available.
Introduced in ECMAScript 6, we can now deal with undefined
in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.
var handler = {
get: function(target, name) {
return name in target ? target[name] : 'N/A';
}
};
var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)
Will output the below text without getting any undefined.
Name: Kevin , Age: N/A , Gender: N/A
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this
For your second question, it seems the leading-quote syntax (\'A
) is specific to printf
:
If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote.
From https://pubs.opengroup.org/onlinepubs/9699919799/utilities/printf.html
Set level to OFF (instead of DEBUG, INFO, ....)
Your diameter variable won't work because you're trying to store a String into a variable that will only accept a double. In order for it to work you will need to parse it
Ex:
diameter = Double.parseDouble(JOptionPane.showInputDialog("enter the diameter of a sphere.");
Just use a bytearray()
which is a list of bytes.
Python2:
s = "ABCD"
b = bytearray()
b.extend(s)
Python3:
s = "ABCD"
b = bytearray()
b.extend(map(ord, s))
By the way, don't use str
as a variable name since that is builtin.
If your python
and pip
binaries are from different versions, modules installed using pip will not be available to python.
Steps to resolve:
pip
and python
.readlink $(which pip)
../Cellar/python@2/2.7.15_1/bin/pip
readlink $(which python)
/usr/local/bin/python3 <-- another symlink
readlink /usr/local/bin/python3
../Cellar/python/3.7.2/bin/python3
Here you can see an obvious mismatch between the versions 2.7.15_1
and 3.7.2
in my case.
ln -is /usr/local/Cellar/python/3.7.2/bin/pip3 $(which pip)
The -i
flag promts you to overwrite if the target exists.
That should do the trick.
This is a preferable answer in most use cases, because it allows you to decouple execution of the software from direct knowledge of the server platform, which keeps your code much more portable. If you are doing a lot of cron/cgi, this may not help directly, but it can be set into a config at web runtime that the cron/cgi scripts pull from to keep the log location consistent in that case.
You can get the current log file assigned natively to php on any platform at runtime by using:
ini_get('error_log');
This returns the value distributed directly to the php binary by the webserver, which is what you want in 90% of use cases (with the glaring exception being cgi). Cgi will often log to this same location as the http webserver client, but not always.
You will also want to check that it is writeable before committing anything to it to avoid errors. The conf file that defines it's location (typically either apache.conf globally or vhosts.conf on a per-domain basis), but the conf does not ensure that file permissions allow write access at runtime.
By default, the DirectoryIndex is set to:
DirectoryIndex index.html index.htm default.htm index.php index.php3 index.phtml index.php5 index.shtml mwindex.phtml
Apache will look for each of the above files, in order, and serve the first one it finds when a visitor requests just a directory. If the webserver finds no files in the current directory that match names in the DirectoryIndex directive, then a directory listing will be displayed to the browser, showing all files in the current directory.
The order should be DirectoryIndex index.html index.php
// default is index.html
Reference: Here.
If you know the exact size of the view, just use setLayoutParams()
:
graphView.setLayoutParams(new LayoutParams(width, height));
Or in Kotlin:
graphView.layoutParams = LayoutParams(width, height)
However, if you need a more flexible approach you can override onMeasure()
to measure the view more precisely depending on the space available and layout constraints (wrap_content
, match_parent
, or a fixed size). You can find more details about onMeasure()
in the android docs.
test
is a non-destructive and
, it doesn't return the result of the operation but it sets the flags register accordingly. To know what it really tests for you need to check the following instruction(s). Often out is used to check a register against 0, possibly coupled with a jz
conditional jump.
If you want this without loops or jquery you could use the following This is straight up JavaScript. This works for current web browsers. Given the age of the question I am not sure if this would have worked back in 2011. Please note that using css style selectors is extremely powerful and can help shorten a lot of code.
// Please note that querySelectorAll will return a match for _x000D_
// for the term...if there is more than one then you will _x000D_
// have to loop through the returned object_x000D_
var selectAnimal = function() {_x000D_
var animals = document.getElementById('animal');_x000D_
if (animals) {_x000D_
var x = animals.querySelectorAll('option[value="frog"]');_x000D_
if (x.length === 1) {_x000D_
console.log(x[0].index);_x000D_
animals.selectedIndex = x[0].index;_x000D_
}_x000D_
}_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
<title>Test without loop or jquery</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<label>Animal to select_x000D_
<select id='animal'>_x000D_
<option value='nothing'></option>_x000D_
<option value='dog'>dog</option>_x000D_
<option value='cat'>cat</option>_x000D_
<option value='mouse'>mouse</option>_x000D_
<option value='rat'>rat</option>_x000D_
<option value='frog'>frog</option>_x000D_
<option value='horse'>horse</option>_x000D_
</select>_x000D_
</label>_x000D_
<button onclick="selectAnimal()">Click to select animal</button>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
document.getElementById('Animal').querySelectorAll('option[value="searchterm"]'); in the index object you can now do the following: x[0].index
myInt=10
myList=[tmpList/myInt for tmpList in range(10,100,10)]
An alternative for the bind() method.
Use the click() method, do something like this:
commentbtn.click({id: 10, name: "João"}, onClickCommentBtn);
function onClickCommentBtn(event)
{
alert("Id=" + event.data.id + ", Name = " + event.data.name);
}
Or, if you prefer:
commentbtn.click({id: 10, name: "João"}, function (event) {
alert("Id=" + event.data.id + ", Nome = " + event.data.name);
});
It will show an alert box with the following infos:
Id = 10, Name = João
You can try below query:
select
count(*)
from
all_tab_columns
where
table_name = 'your_table'
I was able to do that by using the "branches to build" parameter:
Branch Specifier (blank for default): tags/[tag-name]
Replace [tag-name] by the name of your tag.
There are several ways to do plots in R; lattice
is one of them, and always a reasonable solution, +1 to @agstudy. If you want to do this in base graphics, you could try the following:
Reasonstats <- read.table(text="Category Reason Species
Decline Genuine 24
Improved Genuine 16
Improved Misclassified 85
Decline Misclassified 41
Decline Taxonomic 2
Improved Taxonomic 7
Decline Unclear 41
Improved Unclear 117", header=T)
ReasonstatsDec <- Reasonstats[which(Reasonstats$Category=="Decline"),]
ReasonstatsImp <- Reasonstats[which(Reasonstats$Category=="Improved"),]
Reasonstats3 <- cbind(ReasonstatsImp[,3], ReasonstatsDec[,3])
colnames(Reasonstats3) <- c("Improved", "Decline")
rownames(Reasonstats3) <- ReasonstatsImp$Reason
windows()
barplot(t(Reasonstats3), beside=TRUE, ylab="number of species",
cex.names=0.8, las=2, ylim=c(0,120), col=c("darkblue","red"))
box(bty="l")
Here's what I did: I created a matrix with two columns (because your data were in columns) where the columns were the species counts for Decline
and for Improved
. Then I made those categories the column names. I also made the Reason
s the row names. The barplot()
function can operate over this matrix, but wants the data in rows rather than columns, so I fed it a transposed version of the matrix. Lastly, I deleted some of your arguments to your barplot()
function call that were no longer needed. In other words, the problem was that your data weren't set up the way barplot()
wants for your intended output.
In Eclipse Ganymede (3.4.0):
The raw.githubusercontent.com
domain is used to serve unprocessed versions of files stored in GitHub repositories. If you browse to a file on GitHub and then click the Raw link, that's where you'll go.
The URL in your question references the install
file in the master
branch of the Homebrew/install
repository. The rest of that command just retrieves the file and runs ruby
on its contents.
Of course it is. Here is a sample annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TestAnnotation {
String testText();
}
And a sample annotated method:
class TestClass {
@TestAnnotation(testText="zyx")
public void doSomething() {}
}
And a sample method in another class that prints the value of the testText:
Method[] methods = TestClass.class.getMethods();
for (Method m : methods) {
if (m.isAnnotationPresent(TestAnnotation.class)) {
TestAnnotation ta = m.getAnnotation(TestAnnotation.class);
System.out.println(ta.testText());
}
}
Not much different for field annotations like yours.
Cheerz!
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
I implemented @user3016183 method using a custom decorator:
def changeNow(func, newNow = datetime(2015, 11, 23, 12, 00, 00)):
"""decorator used to change datetime.datetime.now() in the tested function."""
def retfunc(self):
with mock.patch('mymodule.datetime') as mock_date:
mock_date.now.return_value = newNow
mock_date.side_effect = lambda *args, **kw: datetime(*args, **kw)
func(self)
return retfunc
I thought that might help someone one day...
For the absolute coordinates of any jquery element I wrote this function, it probably doesnt work for all css position types but maybe its a good start for someone ..
function AbsoluteCoordinates($element) {
var sTop = $(window).scrollTop();
var sLeft = $(window).scrollLeft();
var w = $element.width();
var h = $element.height();
var offset = $element.offset();
var $p = $element;
while(typeof $p == 'object') {
var pOffset = $p.parent().offset();
if(typeof pOffset == 'undefined') break;
offset.left = offset.left + (pOffset.left);
offset.top = offset.top + (pOffset.top);
$p = $p.parent();
}
var pos = {
left: offset.left + sLeft,
right: offset.left + w + sLeft,
top: offset.top + sTop,
bottom: offset.top + h + sTop,
}
pos.tl = { x: pos.left, y: pos.top };
pos.tr = { x: pos.right, y: pos.top };
pos.bl = { x: pos.left, y: pos.bottom };
pos.br = { x: pos.right, y: pos.bottom };
//console.log( 'left: ' + pos.left + ' - right: ' + pos.right +' - top: ' + pos.top +' - bottom: ' + pos.bottom );
return pos;
}
~/Library/Developer/Xcode/DerivedData
is now the default.
You can set the prefs in Xcode to allow projects to specify their build directories.
--DROP TABLE #Employee
CREATE TABLE #Employee(EmpId BIGINT IDENTITY,EmpName VARCHAR(25),Designation VARCHAR(25),ManagerID BIGINT)
INSERT INTO #Employee VALUES('M11M','Manager',NULL)
INSERT INTO #Employee VALUES('P11P','Manager',NULL)
INSERT INTO #Employee VALUES('AA','Clerk',1)
INSERT INTO #Employee VALUES('AB','Assistant',1)
INSERT INTO #Employee VALUES('ZC','Supervisor',2)
INSERT INTO #Employee VALUES('ZD','Security',2)
SELECT * FROM #Employee (NOLOCK)
;
WITH Emp_CTE
AS
(
SELECT EmpId,EmpName,Designation, ManagerID
,CASE WHEN ManagerID IS NULL THEN EmpId ELSE ManagerID END ManagerID_N
FROM #Employee
)
select EmpId,EmpName,Designation, ManagerID
FROM Emp_CTE
order BY ManagerID_N, EmpId
The new hooks way of doing this is to use useEffect instead of componentWillReceiveProps the old way:
componentWillReceiveProps(nextProps) {
// You don't have to do this check first, but it can help prevent an unneeded render
if (nextProps.startTime !== this.state.startTime) {
this.setState({ startTime: nextProps.startTime });
}
}
becomes the following in a functional hooks driven component:
// store the startTime prop in local state
const [startTime, setStartTime] = useState(props.startTime)
//
useEffect(() => {
if (props.startTime !== startTime) {
setStartTime(props.startTime);
}
}, [props.startTime]);
we set the state using setState, using useEffect we check for changes to the specified prop, and take the action to update the state on change of the prop.
just had this problem with a nodejs server.
here is how i fixed it.
i run my node server through a nginx proxy
and i set nginx and node
to both allow cross domain requests
and it didnt like that so i removed it from nginx and left it in node and all was well.
I find git stash very useful for temporal handling of all 'dirty' states.
Easiest way to export Excel to Html table
$file_name ="file_name.xls";
$excel_file="Your Html Table Code";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file_name");
echo $excel_file;
Neither one of the solutions worked form me. The only one that worked for me in Spring form is:
action="./upload?${_csrf.parameterName}=${_csrf.token}"
REPLACED WITH:
action="./upload?_csrf=${_csrf.token}"
(Spring 5 with enabled csrf in java configuration)
One big difference with python 3.4 + pycharm is that the dict() constructor produces a "syntax error" message if the number of keys exceeds 256.
I prefer using the dict literal now.
Use listboxControl.Column(intColumn,intRow)
. Both Column and Row are zero-based.
Windows 10 Solution:
For me this issue was due to downloading and creating an AVD using Android Studio and then trying to use that virtual device with the Ionic command line. I resolved this by deleting all existing emulators and creating a new one from the command line.
(the avdmanager file typically lives in C:\Users\\Android\sdk\tools\bin)
List existing emulators: avdmanager list avd
Delete an existing emulator: avdmanager delete avd -n emulator_name
Add system image: sdkmanager "system-images;android-24;default;x86_64"
Create new emulator: sdkmanager "system-images;android-27;google_apis_playstore;x86"
Instead of wading through the description of all the options, you can jump to 3.4.3 Short Options Cross Reference
under the info tar
command.
x
means --extract
. v
means --verbose
. f
means --file
. z
means --gzip
. You can combine one-letter arguments together, and f
takes an argument, the filename. There is something you have to watch out for:
Short options' letters may be clumped together, but you are not required to do this (as compared to old options; see below). When short options are clumped as a set, use one (single) dash for them all, e.g., ''tar' -cvf'. Only the last option in such a set is allowed to have an argument(1).
This old way of writing 'tar' options can surprise even experienced users. For example, the two commands:tar cfz archive.tar.gz file tar -cfz archive.tar.gz file
are quite different. The first example uses 'archive.tar.gz' as the value for option 'f' and recognizes the option 'z'. The second example, however, uses 'z' as the value for option 'f' -- probably not what was intended.
Creating the template page is the correct answer. For this, just add this into the page you created inside the theme folder:
<?php
/*
Template Name: mytemplate
*/
?>
For running this code, you need to select "mytemplate" as the template of the page from the back end.
Please see this link for getting the correct details https://developer.wordpress.org/themes/template-files-section/page-template-files/.
You should better use jquery-confirm rather than trying to remove that checkbox.
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to refund invoice ?',
confirm: function(){
//do something
},
cancel: function(){
//do something
}
});
time.monotonic() (basically your computer's uptime in seconds) is guarranteed to not misbehave when your computer's clock is adjusted (such as when transitioning to/from daylight saving time).
>>> import time
>>>
>>> time.monotonic()
452782.067158593
>>>
>>> a = time.monotonic()
>>> time.sleep(1)
>>> b = time.monotonic()
>>> print(b-a)
1.001658110995777
Without using a lambda function and for valid inputs only, I think it's clearer to do this:
Array.ConvertAll<string, int>(value.Split(','), Convert.ToInt32);
Use http://www.proxomitron.info and set up the header you want, etc.
If the vectors are not showing individually set colors using fillColor then they may be being set to a default widget parameter.
Try adding app:itemIconTint="@color/lime"
to activity_main.xml to set a default color type for the widget icons.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="@layout/app_bar_main"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="@+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="@layout/nav_header_main"
app:itemIconTint="@color/lime"
app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>
I've taken the OP's sproc and made it reusable and schema independent. Obviously it still requires MySQL 5.
DROP PROCEDURE IF EXISTS AddCol;
DELIMITER //
CREATE PROCEDURE AddCol(
IN param_schema VARCHAR(100),
IN param_table_name VARCHAR(100),
IN param_column VARCHAR(100),
IN param_column_details VARCHAR(100)
)
BEGIN
IF NOT EXISTS(
SELECT NULL FROM information_schema.COLUMNS
WHERE COLUMN_NAME=param_column AND TABLE_NAME=param_table_name AND table_schema = param_schema
)
THEN
set @paramTable = param_table_name ;
set @ParamColumn = param_column ;
set @ParamSchema = param_schema;
set @ParamColumnDetails = param_column_details;
/* Create the full statement to execute */
set @StatementToExecute = concat('ALTER TABLE `',@ParamSchema,'`.`',@paramTable,'` ADD COLUMN `',@ParamColumn,'` ',@ParamColumnDetails);
/* Prepare and execute the statement that was built */
prepare DynamicStatement from @StatementToExecute ;
execute DynamicStatement ;
/* Cleanup the prepared statement */
deallocate prepare DynamicStatement ;
END IF;
END //
DELIMITER ;
/* Portrait and Landscape */
@media only screen
and (min-device-width: 375px)
and (max-device-width: 812px)
and (-webkit-min-device-pixel-ratio: 3)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
/* Portrait and Landscape */
@media only screen
and (min-device-width: 414px)
and (max-device-width: 736px)
and (-webkit-min-device-pixel-ratio: 3)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
/* Portrait and Landscape */
@media only screen
and (min-device-width: 375px)
and (max-device-width: 667px)
and (-webkit-min-device-pixel-ratio: 2)
/* uncomment for only portrait: */
/* and (orientation: portrait) */
/* uncomment for only landscape: */
/* and (orientation: landscape) */ {
}
Instead of using the pyodbc library, use the pypyodbc library... This worked for me.
import pypyodbc
conn = pypyodbc.connect("DRIVER={SQL Server};"
"SERVER=server;"
"DATABASE=database;"
"Trusted_Connection=yes;")
cursor = conn.cursor()
cursor.execute('SELECT * FROM [table]')
for row in cursor:
print('row = %r' % (row,))
input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}
__file__
is absolute since Python 3.4, except when executing a script directly using a relative path:
Module
__file__
attributes (and related values) should now always contain absolute paths by default, with the sole exception of__main__.__file__
when a script has been executed directly using a relative path. (Contributed by Brett Cannon in bpo-18416.)
Not sure if it resolves symlinks though.
Example of passing a relative path:
$ python script.py
You can't alter the existing columns for identity.
You have 2 options,
Create a new table with identity & drop the existing table
Create a new column with identity & drop the existing column
Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.
CREATE TABLE dbo.Tmp_Names
(
Id int NOT NULL
IDENTITY(1, 1),
Name varchar(50) NULL
)
ON [PRIMARY]
go
SET IDENTITY_INSERT dbo.Tmp_Names ON
go
IF EXISTS ( SELECT *
FROM dbo.Names )
INSERT INTO dbo.Tmp_Names ( Id, Name )
SELECT Id,
Name
FROM dbo.Names TABLOCKX
go
SET IDENTITY_INSERT dbo.Tmp_Names OFF
go
DROP TABLE dbo.Names
go
Exec sp_rename 'Tmp_Names', 'Names'
Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.
Alter Table Names
Add Id_new Int Identity(1, 1)
Go
Alter Table Names Drop Column ID
Go
Exec sp_rename 'Names.Id_new', 'ID', 'Column'
See the following Microsoft SQL Server Forum post for more details:
Void doesn't return anything; it tells the compiler the method doesn't have a return value.
MessageBox::Show
uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form
f = open('file.txt', 'r')
print f.read()
f.close()
From http://docs.python.org/tutorial/inputoutput.html
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’s memory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ("").
ng-model
and ng-checked
directives should not be used togetherFrom the Docs:
ngChecked
Sets the checked attribute on the element, if the expression inside
ngChecked
is truthy.Note that this directive should not be used together with
ngModel
, as this can lead to unexpected behavior.
Instead set the desired initial value from the controller:
<input type="checkbox" name="test" ng-model="testModel['item1']" ?n?g?-?c?h?e?c?k?e?d?=?"?t?r?u?e?"? />
Testing<br />
<input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2<br />
<input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3<br />
<input type="button" ng-click="submit()" value="Submit" />
$scope.testModel = { item1: true };
All below options worked for me.
Option 1: Annotation for FIELD at class & field level with getter/setter methods
@XmlRootElement(name = "fields")
@XmlAccessorType(XmlAccessType.FIELD)
public class Fields {
@XmlElement(name = "field")
List<Field> fields = new ArrayList<Field>();
//getter, setter
}
Option 2: No Annotation for FIELD at class level(@XmlAccessorType(XmlAccessType.FIELD) and with only getter method. Adding Setter method will throw the error as we are not including the Annotation in this case. Remember, setter is not required when you explicitly set the values in your XML file.
@XmlRootElement(name = "fields")
public class Fields {
@XmlElement(name = "field")
List<Field> fields = new ArrayList<Field>();
//getter
}
Option 3: Annotation at getter method alone. Remember we can also use the setter method here as we are not doing any FIELD level annotation in this case.
@XmlRootElement(name = "fields")
public class Fields {
List<Field> fields = new ArrayList<Field>();
@XmlElement(name = "field")
//getter
//setter
}
Hope this helps you!
You could use Convert.ChangeType()
:
public static T ConfigSetting<T>(string settingName)
{
return (T)Convert.ChangeType(ConfigurationManager.AppSettings[settingName], typeof(T));
}
With the parentheses:
setTimeout("alertMsg()", 3000); // It work, here it treat as a function
Without the quotes and the parentheses:
setTimeout(alertMsg, 3000); // It also work, here it treat as a function
And the third is only using quotes:
setTimeout("alertMsg", 3000); // It not work, here it treat as a string
function alertMsg1() {_x000D_
alert("message 1");_x000D_
}_x000D_
function alertMsg2() {_x000D_
alert("message 2");_x000D_
}_x000D_
function alertMsg3() {_x000D_
alert("message 3");_x000D_
}_x000D_
function alertMsg4() {_x000D_
alert("message 4");_x000D_
}_x000D_
_x000D_
// this work after 2 second_x000D_
setTimeout(alertMsg1, 2000);_x000D_
_x000D_
// This work immediately_x000D_
setTimeout(alertMsg2(), 4000);_x000D_
_x000D_
// this fail_x000D_
setTimeout('alertMsg3', 6000);_x000D_
_x000D_
// this work after 8second_x000D_
setTimeout('alertMsg4()', 8000);
_x000D_
In the above example first alertMsg2() function call immediately (we give the time out 4S but it don't bother) after that alertMsg1() (A time wait of 2 Second) then alertMsg4() (A time wait of 8 Second) but the alertMsg3() is not working because we place it within the quotes without parties so it is treated as a string.
You can use JPQL:
TypedQuery <Object[]> query = em.createQuery(
"SELECT p.projectId, p.projectName FROM projects AS p", Object[].class);
List<Object[]> results = query.getResultList();
or you can use native sql query.
Query query = em.createNativeQuery("sql statement");
List<Object[]> results = query.getResultList();
Basically there are two ways: query DB (data length + index length) or check files size. Index length is related to data stored in indexes.
Everything is described here:
http://www.mkyong.com/mysql/how-to-calculate-the-mysql-database-size/
'&' performs both tests, while '&&' only performs the 2nd test if the first is also true. This is known as shortcircuiting and may be considered as an optimization. This is especially useful in guarding against nullness(NullPointerException).
if( x != null && x.equals("*BINGO*") {
then do something with x...
}
The easiest way is to use date
, which lets you mix hard-coded values with ones extracted from a timestamp. If you don't give a timestamp, it assumes the current date and time.
// Current timestamp is assumed, so these find first and last day of THIS month
$first_day_this_month = date('m-01-Y'); // hard-coded '01' for first day
$last_day_this_month = date('m-t-Y');
// With timestamp, this gets last day of April 2010
$last_day_april_2010 = date('m-t-Y', strtotime('April 21, 2010'));
date()
searches the string it's given, like 'm-t-Y'
, for specific symbols, and it replaces them with values from its timestamp. So we can use those symbols to extract the values and formatting that we want from the timestamp. In the examples above:
Y
gives you the 4-digit year from the timestamp ('2010')m
gives you the numeric month from the timestamp, with a leading zero ('04')t
gives you the number of days in the timestamp's month ('30')You can be creative with this. For example, to get the first and last second of a month:
$timestamp = strtotime('February 2012');
$first_second = date('m-01-Y 00:00:00', $timestamp);
$last_second = date('m-t-Y 12:59:59', $timestamp); // A leap year!
See http://php.net/manual/en/function.date.php for other symbols and more details.
I found that, despite what the docs indicate, the only way to get this to work is like this:
$ids = array(...); // Array of your values
$qb->add('where', $qb->expr()->in('r.winner', $ids));
http://groups.google.com/group/doctrine-dev/browse_thread/thread/fbf70837293676fb
\b\d+,
\b------->word boundary
\d+------>one or digit
,-------->containing commas,
Eg:
sddsgg 70,000 sdsfdsf fdgfdg70,00
sfsfsd 5,44,4343 5.7788,44 555
It will match:
70,
5,
44,
,44
On Mac
Netbeans 8.0.2 Tools -> Plugins -> type in search: Dark Look and Feel. Then install plugin.
NOTE: There is no "Option" Or "Appearance" in the "Tools" section in Netbeans 8.0.2.
It allows browsers to determine if they can handle the scripting/style language before making a request for the script or stylesheet (or, in the case of embedded script/style, identify which language is being used).
This would be much more important if there had been more competition among languages in browser space, but VBScript never made it beyond IE and PerlScript never made it beyond an IE specific plugin while JSSS was pretty rubbish to begin with.
The draft of HTML5 makes the attribute optional.
_x000D_
table tbody_x000D_
{_x000D_
border:1px solid red;_x000D_
}_x000D_
table td_x000D_
{_x000D_
background:yellow;_x000D_
_x000D_
border-bottom:1px solid green;_x000D_
_x000D_
_x000D_
}_x000D_
.tr0{_x000D_
line-height:0;_x000D_
}_x000D_
.tr0 td{_x000D_
background:red;_x000D_
}
_x000D_
<table>_x000D_
<tbody>_x000D_
<tr><td>test</td></tr>_x000D_
<tr><td>test</td></tr> _x000D_
<tr class="tr0"><td></td></tr>_x000D_
</tbody>_x000D_
</table>
_x000D_
It might not work correctly when using a program that is not attached to the console, because that app might still be running while you think you have the exit code. A solution to do it in C++ looks like below:
#include "stdafx.h"
#include "windows.h"
#include "stdio.h"
#include "tchar.h"
#include "stdio.h"
#include "shellapi.h"
int _tmain( int argc, TCHAR *argv[] )
{
CString cmdline(GetCommandLineW());
cmdline.TrimLeft('\"');
CString self(argv[0]);
self.Trim('\"');
CString args = cmdline.Mid(self.GetLength()+1);
args.TrimLeft(_T("\" "));
printf("Arguments passed: '%ws'\n",args);
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc < 2 )
{
printf("Usage: %s arg1,arg2....\n", argv[0]);
return -1;
}
CString strCmd(args);
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
(LPTSTR)(strCmd.GetString()), // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d)\n", GetLastError() );
return GetLastError();
}
else
printf( "Waiting for \"%ws\" to exit.....\n", strCmd );
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
int result = -1;
if(!GetExitCodeProcess(pi.hProcess,(LPDWORD)&result))
{
printf("GetExitCodeProcess() failed (%d)\n", GetLastError() );
}
else
printf("The exit code for '%ws' is %d\n",(LPTSTR)(strCmd.GetString()), result );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
return result;
}
I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;
Width:100%
and text-align:center
would work in my experience
<p style="display:block; line-height: 70px; width:100%; text-align:center; margin:0 auto;"><button type="submit" class="btn">Confirm</button></p>
Easier way is also to do this.
let elementReference = document.querySelector('<your css, #id selector>');
if (elementReference instanceof HTMLElement) {
elementReference.focus();
}
In some cases (e.g. html generated and inserted by JavaScript) you also may want to try to insert a zero width joiner:
.wrapper{_x000D_
width: 290px; _x000D_
white-space: no-wrap;_x000D_
resize:both;_x000D_
overflow:auto; _x000D_
border: 1px solid gray;_x000D_
}_x000D_
_x000D_
.breakable-text{_x000D_
display: inline;_x000D_
white-space: no-wrap;_x000D_
}_x000D_
_x000D_
.no-break-before {_x000D_
padding-left: 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<span class="breakable-text">Lorem dorem tralalalala LAST_WORDS</span>‍<span class="no-break-before">TOGETHER</span>_x000D_
</div>
_x000D_
Not only can you add raw strings to matplotlib but you can also specify the font in matplotlibrc or locally with:
from matplotlib import rc
rc('font', **{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)
This would change your serif latex font. You can also specify the sans-serif Helvetica like so
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
Other options are cursive
and monospace
with their respective font names.
Your label would then be
fig.gca().set_xlabel(r'wavelength $5000 \AA$')
If the font doesn't supply an Angstrom symbol you can try using \mathring{A}
Simply create a new column, set the Name
to whatever you like, set the Type
to INT
and check the box that says A_I
.
The A_I
checkbox stands for AUTO_INCREMENT
, which essentially means that sequence numbers are assigned automatically in that new column (see below).
column1 | column2 | id
-----------------------
value | value | 1
-----------------------
value | value | 2
-----------------------
value | value | 3
-----------------------
value | value | 4
This column essentially acts as a reference for phpMyAdmin to delete rows from. If necessary, click on the unique button for this new column, although this happened automatically for me. After following the above steps, you should no longer have the error message and buttons should appear for editing rows in phpMyAdmin!
Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim
Due to this article is a good SEO site, so I suggest to use build-in function "mb_convert_variables" to solve this problem. It works with simple syntax.
mb_convert_variables('utf-8', 'original encode', array/object)
Such unexpected problems can appear when you copy the code from a web page or email and the text contains unprintable characters like individual CR or LF and non-breaking spaces.
Found this in google groups and this worked for me..
Paint clearPaint = new Paint();
clearPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
canvas.drawRect(0, 0, width, height, clearPaint);
This removes drawings rectangles etc. while keeping set bitmap..
add setOnItemSelectedListener to spinner reference and get the data like that`
mSizeSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
selectedSize=adapterView.getItemAtPosition(position).toString();
This is taken from the Python docs:
Identifiers (also referred to as names) are described by the following lexical definitions:
identifier ::= (letter|"_") (letter | digit | "_")*
letter ::= lowercase | uppercase
lowercase ::= "a"..."z"
uppercase ::= "A"..."Z"
digit ::= "0"..."9"
Identifiers are unlimited in length. Case is significant.
That should explain how to name your variables.
This is link by Tomas has a well written script to zip contents of a folder.
To make it work just copy the script into a batch file and execute it by specifying the folder to be zipped(source).
No need to mention destination directory as it is defaulted in the script to Desktop ("%USERPROFILE%\Desktop")
Copying the script here, just incase the web-link is down:
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET sourceDirPath=%1
IF [%2] EQU [] (
SET destinationDirPath="%USERPROFILE%\Desktop"
) ELSE (
SET destinationDirPath="%2"
)
IF [%3] EQU [] (
SET destinationFileName="%~n1%.zip"
) ELSE (
SET destinationFileName="%3"
)
SET tempFilePath=%TEMP%\FilesToZip.txt
TYPE NUL > %tempFilePath%
FOR /F "DELIMS=*" %%i IN ('DIR /B /S /A-D "%sourceDirPath%"') DO (
SET filePath=%%i
SET dirPath=%%~dpi
SET dirPath=!dirPath:~0,-1!
SET dirPath=!dirPath:%sourceDirPath%=!
SET dirPath=!dirPath:%sourceDirPath%=!
ECHO .SET DestinationDir=!dirPath! >> %tempFilePath%
ECHO "!filePath!" >> %tempFilePath%
)
MAKECAB /D MaxDiskSize=0 /D CompressionType=MSZIP /D Cabinet=ON /D Compress=ON /D UniqueFiles=OFF /D DiskDirectoryTemplate=%destinationDirPath% /D CabinetNameTemplate=%destinationFileName% /F %tempFilePath% > NUL 2>&1
DEL setup.inf > NUL 2>&1
DEL setup.rpt > NUL 2>&1
DEL %tempFilePath% > NUL 2>&1
They all do different things, since matplotlib uses a hierarchical order in which a figure window contains a figure which may consist of many axes. Additionally, there are functions from the pyplot interface and there are methods on the Figure
class. I will discuss both cases below.
pyplot
is a module that collects a couple of functions that allow matplotlib to be used in a functional manner. I here assume that pyplot
has been imported as import matplotlib.pyplot as plt
.
In this case, there are three different commands that remove stuff:
plt.cla()
clears an axes, i.e. the currently active axes in the current figure. It leaves the other axes untouched.
plt.clf()
clears the entire current figure with all its axes, but leaves the window opened, such that it may be reused for other plots.
plt.close()
closes a window, which will be the current window, if not specified otherwise.
Which functions suits you best depends thus on your use-case.
The close()
function furthermore allows one to specify which window should be closed. The argument can either be a number or name given to a window when it was created using figure(number_or_name)
or it can be a figure instance fig
obtained, i.e., usingfig = figure()
. If no argument is given to close()
, the currently active window will be closed. Furthermore, there is the syntax close('all')
, which closes all figures.
Additionally, the Figure
class provides methods for clearing figures.
I'll assume in the following that fig
is an instance of a Figure
:
fig.clf()
clears the entire figure. This call is equivalent to plt.clf()
only if fig
is the current figure.
fig.clear()
is a synonym for fig.clf()
Note that even del fig
will not close the associated figure window. As far as I know the only way to close a figure window is using plt.close(fig)
as described above.
In header.php
insert this code to show menu:
<?php
wp_nav_menu(
array(
'theme_location' => 'menu-one',
'walker' => new Custom_Walker_Nav_Menu_Top
)
);
?>
In functions.php
use this:
class Custom_Walker_Nav_Menu_top extends Walker_Nav_Menu
{
function start_el( &$output, $item, $depth = 0, $args = array(), $id = 0 ) {
$is_current_item = '';
if(array_search('current-menu-item', $item->classes) != 0)
{
$is_current_item = ' class="active"';
}
echo '<li'.$is_current_item.'><a href="'.$item->url.'">'.$item->title;
}
function end_el( &$output, $item, $depth = 0, $args = array() ) {
echo '</a></li>';
}
}
Even better
#include <stdio.h>
int
main(void)
{
char *line = NULL;
size_t count;
char *dup_line;
getline(&line,&count, stdin);
dup_line=strdup(line);
puts(dup_line);
free(dup_line);
free(line);
return 0;
}
Give the Exec Maven plugin a try
The JSON approach works, on ie 7 you need json2.js, with it it works perfectly and despite the one comment saying otherwise there is localStorage on it. it really seems like the best solution with the least hassle. Of course one could write scripts to do essentially the same thing as json2 does but there is little point in that.
at least with the following version string there is localStorage, but as said you need to include json2.js because that isn't included by the browser itself: 4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; BRI/2; NP06; .NET4.0C; .NET4.0E; Zune 4.7) (I would have made this a comment on the reply, but can't).
$ rails server -b $IP -p $PORT - that solved the same problem for me
In the W3 wiki page about structuring HTML5, it says:
<section>
: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.
And then displays an image that I cleaned up:
It's also important to know how to use the <article>
tag (from the same W3 link above):
<article>
is related to<section>
, but is distinctly different. Whereas<section>
is for grouping distinct sections of content or functionality,<article>
is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then<article>
is suitable for marking them up.In our example,
<section id="main">
contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore<article>
is perfect for them:
<section id="main">
<article>
<!-- first blog post -->
</article>
<article>
<!-- second blog post -->
</article>
<article>
<!-- third blog post -->
</article>
</section>
Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:
<article>
<section id="introduction">
</section>
<section id="content">
</section>
<section id="summary">
</section>
</article>
For completeness: with dplyr v0.2 ddply
with colwise
will also do this:
> ddply(df, .(grp), colwise(mean))
grp a b c d
1 1 4.333333 4.00 1.000000 2.000000
2 2 2.000000 2.75 2.750000 2.750000
3 3 3.000000 4.00 4.333333 3.666667
but it is slower, at least in this case:
> microbenchmark(ddply(df, .(grp), colwise(mean)),
df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
expr min lq mean
ddply(df, .(grp), colwise(mean)) 3.278002 3.331744 3.533835
df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337
median uq max neval
3.353633 3.378089 7.592209 100
1.121954 1.133428 2.292216 100
Starting file:
line 1
line 2
line 3
line 4
Code:
with open("filename.txt", "r") as f:
lines = f.readlines()
for line in lines:
stripped = line.strip()
print(stripped)
Output:
line 1
line 2
line 3
line 4
you can use this
List<Car> requiredCars = cars.stream()
.filter (t-> t!= null && StringUtils.startsWith(t.getName(),"M"))
.collect(Collectors.toList());
The correct answer is don't do that, use the HTML Agility Pack.
Edited to add:
To shamelessly steal from the comment below by jesse, and to avoid being accused of inadequately answering the question after all this time, here's a simple, reliable snippet using the HTML Agility Pack that works with even most imperfectly formed, capricious bits of HTML:
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(Properties.Resources.HtmlContents);
var text = doc.DocumentNode.SelectNodes("//body//text()").Select(node => node.InnerText);
StringBuilder output = new StringBuilder();
foreach (string line in text)
{
output.AppendLine(line);
}
string textOnly = HttpUtility.HtmlDecode(output.ToString());
There are very few defensible cases for using a regular expression for parsing HTML, as HTML can't be parsed correctly without a context-awareness that's very painful to provide even in a nontraditional regex engine. You can get part way there with a RegEx, but you'll need to do manual verifications.
Html Agility Pack can provide you a robust solution that will reduce the need to manually fix up the aberrations that can result from naively treating HTML as a context-free grammar.
A regular expression may get you mostly what you want most of the time, but it will fail on very common cases. If you can find a better/faster parser than HTML Agility Pack, go for it, but please don't subject the world to more broken HTML hackery.
Put a progress bar and the webview inside a relativelayout and set the properties for the progress bar as follows,
and then in onPageStarted() of the webclient make the progress bar visible so that it shows the progressbar when you have clicked on a link. In onPageFinished() make the progress bar visiblility as GONE so that it disappears when the page has finished loading... This will work fine for your scenario. Hope this helps...
Do it manually:
public static int strToInt(String str){
int i = 0;
int num = 0;
boolean isNeg = false;
// Check for negative sign; if it's there, set the isNeg flag
if (str.charAt(0) == '-') {
isNeg = true;
i = 1;
}
// Process each character of the string;
while( i < str.length()) {
num *= 10;
num += str.charAt(i++) - '0'; // Minus the ASCII code of '0' to get the value of the charAt(i++).
}
if (isNeg)
num = -num;
return num;
}
Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.
(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )
It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:
define('SMTP_SERVER', 'smtp.ebola.cz');
into this:
define('SMTP_SERVER', 'ssl://smtp.ebola.cz');
Multiple column search with dataframe:
frame[frame.filename.str.match('*.'+MetaData+'.*') & frame.file_path.str.match('C:\test\test.txt')]
Unfortunately oracle doesnot support auto_increment like mysql does. You need to put a little extra effort to get that.
say this is your table -
CREATE TABLE MYTABLE (
ID NUMBER NOT NULL,
NAME VARCHAR2(100)
CONSTRAINT "PK1" PRIMARY KEY (ID)
);
You will need to create a sequence -
CREATE SEQUENCE S_MYTABLE
START WITH 1
INCREMENT BY 1
CACHE 10;
and a trigger -
CREATE OR REPLACE TRIGGER T_MYTABLE_ID
BEFORE INSERT
ON MYTABLE
REFERENCING NEW AS NEW
FOR EACH ROW
BEGIN
if(:new.ID is null) then
SELECT S_MYTABLE.nextval
INTO :new.ID
FROM dual;
end if;
END;
/
ALTER TRIGGER "T_MYTABLE_ID" ENABLE;
The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc
A set of simple examples:
Using Gson:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
public class Gson {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
com.google.gson.Gson gson = new com.google.gson.Gson();
Response respuesta = gson.fromJson(json, Response.class);
System.out.println(respuesta.getExample());
System.out.println(respuesta.getFr());
} catch (IOException ex) {
}
return null;
}
public class Response{
private String example;
private String fr;
public String getExample() {
return example;
}
public void setExample(String example) {
this.example = example;
}
public String getFr() {
return fr;
}
public void setFr(String fr) {
this.fr = fr;
}
}
}
Using json-simple:
import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
public class JsonSimple {
public static void main(String[] args) {
}
public HttpResponse http(String url, String body) {
try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
HttpPost request = new HttpPost(url);
StringEntity params = new StringEntity(body);
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse result = httpClient.execute(request);
String json = EntityUtils.toString(result.getEntity(), "UTF-8");
try {
JSONParser parser = new JSONParser();
Object resultObject = parser.parse(json);
if (resultObject instanceof JSONArray) {
JSONArray array=(JSONArray)resultObject;
for (Object object : array) {
JSONObject obj =(JSONObject)object;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
}else if (resultObject instanceof JSONObject) {
JSONObject obj =(JSONObject)resultObject;
System.out.println(obj.get("example"));
System.out.println(obj.get("fr"));
}
} catch (Exception e) {
// TODO: handle exception
}
} catch (IOException ex) {
}
return null;
}
}
etc...
You need to set
document["pic1"].src = searchPic.src;
The searchPic itself is your Image(), you need to read the src that you set.
This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"
>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'
If you're inserting text content in your document in a location where text content is expected1, you typically only need to escape the same characters as you would in XML. Inside of an element, this just includes the entity escape ampersand &
and the element delimiter less-than and greater-than signs <
>
:
& becomes &
< becomes <
> becomes >
Inside of attribute values you must also escape the quote character you're using:
" becomes "
' becomes '
In some cases it may be safe to skip escaping some of these characters, but I encourage you to escape all five in all cases to reduce the chance of making a mistake.
If your document encoding does not support all of the characters that you're using, such as if you're trying to use emoji in an ASCII-encoded document, you also need to escape those. Most documents these days are encoded using the fully Unicode-supporting UTF-8 encoding where this won't be necessary.
In general, you should not escape spaces as
.
is not a normal space, it's a non-breaking space. You can use these instead of normal spaces to prevent a line break from being inserted between two words, or to insert extra space without it being automatically collapsed, but this is usually a rare case. Don't do this unless you have a design constraint that requires it.
1 By "a location where text content is expected", I mean inside of an element or quoted attribute value where normal parsing rules apply. For example: <p>HERE</p>
or <p title="HERE">...</p>
. What I wrote above does not apply to content that has special parsing rules or meaning, such as inside of a script or style tag, or as an element or attribute name. For example: <NOT-HERE>...</NOT-HERE>
, <script>NOT-HERE</script>
, <style>NOT-HERE</style>
, or <p NOT-HERE="...">...</p>
.
In these contexts, the rules are more complicated and it's much easier to introduce a security vulnerability. I strongly discourage you from ever inserting dynamic content in any of these locations. I have seen teams of competent security-aware developers introduce vulnerabilities by assuming that they had encoded these values correctly, but missing an edge case. There's usually a safer alternative, such as putting the dynamic value in an attribute and then handling it with JavaScript.
If you must, please read the Open Web Application Security Project's XSS Prevention Rules to help understand some of the concerns you will need to keep in mind.
Assuming your json object from your GET request looks like the one you posted above simply do:
let list: string[] = [];
json.Results.forEach(element => {
list.push(element.Id);
});
Or am I missing something that prevents you from doing it this way?
db.users.count()
db.users.remove({})
db.users.count()
visibility=hidden
is very useful, but it will still take up space on the page. You can also use
display=none
because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")
using 'm_' or '_' in the front of a variable makes it easier to spot member variables in methods throughout an object.
As a side benefit typing 'm_' or '_' will make intellsense pop them up first ;)
Using Following Code You Solve thisQuestion.... If you run a file using localhost server than this problem solve by following Jsp Page Code.This Code put Between Head Tag in jsp file
<style type="text/css">
<%@include file="css/style.css" %>
</style>
<script type="text/javascript">
<%@include file="js/script.js" %>
</script>
You can use card-deck, it will align all the cards... this come from bootstrap 4 official page.
<div class="card-deck">
<div class="card">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a longer card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
<div class="card">
<img class="card-img-top" src="..." alt="Card image cap">
<div class="card-body">
<h5 class="card-title">Card title</h5>
<p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>
<p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p>
</div>
</div>
</div>
The initial issue is solved by changing lat
and lon
to double.
I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider);
It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).
Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);
Also, even with permissions in manifest
, the code works when location service is enabled in Android settings on a device.
It can be done this way as well
foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
{
//do your stuff here
company.Id= 2;
company.Name= "Sample"
}
It's worth reading Oracle Java Tutorial - Getting and Setting Field Values
Field#set(Object object, Object value) sets the field represented by this Field
object on the specified object argument to the specified new value.
It should be like this
f.set(objectOfTheClass, new ConcurrentHashMap<>());
You can't set any value in null
Object If tried then it will result in NullPointerException
Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.
Internet Explorer doesn't fully support Flexbox due to:
Partial support is due to large amount of bugs present (see known issues).
Screenshot and infos taken from caniuse.com
Internet Explorer before 10 doesn't support Flexbox, while IE 11 only supports the 2012 syntax.
display: flex
and flex-direction: column
will not properly calculate their flexed childrens' sizes if the container has min-height
but no explicit height
property. See bug.flex
is 0 0 auto
rather than 0 1 auto
as defined in the latest spec.min-height
is used. See bug.Flexbugs is a community-curated list of Flexbox issues and cross-browser workarounds for them. Here's a list of all the bugs with a workaround available and the browsers that affect.
align-items: center
overflow their containermin-height
on a flex container won't apply to its flex itemsflex
shorthand declarations with unitless flex-basis
values are ignoredflex
items don't always preserve intrinsic aspect ratiosflex-basis
doesn't account for box-sizing: border-box
flex-basis
doesn't support calc()
align-items: baseline
doesn't work with nested flex containersflex-flow: column wrap
do not contain their itemsmargin: auto
on the cross axisflex-basis
cannot be animatedmax-width
is usedOS : Windows 7 & IIS 7
If you still have permission denied after adding IUSR & NETWORK SERVICE. Add also IIS_WPG. The addition of this last user solved my problem.
For people who can't find those users: when you're trying to add a user in security of the folder (properties of the folder), click on "Advanced" of the window "Select Users or Groups". Change the location to the computer name then click on "Find Now". You'll find those users in the list below.
Make sure to target x86 on your project in Visual Studio. This should fix your trouble.
In addition to the missing quotes around 100Mb
in the last else
, you also want to quote the constants in your if-statements if tSizeAns == "1":
, because raw_input
returns a string, which in comparison with an integer will always return false.
However the missing quotes are not the reason for the particular error message, because it would result in an syntax error before execution. Please check your posted code. I cannot reproduce the error message.
Also if ... elif ... else
in the way you use it is basically equivalent to a case
or switch
in other languages and is neither less readable nor much longer. It is fine to use here. One other way that might be a good idea to use if you just want to assign a value based on another value is a dictionary lookup:
tSize = {"1": "100Mb", "2": "200Mb"}[tSizeAns]
This however does only work as long as tSizeAns
is guaranteed to be in the range of tSize
. Otherwise you would have to either catch the KeyError
exception or use a defaultdict:
lookup = {"1": "100Mb", "2": "200Mb"} try: tSize = lookup[tSizeAns] except KeyError: tSize = "100Mb"
or
from collections import defaultdict [...] lookup = defaultdict(lambda: "100Mb", {"1": "100Mb", "2": "200Mb"}) tSize = lookup[tSizeAns]
In your case I think these methods are not justified for two values. However you could use the dictionary to construct the initial output at the same time.