This happened to me earlier (didn't have access to an EC2 instance someone else created but had access to AWS web console) and I blogged the answer: http://readystate4.com/2013/04/09/aws-gaining-ssh-access-to-an-ec2-instance-you-lost-access-to/
Basically, you can detached the EBS drive, attach it to an EC2 that you do have access to. Add your SSH pub key to ~ec2-user/.ssh/authorized_keys
on this attached drive. Then put it back on the old EC2 instance. step-by-step in the link using Amazon AMI.
No need to make snapshots or create a new cloned instance.
Click the "activity monitor" icon in the toolbar.
In SQL Server Management Studio, right click on Server, choose "Activity Monitor" from context menu -or- use keyboard shortcut Ctrl + Alt + A.
Reference: Microsoft Docs - Open Activity Monitor in SQL Server Management Studio (SSMS)
if (dr[dc.ColumnName].GetType().ToString() == "System.DateTime")
To do this with multiple images you need to run though an .each()
function. This works but I'm not sure how efficient it is.
$('img').hide();
$('img').each( function(){
$(this).on('load', function () {
$(this).fadeIn();
});
});
I know this is an old question. But i couldnt get the jquery $(this).change() event to fire correctly onSelect. So i went with the following approach to fire the change event via vanilla js.
$('.date').datepicker({
showOn: 'focus',
dateFormat: 'mm-dd-yy',
changeMonth: true,
changeYear: true,
onSelect: function() {
var event;
if(typeof window.Event == "function"){
event = new Event('change');
this.dispatchEvent(event);
} else {
event = document.createEvent('HTMLEvents');
event.initEvent('change', false, false);
this.dispatchEvent(event);
}
}
});
Using filter_var() will fail for urls with non-ascii chars, e.g. (http://pt.wikipedia.org/wiki/Guimarães). The following function encode all non-ascii chars (e.g. http://pt.wikipedia.org/wiki/Guimar%C3%A3es) before calling filter_var().
Hope this helps someone.
<?php
function validate_url($url) {
$path = parse_url($url, PHP_URL_PATH);
$encoded_path = array_map('urlencode', explode('/', $path));
$url = str_replace($path, implode('/', $encoded_path), $url);
return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}
// example
if(!validate_url("http://somedomain.com/some/path/file1.jpg")) {
echo "NOT A URL";
}
else {
echo "IS A URL";
}
I add the following code to my pom.xml
file. It solved my problem.
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
I found a solution by myself after doing some research:
Now everything works fine.
Again I suggest Simple and Easy
Its Working Perfect with ajax when user search and select it saves the selected information via ajax
$("#vendor-brands").select2({
ajax: {
url:site_url('general/get_brand_ajax_json'),
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
}).on("change", function(e) {
var lastValue = $("#vendor-brands option:last-child").val();
var lastText = $("#vendor-brands option:last-child").text();
alert(lastValue+' '+lastText);
});
app.use(express.favicon(__dirname + '/public/images/favicon.ico'));
I had it working locally without the __dirname +
but couldn't get it working on my deployed server.
You could create a Hashmap<String, Object>
using one of the values as a key, and then seeing if yourHashMap.keySet().contains(yourValue)
returns true.
Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,
Could not open input file: artisan
Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.
I used SOAP UI for functional and automated testing. SOAP UI allows you to run the tests on the click of a button. There is also a spring controllers testing page created by Ted Young. I used this article to create Rest unit tests in our application.
If someone is here in 2020, after making all the pipes, if u pipe %>% na.exclude
will take away all the NAs in the pipe!
If you want to set typeface to all the TextViews in the entire Activity you can use something like this:
public static void setTypefaceToAll(Activity activity)
{
View view = activity.findViewById(android.R.id.content).getRootView();
setTypefaceToAll(view);
}
public static void setTypefaceToAll(View view)
{
if (view instanceof ViewGroup)
{
ViewGroup g = (ViewGroup) view;
int count = g.getChildCount();
for (int i = 0; i < count; i++)
setTypefaceToAll(g.getChildAt(i));
}
else if (view instanceof TextView)
{
TextView tv = (TextView) view;
setTypeface(tv);
}
}
public static void setTypeface(TextView tv)
{
TypefaceCache.setFont(tv, TypefaceCache.FONT_KOODAK);
}
And the TypefaceCache:
import java.util.TreeMap;
import android.graphics.Typeface;
import android.widget.TextView;
public class TypefaceCache {
//Font names from asset:
public static final String FONT_ROBOTO_REGULAR = "fonts/Roboto-Regular.ttf";
public static final String FONT_KOODAK = "fonts/Koodak.ttf";
private static TreeMap<String, Typeface> fontCache = new TreeMap<String, Typeface>();
public static Typeface getFont(String fontName) {
Typeface tf = fontCache.get(fontName);
if(tf == null) {
try {
tf = Typeface.createFromAsset(MyApplication.getAppContext().getAssets(), fontName);
}
catch (Exception e) {
return null;
}
fontCache.put(fontName, tf);
}
return tf;
}
public static void setFont(TextView tv, String fontName)
{
tv.setTypeface(getFont(fontName));
}
}
Another way to do it is using the StructField if you have multiple fields that needs to be modified.
Ex:
from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
StructField('OPEN_FLG',IntegerType(),True),
StructField('I1_GNDR_CODE',StringType(),True),
StructField('TRW_INCOME_CD_V4',StringType(),True),
StructField('ASIAN_CD',IntegerType(),True),
StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)
Output:
Before
root
|-- CLICK_FLG: string (nullable = true)
|-- OPEN_FLG: string (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)
After:
root
|-- CLICK_FLG: integer (nullable = true)
|-- OPEN_FLG: integer (nullable = true)
|-- I1_GNDR_CODE: string (nullable = true)
|-- TRW_INCOME_CD_V4: string (nullable = true)
|-- ASIAN_CD: integer (nullable = true)
|-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)
This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.
It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.
I've used the implementation above and just now I came to know that it doesn't work on iPad running iOS 13. I had to add these lines before present() call in order to make it work
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
That's how it works for me
func shareData(_ dataToShare: [Any]){
let activityViewController = UIActivityViewController(activityItems: dataToShare, applicationActivities: nil)
//exclude some activity types from the list (optional)
//activityViewController.excludedActivityTypes = [
//UIActivity.ActivityType.postToFacebook
//]
//avoiding to crash on iPad
if let popoverController = activityViewController.popoverPresentationController {
popoverController.sourceRect = CGRect(x: UIScreen.main.bounds.width / 2, y: UIScreen.main.bounds.height / 2, width: 0, height: 0)
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
self.present(activityViewController, animated: true, completion: nil)
}
Why don't you just right click on the main()
method and choose "Debug As... Java Application"
?
var isValid = true;
$("#tabledata").find("#tablebody").find("input").each(function() {
var element = $(this);
if (element.val() == "") {
isValid = false;
}
else{
isValid = true;
}
});
console.log(isValid);
Suppose you want to initialize a two dimensional integer vector with n rows and m column each having value 'VAL'
Write it as
std::vector<vector<int>> arr(n, vector<int>(m,VAL));
This VAL can be a integer type variable or constant such as 100
The functions Math.round() and .toFixed() is meant to round to the nearest integer. You'll get incorrect results when dealing with decimals and using the "multiply and divide" method for Math.round() or parameter for .toFixed(). For example, if you try to round 1.005 using Math.round(1.005 * 100) / 100 then you'll get the result of 1, and 1.00 using .toFixed(2) instead of getting the correct answer of 1.01.
You can use following to solve this issue:
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2');
Add .toFixed(2) to get the two decimal places you wanted.
Number(Math.round(100 - (price / listprice) * 100 + 'e2') + 'e-2').toFixed(2);
You could make a function that will handle the rounding for you:
function round(value, decimals) {
return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
}
Example: https://jsfiddle.net/k5tpq3pd/36/
Alternativ
You can add a round function to Number using prototype. I would not suggest adding .toFixed() here as it would return a string instead of number.
Number.prototype.round = function(decimals) {
return Number((Math.round(this + "e" + decimals) + "e-" + decimals));
}
and use it like this:
var numberToRound = 100 - (price / listprice) * 100;
numberToRound.round(2);
numberToRound.round(2).toFixed(2); //Converts it to string with two decimals
Example https://jsfiddle.net/k5tpq3pd/35/
Source: http://www.jacklmoore.com/notes/rounding-in-javascript/
Note that according to the CSS3 spec, you do NOT have to wrap your layout in a table-style element. The browser will infer the existence of containing elements if they do not exist.
To rollback one commit (make sure you note the commit's hash for the next step):
git reset --hard HEAD^
To pull that commit into a different branch:
git checkout other-branch
git cherry-pick COMMIT-HASH
Also note that git reset --hard
will kill any untracked and modified changes you might have, so if you have those you might prefer:
git reset HEAD^
git checkout .
reg
and wire
specify how the object will be assigned and are therefore only meaningful for outputs.
If you plan to assign your output in sequential code,such as within an always
block, declare it as a reg
(which really is a misnomer for "variable" in Verilog). Otherwise, it should be a wire
, which is also the default.
Add the following to the top of your file # coding=utf-8
If you go to the link in the error you can seen the reason why:
Defining the Encoding
Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=
which <cmd>
also see options which
supports for aliases if applicable to your case.
Example
$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$
PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar"
for RHEL.
Its just because of the load time angular takes to give you the current state.
If you try to get the current state by using $timeout
function then it will give you correct result in $state.current.name
$timeout(function(){
$rootScope.currState = $state.current.name;
})
Floats are used to store a wider range of number than can be fit in an integer. These include decimal numbers and scientific notation style numbers that can be bigger values than can fit in 32 bits. Here's the deep dive into them: http://en.wikipedia.org/wiki/Floating_point
you cannot set this in javascript, you have to do this with html/css:
<style type="text/css" media="print">
@page { size: landscape; }
</style>
EDIT: See this Question and the accepted answer for more information on browser support: Is @Page { size:landscape} obsolete?
So before I found this post, I successfully found this to work.
Model._meta.fields
It works equally as
Model._meta.get_fields()
I'm not sure what the difference is in the results, if there is one. I ran this loop and got the same output.
for field in Model._meta.fields:
print(field.name)
A struct is a value type and a value type must have a default value as soon as it is declared.
MyClass m;
MyStruct m2;
If you declare two fields as above without instantiating either, then break the debugger, m
will be null but m2
will not. Given this, a parameterless constructor would make no sense, in fact all any constructor on a struct does is assign values, the thing itself already exists just by declaring it. Indeed m2 could quite happily be used in the above example and have its methods called, if any, and its fields and properties manipulated!
It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:
When location matches the last part of the directive’s value: it is better to use the root directive instead:
which would yield:
server {
listen 8080;
server_name www.mysite.com mysite.com;
error_log /home/www-data/logs/nginx_www.error.log;
error_page 404 /404.html;
location /public/doc/ {
autoindex on;
root /home/www-data/mysite;
}
location = /404.html {
root /home/www-data/mysite/static/html;
}
}
You can explicitly specify the return type of a lambda by using -> Type
after the arguments list:
[]() -> Type { }
However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.
Use the ViewContext
and look at the RouteData
collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.
You can select dropdown option value by name
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.
See my answer on Google Maps API 3 - Custom marker color for default (dot) marker
ssh -t 'command; bash -l'
will execute the command and then start up a login shell when it completes. For example:
ssh -t [email protected] 'cd /some/path; bash -l'
Search MSDN for "How to: Set Environment Variables for Projects". (It's Project>Properties>Configuration Properties>Debugging "Environment" and "Merge Environment" properties for those who are in a rush.)
The syntax is NAME=VALUE and macros can be used (for example, $(OutDir)).
For example, to prepend C:\Windows\Temp to the PATH:
PATH=C:\WINDOWS\Temp;%PATH%
Similarly, to append $(TargetDir)\DLLS to the PATH:
PATH=%PATH%;$(TargetDir)\DLLS
What worked for me, is registering it on the Page while specifying the type as that of the UpdatePanel, like so:
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel) Guid.NewGuid().ToString(), myScript, true);
Use this syntax for VB.NET 2005/2008 compatibility:
Dim theVar As New List(Of String)(New String() {"one", "two", "three"})
Although the VB.NET 2010 syntax is prettier.
You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:
.triple-border:after {_x000D_
content: " ";_x000D_
display: block;_x000D_
width: 100%;_x000D_
background: #FFE962;_x000D_
height: 9px;_x000D_
padding-bottom: 8px;_x000D_
border-bottom: 9px solid #A3C662;_x000D_
box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.
It appears to me that RFC 2616 does not specify this.
From section 4.3:
The presence of a message-body in a request is signaled by the inclusion of a Content-Length or Transfer-Encoding header field in the request's message-headers. A message-body MUST NOT be included in a request if the specification of the request method (section 5.1.1) does not allow sending an entity-body in requests. A server SHOULD read and forward a message-body on any request; if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.
And section 9.7:
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.c
So it's not explicitly allowed or disallowed, and there's a chance that a proxy along the way might remove the message body (although it SHOULD read and forward it).
Just give you some idea may help you, if you want fully control dialog, you can try to avoid use of default button options, and add buttons by yourself in your #dialog div. You also can put data into some dummy attribute of link, like Click. call attr("data") when you need it.
A view is a simple way to save a complex SELECT
in the database.
A store procedure is used when simple SQL just isn't enough. Store procedures contain variables, loops and calls to other stored procedures. It's a programming language, not a query language.
Views are static. Think of them as new tables with a certain layout and the data in them is created on the fly using the query you created it with. As with any SQL table, you can sort and filter it with WHERE
, GROUP BY
and ORDER BY
.
The depends on what you do.
The depends on the database. Simple views just run the query and filter the result. But databases like Oracle allow to create a "materialized" view which is basically a table which is updated automatically when the underlying data of the view changes.
A materialized view allows you to create indexes on the columns of the view (especially on the computed columns which don't exist anywhere in the database).
I don't understand what you're talking about.
This command:
iconv -f utf-8 -t utf-8 -c file.txt
will clean up your UTF-8 file, skipping all the invalid characters.
-f is the source format
-t the target format
-c skips any invalid sequence
best bet is targeting features not devices unless you have to, bootstrap do well and you can extend on their breakpoints, for instance targeting pixel density and larger screens above 1920
I found the following in the site.css generated by VS2013
/* Set width on the form input elements since they're 100% wide by default */
input,
select,
textarea {
max-width: 280px;
}
To override this behavior in a specific element, add the following...
style="max-width: none;"
For example:
<div class="col-md-6">
<textarea style="max-width: none;"
class="form-control"
placeholder="a col-md-6 multiline input box" />
</div>
I have faced similar problem
So
I just do
1.update Maven Project
2.install maven.
From the output of java -X
:
-Xloggc:<file> log GC status to a file with time stamps
Documented here:
-Xloggc:filename
Sets the file to which verbose GC events information should be redirected for logging. The information written to this file is similar to the output of
-verbose:gc
with the time elapsed since the first GC event preceding each logged event. The-Xloggc
option overrides-verbose:gc
if both are given with the samejava
command.Example:
-Xloggc:garbage-collection.log
So the output looks something like this:
0.590: [GC 896K->278K(5056K), 0.0096650 secs] 0.906: [GC 1174K->774K(5056K), 0.0106856 secs] 1.320: [GC 1670K->1009K(5056K), 0.0101132 secs] 1.459: [GC 1902K->1055K(5056K), 0.0030196 secs] 1.600: [GC 1951K->1161K(5056K), 0.0032375 secs] 1.686: [GC 1805K->1238K(5056K), 0.0034732 secs] 1.690: [Full GC 1238K->1238K(5056K), 0.0631661 secs] 1.874: [GC 62133K->61257K(65060K), 0.0014464 secs]
You can use window.open to open a new window/tab(according to browser setting) in javascript.
By using document.write you can write HTML content to the opened window.
Just do Ctrl + Enter inside the text box
On Python 3.4, the pathlib
module was added, and the following code will reliably open a file in the same directory as the current script:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
print(f.read())
You can also use parent.absolute()
to get directory value as a string if needed:
p = Path(__file__)
dir_abs = p.parent.absolute() # Will return the executable directory absolute path
Take a look at jQuery's .load() http://api.jquery.com/load-event/
$('script').load(function () { });
According to the exception, Hibernate wants to write to the table "person", yet in your hbm.xml you define that there is a table "Person", are you sure the correct table exists in your database-schema?
For example if you have two div in XHTML document.
<div id='div1'>
<p>hello, how are you?</p>
<div id='div2'>
<p>I am fine, thank you.</p>
</div>
</div>
Then try this in CSS.
#div1 > #div2 > p{
color: red;
}
affect only 'div2' paragraph.
#div1 > p {
color: red;
}
affect only 'div1' paragraph.
Other workarounds include using SELECT DISTINCT or LIMIT in the subquery, although these are not as explicit in their effect on materialization. this worked for me
yes, there is:
object[] x = new object[2];
x[0] = new { firstName = "john", lastName = "walter" };
x[1] = new { brand = "BMW" };
you were practically there, just the declaration of the anonymous types was a little off.
There are many ways to filter for element ancestors.
if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/}
Beware, closest()
method includes element itself while checking for selector.
Alternatively, if you have a unique selector matching the $elem
, e.g #myElem
, you can use:
if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}
If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:
.parentClass #myElem { /* CSS property set */ }
Sometime the default version will not update. Add this command
AWS_S3_SIGNATURE_VERSION = "s3v4"
in settings.py
To build a regular expression from a variable in JavaScript, you'll need to use the RegExp
constructor with a string parameter.
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
of course, this is a very naive example. It assumes that input
is has been properly escaped for a regular expression. If you're dealing with user-input, or simply want to make it more convenient to match special characters, you'll need to escape special characters:
function regexEscape(str) {
return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
}
function reg(input) {
var flags;
//could be any combination of 'g', 'i', and 'm'
flags = 'g';
input = regexEscape(input);
return new RegExp('ReGeX' + input + 'ReGeX', flags);
}
PostgreSQL 9.5 and newer support INSERT ... ON CONFLICT (key) DO UPDATE
(and ON CONFLICT (key) DO NOTHING
), i.e. upsert.
Comparison with ON DUPLICATE KEY UPDATE
.
For usage see the manual - specifically the conflict_action clause in the syntax diagram, and the explanatory text.
Unlike the solutions for 9.4 and older that are given below, this feature works with multiple conflicting rows and it doesn't require exclusive locking or a retry loop.
The commit adding the feature is here and the discussion around its development is here.
If you're on 9.5 and don't need to be backward-compatible you can stop reading now.
PostgreSQL doesn't have any built-in UPSERT
(or MERGE
) facility, and doing it efficiently in the face of concurrent use is very difficult.
This article discusses the problem in useful detail.
In general you must choose between two options:
Using individual row upserts in a retry loop is the reasonable option if you want many connections concurrently trying to perform inserts.
The PostgreSQL documentation contains a useful procedure that'll let you do this in a loop inside the database. It guards against lost updates and insert races, unlike most naive solutions. It will only work in READ COMMITTED
mode and is only safe if it's the only thing you do in the transaction, though. The function won't work correctly if triggers or secondary unique keys cause unique violations.
This strategy is very inefficient. Whenever practical you should queue up work and do a bulk upsert as described below instead.
Many attempted solutions to this problem fail to consider rollbacks, so they result in incomplete updates. Two transactions race with each other; one of them successfully INSERT
s; the other gets a duplicate key error and does an UPDATE
instead. The UPDATE
blocks waiting for the INSERT
to rollback or commit. When it rolls back, the UPDATE
condition re-check matches zero rows, so even though the UPDATE
commits it hasn't actually done the upsert you expected. You have to check the result row counts and re-try where necessary.
Some attempted solutions also fail to consider SELECT races. If you try the obvious and simple:
-- THIS IS WRONG. DO NOT COPY IT. It's an EXAMPLE.
BEGIN;
UPDATE testtable
SET somedata = 'blah'
WHERE id = 2;
-- Remember, this is WRONG. Do NOT COPY IT.
INSERT INTO testtable (id, somedata)
SELECT 2, 'blah'
WHERE NOT EXISTS (SELECT 1 FROM testtable WHERE testtable.id = 2);
COMMIT;
then when two run at once there are several failure modes. One is the already discussed issue with an update re-check. Another is where both UPDATE
at the same time, matching zero rows and continuing. Then they both do the EXISTS
test, which happens before the INSERT
. Both get zero rows, so both do the INSERT
. One fails with a duplicate key error.
This is why you need a re-try loop. You might think that you can prevent duplicate key errors or lost updates with clever SQL, but you can't. You need to check row counts or handle duplicate key errors (depending on the chosen approach) and re-try.
Please don't roll your own solution for this. Like with message queuing, it's probably wrong.
Sometimes you want to do a bulk upsert, where you have a new data set that you want to merge into an older existing data set. This is vastly more efficient than individual row upserts and should be preferred whenever practical.
In this case, you typically follow the following process:
CREATE
a TEMPORARY
table
COPY
or bulk-insert the new data into the temp table
LOCK
the target table IN EXCLUSIVE MODE
. This permits other transactions to SELECT
, but not make any changes to the table.
Do an UPDATE ... FROM
of existing records using the values in the temp table;
Do an INSERT
of rows that don't already exist in the target table;
COMMIT
, releasing the lock.
For example, for the example given in the question, using multi-valued INSERT
to populate the temp table:
BEGIN;
CREATE TEMPORARY TABLE newvals(id integer, somedata text);
INSERT INTO newvals(id, somedata) VALUES (2, 'Joe'), (3, 'Alan');
LOCK TABLE testtable IN EXCLUSIVE MODE;
UPDATE testtable
SET somedata = newvals.somedata
FROM newvals
WHERE newvals.id = testtable.id;
INSERT INTO testtable
SELECT newvals.id, newvals.somedata
FROM newvals
LEFT OUTER JOIN testtable ON (testtable.id = newvals.id)
WHERE testtable.id IS NULL;
COMMIT;
MERGE
on the PostgreSQL wikiMERGE
?SQL-standard MERGE
actually has poorly defined concurrency semantics and is not suitable for upserting without locking a table first.
It's a really useful OLAP statement for data merging, but it's not actually a useful solution for concurrency-safe upsert. There's lots of advice to people using other DBMSes to use MERGE
for upserts, but it's actually wrong.
INSERT ... ON DUPLICATE KEY UPDATE
in MySQLMERGE
from MS SQL Server (but see above about MERGE
problems)MERGE
from Oracle (but see above about MERGE
problems)This is a classic example of composition vs inheritance.
In this specific case:
Is the team a list of players with added behavior
or
Is the team an object of its own that happens to contain a list of players.
By extending List you are limiting yourself in a number of ways:
You cannot restrict access (for example, stopping people changing the roster). You get all the List methods whether you need/want them all or not.
What happens if you want to have lists of other things as well. For example, teams have coaches, managers, fans, equipment, etc. Some of those might well be lists in their own right.
You limit your options for inheritance. For example you might want to create a generic Team object, and then have BaseballTeam, FootballTeam, etc. that inherit from that. To inherit from List you need to do the inheritance from Team, but that then means that all the various types of team are forced to have the same implementation of that roster.
Composition - including an object giving the behavior you want inside your object.
Inheritance - your object becomes an instance of the object that has the behavior you want.
Both have their uses, but this is a clear case where composition is preferable.
i got the same problem so tried so many things but finally this is the solution.
import time
print (time.strftime("%d/%m/%Y"))
Yes you can and here is one I made earlier:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/listview_background_shape">
<stroke android:width="2dp" android:color="#ff207d94" />
<padding android:left="2dp"
android:top="2dp"
android:right="2dp"
android:bottom="2dp" />
<corners android:radius="5dp" />
<solid android:color="#ffffffff" />
</shape>
You can create a new XML file inside the drawable folder, and add the above code, then save it as rectangle.xml.
To use it inside a layout you would set the android:background
attribute to the new drawable shape. The shape we have defined does not have any dimensions, and therefore will take the dimensions of the View that is defined in the layout.
So putting it all together:
<View
android:id="@+id/myRectangleView"
android:layout_width="200dp"
android:layout_height="50dp"
android:background="@drawable/rectangle"/>
Finally; you can set this rectangle to be the background of any View, although for ImageViews you would use android:src
. This means you could use the rectangle as the background for ListViews, TextViews...etc.
If you are building the array once and want to find the maximum just once, iterating is the best you can do.
When you want to modify the array and occasionally want to know the maximum element, you should use a Priority Queue. One of the best data structures for that is a Fibonacci Heap, if this is too complicated use a Binary Heap which is slower but still good.
To find minimum and maximum, just build two heaps and change the sign of the numbers in one of them.
Look at Compare-Object
Compare-Object $a1 $b1 | ForEach-Object { $_.InputObject }
Or if you would like to know where the object belongs to, then look at SideIndicator:
$a1=@(1,2,3,4,5,8)
$b1=@(1,2,3,4,5,6)
Compare-Object $a1 $b1
For windows users:
Download gradle binary from the link in the answer Gradle Download
Extract the zip file to 'C:\Gradle' or somewhere else
open Edit Environment variable dialog from start menu > Search
Click 'New' under system variables and add as below
Variable Name GRADLE_HOME
Variable Value C:\Gradle\gradle-4.0.1
Then choose PATH
variable from system variable list
append the gradle path to variable value like this C:\Gradle\gradle-4.0.1\bin
then press win Key+R type cmd then enter > in command terminal type gradle -v
if the setup is correct you will see the gradle installation details
I managed to remove the errors by disabling the validations:
{
"javascript.validate.enable": false,
"html.validate.styles": false,
"html.validate.scripts": false,
"css.validate": false,
"scss.validate": false
}
Obs: My project is a PWA using StyledComponents, React, Flow, Eslint and Prettier.
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
After many hours of experimenting with using jQueryDataTables with Angular, I found what I needed was available with a native Angular directive called ng-table. It provides sorting, pagination, and ajax reloads (sort of lazy loading capable with a few tweaks).
val source_html = Source.fromResource("file.html").mkString
There is an error on $.map()
invocation, try this:
function getData(data) {
this.productID = data.product_id;
this.productData = data.product_data;
this.imageID = data.product_data.image_id;
this.text = data.product_data.text;
this.link = data.product_data.link;
this.imageUrl = data.product_data.image_url;
}
$.getJSON("json.json?sdfsdfg").done(function (data) {
var allPosts = $.map(data,function (item) {
for (var i = 0; i < item.length; i++) {
new getData(item[i]);
};
});
});
The error in your code was that you made return
in your AJAX call, so it executed only one time.
You have a numpy array of strings, not floats. This is what is meant by dtype('<U9')
-- a little endian encoded unicode string with up to 9 characters.
try:
return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))
However, you don't need numpy here at all. You can really just do:
return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)
Or if you're really set on using numpy.
return np.asarray(listOfEmb, dtype=float).mean()
I solved this problem this way. I used kotlin.
var timer = Timer()
var DELAY:Long = 2000
editText.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
Log.e("TAG","timer start")
timer = Timer()
timer.schedule(object : TimerTask() {
override fun run() {
//do something
}
}, DELAY)
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
Log.e("TAG","timer cancel ")
timer.cancel() //Terminates this timer,discarding any currently scheduled tasks.
timer.purge() //Removes all cancelled tasks from this timer's task queue.
}
})
sudo apt-get install phpx.x-gd
sudo service apache2 restart
x.x is the versión php.
In Kotlin: How to check GPS is enable or not
val manager = getSystemService(Context.LOCATION_SERVICE) as LocationManager
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
checkGPSEnable()
}
private fun checkGPSEnable() {
val dialogBuilder = AlertDialog.Builder(this)
dialogBuilder.setMessage("Your GPS seems to be disabled, do you want to enable it?")
.setCancelable(false)
.setPositiveButton("Yes", DialogInterface.OnClickListener { dialog, id
->
startActivity(Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS))
})
.setNegativeButton("No", DialogInterface.OnClickListener { dialog, id ->
dialog.cancel()
})
val alert = dialogBuilder.create()
alert.show()
}
You really should fix whatever's causing the warning, but you can control visibility of errors with error_reporting()
. To skip warning messages, you could use something like:
error_reporting(E_ERROR | E_PARSE);
Expanding on @Harmon above, looks like you can combine the display
and print
statements together ... if you need. Or, maybe it's easier to just format your entire HTML as one string and then use display. Either way, nice feature.
display(HTML('<h1>Hello, world!</h1>'))
print("Here's a link:")
display(HTML("<a href='http://www.google.com' target='_blank'>www.google.com</a>"))
print("some more printed text ...")
display(HTML('<p>Paragraph text here ...</p>'))
Outputs something like this:
Here's a link:
some more printed text ...
Paragraph text here ...
You can simply concatnate two lists, e.g:
list1 = [0, 1]
list2 = [2, 3]
list3 = list1 + list2
print(list3)
>> [0, 1, 2, 3]
As many have stated more or less correctly what reference and primitive types are, one might be interested that we have some more relevant types in Java. Here is the complete lists of types in java (as far as I am aware of (JDK 11)).
Describes a value (and not a type).
11
Describes a concrete type which instances extend Object (interface, class, enum, array). Furthermore TypeParameter is actually a reference type!
Integer
Note: The difference between primitive and reference type makes it necessary to rely on boxing to convert primitives in Object instances and vise versa.
Note2: A type parameter describes a type having an optional lower or upper bound and can be referenced by name within its context (in contrast to the wild card type). A type parameter typically can be applied to parameterized types (classes/interfaces) and methods. The parameter type defines a type identifier.
Expresses an unknown type (like any in TypeScript) that can have a lower or upper bound by using super or extend.
? extends List<String>
? super ArrayList<String>
Nothingness. No value/instance possible.
void method();
The only representation is 'null'. It is used especially during type interference computations. Null is a special case logically belonging to any type (can be assigned to any variable of any type) but is actual not considered an instance of any type (e.g. (null instanceof Object) == false).
null
A union type is a type that is actual a set of alternative types. Sadly in Java it only exists for the multi catch statement.
catch(IllegalStateException | IOException e) {}
A type that is compatibile to multiple types. Since in Java a class has at most one super class (Object has none), interference types allow only the first type to be a class and every other type must be an interface type.
void method(List<? extends List<?> & Comparable> comparableList) {}
The type is unknown. That is the case for certain Lambda definitions (not enclosed in brackets, single parameter).
list.forEach(element -> System.out.println(element.toString)); //element is of unknown type
Unknown type introduced by a variable declaration spotting the 'var' keyword.
var variable = list.get(0);
You have to make a new instance of OrderedDict
. If your keys are unique:
d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("d",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)
#OrderedDict([('c', 3), ('d', 99), ('a', 1), ('b', 2)])
But if not, beware as this behavior may or may not be desired for you:
d1=OrderedDict([("a",1),("b",2)])
d2=OrderedDict([("c",3),("b",99)])
both=OrderedDict(list(d2.items()) + list(d1.items()))
print(both)
#OrderedDict([('c', 3), ('b', 2), ('a', 1)])
window.isset = function(v_var) {
if(typeof(v_var) == 'number'){ if(isNaN(v_var)){ return false; }}
if(typeof(v_var) == 'undefined' || v_var === null){ return false; } else { return true; }
};
plus Tests:
https://gist.github.com/daylik/24acc318b6abdcdd63b46607513ae073
For multiple plots in a single pdf file you can use PdfPages
In the plotGraph
function you should return the figure and than call savefig
of the figure object.
------ plotting module ------
def plotGraph(X,Y):
fig = plt.figure()
### Plotting arrangements ###
return fig
------ plotting module ------
----- mainModule ----
from matplotlib.backends.backend_pdf import PdfPages
plot1 = plotGraph(tempDLstats, tempDLlabels)
plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
pp = PdfPages('foo.pdf')
pp.savefig(plot1)
pp.savefig(plot2)
pp.savefig(plot3)
pp.close()
Developing Android REST client applications has been an awesome resource for me. The speaker does not show any code, he just goes over design considerations and techniques in putting together a rock solid Rest Api in android. If your a podcast kinda person or not, I'd recommend giving this one at least one listen but, personally I've listened to it like 4 or five times thus far and I'm probably going to listen to it again.
Developing Android REST client applications
Author: Virgil Dobjanschi
Description:
This session will present architectural considerations for developing RESTful applications on the Android platform. It focuses on design patterns, platform integration and performance issues specific to the Android platform.
And there are so many considerations I really hadn't made in the first version of my api that I've had to refactor
Thanks @davy-landmann for https://stackoverflow.com/a/638064/417153. That's what I was looking for! Same effect with LESS code:
@searchResultMinHeight = 200px;
.searchResult {
min-height: @searchResultMinHeight;
position: relative;
.innerTrans {
background: white;
.opacity(0.5);
min-height: @searchResultMinHeight;
}
.innerBody {
padding: 0.5em;
position: absolute;
top: 0;
}
}
FETCH_HEAD
is a short-lived ref, to keep track of what has just been fetched from the remote repository.
Actually, ... not always considering that, with Git 2.29 (Q4 2020), "git fetch
"(man) learned --no-write-fetch-head
option to avoid writing the FETCH_HEAD
file.
See commit 887952b (18 Aug 2020) by Junio C Hamano (gitster
).
(Merged by Junio C Hamano -- gitster
-- in commit b556050, 24 Aug 2020)
fetch
: optionally allow disablingFETCH_HEAD
updateSigned-off-by: Derrick Stolee
If you run fetch but record the result in remote-tracking branches, and either if you do nothing with the fetched refs (e.g. you are merely mirroring) or if you always work from the remote-tracking refs (e.g. you fetch and then merge
origin/branchname
separately), you can get away with having noFETCH_HEAD
at all.Teach "
git fetch
"(man) a command line option "--[no-]write-fetch-head
".
- The default is to write
FETCH_HEAD,
and the option is primarily meant to be used with the "--no-
" prefix to override this default, because there is no matchingfetch.writeFetchHEAD
configuration variable to flip the default to off (in which case, the positive form may become necessary to defeat it).Note that under "
--dry-run
" mode,FETCH_HEAD
is never written; otherwise you'd see list of objects in the file that you do not actually have.Passing
--write-fetch-head
does not force[
git fetch](https://github.com/git/git/blob/887952b8c680626f4721cb5fa57704478801aca4/Documentation/git-fetch.txt)<sup>([man](https://git-scm.com/docs/git-fetch))</sup>
to write the file.
fetch-options
now includes in its man page:
--[no-]write-fetch-head
Write the list of remote refs fetched in the
FETCH_HEAD
file directly under$GIT_DIR
.
This is the default.Passing
--no-write-fetch-head
from the command line tells Git not to write the file.
Under--dry-run
option, the file is never written.
Consider also, still with Git 2.29 (Q4 2020), the FETCH_HEAD
is now always read from the filesystem regardless of the ref backend in use, as its format is much richer than the normal refs, and written directly by "git fetch
"(man) as a plain file..
See commit e811530, commit 5085aef, commit 4877c6c, commit e39620f (19 Aug 2020) by Han-Wen Nienhuys (hanwen
).
(Merged by Junio C Hamano -- gitster
-- in commit 98df75b, 27 Aug 2020)
refs
: readFETCH_HEAD
andMERGE_HEAD
genericallySigned-off-by: Han-Wen Nienhuys
The
FETCH_HEAD
andMERGE_HEAD
refs must be stored in a file, regardless of the type of ref backend. This is because they can hold more than just a single ref.To accomodate them for alternate ref backends, read them from a file generically in
refs_read_raw_ref()
.
With Git 2.29 (Q4 2020), Updates to on-demand fetching code in lazily cloned repositories.
See commit db3c293 (02 Sep 2020), and commit 9dfa8db, commit 7ca3c0a, commit 5c3b801, commit abcb7ee, commit e5b9421, commit 2b713c2, commit cbe566a (17 Aug 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit b4100f3, 03 Sep 2020)
fetch
: noFETCH_HEAD
display if --no-write-fetch-headSigned-off-by: Jonathan Tan
887952b8c6 ("
fetch
: optionally allow disablingFETCH_HEAD
update", 2020-08-18, Git v2.29.0 -- merge listed in batch #10) introduced the ability to disable writing toFETCH_HEAD
during fetch, but did not suppress the "<source> -> FETCH_HEAD"
message when this ability is used.This message is misleading in this case, because
FETCH_HEAD
is not written.Also, because "
fetch
" is used to lazy-fetch missing objects in a partial clone, this significantly clutters up the output in that case since the objects to be fetched are potentially numerous.Therefore, suppress this message when
--no-write-fetch-head
is passed (but not when--dry-run
is set).
JDBC is the predecessor of JPA.
JDBC is a bridge between the Java world and the databases world. In JDBC you need to expose all dirty details needed for CRUD operations, such as table names, column names, while in JPA (which is using JDBC underneath), you also specify those details of database metadata, but with the use of Java annotations.
So JPA creates update queries for you and manages the entities that you looked up or created/updated (it does more as well).
If you want to do JPA without a Java EE container, then Spring and its libraries may be used with the very same Java annotations.
For straight HTML, with no JavaScript required:
<a href="#something">Add '#something' to URL</a>
Or, to take your question more literally, to just add '#' to the URL:
<a href="#">Add '#' to URL</a>
perhaps, you can first determine if the DOM does really exists,
function walkmydog() {
//when the user starts entering
var dom = document.getElementById('WallSearch');
if(dom == null){
alert('sorry, WallSearch DOM cannot be found');
return false;
}
if(dom.value.length == 0){
alert("nothing");
}
}
if (document.addEventListener){
document.addEventListener("DOMContentLoaded", walkmydog, false);
}
The equivalent of LIMIT
is SET ROWCOUNT
, but if you want generic pagination it's better to write a query like this:
;WITH Results_CTE AS
(
SELECT
Col1, Col2, ...,
ROW_NUMBER() OVER (ORDER BY SortCol1, SortCol2, ...) AS RowNum
FROM Table
WHERE <whatever>
)
SELECT *
FROM Results_CTE
WHERE RowNum >= @Offset
AND RowNum < @Offset + @Limit
The advantage here is the parameterization of the offset and limit in case you decide to change your paging options (or allow the user to do so).
Note: the @Offset
parameter should use one-based indexing for this rather than the normal zero-based indexing.
Try this:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider NuGet -Force
Set-PSRepository PSGallery -InstallationPolicy Trusted
Edit: As per the Mr Me comment on this answer, it looks like compression is now available for JPG/WebP formats ( see https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toDataURL ).
As far as I know, you cannot compress images using canvas, instead, you can resize it. Using canvas.toDataURL will not let you choose the compression ratio to use. You can take a look at canimage that does exactly what you want : https://github.com/nfroidure/CanImage/blob/master/chrome/canimage/content/canimage.js
In fact, it's often sufficient to just resize the image to decrease it's size but if you want to go further, you'll have to use newly introduced method file.readAsArrayBuffer to get a buffer containing the image data.
Then, just use a DataView to read it's content according to the image format specification (http://en.wikipedia.org/wiki/JPEG or http://en.wikipedia.org/wiki/Portable_Network_Graphics).
It'll be hard to deal with image data compression, but it is worse a try. On the other hand, you can try to delete the PNG headers or the JPEG exif data to make your image smaller, it should be easier to do so.
You'll have to create another DataWiew on another buffer and fill it with the filtered image content. Then, you'll just have to encode you're image content to DataURI using window.btoa.
Let me know if you implement something similar, will be interesting to go through the code.
Alternatively to the suggested 3 methods you can try let
which carries out arithmetic operations on variables as follows:
let COUNT=$FIRSTV-$SECONDV
or
let COUNT=FIRSTV-SECONDV
There are two ways for writing a proper media queries in css. If you are writing media queries for larger device first, then the correct way of writing will be:
@media only screen
and (min-width : 415px){
/* Styles */
}
@media only screen
and (min-width : 769px){
/* Styles */
}
@media only screen
and (min-width : 992px){
/* Styles */
}
But if you are writing media queries for smaller device first, then it would be something like:
@media only screen
and (max-width : 991px){
/* Styles */
}
@media only screen
and (max-width : 768px){
/* Styles */
}
@media only screen
and (max-width : 414px){
/* Styles */
}
You can access the elements in a list-of-lists by first specifying which list you're interested in and then specifying which element of that list you want. For example, 17
is element 2
in list 0
, which is list1[0][2]
:
>>> list1 = [[10,13,17],[3,5,1],[13,11,12]]
>>> list1[0][2]
17
So, your example would be
50 - list1[0][0] + list1[0][1] - list1[0][2]
1) Download new PHP from the official site (better some zip). Old php
directory rename to php_old
and create again php
directory and put there unzipped files.
In php.ini
connect needed modules if you used something that was turned off by default (like Memcached etc.), but doesn't forget to add corresponding .dll
files.
2) In my case, I had to update Apache. So repeat the same steps: download the new package, rename directories, create new apache
directory and put their new files.
Now you can try to restart apache running apache_start.bat
from xampp
folder (better run this bat, than restart apache service from Windows services window, cause in this case in console you'll see all errors if there will be some, including lines in config where you'll have problem). If you updated Apache and run this file, in the list of services you'll see Apache2.2, but in description you can get another version (in my case that was Apache/2.4.7).
In case of Apache update you can get some problems, so mind:
after you replace the whole directory, you may need to configure you apache/conf/httpd.conf
file (copy virtual hosts from old config, set up DocumentRoots, permissions for directories, all paths, extend the list of index files (by default apache has only index.html
so other index files will be just ignored and Apache will just list the site root directory in browser), configure you logs etc.)
connect modules you need (if you used something that was not turned on by default like mod_rewrite etc.)
Because System.exit()
is just another method to the compiler. It doesn't read ahead and figure out that the whole program will quit at that point (the JVM quits). Your OS or shell can read the integer that is passed back in the System.exit()
method. It is standard for 0
to mean "program quit and everything went OK" and any other value to notify an error occurred. It is up to the developer to document these return values for any users.
return
on the other hand is a reserved key word that the compiler knows well.
return
returns a value and ends the current function's run moving back up the stack to the function that invoked it (if any). In your code above it returns void
as you have not supplied anything to return.
I found a solution using set-url which is concise and fairly easy to understand:
cd
into the existing repository on your local machine (if you haven't cloned it yet, then do this first)git remote set-url origin https://github.com/user/example.git
git push -u origin master
I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:
private boolean isCallable(Intent intent) {
List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
In use when I would usually just start the activity:
final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
// call the intent as you intended.
} else {
// make alternative arrangements.
}
obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.
I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.
I got so:
git config --global http.proxy http://{domain}\\\{username}:{password}@{proxy ip}:{proxy port}
git config --global http.sslverify false
Python String rindex() Method
Description
Python string method rindex() returns the last index where the substring str is found, or raises an exception if no such index exists, optionally restricting the search to string[beg:end].
Syntax
Following is the syntax for rindex() method -
str.rindex(str, beg=0 end=len(string))
Parameters
str - This specifies the string to be searched.
beg - This is the starting index, by default its 0
len - This is ending index, by default its equal to the length of the string.
Return Value
This method returns last index if found otherwise raises an exception if str is not found.
Example
The following example shows the usage of rindex() method.
Live Demo
str1 = "this is string example....wow!!!";
str2 = "is";
print str1.rindex(str2)
print str1.index(str2)
When we run above program, it produces following result -
5
2
Check output of console.log(req)
or console.log(req.headers);
IMHO easiest solution is to prepend and append the original string with a space and check against a regex with [[ ]]
haystack='foo bar'
needle='bar'
if [[ " $haystack " =~ .*\ $needle\ .* ]]; then
...
fi
this will not be false positive on values with values containing the needle as a substring, e.g. with a haystack foo barbaz
.
(The concept is shamelessly stolen form JQuery's hasClass()
-Method)
There is another way doing this, using the *.sol, *csproj files.
It will be like this (relative to the *.sol file):
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Shani.Commands.Impl", "Shani.Commands.Impl\Shani.Commands.Impl.csproj", "{747CFA4B-FC83-419A-858E-5E2DE2B948EE}"
And just change the first part to the new diretory for example:
Impl\Shani.Commands.Impl\Shani.Commands.Impl.csproj
Of course, don't forget to move the whole project to that directory.
! [rejected] master -> master (fetch first) error: failed to push some refs to '[email protected]:'
Successfully solved the problem using --force command.
so, you must used
git push origin master --force
In order to delete all images, use the given command
docker rmi $(docker images -q)
In order to delete all containers, use the given command
docker rm $(docker ps -a -q)
Warning: This will destroy all your images and containers. It will not be possible to restore them!
This solution is provided by Techoverflow.net.
I'm replacing a submit button with an anchor link. Since calling form.submit() does not activate onsubmit's, I'm finding it, and eval()ing it myself. But I'd like to check if the function exists before just eval()ing what's there. – gms8994
<script type="text/javascript">
function onsubmitHandler() {
alert('running onsubmit handler');
return true;
}
function testOnsubmitAndSubmit(f) {
if (typeof f.onsubmit === 'function') {
// onsubmit is executable, test the return value
if (f.onsubmit()) {
// onsubmit returns true, submit the form
f.submit();
}
}
}
</script>
<form name="theForm" onsubmit="return onsubmitHandler();">
<a href="#" onclick="
testOnsubmitAndSubmit(document.forms['theForm']);
return false;
"></a>
</form>
EDIT : missing parameter f in function testOnsubmitAndSubmit
The above should work regardless of whether you assign the onsubmit
HTML attribute or assign it in JavaScript:
document.forms['theForm'].onsubmit = onsubmitHandler;
Add one more condition in where clause
SELECT * FROM product
WHERE pdate >= DATEADD(day,-30,GETDATE())
and pdate <= getdate()
Or use DateDiff
SELECT * FROM product
WHERE DATEDIFF(day,pdate,GETDATE()) between 0 and 30
mkdirs()
will create the specified directory path in its entirety where mkdir()
will only create the bottom most directory, failing if it can't find the parent directory of the directory it is trying to create.
In other words mkdir()
is like mkdir
and mkdirs()
is like mkdir -p
.
For example, imagine we have an empty /tmp
directory. The following code
new File("/tmp/one/two/three").mkdirs();
would create the following directories:
/tmp/one
/tmp/one/two
/tmp/one/two/three
Where this code:
new File("/tmp/one/two/three").mkdir();
would not create any directories - as it wouldn't find /tmp/one/two
- and would return false
.
Use the following code to remove element from the list:
list = [1, 2, 3, 4]
list.remove(1)
print(list)
output = [2, 3, 4]
If you want to remove index element data from the list use:
list = [1, 2, 3, 4]
list.remove(list[2])
print(list)
output : [1, 2, 4]
Entering a PIN is actually an outdated method of pairing, now called Legacy Pairing. Secure Simple Pairing Mode is available in Bluetooth v2.1 and later, which comprises most modern Bluetooth devices. SSPMode authentication is handled by the Bluetooth protocol stack and thus works without user interaction.
Here is how one might go about connecting to a device:
# hciconfig hci0 sspmode 1
# hciconfig hci0 sspmode
hci0: Type: BR/EDR Bus: USB
BD Address: AA:BB:CC:DD:EE:FF ACL MTU: 1021:8 SCO MTU: 64:1
Simple Pairing mode: Enabled
# hciconfig hci0 piscan
# sdptool add SP
# hcitool scan
00:11:22:33:44:55 My_Device
# rfcomm connect /dev/rfcomm0 00:11:22:33:44:55 1 &
Connected /dev/rfcomm0 to 00:11:22:33:44:55 on channel 1
Press CTRL-C for hangup
This would establish a serial connection to the device.
no any libs are used:
dict_format_string = "{'1':'one', '2' : 'two'}"
d = {}
elems = filter(str.isalnum,dict_format_string.split("'"))
values = elems[1::2]
keys = elems[0::2]
d.update(zip(keys,values))
NOTE: As it has hardcoded split("'")
will work only for strings where data is "single quoted".
If you are using Windows, the virtual machine should have it's own process that is visible in task manager. Use sysinternals Process Explorer to find the right one and then kill it from there.
Status code '0' can occur because of three reasons
1) The Client cannot connect to the server
2) The Client cannot receive the response within the timeout period
3) The Request was "stopped(aborted)" by the Client.
But these three reasons are not standardized
interface:
defines the contract for a class which implements it
@interface:
defines the contract for an annotation
div hover background color change
Try like this:
.class_name:hover{
background-color:#FF0000;
}
For those looking at this in 2020, you may notice that accepted answer is deprecated in 2020, but there is a similar approach available using terms_set
and minimum_should_match_script
combination.
Please see the detailed answer here in the SO thread
For me, the problem was I was using a package that isn't included in package.json
nor installed.
import { ToastrService } from 'ngx-toastr';
So when the compiler tried to compile this, it threw an error.
(I installed it locally, and when running a build on an external server the error was thrown)
i use jquery to send the data when the user press the like button.
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'xxxxxxxxxxxxx', status: true, cookie: true,
xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$(document).ready(function() {
var h_fbl=href.split("/");
var fbl_id= h_fbl[4];
$.post("http://xxxxxx.com/inc/like.php",{ idfb:fbl_id,rand:Math.random() } )
}) });
};
</script>
Note:you can use some hidden input text to get the id of your button.in my case i take it from the url itself in "var fbl_id=h_fbl[4];" becasue there is the id example: url: http://mywebsite.com/post/22/some-tittle
so i parse the url to get the id and then insert it to my databse in the like.php file. in this way you dont need to ask for permissions to know if some one press the like button, but if you whant to know who press it, permissions are needed.
I use:
private void WaitNSeconds(int segundos)
{
if (segundos < 1) return;
DateTime _desired = DateTime.Now.AddSeconds(segundos);
while (DateTime.Now < _desired) {
System.Windows.Forms.Application.DoEvents();
}
}
std::map
already sorts the values using a predicate you define or std::less
if you don't provide one. std::set
will also store items in order of the of a define comparator. However neither set nor map allow you to have multiple keys. I would suggest defining a std::map<int,std::set<string>
if you want to accomplish this using your data structure alone. You should also realize that std::less
for string will sort lexicographically not alphabetically.
Okay, here are the explanations.
e.keyCode - used to get the number that represents the key on the keyboard
e.charCode - a number that represents the unicode character of the key on keyboard
e.which - (jQuery specific) is a property introduced in jQuery (DO Not use in plain javascript)
Below is the code snippet to get the keyCode and charCode
<script>
// get key code
function getKey(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
alert(keyCode);
}
// get char code
function getChar(event) {
event = event || window.event;
var keyCode = event.which || event.keyCode;
var typedChar = String.fromCharCode(keyCode);
alert(typedChar);
}
</script>
Live example of Getting keyCode and charCode in JavaScript.
ChangeDetectorRef.detectChanges()
is usually the most focused way of doing this. ApplicationRef.tick()
is usually too much of a sledgehammer approach.
To use ChangeDetectorRef.detectChanges()
, you'll need this at the top of your component:
import { ChangeDetectorRef } from '@angular/core';
... then, usually you alias that when you inject it in your constructor like this:
constructor( private cdr: ChangeDetectorRef ) { ... }
Then, in the appropriate place, you call it like this:
this.cdr.detectChanges();
Where you call ChangeDetectorRef.detectChanges()
can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges()
appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).
Try the following date Format.
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter. dateFromString (strDate)
Hope it helps..
Swift 4.1 :
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.date(from: strDate)
Try fopen() http://www.php.net/manual/en/function.fopen.php
w as mode will truncate the file.
The @Qualifier
annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.
The @Qualifier
annotation can be used on any class annotated with @Component
or on methods annotated with @Bean
. This annotation can also be applied on constructor arguments or method parameters.
Ex:-
public interface Vehicle {
public void start();
public void stop();
}
There are two beans, Car and Bike implements Vehicle interface
@Component(value="car")
public class Car implements Vehicle {
@Override
public void start() {
System.out.println("Car started");
}
@Override
public void stop() {
System.out.println("Car stopped");
}
}
@Component(value="bike")
public class Bike implements Vehicle {
@Override
public void start() {
System.out.println("Bike started");
}
@Override
public void stop() {
System.out.println("Bike stopped");
}
}
Injecting Bike bean in VehicleService using @Autowired
with @Qualifier
annotation. If you didn't use @Qualifier
, it will throw NoUniqueBeanDefinitionException.
@Component
public class VehicleService {
@Autowired
@Qualifier("bike")
private Vehicle vehicle;
public void service() {
vehicle.start();
vehicle.stop();
}
}
Reference:- @Qualifier annotation example
We can use summary
on factor column:
summary(myDF$factorColumn)
I am late to the party, but since this question turns up often in search results, I would just like to add a solution that I consider to be the best in terms of readability while not being long (which is ideal for any codebase IMO). It mutates, but I'd make that tradeoff for KISS principles.
let times = 5
while( times-- )
console.log(times)
// logs 4, 3, 2, 1, 0
Remove a list’s bullets and apply some light margin with a combination of two classes, .list-inline and .list-inline-item.
<ul class="list-inline">
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">FB</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">G+</a></li>
<li class="list-inline-item"><a class="social-icon text-xs-center" target="_blank" href="#">T</a></li>
</ul>
The proper Swift operator is is
:
if touch.view is UIPickerView {
// touch.view is of type UIPickerView
}
Of course, if you also need to assign the view to a new constant, then the if let ... as? ...
syntax is your boy, as Kevin mentioned. But if you don't need the value and only need to check the type, then you should use the is
operator.
I like this:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
if (typeof wlocation !== "undefined")
Here is a simple and backward compatible way to deliver ripple effect to raised buttons with the custom background.
Your layout should look like this
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/my_custom_background"
android:foreground="?android:attr/selectableItemBackground"/>
What I would do is run the loop until the ans is Q
ans=(R)
while not ans=='Q':
print('Your score is so far '+str(myScore)+'.')
print("Would you like to roll or quit?")
ans=input("Roll...")
if ans=='R':
R=random.randint(1, 8)
print("You rolled a "+str(R)+".")
myScore=R+myScore
To get the current time's milliseconds, use http://momentjs.com/docs/#/get-set/millisecond/
var timeInMilliseconds = moment().milliseconds();
Can you not just remove the href attribute from the a tag?
Moshe's solution is great but the problem may still exist if you need to put the list inside a div
. (read: CSS counter-reset on nested list)
This style could prevent that issue:
ol > li {_x000D_
counter-increment: item;_x000D_
}_x000D_
_x000D_
ol > li:first-child {_x000D_
counter-reset: item;_x000D_
}_x000D_
_x000D_
ol ol > li {_x000D_
display: block;_x000D_
}_x000D_
_x000D_
ol ol > li:before {_x000D_
content: counters(item, ".") ". ";_x000D_
margin-left: -20px;_x000D_
}
_x000D_
<ol>_x000D_
<li>list not nested in div</li>_x000D_
</ol>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div>_x000D_
<ol>_x000D_
<li>nested in div</li>_x000D_
<li>two_x000D_
<ol>_x000D_
<li>two.one</li>_x000D_
<li>two.two</li>_x000D_
<li>two.three</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>three_x000D_
<ol>_x000D_
<li>three.one</li>_x000D_
<li>three.two_x000D_
<ol>_x000D_
<li>three.two.one</li>_x000D_
<li>three.two.two</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ol>_x000D_
</li>_x000D_
<li>four</li>_x000D_
</ol>_x000D_
</div>
_x000D_
You can also set the counter-reset on li:before
.
In addition the other great answers, I suggest that you try to separate the error flag and the error code in order to save one line on each call, i.e.:
if( !doit(a, b, c, &errcode) )
{ (* handle *)
(* thine *)
(* error *)
}
When you have lots of error-checking, this little simplification really helps.
Following the instructions here http://help.loftware.com/pages/viewpage.action?pageId=27099554 I had to install the Microsoft Access Database Engine 2010 Redistributable before I had the Excel driver installed to use the DSN-less connection I wanted to use from perl.
The fragment identifier (also known as: Fragment IDs, Anchor Identifiers, Named Anchors) introduced by a hash mark # is the optional last part of a URL for a document. It is typically used to identify a portion of that document.
<a href="http://www.someuri.com/page#fragment">Link to fragment identifier</a>
Syntax for URIs also allows an optional query part introduced by a question mark ?. In URIs with a query and a fragment the fragment follows the query.
<a href="http://www.someuri.com/page?query=1#fragment">Link to fragment with a query</a>
When a Web browser requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment. Instead, the agent waits for the server to send the resource, and then the agent (Web browser) processes the resource according to the document type and fragment value.
Named Anchors <a name="fragment">
are deprecated in XHTML 1.0, the ID attribute is the suggested replacement. <div id="fragment"></div>
I'm assuming that you want to be able to view data present in your container everytime you connect to it from outside. To do this, you will have to persist data on the postgres image.
If you dont have persistant data, you will have to repeat everything you did the first time.
Steps 3, 5, 6, 7, and 8 answer your question directly.
Here is the detailed overview of the entire process I followed on Windows 10 powershell (commands are the same in Linux and macOS as well):
Step 1: Start powershell in non-admin mode
Step 2: Download postgres docker image:
docker pull postgres:latest
Step 3: Start docker container in detached mode and persist data on postgres image by creating a volume and binding it to a destination
(Note: by default 5432 is the default port that is used; but state it explicitly to prevent connection errors from clients like pgadmin, dbeaver, etc.)
docker run --name postgres-test -e POSTGRES_PASSWORD=password -p 5432:5432 -v postgres-data:/var/lib/postgresql/data -d postgres:latest
Step 4: Check status of running containers
docker ps -a
Step 5: Go inside container_name in interactive mode
(Note: commands like ls, pwd, etc. can be executed here if you've checked linux containers during installation)
docker exec -it postgres-test psql -U postgres
Step 6: Create sample data. At this point, you can play with psql
commands in the following manner:
# CREATE DATABASE test;
# \c test
# CREATE TABLE test_table(something int);
# INSERT INTO test_table VALUES (123);
# SELECT * FROM test_table;
# \q
Step 7: Open a database client application like pgadmin
or dbeaver
and enter the below in the connection fields:
Host: localhost
Database: test
User: postgres
Password: password
Step 8: Enter the query select * from test_table
in the query editor and you should be able to see the output 123
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
The above has a mix of correct answers. What worked for me for having the exact same errors are:
1) edit your bash config file
$ cd ~ && vim .bashrc
2) in your bash config file, make sure default editor is vim rather than vi (which causes the problem)
export EDITOR=vim
3) edit your vim config file
$cd ~ && vim .vimrc
4) make sure set backupcopy is yes in your .vimrc
set backupcopy=yes
5) restart terminal
6) now try crontab edit
$ crontab -e
10 * * * * echo "hello world"
You should see that it creates the crontab file correctly. If you exit vim (either ZZ or :wq) and list crontab with following command; you should see the new cron job. Hope this helps.
$ crontab -l
I realize this is a very old post and has some great answers already, but I wanted to make a simple MCVE to demonstrate one such approach and allow new coders a way to quickly see the concept in action.
In this example, we will use 5 files:
All files are listed in their entirety at the bottom of this post.
The Goal: To demonstrate passing values from Controller1
to Controller2
and vice versa.
The Program Flow:
TextField
, a Button
, and a Label
. When the Button
is clicked, the second window is loaded and displayed, including the text entered in the TextField
.TextField
, a Button
, and a Label
. The Label
will display the text entered in the TextField
on the first scene.TextField
and clicking its Button
, the first scene's Label
is updated to show the entered text.This is a very simple demonstration and could surely stand for some improvement, but should make the concept very clear.
The code itself is also commented with some details of what is happening and how.
THE CODE
Main.java:
import javafx.application.Application;
import javafx.stage.Stage;
public class Main extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) {
// Create the first controller, which loads Layout1.fxml within its own constructor
Controller1 controller1 = new Controller1();
// Show the new stage
controller1.showStage();
}
}
Controller1.java:
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
public class Controller1 {
// Holds this controller's Stage
private final Stage thisStage;
// Define the nodes from the Layout1.fxml file. This allows them to be referenced within the controller
@FXML
private TextField txtToSecondController;
@FXML
private Button btnOpenLayout2;
@FXML
private Label lblFromController2;
public Controller1() {
// Create the new stage
thisStage = new Stage();
// Load the FXML file
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout1.fxml"));
// Set this class as the controller
loader.setController(this);
// Load the scene
thisStage.setScene(new Scene(loader.load()));
// Setup the window/stage
thisStage.setTitle("Passing Controllers Example - Layout1");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Show the stage that was loaded in the constructor
*/
public void showStage() {
thisStage.showAndWait();
}
/**
* The initialize() method allows you set setup your scene, adding actions, configuring nodes, etc.
*/
@FXML
private void initialize() {
// Add an action for the "Open Layout2" button
btnOpenLayout2.setOnAction(event -> openLayout2());
}
/**
* Performs the action of loading and showing Layout2
*/
private void openLayout2() {
// Create the second controller, which loads its own FXML file. We pass a reference to this controller
// using the keyword [this]; that allows the second controller to access the methods contained in here.
Controller2 controller2 = new Controller2(this);
// Show the new stage/window
controller2.showStage();
}
/**
* Returns the text entered into txtToSecondController. This allows other controllers/classes to view that data.
*/
public String getEnteredText() {
return txtToSecondController.getText();
}
/**
* Allows other controllers to set the text of this layout's Label
*/
public void setTextFromController2(String text) {
lblFromController2.setText(text);
}
}
Controller2.java:
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import java.io.IOException;
public class Controller2 {
// Holds this controller's Stage
private Stage thisStage;
// Will hold a reference to the first controller, allowing us to access the methods found there.
private final Controller1 controller1;
// Add references to the controls in Layout2.fxml
@FXML
private Label lblFromController1;
@FXML
private TextField txtToFirstController;
@FXML
private Button btnSetLayout1Text;
public Controller2(Controller1 controller1) {
// We received the first controller, now let's make it usable throughout this controller.
this.controller1 = controller1;
// Create the new stage
thisStage = new Stage();
// Load the FXML file
try {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Layout2.fxml"));
// Set this class as the controller
loader.setController(this);
// Load the scene
thisStage.setScene(new Scene(loader.load()));
// Setup the window/stage
thisStage.setTitle("Passing Controllers Example - Layout2");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Show the stage that was loaded in the constructor
*/
public void showStage() {
thisStage.showAndWait();
}
@FXML
private void initialize() {
// Set the label to whatever the text entered on Layout1 is
lblFromController1.setText(controller1.getEnteredText());
// Set the action for the button
btnSetLayout1Text.setOnAction(event -> setTextOnLayout1());
}
/**
* Calls the "setTextFromController2()" method on the first controller to update its Label
*/
private void setTextOnLayout1() {
controller1.setTextFromController2(txtToFirstController.getText());
}
}
Layout1.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
<VBox alignment="CENTER" spacing="10.0">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<Label style="-fx-font-weight: bold;" text="This is Layout1!"/>
<HBox alignment="CENTER_LEFT" spacing="10.0">
<Label text="Enter Text:"/>
<TextField fx:id="txtToSecondController"/>
<Button fx:id="btnOpenLayout2" mnemonicParsing="false" text="Open Layout2"/>
</HBox>
<VBox alignment="CENTER">
<Label text="Text From Controller2:"/>
<Label fx:id="lblFromController2" text="Nothing Yet!"/>
</VBox>
</VBox>
</AnchorPane>
Layout2.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.geometry.Insets?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.layout.HBox?>
<?import javafx.scene.layout.VBox?>
<AnchorPane xmlns="http://javafx.com/javafx/9.0.1" xmlns:fx="http://javafx.com/fxml/1">
<VBox alignment="CENTER" spacing="10.0">
<padding>
<Insets bottom="10.0" left="10.0" right="10.0" top="10.0"/>
</padding>
<Label style="-fx-font-weight: bold;" text="Welcome to Layout 2!"/>
<VBox alignment="CENTER">
<Label text="Text From Controller1:"/>
<Label fx:id="lblFromController1" text="Nothing Yet!"/>
</VBox>
<HBox alignment="CENTER_LEFT" spacing="10.0">
<Label text="Enter Text:"/>
<TextField fx:id="txtToFirstController"/>
<Button fx:id="btnSetLayout1Text" mnemonicParsing="false" text="Set Text on Layout1"/>
</HBox>
</VBox>
</AnchorPane>
The whole point of HttpOnly cookies is that they can't be accessed by JavaScript.
The only way (except for exploiting browser bugs) for your script to read them is to have a cooperating script on the server that will read the cookie value and echo it back as part of the response content. But if you can and would do that, why use HttpOnly cookies in the first place?
P stands for polynomial time. NP stands for non-deterministic polynomial time.
Definitions:
Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.
Complexity is time measured in the number of operations it would take, as a function of the number of data items.
Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.
Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.
There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.
It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.
NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.
An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.
Foo
variable will never ever take up memory.using
statement simply calls dispose on an IDisposable
object when it exits, so this is equivalent to your second bullet point. Both will indicate that you are done with the object and tell the GC that you are ready to let go of it. Overwriting the only reference to the object will have a similar effect.Push SVG element to last, so that its z-index will be in top. In SVG, there s no property called z-index. try below javascript to bring the element to top.
var Target = document.getElementById(event.currentTarget.id);
var svg = document.getElementById("SVGEditor");
svg.insertBefore(Target, svg.lastChild.nextSibling);
Target: Is an element for which we need to bring it to top svg: Is the container of elements
I tried this code, to retrieve shared preferences from an activity, and could not get it to work:
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.getAll();
Log.d("AddNewRecord", "getAll: " + sharedPreferences.getAll());
Log.d("AddNewRecord", "Size: " + sharedPreferences.getAll().size());
Every time I tried, my preferences returned 0, even though I have 14 preferences saved by the preference activity. I finally found the answer. I added this to the preferences in the onCreate section.
getPreferenceManager().setSharedPreferencesName("defaultPreferences");
After I added this statement, my saved preferences returned as expected. I hope that this helps someone else who may experience the same issue that I did.
i think you should use $('.calltoaction').val;
also, i would be using id (#) instead of a class for that.. if u have more than one of such classes which how would it handle it?
PowerShell solution
Using Posh-SSH:
New-SSHSession -ComputerName 0.0.0.0 -Credential $cred | Out-Null
Invoke-SSHCommand -SessionId 1 -Command "nohup sleep 5 >> abs.log &" | Out-Null
When you set 64-bit the resulting binary is a "Fat" binary, which contains all three Mach-O images bundled with a thin fat header. You can see that using otool or jtool. You can check out some fat binaries included as part of the iOS 7.0 SDK, for example the AVFoundation Framework, like so:
% cd /Developer/Platforms/iPhoneOS.platform/DeviceSupport/7.0\ \(11A465\)/Symbols/System/Library/Frameworks/AVFoundation.framework/
%otool -V -f AVFoundation 9:36
Fat headers
fat_magic FAT_MAGIC
nfat_arch 3
architecture arm64 # The 64-bit version (A7)
cputype CPU_TYPE_ARM64
cpusubtype CPU_SUBTYPE_ARM64_ALL
capabilities 0x0
offset 16384
size 2329888
align 2^14 (16384)
architecture armv7 # A5X - packaged after the arm64version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7
capabilities 0x0
offset 2359296
size 2046336
align 2^14 (16384)
architecture armv7s # A6 - packaged after the armv7 version
cputype CPU_TYPE_ARM
cpusubtype CPU_SUBTYPE_ARM_V7S
capabilities 0x0
offset 4407296
size 2046176
align 2^14 (16384)
As for the binary itself, it uses the ARM64 bit instruction set, which is (mostly compatible with 32-bit, but) a totally different instruction set. This is especially important for graphics program (using NEON instructions and registers). Likewise, the CPU has more registers, which makes quite an impact on program speed. There's an interesting discussion in http://blogs.barrons.com/techtraderdaily/2013/09/19/apple-the-64-bit-question/?mod=yahoobarrons on whether or not this makes a difference; benchmarking tests have so far clearly indicated that it does.
Using otool -tV will dump the assembly (if you have XCode 5 and later), and then you can see the instruction set differences for yourself. Most (but not all) developers will remain agnostic to the changes, as for the most part they do not directly affect Obj-C (CG* APIs notwithstanding), and have to do more with low level pointer handling. The compiler will work its magic and optimizations.
Here's what I came up with:
std::stringstream trimmer;
trimmer << str;
trimmer >> str;
Stream extraction eliminates whitespace automatically, so this works like a charm.
Pretty clean and elegant too, if I do say so myself. ;)
Symbol You Want on Color You Want!
I was looking for this answer for days and here it is the right and easy way to create a custom marker:
'http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=xxx%7c5680FC%7c000000&.png' where xxx is the text and 5680fc is the hexadecimal color code of the background and 000000 is the hexadecimal color code of the text.
Theses markers are totally dynamic and you can create whatever balloon icon you want. Just change the URL.
Some "data mining" accounts for that src/main/resources
is the typical place.
Results on Google Code Search:
src/main/resources/log4j.properties
: 4877src/main/java/log4j.properties
: 215 Definitely late to the party; anyway, for those interested, picking up on Lan's mention of HTML5 canvas, you can use gRaphaël Charting which has a MIT License (instead of HighCharts dual license). It's not Bootstrap-specific either, so it's more of a general suggestion.
I have to admit that HighCharts demos seem very pretty, and I have to warn that gRaphaël is quite hard to understand before becoming proficient with it. Anyway you can easily add nice features to your gRaphaël charts (say, tooltips or zooming effects), so it may be worth the effort.
Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/
.tinted-image {
width: 300px;
height: 200px;
background:
/* top, transparent red */
linear-gradient(
rgba(255, 0, 0, 0.45),
rgba(255, 0, 0, 0.45)
),
/* bottom, image */
url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}
I don't think there is a more "angular way" to select an element. See, for instance, the way they are achieving this goal in the last example of this old documentation page:
{
template: '<div>' +
'<div class="title">{{title}}</div>' +
'<div class="body" ng-transclude></div>' +
'</div>',
link: function(scope, element, attrs) {
// Title element
var title = angular.element(element.children()[0]),
// ...
}
}
The Access runtime license has never been all that expensive -- the cost for the developer tools/extensions has been around $300 as long as I can remember (which would be as far back to the Access 2 Developers Toolkit, or ADT), but that gives you the ability to distribute your app with the runtime to an unlimited number of users. As long as your runtime app was used by three or more users, you'd have been saving money (assuming a cost of $100/user to install a full copy of Access).
The runtime for Access 2007 is completely free, but really, the cost before that was not all that great.
Marc Gravell added (in what should have been a comment, in my opinion):
Being free, though, is certainly an encouragement for people to try it out which the $300 price really would have discouraged.
In Laravel 6 you have to add 'change' to your migrations file as follows:
$table->enum('is_approved', array('0','1'))->default('0')->change();
Assuming a forward-compatible context in OpenGL 3 and up, you can either use glPolygonMode
as mentioned before, but note that lines with thickness more than 1px are now deprecated. So while you can draw triangles as wire-frame, they need to be very thin. In OpenGL ES, you can use GL_LINES
with the same limitation.
In OpenGL it is possible to use geometry shaders to take incoming triangles, disassemble them and send them for rasterization as quads (pairs of triangles really) emulating thick lines. Pretty simple, really, except that geometry shaders are notorious for poor performance scaling.
What you can do instead, and what will also work in OpenGL ES is to employ fragment shader. Think of applying a texture of wire-frame triangle to the triangle. Except that no texture is needed, it can be generated procedurally. But enough talk, let's code. Fragment shader:
in vec3 v_barycentric; // barycentric coordinate inside the triangle
uniform float f_thickness; // thickness of the rendered lines
void main()
{
float f_closest_edge = min(v_barycentric.x,
min(v_barycentric.y, v_barycentric.z)); // see to which edge this pixel is the closest
float f_width = fwidth(f_closest_edge); // calculate derivative (divide f_thickness by this to have the line width constant in screen-space)
float f_alpha = smoothstep(f_thickness, f_thickness + f_width, f_closest_edge); // calculate alpha
gl_FragColor = vec4(vec3(.0), f_alpha);
}
And vertex shader:
in vec4 v_pos; // position of the vertices
in vec3 v_bc; // barycentric coordinate inside the triangle
out vec3 v_barycentric; // barycentric coordinate inside the triangle
uniform mat4 t_mvp; // modeview-projection matrix
void main()
{
gl_Position = t_mvp * v_pos;
v_barycentric = v_bc; // just pass it on
}
Here, the barycentric coordinates are simply (1, 0, 0)
, (0, 1, 0)
and (0, 0, 1)
for the three triangle vertices (the order does not really matter, which makes packing into triangle strips potentially easier).
The obvious disadvantage of this approach is that it will eat some texture coordinates and you need to modify your vertex array. Could be solved with a very simple geometry shader but I'd still suspect it will be slower than just feeding the GPU with more data.
I am a synthesizer:). Here I combined the answers into one function:
#' keep rows that have a certain number (range) of NAs anywhere/somewhere and delete others
#' @param df a data frame
#' @param col restrict to the columns where you would like to search for NA; eg, 3, c(3), 2:5, "place", c("place","age")
#' \cr default is NULL, search for all columns
#' @param n integer or vector, 0, c(3,5), number/range of NAs allowed.
#' \cr If a number, the exact number of NAs kept
#' \cr Range includes both ends 3<=n<=5
#' \cr Range could be -Inf, Inf
#' @return returns a new df with rows that have NA(s) removed
#' @export
ez.na.keep = function(df, col=NULL, n=0){
if (!is.null(col)) {
# R converts a single row/col to a vector if the parameter col has only one col
# see https://radfordneal.wordpress.com/2008/08/20/design-flaws-in-r-2-%E2%80%94-dropped-dimensions/#comments
df.temp = df[,col,drop=FALSE]
} else {
df.temp = df
}
if (length(n)==1){
if (n==0) {
# simply call complete.cases which might be faster
result = df[complete.cases(df.temp),]
} else {
# credit: http://stackoverflow.com/a/30461945/2292993
log <- apply(df.temp, 2, is.na)
logindex <- apply(log, 1, function(x) sum(x) == n)
result = df[logindex, ]
}
}
if (length(n)==2){
min = n[1]; max = n[2]
log <- apply(df.temp, 2, is.na)
logindex <- apply(log, 1, function(x) {sum(x) >= min && sum(x) <= max})
result = df[logindex, ]
}
return(result)
}
Actually, this is just the validation issue, EF will validate the entity properties first before making any changes to the database. So, EF will check whether the property's value is out of range, like when you designed the table. Table_Column_UserName is varchar(20). But, in EF, you entered a value that longer than 20. Or, in other cases, if the column does not allow to be a Null. So, in the validation process, you have to set a value to the not null column, no matter whether you are going to make the change on it. I personally, like the Leniel Macaferi answer. It can show you the detail of the validation issues
A web service, as used by software developers, generally refers to an operation that is performed on a remote server and invoked using the XML/SOAP specification. As with all definitions, there are nuances to it, but that's the most common use of the term.
This may be an old post, but if anyone is still facing this issue after trying all the above mentioned steps, ensure whether the default path of PowerShell module is specified under the "PSModulePath" environment variable.
The default path should be "%SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\"
I had this problem. Just run SQL Server as administrator
As an improvement to the accepted answer, in order to reduce nesting, you could do this instead, provided that the key is not inherited:
for (var key in dictionary) {
if (!dictionary.hasOwnProperty(key)) {
continue;
}
console.log(key, dictionary[key]);
}
Edit: info about Object.hasOwnProperty
here
In my situation this error appeared when I didn't declare function within an array argument.
The one with error:
taskAppControllers.controller('MainMenuCtrl', []);
The fixed one:
taskAppControllers.controller('MainMenuCtrl', [function(){
}]);
Try this:
UPDATE test
SET
field = 1
WHERE id = 123 and condition
KeyPress is a higher level of abstraction than KeyDown (and KeyUp). KeyDown and KeyUp are hardware related: the actual action of a key on the keyboard. KeyPress is more "I received a character from the keyboard".
or you can also do ( for pem file )
scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/
Abridged from: XML, Escaping
There are five predefined entities:
< represents "<"
> represents ">"
& represents "&"
' represents '
" represents "
"All permitted Unicode characters may be represented with a numeric character reference." For example:
中
Most of the control characters and other Unicode ranges are specifically excluded, meaning (I think) they can't occur either escaped or direct:
Most of the times in Linux, ng serve
or ng build --watch
doesn't work if the directory doesn't have sufficient permissions.
The solution is either to provide the necessary permissions or to use sudo
instead.
UPDATE
watch flag in ng serve
is actually redundant as it is the default option. Credit to @Zaphoid for pointing out the mistake.
Update
This is mainly to query the container not to update as building images is the way to be done
I had the same issue so I created docker-run, a very simple command-line tool that runs inside a docker container to update packages in other running containers.
It uses docker-py to communicate with running docker containers and update packages or run any arbitrary single command
Examples:
docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run exec
by default this will run date
command in all running containers and return results but you can issue any command e.g. docker-run exec "uname -a"
To update packages (currently only using apt-get):
docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run update
You can create and alias and use it as a regular command line e.g.
alias docker-run='docker run --rm -v /var/run/docker.sock:/tmp/docker.sock itech/docker-run'
I do not know if your still looking for the answer to this problem but today I happened the same problem and solved it. You need to specify in the HTML code,
**<Div class = "navbar"**>
div class = "container">
<Div class = "navbar-header">
or
**<Div class = "navbar navbar-default">**
div class = "container">
<Div class = "navbar-header">
You got that place in your CSS
.navbar-default-toggle .navbar .icon-bar {
background-color: # 0000ff;
}
and what I did was add above
.navbar .navbar-toggle .icon-bar {
background-color: # ff0000;
}
Because my html code is
**<Div class = "navbar">**
div class = "container">
<Div class = "navbar-header">
and if you associate a file less / css
search this section and also here placed the color you want to change, otherwise it will self-correct the css file to the state it was before
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-default-toggle-icon-bar-bg: # 888;**
@ Navbar-default-toggle-border-color: #ddd;
if your html code is like mine and is not navbar-default, add it as you did with the css.
// Toggle Navbar
@ Navbar-default-toggle-hover-bg: #ddd;
**@ Navbar-toggle-icon-bar-bg : #888;**
@ Navbar-default-toggle-icon-bar-bg: # 888;
@ Navbar-default-toggle-border-color: #ddd;
good luck
This code works well for returning all of the IP addresses that might belong to a particular URI. Since many systems are now in a hosted environment (AWS/Akamai/etc.), systems may return several IP addresses. The lambda was "borrowed" from @Peter Silva.
def get_ips_by_dns_lookup(target, port=None):
'''
this function takes the passed target and optional port and does a dns
lookup. it returns the ips that it finds to the caller.
:param target: the URI that you'd like to get the ip address(es) for
:type target: string
:param port: which port do you want to do the lookup against?
:type port: integer
:returns ips: all of the discovered ips for the target
:rtype ips: list of strings
'''
import socket
if not port:
port = 443
return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))
ips = get_ips_by_dns_lookup(target='google.com')
I faced the same issue recently. I found a solution that apparently works for all devices. You can't do async focus programmatically but you can switch focus to your target input when some other input is already focused. So what you need to do is create, hide, append to DOM & focus a fake input on trigger event and, when the async action completes, just call focus again on the target input. Here's an example snippet - run it on your mobile.
edit:
Here's a fiddle with the same code. Apparently you can't run attached snippets on mobiles (or I'm doing something wrong).
var $triggerCheckbox = $("#trigger-checkbox");_x000D_
var $targetInput = $("#target-input");_x000D_
_x000D_
// Create fake & invisible input_x000D_
var $fakeInput = $("<input type='text' />")_x000D_
.css({_x000D_
position: "absolute",_x000D_
width: $targetInput.outerWidth(), // zoom properly (iOS)_x000D_
height: 0, // hide cursor (font-size: 0 will zoom to quarks level) (iOS)_x000D_
opacity: 0, // make input transparent :]_x000D_
});_x000D_
_x000D_
var delay = 2000; // That's crazy long, but good as an example_x000D_
_x000D_
$triggerCheckbox.on("change", function(event) {_x000D_
// Disable input when unchecking trigger checkbox (presentational purpose)_x000D_
if (!event.target.checked) {_x000D_
return $targetInput_x000D_
.attr("disabled", true)_x000D_
.attr("placeholder", "I'm disabled");_x000D_
}_x000D_
_x000D_
// Prepend to target input container and focus fake input_x000D_
$fakeInput.prependTo("#container").focus();_x000D_
_x000D_
// Update placeholder (presentational purpose)_x000D_
$targetInput.attr("placeholder", "Wait for it...");_x000D_
_x000D_
// setTimeout, fetch or any async action will work_x000D_
setTimeout(function() {_x000D_
_x000D_
// Shift focus to target input_x000D_
$targetInput_x000D_
.attr("disabled", false)_x000D_
.attr("placeholder", "I'm alive!")_x000D_
.focus();_x000D_
_x000D_
// Remove fake input - no need to keep it in DOM_x000D_
$fakeInput.remove();_x000D_
}, delay);_x000D_
});
_x000D_
label {_x000D_
display: block;_x000D_
margin-top: 20px;_x000D_
}_x000D_
_x000D_
input {_x000D_
box-sizing: border-box;_x000D_
font-size: inherit;_x000D_
}_x000D_
_x000D_
#container {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
#target-input {_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id="container">_x000D_
<input type="text" id="target-input" placeholder="I'm disabled" />_x000D_
_x000D_
<label>_x000D_
<input type="checkbox" id="trigger-checkbox" />_x000D_
focus with setTimetout_x000D_
</label>_x000D_
</div>
_x000D_
Following width worked well in HTML5: -
<table >
<tr>
<th style="min-width:120px">Month</th>
<th style="min-width:60px">Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$80</td>
</tr>
</table>
Please note that
You're almost here, you're just missing a few things:
PUT /test
{
"mappings": {
"type_name": { <--- add the type name
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
},
"settings": {
...
}
}
UPDATE
If your index already exists, you can also modify your mappings like this:
PUT test/_mapping/type_name
{
"properties": { <--- enclose all field definitions in "properties"
"field1": {
"type": "integer"
},
"field2": {
"type": "integer"
},
"field3": {
"type": "string",
"index": "not_analyzed"
},
"field4,": {
"type": "string",
"analyzer": "autocomplete",
"search_analyzer": "standard"
}
}
}
UPDATE:
As of ES 7, mapping types have been removed. You can read more details here
Select SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3)
from your Table Name
The accepted answer by Francisco Spaeth works and is easy to follow. However, I think that method of building JSON sucks! This was really driven home for me as I converted some Python to Java where I could use dictionaries and nested lists, etc. to build JSON with ridiculously greater ease.
What I really don't like is having to instantiate separate objects (and generally even name them) to build up these nestings. If you have a lot of objects or data to deal with, or your use is more abstract, that is a real pain!
I tried getting around some of that by attempting to clear and reuse temp json objects and lists, but that didn't work for me because all the puts and gets, etc. in these Java objects work by reference not value. So, I'd end up with JSON objects containing a bunch of screwy data after still having some ugly (albeit differently styled) code.
So, here's what I came up with to clean this up. It could use further development, but this should help serve as a base for those of you looking for more reasonable JSON building code:
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.List;
import org.json.simple.JSONObject;
// create and initialize an object
public static JSONObject buildObject( final SimpleEntry... entries ) {
JSONObject object = new JSONObject();
for( SimpleEntry e : entries ) object.put( e.getKey(), e.getValue() );
return object;
}
// nest a list of objects inside another
public static void putObjects( final JSONObject parentObject, final String key,
final JSONObject... objects ) {
List objectList = new ArrayList<JSONObject>();
for( JSONObject o : objects ) objectList.add( o );
parentObject.put( key, objectList );
}
Implementation example:
JSONObject jsonRequest = new JSONObject();
putObjects( jsonRequest, "parent1Key",
buildObject(
new SimpleEntry( "child1Key1", "someValue" )
, new SimpleEntry( "child1Key2", "someValue" )
)
, buildObject(
new SimpleEntry( "child2Key1", "someValue" )
, new SimpleEntry( "child2Key2", "someValue" )
)
);
You can use the os Module:
var os = require("os");
os.hostname();
See http://nodejs.org/docs/latest/api/os.html#os_os_hostname
Caveats:
if you can work with the IP address -- Machines may have several Network Cards and unless you specify it node will listen on all of them, so you don't know on which NIC the request came in, before it comes in.
Hostname is a DNS matter -- Don't forget that several DNS aliases can point to the same machine.
Sorry, much late to the party, but I'll add here that if you wanted to capture processes with names identical to your search string, you could do
pgrep -x PROCESS_NAME
-x Require an exact match of the process name, or argument list if -f is given. The default is to match any substring.
This is extremely useful if your original process created child processes (possibly zombie when you query) which prefix the original process' name in their own name and you are trying to exclude them from your results. There are many UNIX daemons which do this. My go-to example is ninja-dev-sync.
Instead of removeClass and addClass, you can also do it like this:
$('.IsBestAnswer').toggleClass('IsBestAnswer bestanswer');
Have you tried using rclone.org?
With rclone
you could do something like
rclone copy "${source}/${subfolder}/" "${target}/${subfolder}/" --progress --multi-thread-streams=N
where --multi-thread-streams=N
represents the number of threads you wish to spawn.
You can accomplish this with a slightly different syntax:
ng-class="{'approved': selectedForApproval.indexOf(jobSet) === -1}"
This is to synchronize IOs from C and C++ world. If you synchronize, then you have a guaranty that the orders of all IOs is exactly what you expect. In general, the problem is the buffering of IOs that causes the problem, synchronizing let both worlds to share the same buffers. For example cout << "Hello"; printf("World"); cout << "Ciao";
; without synchronization you'll never know if you'll get HelloCiaoWorld
or HelloWorldCiao
or WorldHelloCiao
...
tie
lets you have the guaranty that IOs channels in C++ world are tied one to each other, which means for example that every output have been flushed before inputs occurs (think about cout << "What's your name ?"; cin >> name;
).
You can always mix C or C++ IOs, but if you want some reasonable behavior you must synchronize both worlds. Beware that in general it is not recommended to mix them, if you program in C use C stdio, and if you program in C++ use streams. But you may want to mix existing C libraries into C++ code, and in such a case it is needed to synchronize both.
You also should set border:none
to that css class.
Using the PHPExcel library, the following code will do.
require_once dirname(__FILE__) . '/../Classes/PHPExcel/IOFactory.php';
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true); //optional
$objPHPExcel = $objReader->load(__DIR__.'/YourExcelFile.xlsx');
$objWorksheet = $objPHPExcel->getActiveSheet();
$i=1;
foreach ($objWorksheet->getRowIterator() as $row) {
$column_A_Value = $objPHPExcel->getActiveSheet()->getCell("A$i")->getValue();//column A
//you can add your own columns B, C, D etc.
//inset $column_A_Value value in DB query here
$i++;
}
if (!empty($web)) {
?>
<span class="field-label">Website: </span><a href="http://<?php the_field('website'); ?>" target="_blank"><?php the_field('website'); ?></a>
<?php
} else { echo "Niente";}
Navigate to the jmeter/bin
directory from command line and
jmeter -n -t <YourTestScript.jmx> -l <TestScriptsResults.jtl>
You will not be able to retrieve a plain text password from wordpress.
Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.
See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password
If you just want the bitmap, This too works
InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();
sample uri : content://media/external/images/media/12345
Node.js:
var fs = require('fs');
fs.writeFile("test.txt", jsonData, function(err) {
if (err) {
console.log(err);
}
});
Browser (webapi):
function download(content, fileName, contentType) {
var a = document.createElement("a");
var file = new Blob([content], {type: contentType});
a.href = URL.createObjectURL(file);
a.download = fileName;
a.click();
}
download(jsonData, 'json.txt', 'text/plain');
Prefixing the string with an @ indicates that it should be treated as a literal, i.e. no escaping.
For example if your string contains a path you would typically do this:
string path = "c:\\mypath\\to\\myfile.txt";
The @ allows you to do this:
string path = @"c:\mypath\to\myfile.txt";
Notice the lack of double slashes (escaping)
In this example, nothing really. The exact
param comes into play when you have multiple paths that have similar names:
For example, imagine we had a Users
component that displayed a list of users. We also have a CreateUser
component that is used to create users. The url for CreateUsers
should be nested under Users
. So our setup could look something like this:
<Switch>
<Route path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
Now the problem here, when we go to http://app.com/users
the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users
route first and then return it. All good.
But, if we went to http://app.com/users/create
, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users
partially matches /users/create
, so it would incorrectly return the Users
route again!
The exact
param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.
So in this case, we should add exact
to our Users
route so that it will only match on /users
:
<Switch>
<Route exact path="/users" component={Users} />
<Route path="/users/create" component={CreateUser} />
</Switch>
This is the value that i want to clear and create it in state 1st STEP
state={
TemplateCode:"",
}
craete submitHandler function for Button or what you want 3rd STEP
submitHandler=()=>{
this.clear();//this is function i made
}
This is clear function Final STEP
clear = () =>{
this.setState({
TemplateCode: ""//simply you can clear Templatecode
});
}
when click button Templatecode is clear 2nd STEP
<div class="col-md-12" align="right">
<button id="" type="submit" class="btn btnprimary" onClick{this.submitHandler}> Save
</button>
</div>
# Set the HEAD to the old commit that we want to tag
git checkout 9fceb02
# temporarily set the date to the date of the HEAD commit, and add the tag
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" \
git tag -a v1.2 -m"v1.2"
# set HEAD back to whatever you want it to be
git checkout master
The answer by @dkinzer creates tags whose date is the current date (when you ran the git tag
command), not the date of the commit. The Git help for tag
has a section "On Backdating Tags" which says:
If you have imported some changes from another VCS and would like to add tags for major releases of your work, it is useful to be able to specify the date to embed inside of the tag object; such data in the tag object affects, for example, the ordering of tags in the gitweb interface.
To set the date used in future tag objects, set the environment variable
GIT_COMMITTER_DATE
(see the later discussion of possible values; the most common form is "YYYY-MM-DD HH:MM").For example:
$ GIT_COMMITTER_DATE="2006-10-02 10:31" git tag -s v1.0.1
The page "How to Tag in Git" shows us that we can extract the time of the HEAD commit via:
git show --format=%aD | head -1
#=> Wed, 12 Feb 2014 12:36:47 -0700
We could extract the date of a specific commit via:
GIT_COMMITTER_DATE="$(git show 9fceb02 --format=%aD | head -1)" \
git tag -a v1.2 9fceb02 -m "v1.2"
However, instead of repeating the commit twice, it seems easier to just change the HEAD to that commit and use it implicitly in both commands:
git checkout 9fceb02
GIT_COMMITTER_DATE="$(git show --format=%aD | head -1)" git tag -a v1.2 -m "v1.2"