I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem
Player.cpp
require the definition of Ball
class. So simply add #include "Ball.h"
Player.cpp:
#include "Player.h"
#include "Ball.h"
void Player::doSomething(Ball& ball) {
ball.ballPosX += 10; // incomplete type error occurs here.
}
If you are using the AppCompat library v7 you may want to use the LinearLayoutCompat
view. Using this approach you can use drawable dividers on Android 2.1, 2.2 and 2.3.
Example code:
<android.support.v7.widget.LinearLayoutCompat
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:showDividers="middle"
app:divider="@drawable/divider">
drawable/divider.xml: (divider with some padding on the top and bottom)
<?xml version="1.0" encoding="UTF-8"?>
<inset xmlns:android="http://schemas.android.com/apk/res/android"
android:insetBottom="2dp"
android:insetTop="2dp">
<shape>
<size android:width="1dp" />
<solid android:color="#FFCCCCCC" />
</shape>
</inset>
Very important note: The LinearLayoutCompat
view does not extend LinearLayout
and therefor you should not use the android:showDividers
or android:divider
properties but the custom ones: app:showDividers
and app:divider
. In code you should also use the LinearLayoutCompat.LayoutParams
not the LinearLayout.LayoutParams
!
For Obj-C, for example, there's a CocoaPod SHControlBlocks, whose usage would be:
[self.btnFirst SH_addControlEvents:UIControlEventTouchDown withBlock:^(UIControl *sender) {
[weakSelf performSegueWithIdentifier:@"second" sender:nil];
NSLog(@"first");
}];
For Swift, I love the pod Actions, which allows blocks for UIControl
s [1]:
// UIControl
let button = UIButton()
button.add(event: .touchUpInside) {
print("Button tapped")
playMusic(from: speakers_mp4, withSongAtPosition: indexPath.row)
}
Not that anyone is reading a 3-year old thread. ::crickets::
[1] And UIView
, UITextField
, UIGestureRecognizer
, UIBarButtonItem
, Timer
(formally NSTimer), and NotificationCenter
(formally NSNotificationCenter).
You can use DataSet.Tables(0).Columns.Contains(name)
to check whether the DataTable
contains a column with a particular name.
This regex is very short and sweet for working.
/^([+]\d{2})?\d{10}$/
Ex: +910123456789 or 0123456789
-> /^ and $/ is for starting and ending
-> The ? mark is used for conditional formatting where before question mark is available or not it will work
-> ([+]\d{2}) this indicates that the + sign with two digits '\d{2}' here you can place digit as per country
-> after the ? mark '\d{10}' this says that the digits must be 10 of length change as per your country mobile number length
This is how this regex for mobile number is working.
+ sign is used for world wide matching of number.
if you want to add the space between than you can use the
[ ]
here the square bracket represents the character sequence and a space is character for searching in regex.
for the space separated digit you can use this regex
/^([+]\d{2}[ ])?\d{10}$/
Ex: +91 0123456789
Thanks ask any question if you have.
Having following html:
<!-- note that not all browsers focus on links when Tab is pressed -->
<a href="http://example.com">Link</a>
<input type="text" placeholder="Some input" />
<a href="http://example.com">Another Link</a>
<textarea>...</textarea>
You can get to active link with:
// event listener for keyup
function checkTabPress(e) {
"use strict";
// pick passed event or global event object if passed one is empty
e = e || event;
var activeElement;
if (e.keyCode == 9) {
// Here read the active selected link.
activeElement = document.activeElement;
// If HTML element is an anchor <a>
if (activeElement.tagName.toLowerCase() == 'a')
// get it's hyperlink
alert(activeElement.href);
}
}
var body = document.querySelector('body');
body.addEventListener('keyup', checkTabPress);
Here is working example.
Same error, different situation. I'm posting this here because someone might be in same situation as mine.
I was using context API like below.
export const withDB = Component => props => {
<DBContext.Consumer>
{db => <Component {...props} db={db} />}
</DBContext.Consumer>
}
So basically the error message is giving you the answer.
Nothing was returned from render. This usually means a return statement is missing
withDB
should return a html block. But it wasn't returning anything. Revising my code to below solved my issue.
export const withDB = Component => props => {
return (
<DBContext.Consumer>
{db => <Component {...props} db={db} />}
</DBContext.Consumer>
)
}
Simply using
input("Press Enter to continue...")
will cause a SyntaxError: expected EOF while parsing.
Simple fix use:
try:
input("Press enter to continue")
except SyntaxError:
pass
I know this is old question, but I am currently playing with library to handle exactly this problem. It requires c++14.
#include "htl.hpp"
htl::Token _;
std::vector<int> vec = _[0, _, 100];
// or
for (auto const e: _[0, _, 100]) { ... }
// supports also custom steps
// _[0, _%3, 100] == 0, 4, 7, 10, ...
#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29
Check the below snippet
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker4'>
<input type='text' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function() {
// Bootstrap DateTimePicker v4
$('#datetimepicker4').datetimepicker({
format: 'DD/MM/YYYY'
});
});
</script>
</div>
You can refer http://eonasdan.github.io/bootstrap-datetimepicker/ for documentation and other functions in detail. This should work.
Use localized formats of moment.js:
L
for date onlyLT
for time onlyL LT
for date and timeSee other localized formats in the moment.js documentation (https://momentjs.com/docs/#/displaying/format/)
To be honest, as other posters have mentioned, Wikipedia has a very good article on this so have a look there. This type of error is very common and often called other things such as Access Violation or General Protection Fault.
They are no different in C, C++ or any other language that allows pointers. These kinds of errors are usually caused by pointers that are
As you can see in the templates, the text is delivered via the localization framework (note the use of the trans
template tag). You can make changes to the translation files to override the text without making your own copy of the templates.
mkdir locale
./manage.py makemessages
Edit locale/en/LC_MESSAGES/django.po
, adding these lines:
msgid "Django site admin"
msgstr "MySite site admin"
msgid "Django administration"
msgstr "MySite administration"
./manage.py compilemessages
See https://docs.djangoproject.com/en/1.3/topics/i18n/localization/#message-files
Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways
setNull(..)
and
set<ClassName>(.., null))
behave the same way.
the instructions for Vs2012
To Install FreeGLUT
Extract the compressed file freeglut-MSVC.zip to a folder freeglut
Inside freeglut folder:
On 32bit versions of windows
copy all files in include/GL folder to C:\Program Files\Windows Kits\8.0\Include\um\gl
copy all files in lib folder to C:\Program Files\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)
copy freeglut.dll to C:\windows\system32
On 64bit versions of windows:(not 100% sure but try)
copy all files in include/GL folder to C:\Program Files(x86)\Windows Kits\8.0\Include\um\gl
copy all files in lib folder to C:\Program Files(x86)\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)
copy freeglut.dll to C:\windows\SysWOW64
What I did is create a separate content view as shown here.
The content view is freeform and can has all subviews added to it with their own constraints in relation to the contentView.
The UIScrollView is added to the main view controller.
Programatically I add the contentView which is linked via IBOutlet to class and set the contentView of UIScrollView.
I think, it is redundant. rs.getObject("ID_PARENT")
should return an Integer
object or null
, if the column value actually was NULL
. So it should even be possible to do something like:
if (rs.next()) {
Integer idParent = (Integer) rs.getObject("ID_PARENT");
if (idParent != null) {
iVal = idParent; // works for Java 1.5+
} else {
// handle this case
}
}
So, to summarize:
I don't want to make things more confusing but note that Java EE 6 provides modern, standardized and very nice equivalent of the above frameworks: JSF 2.0 and Facelets for the presentation, JPA 2.0 for the persistence, Dependency Injection, etc. For a new development, this is IMO a serious option, Java EE 6 is a great stack.
You have to arrange for a distinct copy of "i" to be present for each of the timeout functions.
function doSetTimeout(i) {
setTimeout(function() { alert(i); }, 100);
}
for (var i = 1; i <= 2; ++i)
doSetTimeout(i);
If you don't do something like this (and there are other variations on this same idea), then each of the timer handler functions will share the same variable "i". When the loop is finished, what's the value of "i"? It's 3! By using an intermediating function, a copy of the value of the variable is made. Since the timeout handler is created in the context of that copy, it has its own private "i" to use.
edit — there have been a couple of comments over time in which some confusion was evident over the fact that setting up a few timeouts causes the handlers to all fire at the same time. It's important to understand that the process of setting up the timer — the calls to setTimeout()
— take almost no time at all. That is, telling the system, "Please call this function after 1000 milliseconds" will return almost immediately, as the process of installing the timeout request in the timer queue is very fast.
Thus, if a succession of timeout requests is made, as is the case in the code in the OP and in my answer, and the time delay value is the same for each one, then once that amount of time has elapsed all the timer handlers will be called one after another in rapid succession.
If what you need is for the handlers to be called at intervals, you can either use setInterval()
, which is called exactly like setTimeout()
but which will fire more than once after repeated delays of the requested amount, or instead you can establish the timeouts and multiply the time value by your iteration counter. That is, to modify my example code:
function doScaledTimeout(i) {
setTimeout(function() {
alert(i);
}, i * 5000);
}
(With a 100
millisecond timeout, the effect won't be very obvious, so I bumped the number up to 5000.) The value of i
is multiplied by the base delay value, so calling that 5 times in a loop will result in delays of 5 seconds, 10 seconds, 15 seconds, 20 seconds, and 25 seconds.
Update
Here in 2018, there is a simpler alternative. With the new ability to declare variables in scopes more narrow than functions, the original code would work if so modified:
for (let i = 1; i <= 2; i++) {
setTimeout(function() { alert(i) }, 100);
}
The let
declaration, unlike var
, will itself cause there to be a distinct i
for each iteration of the loop.
You can also toggle this for select lines in your script by wrapping them in set -x
and set +x
, for example,
#!/bin/bash
...
if [[ ! -e $OUT_FILE ]];
then
echo "grabbing $URL"
set -x
curl --fail --noproxy $SERV -s -S $URL -o $OUT_FILE
set +x
fi
In order to overcome
Ambiguous output in step `CR-LF..data'
simply solution might be to add -f
flag to force conversion.
I had a similar problem, but I had the existing id, and as egiray said, I was calling DOM before it loaded and Javascript console was showing the same error, so I tried:
window.onload = (function(){myfuncname()});
and it starts working.
I think using ValueTuples like this can work. You have to add the ValueTuple NuGet package first though:
public async void Method1()
{
(int op, int result) tuple = await GetDataTaskAsync();
int op = tuple.op;
int result = tuple.result;
}
public async Task<(int op, int result)> GetDataTaskAsync()
{
int x = 5;
int y = 10;
return (op: x, result: y):
}
this Func may help you . it add every list object to grid view
private void show_data()
{
BindingSource Source = new BindingSource();
for (int i = 0; i < CC.Contects.Count; i++)
{
Source.Add(CC.Contects.ElementAt(i));
};
Data_View.DataSource = Source;
}
I write this for simple database app
My case: I use Windows and I have more than 1 user account. I was receiving the same error and the fix was to start the git bash with administrator rights.
To clarify Alvaro's answer, you need to add the -D option to the list of command lines. I'm using PyCharm, but the concept is the same:
pycharm{64,.exe,64.exe}.vmoptions:
<code>
-server
-Xms128m
...
-Didea.max.intellisense.filesize=999999 # <--- new line
</code>
Okay, but you all know that the * is a wildcard and allows cross site scripting from every domain?
You would like to send multiple Access-Control-Allow-Origin
headers for every site that's allowed to - but unfortunately its officially not supported to send multiple Access-Control-Allow-Origin
headers, or to put in multiple origins.
You can solve this by checking the origin, and sending back that one in the header, if it is allowed:
$origin = $_SERVER['HTTP_ORIGIN'];
$allowed_domains = [
'http://mysite1.com',
'https://www.mysite2.com',
'http://www.mysite2.com',
];
if (in_array($origin, $allowed_domains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
Thats much safer. You might want to edit the matching and change it to a manual function with some regex, or something like that. At least this will only send back 1 header, and you will be sure its the one that the request came from. Please do note that all HTTP headers can be spoofed, but this header is for the client's protection. Don't protect your own data with those values. If you want to know more, read up a bit on CORS and CSRF.
Why is it safer?
Allowing access from other locations then your own trusted site allows for session highjacking. I'm going to go with a little example - image Facebook allows a wildcard origin - this means that you can make your own website somewhere, and make it fire AJAX calls (or open iframes) to facebook. This means you can grab the logged in info of the facebook of a visitor of your website. Even worse - you can script POST
requests and post data on someone's facebook - just while they are browsing your website.
Be very cautious when using the ACAO
headers!
Edit. As noted in the comments, this is no longer working with the latest Android Studio releases.
The latest Android studio seems to only reference to "Offline mode" via the keymap, but toggling this does not seem to change anything anymore.
In Android Studio open the settings and search for offline it will find the Gradle
category which contains Offline work. You can disable it there.
rsync is not necessarily more efficient, due to the more detailed inventory of files and blocks it performs. The algorithm is fantastic at what it does, but you need to understand your problem to know if it is really going to be the best choice.
On a very large file system (say many thousands or millions of files) where files tend to be added but not updated, "cp -u" will likely be more efficient. cp makes the decision to copy solely on metadata and can simply get to the business of copying.
Note that you might want some buffering, e.g. by using tar rather than straight cp, depending on the size of the files, network performance, other disk activity, etc. I find the following idea very useful:
tar cf - . | tar xCf directory -
Metadata itself may actually become a significant overhead on very large (cluster) file systems, but rsync and cp will share this problem.
rsync seems to frequently be the preferred tool (and in general purpose applications is my usual default choice), but there are probably many people who blindly use rsync without thinking it through.
Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError
that implements the LocalizedError
protocol.
struct DisplayableError: Error, LocalizedError {
let errorDescription: String?
init(_ description: String) {
errorDescription = description
}
}
Usage for throwing:
throw DisplayableError("Out of pixie dust.")
Usage for display:
let messageToDisplay = error.localizedDescription
var string="<script>...</script>";
string=encodeURIComponent(string); // %3Cscript%3E...%3C/script%3
To get only uploaded file Name use this,
fake_path=document.getElementById('FileUpload1').value
alert(fake_path.split("\\").pop())
FileUpload1
value contains fake path, that you probably don't want, to avoid that use split and pop last element from your file.
If you want to test if an object is strictly or extends a Hash
, use:
value = {}
value.is_a?(Hash) || value.is_a?(Array) #=> true
But to make value of Ruby's duck typing, you could do something like:
value = {}
value.respond_to?(:[]) #=> true
It is useful when you only want to access some value using the value[:key]
syntax.
Please note that
Array.new["key"]
will raise aTypeError
.
Unpopular opinion from 2020:
When it comes to ASP.NET apps I still prefer WebClient
over HttpClient
because:
I had a huge problems with auto layout. We have two containers inside table cell. Second container is resized depending on Item description (0 - 1000 chars), and row should be resized based on them.
The missing ingredient was bottom constraint for description.
I've changed bottom constraint of dynamic element from = 0 to >= 0.
Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:
var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
if (functionLock) {
functionCallbacks.push(callback);
} else {
$.longRunning(function(response) {
while(functionCallbacks.length){
var thisCallback = functionCallbacks.pop();
thisCallback(response);
}
});
}
}
You can also implement this using DOM event listeners or a pubsub solution.
int
It is a primitive data type defined in C#.
It is mapped to Int32 of FCL type.
It is a value type and represent System.Int32 struct.
It is signed and takes 32 bits.
It has minimum -2147483648 and maximum +2147483647 value.
Int16
It is a FCL type.
In C#, short is mapped to Int16.
It is a value type and represent System.Int16 struct.
It is signed and takes 16 bits.
It has minimum -32768 and maximum +32767 value.
Int32
It is a FCL type.
In C#, int is mapped to Int32.
It is a value type and represent System.Int32 struct.
It is signed and takes 32 bits.
It has minimum -2147483648 and maximum +2147483647 value.
Int64
It is a FCL type.
In C#, long is mapped to Int64.
It is a value type and represent System.Int64 struct.
It is signed and takes 64 bits.
It has minimum –9,223,372,036,854,775,808 and maximum 9,223,372,036,854,775,807 value.
To set the cookie, use the ensure_csrf_cookie
decorator in your view:
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def hello(request):
code_here()
For case-insensitive string search, use index
(or rindex
) in combination with fc
. This example expands on the answer by Eugene Yarmash:
use feature qw( fc );
my $str = "Abc";
my $substr = "aB";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints: found
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints: found
$str = "Abc";
$substr = "bA";
print "found" if index( fc $str, fc $substr ) != -1;
# Prints nothing
print "found" if rindex( fc $str, fc $substr ) != -1;
# Prints nothing
Both index
and rindex
return -1
if the substring is not found.
And fc
returns a casefolded version of its string argument, and should be used here instead of the (more familiar) uc
or lc
. Remember to enable this function, for example with use feature qw( fc );
.
You have to give a separate id to the label too.
<label for="foo" id="foo_label">text</label>
#foo_label {display: none;}
Or hide the whole row
<tr id="foo_row">/***/</tr>
#foo_row {display: none;}
Just document it here
on Windows you need to escape the \
character:
"e:\\directory\\-"
There are several ways of checking if an variable is an array or not. The best solution is the one you have chosen.
variable.constructor === Array
This is the fastest method on Chrome, and most likely all other browsers. All arrays are objects, so checking the constructor property is a fast process for JavaScript engines.
If you are having issues with finding out if an objects property is an array, you must first check if the property is there.
variable.prop && variable.prop.constructor === Array
Some other ways are:
Array.isArray(variable)
Update May 23, 2019 using Chrome 75, shout out to @AnduAndrici for having me revisit this with his question
This last one is, in my opinion the ugliest, and it is one of the slowest fastest. Running about 1/5 the speed as the first example. This guy is about 2-5% slower, but it's pretty hard to tell. Solid to use! Quite impressed by the outcome. Array.prototype, is actually an array. you can read more about it here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
variable instanceof Array
This method runs about 1/3 the speed as the first example. Still pretty solid, looks cleaner, if you're all about pretty code and not so much on performance. Note that checking for numbers does not work as variable instanceof Number
always returns false
. Update: instanceof
now goes 2/3 the speed!
So yet another update
Object.prototype.toString.call(variable) === '[object Array]';
This guy is the slowest for trying to check for an Array. However, this is a one stop shop for any type you're looking for. However, since you're looking for an array, just use the fastest method above.
Also, I ran some test: http://jsperf.com/instanceof-array-vs-array-isarray/35 So have some fun and check it out.
Note: @EscapeNetscape has created another test as jsperf.com is down. http://jsben.ch/#/QgYAV I wanted to make sure the original link stay for whenever jsperf comes back online.
After creating your client specifying the binding and endpoint address, you can assign an OperationTimeout,
client.InnerChannel.OperationTimeout = new TimeSpan(0, 5, 0);
There's no special case for String
, because String
is an ordinary referential type on JVM, in contrast with Java primitives (int
, double
, ...) -- storing them in a reference Array<T>
requires boxing them into objects like Integer
and Double
. The purpose of specialized arrays like IntArray
in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[]
instead of Integer[]
).
You can use Array<String>
(and Array<String?>
for nullables), which is equivalent to String[]
in Java:
val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")
See also: Arrays in the language reference
I know this is an old question, but as long as the dates are >= 01-Jan-1753 I use:
DATEDIFF(MONTH, DATEADD(DAY,-DAY(@Start)+1,@Start),DATEADD(DAY,-DAY(@Start)+1,@End))
By the way, a history of Java SE versions.
Python has a built-in datatype for an unordered collection of (hashable) things, called a set
. If you convert both lists to sets, the comparison will be unordered.
set(x) == set(y)
EDIT: @mdwhatcott points out that you want to check for duplicates. set
ignores these, so you need a similar data structure that also keeps track of the number of items in each list. This is called a multiset; the best approximation in the standard library is a collections.Counter
:
>>> import collections
>>> compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
>>>
>>> compare([1,2,3], [1,2,3,3])
False
>>> compare([1,2,3], [1,2,3])
True
>>> compare([1,2,3,3], [1,2,2,3])
False
>>>
In case you need to parse it from a file, I find the best solution to use a HashMap<String, String>
to use it inside your java code for better manipultion.
Try out this code:
public HashMap<String, String> myMethodName() throws FileNotFoundException
{
String path = "absolute path to your file";
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
Gson gson = new Gson();
HashMap<String, String> json = gson.fromJson(bufferedReader, HashMap.class);
return json;
}
Bitmap yourBitmap;
Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);
or:
resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);
You can't use
$('#Id').attr('style',' color:red');
and
$('#Id').css('padding-left','20%');
at the same time.
You can either use attr
or css
but both only works when they are used alone.
Using Java 8's Stream.filter()
method in combination with List.contains()
:
import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toList;
/* ... */
List<Integer> list1 = asList(1, 2, 3, 4, 5);
List<Integer> list2 = asList(1, 3, 5, 7, 9);
List<Integer> common = list1.stream().filter(list2::contains).collect(toList());
The marked answer here did not solve my issue, possibly different angular versions. I was able to achieve the desired outcome with the following angular cli
command in terminal / shell:
ng build --base-href /myUrl/
ng build --bh /myUrl/
or ng build --prod --bh /myUrl/
This changes the <base href="/">
to <base href="/myUrl/">
in the built version only which was perfect for our change in environment between development and production. The best part was no code base requires changing using this method.
index.html
base href as: <base href="/">
then run ng build --bh ./
with angular cli to make it a relative path, or replace the ./
with whatever you require.
As the example above shows how to do it from command line, here is how to add it to your angular.json configuration file.
This will be used for all ng serving
for local development
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"baseHref": "/testurl/",
This is the config specific for configuration builds such as prod:
"configurations": {
"Prod": {
"fileReplacements": [
{
"replace": src/environments/environment.ts",
"with": src/environments/environment.prod.ts"
}
],
"baseHref": "./productionurl/",
The official angular-cli
documentation referring to usage.
There is many ways to use it and i recomend you to see this documentation about String Format.
http://developer.android.com/intl/pt-br/reference/java/util/Formatter.html
But, if you need only one variable, you'll need to use %[type] where [type] could be any Flag (see Flag types inside site above). (i.e. "My name is %s" or to set my name UPPERCASE, use this "My name is %S")
<string name="welcome_messages">Hello, %1$S! You have %2$d new message(s) and your quote is %3$.2f%%.</string>
Hello, ANDROID! You have 1 new message(s) and your quote is 80,50%.
impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl
All the above answers are correct, but I noticed something very important. Leaving a space between the variable and the equal sign might result in a problem. For example, (?variablename =value)
//query is your json
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost("http://my.site/test/v1/product/search?qy=");
StringEntity input = new StringEntity(query, "UTF-8");
input.setContentType("application/json");
postRequest.setEntity(input);
HttpResponse response=response = httpClient.execute(postRequest);
You need to have the class inside a folder Devices
.
If you're developing on an XAMPP, then you'll need an SMTP service to send the email. Try using a MailGun account. It's free and easy to use.
var timeout_check_change_class;
function check_change_class( selector )
{
$(selector).each(function(index, el) {
var data_old_class = $(el).attr('data-old-class');
if (typeof data_old_class !== typeof undefined && data_old_class !== false)
{
if( data_old_class != $(el).attr('class') )
{
$(el).trigger('change_class');
}
}
$(el).attr('data-old-class', $(el).attr('class') );
});
clearTimeout( timeout_check_change_class );
timeout_check_change_class = setTimeout(check_change_class, 10, selector);
}
check_change_class( '.breakpoint' );
$('.breakpoint').on('change_class', function(event) {
console.log('haschange');
});
Above solutions are good but for me, I find this code simple and workable. Just create a temporary file. If the file is created, its mean user has the write access.
public static bool HasWritePermission(string tempfilepath)
{
try
{
System.IO.File.Create(tempfilepath + "temp.txt").Close();
System.IO.File.Delete(tempfilepath + "temp.txt");
}
catch (System.UnauthorizedAccessException ex)
{
return false;
}
return true;
}
If you are using Gradle, include right jar of driver as below:
compile("org.mongodb:mongo-java-driver:3.3.0")
Or if using Maven then do it in Maven style, it should solve your problem.
I think you should consider using IO.binread("/path/to/file")
if you have a recent ruby interpreter (i.e. >= 1.9.2)
You could find IO
class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html
You have to placed this code in application.rb
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}
In C++11 and above, you can also initialize std::vector
with an initializer list. For example:
using namespace std; // for example only
for (auto s : vector<string>{"one","two","three"} )
cout << s << endl;
So, your example would become:
void foo(vector<string> strArray){
// some code
}
vector<string> s {"hi", "there"}; // Works
foo(s); // Works
foo(vector<string> {"hi", "there"}); // also works
It just means that the server cannot find your image.
Remember The image path must be relative to the CSS file location
Check the path and if the image file exist.
Since Redis 2.6, lua is supported, you can get number of wildcard keys like this
eval "return #redis.call('keys', 'prefix-*')" 0
see eval command
First instantiate a firefox driver
WebDriver driver = new FirefoxDriver();
then maximize it
driver.manage().window().maximize();
I don't know if that answers your question, but yes, you can use angularjs links, such as:
<a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
There is a good example on the AngularJS website:
http://docs.angularjs.org/api/ng.directive:ngHref
UPDATE: The AngularJS documentation was a bit obscure and it didn't provide a good solution for it. Sorry!
You can find a better solution here: How to handle anchor hash linking in AngularJS
If you are using bootstrap.js then the below code might be useful. This is very simple. Dont have to write anything in js to invoke the pop-up.
Source :http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_modal&stacked=h
<!DOCTYPE html>
<html lang="en">
<head>
<title>Bootstrap Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
If you are using Float or Integer then you can assign default value like this ...
Integer[] data = new Integer[20];
Arrays.fill(data,new Integer(0));
With small custom synchronization context, sync function can wait for completion of async function, without creating deadlock. Here is small example for WinForms app.
Imports System.Threading
Imports System.Runtime.CompilerServices
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
SyncMethod()
End Sub
' waiting inside Sync method for finishing async method
Public Sub SyncMethod()
Dim sc As New SC
sc.WaitForTask(AsyncMethod())
sc.Release()
End Sub
Public Async Function AsyncMethod() As Task(Of Boolean)
Await Task.Delay(1000)
Return True
End Function
End Class
Public Class SC
Inherits SynchronizationContext
Dim OldContext As SynchronizationContext
Dim ContextThread As Thread
Sub New()
OldContext = SynchronizationContext.Current
ContextThread = Thread.CurrentThread
SynchronizationContext.SetSynchronizationContext(Me)
End Sub
Dim DataAcquired As New Object
Dim WorkWaitingCount As Long = 0
Dim ExtProc As SendOrPostCallback
Dim ExtProcArg As Object
<MethodImpl(MethodImplOptions.Synchronized)>
Public Overrides Sub Post(d As SendOrPostCallback, state As Object)
Interlocked.Increment(WorkWaitingCount)
Monitor.Enter(DataAcquired)
ExtProc = d
ExtProcArg = state
AwakeThread()
Monitor.Wait(DataAcquired)
Monitor.Exit(DataAcquired)
End Sub
Dim ThreadSleep As Long = 0
Private Sub AwakeThread()
If Interlocked.Read(ThreadSleep) > 0 Then ContextThread.Resume()
End Sub
Public Sub WaitForTask(Tsk As Task)
Dim aw = Tsk.GetAwaiter
If aw.IsCompleted Then Exit Sub
While Interlocked.Read(WorkWaitingCount) > 0 Or aw.IsCompleted = False
If Interlocked.Read(WorkWaitingCount) = 0 Then
Interlocked.Increment(ThreadSleep)
ContextThread.Suspend()
Interlocked.Decrement(ThreadSleep)
Else
Interlocked.Decrement(WorkWaitingCount)
Monitor.Enter(DataAcquired)
Dim Proc = ExtProc
Dim ProcArg = ExtProcArg
Monitor.Pulse(DataAcquired)
Monitor.Exit(DataAcquired)
Proc(ProcArg)
End If
End While
End Sub
Public Sub Release()
SynchronizationContext.SetSynchronizationContext(OldContext)
End Sub
End Class
data
names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']
You can achieve this by creating a simple pipe
<input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">
Pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
transform(value: any, input: string) {
if (input) {
input = input.toLowerCase();
return value.filter(function (el: any) {
return el.toLowerCase().indexOf(input) > -1;
})
}
return value;
}
}
This will filter the result based on the search term
Just to complete, you could send 3 arguments like this:
objShell.Run "TestScript.vbs 42 ""an arg containing spaces"" foo"
I really like grep() and grepl() for this purpose.
grep() returns a vector of integers, which indicate where matches are.
yo <- c("a", "a", "b", "b", "c", "c")
grep("b", yo)
[1] 3 4
grepl() returns a logical vector, with "TRUE" at the location of matches.
yo <- c("a", "a", "b", "b", "c", "c")
grepl("b", yo)
[1] FALSE FALSE TRUE TRUE FALSE FALSE
These functions are case-sensitive.
I was Forming some Programming Logic Used CHAR(34) for Quotes at Excel : A small Part of same I am posting which can be helpfull ,Hopefully
1 Customers
2 Invoices
Formula Used :
=CONCATENATE("listEvents.Add(",D4,",",CHAR(34),E4,CHAR(34),");")
Result :
listEvents.Add(1,"Customers");
listEvents.Add(2,"Invoices");
In addition to @chanafdo answer, you can use route name
<a href="{{route('login')}}">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="{{route('profile', ['id' => 1])}}">login here</a>
<a href="<?php echo route('login')?>">login here</a>
with parameter in route name
when go to url like URI: profile/{id}
<a href="<?php echo route('profile', ['id' => 1])?>">login here</a>
As of laravel 5.2 you can use @php @endphp
to create as <?php ?>
in laravel blade.
Using blade your personal opinion but I suggest to use it. Learn it.
It has many wonderful features as template inheritance, Components & Slots,subviews etc...
The issue you are running into is that you are starting up a second MySqlCommand
while still reading back data with the DataReader
. The MySQL connector only allows one concurrent query. You need to read the data into some structure, then close the reader, then process the data. Unfortunately you can't process the data as it is read if your processing involves further SQL queries.
Another option in SQL Server is to do all of your dynamic querying into table variable in a stored proc, then use a cursor to query and process that. As to the dreaded cursor debate :), I have seen studies that show that in some situations, a cursor can actually be faster if properly set up. I use them myself when the required query is too complex, or just not humanly (for me ;) ) possible.
Can you try this, readfile
need the full file path.
$filename='/pdf/jobs/pdffile.pdf';
$url_download = BASE_URL . RELATIVE_PATH . $filename;
//header("Content-type:application/pdf");
header("Content-type: application/octet-stream");
header("Content-Disposition:inline;filename='".basename($filename)."'");
header('Content-Length: ' . filesize($filename));
header("Cache-control: private"); //use this to open files directly
readfile($filename);
SciPy's imresize()
method was another resize method, but it will be removed starting with SciPy v 1.3.0 . SciPy refers to PIL image resize method: Image.resize(size, resample=0)
size – The requested size in pixels, as a 2-tuple: (width, height).
resample – An optional resampling filter. This can be one of PIL.Image.NEAREST (use nearest neighbour), PIL.Image.BILINEAR (linear interpolation), PIL.Image.BICUBIC (cubic spline interpolation), or PIL.Image.LANCZOS (a high-quality downsampling filter). If omitted, or if the image has mode “1” or “P”, it is set PIL.Image.NEAREST.
Link here: https://pillow.readthedocs.io/en/3.1.x/reference/Image.html#PIL.Image.Image.resize
For Googlers, another way to get a list of users is to use:
Get-WmiObject -Class Win32_UserAccount
You need a semicolon after font-family: Arial, Helvetica, sans-serif
. This will make your updated code the following:
<!DOCTYPE>
<html>
<head>
<title>DIV Font</title>
<style>
.my_text
{
font-family: Arial, Helvetica, sans-serif;
font-size: 40px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="my_text">some text</div>
</body>
</html>
By default:
join
is a column-wise left join
pd.merge
is a column-wise inner join
pd.concat
is a row-wise outer join
pd.concat
:
takes Iterable arguments. Thus, it cannot take DataFrames directly (use [df,df2]
)
Dimensions of DataFrame should match along axis
Join
and pd.merge
:
can take DataFrame arguments
If by "going crazy" you mean that each window keeps stealing focus from the other, TopMost will not solve the problem.
Instead, try:
CalledForm.Owner = CallerForm;
CalledForm.Show();
This will show the 'child' form without it stealing focus. The child form will also stay on top of its parent even if the parent is activated or focused. This code only works easily if you've created an instance of the child form from within the owner form. Otherwise, you might have to set the owner using the API.
The first solution does not work for any UTF-8 alphabet. (It will cut text such as ????). I have managed to create a function which does not use RegExp and use good UTF-8 support in the JavaScript engine. The idea is simple if a symbol is equal in uppercase and lowercase it is a special character. The only exception is made for whitespace.
function removeSpecials(str) {
var lower = str.toLowerCase();
var upper = str.toUpperCase();
var res = "";
for(var i=0; i<lower.length; ++i) {
if(lower[i] != upper[i] || lower[i].trim() === '')
res += str[i];
}
return res;
}
Update: Please note, that this solution works only for languages where there are small and capital letters. In languages like Chinese, this won't work.
Update 2: I came to the original solution when I was working on a fuzzy search. If you also trying to remove special characters to implement search functionality, there is a better approach. Use any transliteration library which will produce you string only from Latin characters and then the simple Regexp will do all magic of removing special characters. (This will work for Chinese also and you also will receive side benefits by making Tromsø
== Tromso
).
not sure if this is what you wanted but
var arr = ["A", "B", "C"];
var arrString = arr.join(", ");
This results in the following output:
A, B, C
I have done this code snippet with the new renderer api
constructor(private renderer: Renderer2){}
addJsToElement(src: string): HTMLScriptElement {
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
this.renderer.appendChild(document.body, script);
return script;
}
And then call it like this
this.addJsToElement('https://widgets.skyscanner.net/widget-server/js/loader.js').onload = () => {
console.log('SkyScanner Tag loaded');
}
There's no 'onclick' event for an iframe, but you can try to catch the click event of the document in the iframe:
document.getElementById("iframe_id").contentWindow.document.body.onclick =
function() {
alert("iframe clicked");
}
EDIT Though this doesn't solve your cross site problem, FYI jQuery has been updated to play well with iFrames:
$('#iframe_id').on('click', function(event) { });
Update 1/2015 The link to the iframe explanation has been removed as it's no longer available.
Note The code above will not work if the iframe is from different domain than the host page. You can still try to use hacks mentioned in comments.
You can use the :not
filter selector:
$('foo:not(".someClass")')
Or not()
method:
$('foo').not(".someClass")
More Info:
Array.prototype.moveUp = function (value, by) {
var index = this.indexOf(value),
newPos = index - (by || 1);
if (index === -1)
throw new Error("Element not found in array");
if (newPos < 0)
newPos = 0;
this.splice(index, 1);
this.splice(newPos, 0, value);
};
Array.prototype.moveDown = function (value, by) {
var index = this.indexOf(value),
newPos = index + (by || 1);
if (index === -1)
throw new Error("Element not found in array");
if (newPos >= this.length)
newPos = this.length;
this.splice(index, 1);
this.splice(newPos, 0, value);
};
var arr = ['banana', 'curyWurst', 'pc', 'remembaHaruMembaru'];
alert('withiout changes= '+arr[0]+' ||| '+arr[1]+' ||| '+arr[2]+' ||| '+arr[3]);
arr.moveDown(arr[2]);
alert('third word moved down= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
arr.moveUp(arr[2]);
alert('third word moved up= '+arr[0] + ' ||| ' + arr[1] + ' ||| ' + arr[2] + ' ||| ' + arr[3]);
Here's the answer:
import numpy
num1 = 3.1400
num2 = 3.000
numpy.format_float_positional(num1, 3, trim='-')
numpy.format_float_positional(num2, 3, trim='-')
output "3.14" and "3"
trim='-'
removes both the trailing zero's, and the decimal.
If you have the correct headers defined & are using a non GlibC
library (such as Musl C) gcc
will also throw error: implicit declaration of function
when GNU extensions such as malloc_trim
are encountered.
The solution is to wrap the extension & the header:
#if defined (__GLIBC__)
malloc_trim(0);
#endif
You can convert stdClass object to array like:
$array = (array)$stdClass;
One great way to prevent reloading the page when submitting using a form is by adding return false
with your onsubmit attribute.
<form action="#" onsubmit="yourJsFunction();return false">
<input type="text"/>
<input type="submit"/>
</form>
Use the deployment Toolkit's deployJava.js (though this ensures a minimum version, rather than a specific version)
If you aren't comfortable with using negative margins, check this out.
div {
position: fixed;
left: 50%;
bottom: 20px;
transform: translate(-50%, -50%);
margin: 0 auto;
}
<div>
Your Text
</div>
Especially useful when you don't know the width of the div.
align="center"
has no effect.
Since you have position:absolute
, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.
#manipulate {
position:absolute;
width:300px;
height:300px;
background:#063;
bottom:0px;
right:25%;
left:50%;
margin-left:-150px;
}
With Java 8 we get a new Date / Time API (JSR 310).
The following way can be used to parse the date in Java 8 without relying on Joda-Time:
String str = "January 2nd, 2010";
// if we 2nd even we have changed in pattern also it is not working please workout with 2nd
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMMM Q, yyyy", Locale.ENGLISH);
LocalDate date = LocalDate.parse(str, formatter);
// access date fields
int year = date.getYear(); // 2010
int day = date.getDayOfMonth(); // 2
Month month = date.getMonth(); // JANUARY
int monthAsInt = month.getValue(); // 1
LocalDate is the standard Java 8 class for representing a date (without time). If you want to parse values that contain date and time information you should use LocalDateTime. For values with timezones use ZonedDateTime. Both provide a parse()
method similar to LocalDate
:
LocalDateTime dateWithTime = LocalDateTime.parse(strWithDateAndTime, dateTimeFormatter);
ZonedDateTime zoned = ZonedDateTime.parse(strWithTimeZone, zoneFormatter);
The list formatting characters from DateTimeFormatter Javadoc:
All letters 'A' to 'Z' and 'a' to 'z' are reserved as pattern letters.
The following pattern letters are defined:
Symbol Meaning Presentation Examples
------ ------- ------------ -------
G era text AD; Anno Domini; A
u year year 2004; 04
y year-of-era year 2004; 04
D day-of-year number 189
M/L month-of-year number/text 7; 07; Jul; July; J
d day-of-month number 10
Q/q quarter-of-year number/text 3; 03; Q3; 3rd quarter
Y week-based-year year 1996; 96
w week-of-week-based-year number 27
W week-of-month number 4
E day-of-week text Tue; Tuesday; T
e/c localized day-of-week number/text 2; 02; Tue; Tuesday; T
F week-of-month number 3
a am-pm-of-day text PM
h clock-hour-of-am-pm (1-12) number 12
K hour-of-am-pm (0-11) number 0
k clock-hour-of-am-pm (1-24) number 0
H hour-of-day (0-23) number 0
m minute-of-hour number 30
s second-of-minute number 55
S fraction-of-second fraction 978
A milli-of-day number 1234
n nano-of-second number 987654321
N nano-of-day number 1234000000
V time-zone ID zone-id America/Los_Angeles; Z; -08:30
z time-zone name zone-name Pacific Standard Time; PST
O localized zone-offset offset-O GMT+8; GMT+08:00; UTC-08:00;
X zone-offset 'Z' for zero offset-X Z; -08; -0830; -08:30; -083015; -08:30:15;
x zone-offset offset-x +0000; -08; -0830; -08:30; -083015; -08:30:15;
Z zone-offset offset-Z +0000; -0800; -08:00;
You can do almost everything from a utility provided as part of WAMPServer.
Create a folder inside to contain your project.site. This can be under the C:\wamp\www\
directory or in a completely seperate folder like C:\websites
.
Create a folder inside the location you have chosen EG C:\websites\project1\www
or under the c:\wamp\www\project1\www
Now open localhost wampmanager->localhost
and click on the link Add a Virtual Host
under the TOOLS section on the homepage.
You will see a page like this:
Fill in the fields as specified by the instructions above each field
The Virtual Host config will have been created for you.
Now you must restart the DNS Cache. You can do this from the wampmanager menus like this right click wampmanager->Tools->Restart DNS
. The DNS Cache will be restarted and then Apache will also be stopped and restarted. When the wampmanager icon goes green again all is completed.
Now you must create a simple index.php
file or install your site into the folder you created above.
Assuming your VH was called project.dev
You should see that name under the Your Virtual Hosts Section of the WAMPServer homepage.
You can launch the site from this menu, or just use the new Domain Name in the address bar EG project1.dev
and the site shoudl launch.
There has been a change of concept in WampServer 2.5 and above and there is a good reason for this change!
In WampServer it is now STRONGLY encouraged to create a Virtual Host for each of your projects, even if you hold them in a \wamp\www\subfolder
structure.
The WampServer home page ( \wamp\www\index.php
) now expects you to have created a Virtual Host for all your projects and will therefore work properly only if you do so.
History
In order to make life easier for beginners using WampServer to learn PHP Apache and MySQL it was suggested that you create subfolders under the \wamp\www\
folder.
wamp
|-- www
|-- Chapter1
|-- Chapter2
|-- etc
These subfolders would then show as links in the WampServer Homepage under a menu called 'Your Projects' and these links would contain a link to localhost/subfoldername
.
Acceptable only for simple tutorials
This made life easy for the complete beginner, and was perfectly acceptable for example for those following tutorials to learn PHP coding. However it was never intended for use when developing a real web site that you would later want to copy to your live hosted server. In fact if you did use this mechanism it often caused problems as the live sites configuration would not match your development configuration.
The Problem for real website development.
The reason for this is of course that the default DocumentRoot setting for wamp is
DocumentRoot "c:/wamp/www/"
regardless of what your subfolder was called. This ment that often used PHP code that queried the structure or your site received different information when running on your development WampServer to what it would receive when running on a live hosted server, where the DocumentRoot configuration points to the folder at the top of the website file hierarchy. This kind of code exists in many frameworks and CMS's for example WordPress and Joomla etc.
For Example
Lets say we have a project called project1 held in wamp\www\project1
and run incorrectly as localhost/project1/index.php
This is what would be reported by some of the PHP command in question:
$_SERVER['HTTP_HOST'] = localhost
$_SERVER['SERVER_NAME'] = localhost
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www
Now if we had correctly defined that site using a Virtual Host definition and ran it as http://project1
the results on the WAMPServer devlopment site will match those received when on a live hosted environment.
$_SERVER['HTTP_HOST'] = project1
$_SERVER['SERVER_NAME'] = project1
$_SERVER['DOCUMENT_ROOT'] = c:/wamp/www/project1
Now this difference may seem trivial at first but if you were to use a framework like WordPress or one of the CMS's like Joomla for example, this can and does cause problems when you move your site to a live server.
Actually this should work basically the same for any wndows Apache server, with differences only in where you may find the Apache config files.
There are 3 steps to create your first Virtual Host in Apache, and only 2 if you already have one defined.
Step 1, Create the Virtual Host definition(s)
Edit the file called httpd-hosts.conf
which for WampServer lives in
\wamp\bin\apache\apache2.4.9\conf\extra\httpd-vhosts.conf
(Apache version numbers may differ, engage brain before continuing)
If this is the first time you edit this file, remove the default example code, it is of no use.
I am assuming we want to create a definition for a site called project1 that lives in
\wamp\www\project1
Very important, first we must make sure that localhost still works so that is the first VHOST definition we will put in this file.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www"
ServerName localhost
ServerAlias localhost
<Directory "c:/wamp/www">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
Now we define our project: and this of course you do for each of your projects as you start a new one.
<VirtualHost *:80>
DocumentRoot "c:/wamp/www/project1"
ServerName project1
<Directory "c:/wamp/www/project1">
Options Indexes FollowSymLinks
AllowOverride All
Require local
</Directory>
</VirtualHost>
NOTE: That each Virtual Host as its own DocumentRoot
defined. There are also many other parameters you can add to a Virtual Hosts definition, check the Apache documentation.
Small aside
The way virtual hosts work in Apache: The first definition in this file will also be the default site, so should the domain name used in the browser not match any actually defined virtually hosted domain, making localhost the first domain in the file will therefore make it the site that is loaded if a hack attempt just uses your IP Address. So if we ensure that the Apache security for this domain is ALWAYS SET TO
Require local
any casual hack from an external address will receive an error and not get into your PC, but should you misspell a domain you will be shown the WampServer homepage, because you are on the same PC as WampServer and therfore local
.
Step 2:
Add your new domain name to the HOSTS file. Now we need to add the domain name that we have used in the Virtual Host definition to the HOSTS file so that windows knows where to find it. This is similiar to creating a DNS A record, but it is only visible in this case on this specific PC.
Edit C:\windows\system32\drivers\etc\hosts
The file has no extension and should remain that way. Watch out for notepad, as it may try and add a .txt
extension if you have no better editor.
I suggest you download Notepad++, its free and a very good editor.
Also this is a protected file so you must edit it with administrator privileges, so launch you editor using the Run as Administrator menu option.
The hosts file should look like this when you have completed these edits
127.0.0.1 localhost
127.0.0.1 project1
::1 localhost
::1 project1
Note that you should have definitions in here for the IPV4 loopback address 127.0.0.1
and also the IPV6 loopback address ::1
as Apache is now IPV6 aware and the browser will use either IPV4 or IPV6 or both. I have no idea how it decides which to use, but it can use either if you have the IPV6 stack turned on, and most window OS's do as of XP SP3.
Now we must tell windows to refresh its domain name cache, so launch a command window again using the Run as Administrator menu option again, and do the following.
net stop dnscache
net start dnscache
This forces windows to clear its domain name cache and reload it, in reloading it will re-read the HOSTS file so now it knows about the domain project1
.
Step 3: Uncomment the line in httpd.conf that includes the Virtual Hosts definition file.
Edit your httpd.conf, use the wampmanager.exe menus to make sure you edit the correct file.
Find this line in httpd.conf
# Virtual hosts
#Include conf/extra/httpd-vhosts.conf
And just remove the #
to uncomment that line.
To activate this change in you running Apache we must now stop and restart the Apache service.
wampmanager.exe -> Apache -> Service -> Restart Service
Now if the WAMP icon in the system tray does not go GREEN again, it means you have probably done something wrong in the \wamp\bin\apache\apache2.4.9\conf\extra\httpd-hosts.conf
file.
If so here is a useful mechanism to find out what is wrong. It uses a feature of the Apache exe (httpd.exe) to check its config files and report errors by filename and line numbers.
Launch a command window.
cd \wamp\bin\apache\apache2.4.9\bin
httpd -t
So fix the errors and retest again until you get the output
Syntax OK
Now there is one more thing.
There are actually 2 new menu items on the wampmanager menu system. One called 'My Projects' which is turned on by default. And a second one, called 'My Virtual Hosts', which is not activated by default.
'My Projects' will list any sub directory of the \wamp\www directory and provide a link to launch the site in that sub directory. As I said earlier, it launches 'project1` and not 'localhost/project1' so to make the link work we must create a Virtual Host definition to make this link actually launch that site in your browser, without the Virtual Host definition it's likely to launch a web search for the site name as a keyword or just return a site not found condition.
The 'My Virtual Hosts' menu item is a little different. It searches the file that is used to define Virtual Hosts ( we will get to that in a minute ) and creates menu links for each ServerName parameter it finds and creates a menu item for each one. This may seem a little confusing as once we create a Virtual Host definition for the sub directories of the \wamp\www folder some items will appear on both of the 'My Projects' menu and the 'My Virtual Hosts' menu's.
How do I turn this other 'My Virtual Hosts' menu on?
;WAMPPROJECTSUBMENU
, its in the '[Menu.Left]' section.;WAMPVHOSTSUBMENU
either before or after the ;WAMPPROJECTSUBMENU
parameter.Big Note The new menu will only appear if you already have some Virtual Hosts defined! Otherwise you will see no difference until you define a VHOST.
Now if you take this to its logical extension
You can now move your web site code completely outside the \wamp\
folder structure simply by changing the DocumentRoot parameter in the VHOST definition. So for example you could do this:
Create a folder on the wamp disk or any other disk ( beware of network drive, they are a bit more complicated)
D:
MD websites
CD websites
MD example.com
CD example.com
MD www
You now copy your site code to, or start creating it in the \websites\example.com\www
folder and define your VHOST like this:
<VirtualHost *:80>
DocumentRoot "d:/websites/example.com/www"
ServerName example.dev
ServerAlias www.example.dev
<Directory "d:/websites/example.com/www">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
php_flag display_errors Off
php_flag log_errors On
php_value max_upload_size 40M
php_value max_execution_time 60
php_value error_log "d:/wamp/logs/example_com_phperror.log"
</VirtualHost>
Then add this new development domain to the HOSTS file:
127.0.0.1 localhost
::1 localhost
127.0.0.1 project1
::1 project1
127.0.0.1 example.dev
::1 example.dev
NOTE: It is not a good idea to use a ServerName or ServerAlias that is the same as your live domain name, as if we had used example.com as the ServerName it would mean we could no longer get to the real live site from this PC as it would direct example.com to 127.0.0.1 i.e. this PC and not out onto the internet.
ALSO: See that I have allowed this site to be accessed from the internet from within the VHOST definitions, this change will apply to only this site and no other. Very useful for allowing a client to view your changes for an hour or so without having to copy them to the live server. This does mean that we have to edit this file manually to turn this access on and off rather than use the Put Online/Offline menu item on wampmanager.
Also I have added some modifications to the PHP config, again that will only apply to this one site. Very useful when maintaining a site with specific requirement unlike all the other sites you maintain. I guess we can assume from the parameters used that it has a long running page in it somewhere and it is very badly written and will not run with errors being displayed on the browser without making a horrible mess of the page. Believe me sites like this exist and people still want them maintained badly. But this mean we only have to change these parameters for this specific site and not globally to all Virtual sites running on WampServer.
You can do it like so:
var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId('4edd40c86762e0fb12000003');
ES5 implementation to assign keys is below:
var obj = Object.create(null),
objArgs = (
(objArgs = {}),
(objArgs.someKey = {
value: 'someValue'
}), objArgs);
Object.defineProperties(obj, objArgs);
I've attached a snippet I used to convert to bare object.
var obj = {_x000D_
'key1': 'value1',_x000D_
'key2': 'value2',_x000D_
'key3': [_x000D_
'value3',_x000D_
'value4',_x000D_
],_x000D_
'key4': {_x000D_
'key5': 'value5'_x000D_
}_x000D_
}_x000D_
_x000D_
var bareObj = function(obj) {_x000D_
_x000D_
var objArgs,_x000D_
bareObj = Object.create(null);_x000D_
_x000D_
Object.entries(obj).forEach(function([key, value]) {_x000D_
_x000D_
var objArgs = (_x000D_
(objArgs = {}),_x000D_
(objArgs[key] = {_x000D_
value: value_x000D_
}), objArgs);_x000D_
_x000D_
Object.defineProperties(bareObj, objArgs);_x000D_
_x000D_
});_x000D_
_x000D_
return {_x000D_
input: obj,_x000D_
output: bareObj_x000D_
};_x000D_
_x000D_
}(obj);_x000D_
_x000D_
if (!Object.entries) {_x000D_
Object.entries = function(obj){_x000D_
var arr = [];_x000D_
Object.keys(obj).forEach(function(key){_x000D_
arr.push([key, obj[key]]);_x000D_
});_x000D_
return arr;_x000D_
}_x000D_
}_x000D_
_x000D_
console(bareObj);
_x000D_
If you have a hidden field like this
<asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>
Now you can use your value like this
$(this).parent().find('input[type=hidden]').val()
With stderr (where most of the errors go to):
cmd /c yourscript.cmd > logall.txt 2>&1
.yaml
is apparently the official extension, because some applications fail when using .yml
. On the other hand I am not familiar with any applications which use YAML code, but fail with a .yaml
extension.
I just stumbled across this, as I was used to writing .yml
in Ansible and Docker Compose. Out of habit I used .yml
when writing Netplan files which failed silently. I finally figured out my mistake. The author of a popular Ansible Galaxy role for Netplan makes the same assumption in his code:
- name: Capturing Existing Configurations
find:
paths: /etc/netplan
patterns: "*.yml,*.yaml"
register: _netplan_configs
Yet any files with a .yml
extension get ignored by Netplan in the same way as files with a .bak
extension. As Netplan is very quiet, and gives no feedback whatsoever on success, even with netplan apply --debug
, a config such as 01-netcfg.yml
will fail silently without any meaningful feedback.
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
simple and clean example of how group by works in LINQ
http://www.a2zmenu.com/LINQ/LINQ-to-SQL-Group-By-Operator.aspx
Here's some prebuilt Objective-C dictionaries if anyone wants to type ansi characters:
NSDictionary *lowerCaseCodes = @{
@"Q" : @(12),
@"W" : @(13),
@"E" : @(14),
@"R" : @(15),
@"T" : @(17),
@"Y" : @(16),
@"U" : @(32),
@"I" : @(34),
@"O" : @(31),
@"P" : @(35),
@"A" : @(0),
@"S" : @(1),
@"D" : @(2),
@"F" : @(3),
@"G" : @(5),
@"H" : @(4),
@"J" : @(38),
@"K" : @(40),
@"L" : @(37),
@"Z" : @(6),
@"X" : @(7),
@"C" : @(8),
@"V" : @(9),
@"B" : @(11),
@"N" : @(45),
@"M" : @(46),
@"0" : @(29),
@"1" : @(18),
@"2" : @(19),
@"3" : @(20),
@"4" : @(21),
@"5" : @(23),
@"6" : @(22),
@"7" : @(26),
@"8" : @(28),
@"9" : @(25),
@" " : @(49),
@"." : @(47),
@"," : @(43),
@"/" : @(44),
@";" : @(41),
@"'" : @(39),
@"[" : @(33),
@"]" : @(30),
@"\\" : @(42),
@"-" : @(27),
@"=" : @(24)
};
NSDictionary *shiftCodes = @{ // used in conjunction with the shift key
@"<" : @(43),
@">" : @(47),
@"?" : @(44),
@":" : @(41),
@"\"" : @(39),
@"{" : @(33),
@"}" : @(30),
@"|" : @(42),
@")" : @(29),
@"!" : @(18),
@"@" : @(19),
@"#" : @(20),
@"$" : @(21),
@"%" : @(23),
@"^" : @(22),
@"&" : @(26),
@"*" : @(28),
@"(" : @(25),
@"_" : @(27),
@"+" : @(24)
};
You can simply just set the selectedIndex
property on the UITabBarController to the appropriate index and the view will be changed just like the user tapped the tab button.
Rebooting the machine solved the problem for me. I first tried wiping /tmp/
but node was still complaining.
You will try this
<?php $url = wp_get_attachment_url(get_post_thumbnail_id($post->ID), 'full'); ?> // Here you can manage your image size like medium, thumbnail, or custom size
<img src="<?php echo $url ?>"
/>
Have you tried ApplicationReadyEvent?
@Component
public class ApplicationStartup
implements ApplicationListener<ApplicationReadyEvent> {
/**
* This event is executed as late as conceivably possible to indicate that
* the application is ready to service requests.
*/
@Override
public void onApplicationEvent(final ApplicationReadyEvent event) {
// here your code ...
return;
}
}
Code from: http://blog.netgloo.com/2014/11/13/run-code-at-spring-boot-startup/
This is what the documentation mentions about the startup events:
...
Application events are sent in the following order, as your application runs:
An ApplicationStartedEvent is sent at the start of a run, but before any processing except the registration of listeners and initializers.
An ApplicationEnvironmentPreparedEvent is sent when the Environment to be used in the context is known, but before the context is created.
An ApplicationPreparedEvent is sent just before the refresh is started, but after bean definitions have been loaded.
An ApplicationReadyEvent is sent after the refresh and any related callbacks have been processed to indicate the application is ready to service requests.
An ApplicationFailedEvent is sent if there is an exception on startup.
...
Actually, it is quite easy to write sufficiently clean and compact code with DI (I wonder, will it be/stay pythonic then, but anyway :) ), for example I actually perefer this way of coding:
def polite(name_str):
return "dear " + name_str
def rude(name_str):
return name_str + ", you, moron"
def greet(name_str, call=polite):
print "Hello, " + call(name_str) + "!"
_
>>greet("Peter")
Hello, dear Peter!
>>greet("Jack", rude)
Hello, Jack, you, moron!
Yes, this can be viewed as just a simple form of parameterizing functions/classes, but it does its work. So, maybe Python's default-included batteries are enough here too.
P.S. I have also posted a larger example of this naive approach at Dynamically evaluating simple boolean logic in Python.
As said before, Control
/Command
+ Shift
+ A
gives you basic support for tag matching. Press it again to extend the match to the parent element. Press arrow left/right to jump to the start/end tag.
Anyway, there is no built-in highlighting of matching tags. Emmet is a popular plugin but it's overkill for this purpose and can get in the way if you don't want Emmet-like editing. Bracket Highlighter seems to be a better choice for this use case.
It is possible and is deceptively easy:
bin\Debug
folder below the project file (.csproj).app.publish
folder (they are not needed), and the .pdb files unless you foresee debugging directly on your user's system (for example, by remote control)), and provide it to the users.An added advantage is that, as a ClickOnce application, it does not require administrative privileges to run (if your application follows the normal guidelines for which folders to use for application data, etc.).
As for .NET, you can check for the minimum required version of .NET being installed (or at all) in the application (most users will already have it installed) and present a dialog with a link to the download page on the Microsoft website (or point to one of your pages that could redirect to the Microsoft page - this makes it more robust if the Microsoft URL change). As it is a small utility, you could target .NET 2.0 to reduce the probability of a user to have to install .NET.
It works. We use this method during development and test to avoid having to constantly uninstall and install the application and still being quite close to how the final application will run.
I run into the same issue.
I thought it's something to do with my credentials and authentication.
Then finally I realised it's the URI I configured is not HTTP variant.
I was trying to push to SSH URI of my Git with HTTP configuration.
Check your URL in
Git Perspective > Remotes > Origin > Configure Fetch > Change > Make sure the prtocal is HTTPS and the URL is https version.
@user544079
Even though it is very old and irrelevant now, I am replying to help people like me! it should be like this:
<form method="post" action="mailto:$emailID?subject=$MySubject &message= $MyMessageText">
Here $emailID, $MySubject, $MyMessageText are variables which you assign from a FORM or a DATABASE Table or just you can assign values in your code itself. Alternatively you can put the code like this (normally it is not used):
<form method="post" action="mailto:[email protected]?subject=New Registration Alert &message= New Registration requires your approval">
One thing to note is that not all libraries will use the same meaning for pi, of course, so it never hurts to know what you're using. For example, the symbolic math library Sympy's representation of pi is not the same as math and numpy:
import math
import numpy
import scipy
import sympy
print(math.pi == numpy.pi)
> True
print(math.pi == scipy.pi)
> True
print(math.pi == sympy.pi)
> False
I the following code I had to replace add a GET-parameter to all references to JS-files EXCEPT one.
<link rel="stylesheet" type="text/css" href="/login/css/ABC.css" />
<script type="text/javascript" language="javascript" src="/localization/DEF.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/GHI.js"></script>
<script type="text/javascript" language="javascript" src="/login/jslib/md5.js"></script>
sendRequest('/application/srvc/EXCEPTION.js', handleChallengeResponse, null);
sendRequest('/application/srvc/EXCEPTION.js",handleChallengeResponse, null);
This is the Matcher used:
(?<!EXCEPTION)(\.js)
What that does is look for all occurences of ".js" and if they are preceeded by the "EXCEPTION" string, discard that result from the result array. That's called negative lookbehind. Since I spent a day on finding out how to do this I thought I should share.
Cookies are only sent at the time of the request, and therefore cannot be retrieved as soon as it is assigned (only available after reloading).
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE or $HTTP_COOKIE_VARS arrays.
If output exists prior to calling this function, setcookie() will fail and return FALSE. If setcookie() successfully runs, it will return TRUE. This does not indicate whether the user accepted the cookie.
Cookies will not become visible until the next loading of a page that the cookie should be visible for. To test if a cookie was successfully set, check for the cookie on a next loading page before the cookie expires. Expire time is set via the expire parameter. A nice way to debug the existence of cookies is by simply calling print_r($_COOKIE);.
You can't do it with the layout alone, I've tried. I ended up writing a very simple class to handle it, you can check it out on github. SquareImage.java Its part of a larger project but nothing a little copy and paste can't fix (licensed under Apache 2.0)
Essentially you just need to set the height/width equal to the other dimension (depending on which way you want to scale it)
Note: You can make it square without a custom class using the scaleType
attribute but the view's bounds extend beyond the visible image, which makes it an issue if you are placing other views near it.
This might help someone.
With a little of javascript you can search for all datetime-local inputs, search if the year the user is trying to input, greater that 100 years in the future:
$('input[type=datetime-local]').each(function( index ) {
$(this).change(function() {
var today = new Date();
var date = new Date(this.value);
var yearFuture = new Date();
yearFuture.setFullYear(yearFuture.getFullYear()+100);
if(date.getFullYear() > yearFuture.getFullYear()) {
this.value = today.getFullYear() + this.value.slice(4);
}
})
});
#include <iostream>
#include <iomanip>
using namespace std;
You can enter the line using namespace std;
for your convenience. Otherwise, you'll have to explicitly add std::
every time you wish to use cout
, fixed
, showpoint
, setprecision(2)
and endl
int main()
{
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
return 0;
}
In Python 2.x, it is not guaranteed at all:
>>> False = 5
>>> 0 == False
False
So it could change. In Python 3.x, True, False, and None are reserved words, so the above code would not work.
In general, with booleans you should assume that while False will always have an integer value of 0 (so long as you don't change it, as above), True could have any other value. I wouldn't necessarily rely on any guarantee that True==1
, but on Python 3.x, this will always be the case, no matter what.
Quick and dirty solution for predefined log levels and without defining a new class.
logging.addLevelName( logging.WARNING, "\033[1;31m%s\033[1;0m" % logging.getLevelName(logging.WARNING))
logging.addLevelName( logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR))
Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.
In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.
In my case, this happened due to working on Windows and uploading to Unix server for execution.
This isn't exactly a notification but in the title you say monitor and this can fit that scenario.
Using the SQL Server timestamp column can allow you to easily see any changes (that still persist) between queries.
The SQL Server timestamp column type is badly named in my opinion as it is not related to time at all, it's a database wide value that auto increments on any insert or update. You can select Max(timestamp) in a table you are after or return the timestamp from the row you just inserted then just select where timestamp > storedTimestamp, this will give you all the results that have been updated or inserted between those times.
As it's a database wide value too you can use your stored timestamp to check any table has had data written to it since you last checked/updated your stored timestamp.
Just before the closing body tag, as stated on
http://developer.yahoo.com/performance/rules.html#js_bottom
Put Scripts at the Bottom
The problem caused by scripts is that they block parallel downloads. The HTTP/1.1 specification suggests that browsers download no more than two components in parallel per hostname. If you serve your images from multiple hostnames, you can get more than two downloads to occur in parallel. While a script is downloading, however, the browser won't start any other downloads, even on different hostnames.
I don't think you can set arbitrarily sized images on any of the existing button classes. If you want a simple image behaving like a button, you can write your own QAbstractButton-subclass, something like:
class ImageButton : public QAbstractButton {
Q_OBJECT
public:
...
void setPixmap( const QPixmap& pm ) { m_pixmap = pm; update(); }
QSize sizeHint() const { return m_pixmap.size(); }
protected:
void paintEvent( QPaintEvent* e ) {
QPainter p( this );
p.drawPixmap( 0, 0, m_pixmap );
}
};
There are quite a few answers; some of them are a bit too much theory-heavy. I'll leave why I needed prune once so maybe the need-first/example kind of explanation is useful to someone :)
I had a folder with about 20 node directories, each having its node_modules
directory as expected.
Once you get into any project, you see each ../node_modules/module
. But you know how it is. Almost every module has dependencies, so what you are looking at is more like projectN/node_modules/moduleX/node_modules/moduleZ...
I didn't want to drown with a list with the dependency of the dependency of...
Knowing -d n
/ -depth n
, it wouldn't have helped me, as the main/first node_modules directory I wanted of each project was at a different depth, like this:
Projects/MysuperProjectName/project/node_modules/...
Projects/Whatshisname/version3/project/node_modules/...
Projects/project/node_modules/...
Projects/MysuperProjectName/testProject/november2015Copy/project/node_modules/...
[...]
How can I get the first a list of paths ending at the first node_modules
and move to the next project to get the same?
-prune
When you add -prune
, you'll still have a standard recursive search. Each "path" is analyzed, and every find gets spit out and find
keeps digging down like a good chap. But it's the digging down for more node_modules
what I didn't want.
So, the difference is that in any of those different paths, -prune
will find
to stop digging further down that particular avenue when it has found your item. In my case, the node_modules
folder.
First, make sure you initialize it in document.ready like this:
$(document).ready(function () {
$('select').material_select();
});
Then, populate it with your data in the way you want. My example:
function FillMySelect(myCustomData) {
$("#mySelect").html('');
$.each(myCustomData, function (key, value) {
$("#mySelect").append("<option value='" + value.id+ "'>" + value.name + "</option>");
});
}
Make sure after you are done with the population, to trigger this contentChanged like this:
$("#mySelect").trigger('contentChanged');
I would suggest two interesting lectures:
1.
The with
statement is used to wrap the execution of a block with methods defined by a context manager. This allows common try...except...finally
usage patterns to be encapsulated for convenient reuse.
2. You could do something like:
with open("foo.txt") as foo_file:
data = foo_file.read()
OR
from contextlib import nested
with nested(A(), B(), C()) as (X, Y, Z):
do_something()
OR (Python 3.1)
with open('data') as input_file, open('result', 'w') as output_file:
for line in input_file:
output_file.write(parse(line))
OR
lock = threading.Lock()
with lock:
# Critical section of code
3.
I don't see any Antipattern here.
Quoting Dive into Python:
try..finally is good. with is better.
4.
I guess it's related to programmers's habit to use try..catch..finally
statement from other languages.
I've used this method (reported here )
export class AppComponent {
constructor() {
if(document.getElementById("testScript"))
document.getElementById("testScript").remove();
var testScript = document.createElement("script");
testScript.setAttribute("id", "testScript");
testScript.setAttribute("src", "assets/js/test.js");
document.body.appendChild(testScript);
}
}
it worked for me since I wanted to execute a javascript file AFTER THE COMPONENT RENDERED.
Yes, all you need to do is call finish() in any Activity you would like to close.
In case if one is using nginx proxy as a docker container (e.g. jwilder/nginx-proxy), there is the following way to configure client_max_body_size
(or other properties):
/etc/nginx/proxy.conf
with a right value for this property-v /etc/nginx/proxy.conf:/etc/nginx/conf.d/my_proxy.conf:ro
Personally found this way rather convenient as there's no need to build a custom container to change configs. I'm not affiliated with jwilder/nginx-proxy
, was just using it in my project, and the way described above helped me. Hope it helps someone else, too.
To get a string representation:
From http://golang.org/pkg/fmt/
%T a Go-syntax representation of the type of the value
package main
import "fmt"
func main(){
types := []interface{} {"a",6,6.0,true}
for _,v := range types{
fmt.Printf("%T\n",v)
}
}
Outputs:
string
int
float64
bool
This seems to work just fine:
import sys
print sys._getframe().f_back.f_code.co_name
well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html
but currently attr and prop are not so different and there are almost the same
but they prefer prop for some things
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)
If you want to remove EVERYTHING :
textarea {
border: none;
background-color: transparent;
resize: none;
outline: none;
}
The HTML spec here is really broken. It should allow nested optgroups and recommend user agents render them as nested menus. Instead, only one optgroup level is allowed. However, they do have to say the following on the subject:
Note. Implementors are advised that future versions of HTML may extend the grouping mechanism to allow for nested groups (i.e., OPTGROUP elements may nest). This will allow authors to represent a richer hierarchy of choices.
And user agents could start using submenus to render optgoups instead of displaying titles before the first option element in an optgroup as they do now.
Small addition to Chris Kannon' accepted answer: only print if there actually is a second last column.
(
echo | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
echo 1 2 3 | awk 'NF && NF-1 { print ( $(NF-1) ) }'
)
i have same problem
import android.support.v4.content.IntentCompat;
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK |IntentCompat.FLAG_ACTIVITY_CLEAR_TASK);
this code work for me . Android api 17
zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).
#ifdef DEBUG
#define NSLogDebug(format, ...) \
NSLog(@"<%s:%d> %s, " format, \
strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
#define NSLogDebug(format, ...)
#endif
i just do :
set /p input= yes or no
if %input%==yes echo you clicked yes
if %input%==no echo you clicked no
pause
Try this:
SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches
One (quick & dirty) way to resize images it to use HTML & specify the new size in the image element. This even works for animated images with transparency.
As Eik says, UIStackView
and UIScrollView
play together nicely, see here.
The key is that the UIStackView
handles the variable height/width for different contents and the UIScrollView
then does its job well of scrolling/bouncing that content:
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
scrollView.contentSize = CGSize(width: stackView.frame.width, height: stackView.frame.height)
}
This one solved my issue which is SELinux setting:
chcon -R -t httpd_sys_content_t /home/*
I think you have to use the GetValueOrDefault-Methode. The behaviour with ToString("yy...") is not defined if the instance is null.
dt2.GetValueOrDefault().ToString("yyy...");
The error will be seen when your controller could not be found in the application. You need to make sure that you are correct using values in ng-app
and ng-controller
directives
Haven't needed this much yet, but when I've used console application for Quick tests and required async I've just solved it like this:
class Program
{
static void Main(string[] args)
{
MainAsync(args).Wait();
}
static async Task MainAsync(string[] args)
{
// Code here
}
}
Since Spring 4.0+, the best solution is to annotate the test method with @WithMockUser
@Test
@WithMockUser(username = "user1", password = "pwd", roles = "USER")
public void mytest1() throws Exception {
mockMvc.perform(get("/someApi"))
.andExpect(status().isOk());
}
Remember to add the following dependency to your project
'org.springframework.security:spring-security-test:4.2.3.RELEASE'
First of all, there're two kinds of keystores.
Individual and General
The application will use the one indicated in the startup or the default of the system.
It will be a different folder if JRE or JDK is running, or if you check the personal or the "global" one.
They are encrypted too
In short, the path will be like:
$JAVA_HOME/lib/security/cacerts
for the "general one", who has all the CA for the Authorities and is quite important.
When you want svn-like behavior of git commit, use this in your git aliases in your .gitconfig
commit = "!f() { git commit \"$@\" && git push; };f"
The history limit is a pane attribute that is fixed at the time of pane creation and cannot be changed for existing panes. The value is taken from the history-limit
session option (the default value is 2000).
To create a pane with a different value you will need to set the appropriate history-limit
option before creating the pane.
To establish a different default, you can put a line like the following in your .tmux.conf
file:
set-option -g history-limit 3000
Note: Be careful setting a very large default value, it can easily consume lots of RAM if you create many panes.
For a new pane (or the initial pane in a new window) in an existing session, you can set that session’s history-limit
. You might use a command like this (from a shell):
tmux set-option history-limit 5000 \; new-window
For (the initial pane of the initial window in) a new session you will need to set the “global” history-limit
before creating the session:
tmux set-option -g history-limit 5000 \; new-session
Note: If you do not re-set the history-limit
value, then the new value will be also used for other panes/windows/sessions created in the future; there is currently no direct way to create a single new pane/window/session with its own specific limit without (at least temporarily) changing history-limit
(though show-option
(especially in 1.7 and later) can help with retrieving the current value so that you restore it later).
The Theme My Login plugin may help - it allows you to redirect users of specific roles to specific pages.
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
It's worth noting that the exact steps to follow can differ depending on the plugin. (E.g. I've just manually installed XML Tools and this involved copying some files from a subfolder into the root Notepad++ installation directory.) So would recommend the following:-
C:\Program Files (x86)\Notepad++\plugins\
).I fixed this by changing EntityClient
back to SqlClient
, even though I was using Entity Framework.
So my complete connection string was in the format:
<add name="DefaultConnection" connectionString="Data Source=localhost;Initial Catalog=xxx;Persist Security Info=True;User ID=xxx;Password=xxx" providerName="System.Data.SqlClient" />
As @weichsel stated, CGFloat is just a typedef for either float
or double
. You can see for yourself by Command-double-clicking on "CGFloat" in Xcode — it will jump to the CGBase.h header where the typedef is defined. The same approach is used for NSInteger and NSUInteger as well.
These types were introduced to make it easier to write code that works on both 32-bit and 64-bit without modification. However, if all you need is float
precision within your own code, you can still use float
if you like — it will reduce your memory footprint somewhat. Same goes for integer values.
I suggest you invest the modest time required to make your app 64-bit clean and try running it as such, since most Macs now have 64-bit CPUs and Snow Leopard is fully 64-bit, including the kernel and user applications. Apple's 64-bit Transition Guide for Cocoa is a useful resource.
You can just do something like this and pass in the whole number and then the cents after.
String.format("$%,d.%02d",wholeNum,change);
According to Tom Hawtin
A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.
Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:
//ECMAScript
var f, g;
function foo() {
var x = 0;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
print('inside foo, call to f(): ' + f()); // "2"
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"
Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:
int a[1] = {0}
interface Function1 {
public final IntBag value = new IntBag();
public int apply();
}
class Closure implements Function1 {
private IntBag x = value;
Function1 f;
Function1 g;
@Override
public int apply() {
// print('inside foo, call to f(): ' + f()); // "2"
// inside apply, call to f.apply()
System.out.println("inside foo, call to f.apply(): " + f.apply());
return 0;
}
public Closure() {
f = new Function1() {
@Override
public int apply() {
x.add(1);
return x.get();
}
};
g = new Function1() {
@Override
public int apply() {
x.add(-1);
return x.get();
}
};
// x = 1;
x.set(1);
}
}
public class ClosureTest {
public static void main(String[] args) {
// foo()
Closure foo = new Closure();
foo.apply();
// print('call to g(): ' + g()); // "1"
System.out.println("call to foo.g.apply(): " + foo.g.apply());
// print('call to f(): ' + f()); // "2"
System.out.println("call to foo.f.apply(): " + foo.f.apply());
}
}
It prints:
inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2
In case someone needs a more involved example on how to do cross-database queries, here's an example that cleans up the databasechangeloglock
table on every database that has it:
CREATE EXTENSION IF NOT EXISTS dblink;
DO
$$
DECLARE database_name TEXT;
DECLARE conn_template TEXT;
DECLARE conn_string TEXT;
DECLARE table_exists Boolean;
BEGIN
conn_template = 'user=myuser password=mypass dbname=';
FOR database_name IN
SELECT datname FROM pg_database
WHERE datistemplate = false
LOOP
conn_string = conn_template || database_name;
table_exists = (select table_exists_ from dblink(conn_string, '(select Count(*) > 0 from information_schema.tables where table_name = ''databasechangeloglock'')') as (table_exists_ Boolean));
IF table_exists THEN
perform dblink_exec(conn_string, 'delete from databasechangeloglock');
END IF;
END LOOP;
END
$$
Encountering the same problem, I solved this by reconverting the file with default mp4 settings in iMovie.
Reference of the de-referenced pointer is also same as the address of the pointed variable.
Explanation :-
int var = 3; int *p;
p = &var;
so, let's think address of var is : ABCDE
then,
p = ABCDE and &*p = ABCDE;
that means put &* together ,neutral the referencing and de-referencing.
also when declaring a function ,
the function's arguments should be the pointers,
and in the arguments of the this function when calling it in main method are should been with & operator.
it's bit confusing. But remember that int *p = &var; is also correct as the above pointer declaration.
If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
There are few ways to create empty Set in Python :
So, This are 2 ways to create empty Set.
ClassLoader cl = ClassLoader.getSystemClassLoader();
URL[] urls = ((URLClassLoader)cl).getURLs();
for(URL url: urls){
System.out.println(url.getFile());
}
Upgrade to jQuery 1.3 and use:
$(function() {
$('div._Foo').live("mouseover", function(e) {
// Do something exciting
});
});
Note: live works with most events, but not all. There is a complete list in the documentation.
Reloading the configuration file (my.cnf
) cannot be done without restarting the mysqld
server.
FLUSH LOGS
only rotates a few log files.
SET @@...=...
sets it for anyone not yet logged in, but it will go away after the next restart. But that gives a clue... Do the SET
, and change my.cnf
; that way you are covered. Caveat: Not all settings can be performed via SET
.
New with MySQL 8.0...
SET PERSIST ...
will set the global setting and save it past restarts. Nearly all settings can be adjusted this way.
Visual Studio Code has really nice Node.js debugging support. It is free, open source and cross-platform and runs on Linux, OS X and Windows.
You can even debug grunt and gulp tasks, should you need to...
void foo<TOne, TTwo>()
where TOne : BaseOne
where TTwo : BaseTwo
More info here:
http://msdn.microsoft.com/en-us/library/d5x73970.aspx
In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:
if ! type "$foobar_command_name" > /dev/null; then
# install foobar here
fi
For a real installation script, you'd probably want to be sure that type
doesn't return successfully in the case when there is an alias foobar
. In bash you could do something like this:
if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
# install foobar here
fi
From Terminal: (You need to enter the following three lines)
$ git credential-osxkeychain erase ?
host=github.com ?
protocol=https ?
?
?
NOTE: after you enter “protocol=https” above you need to press ~~RETURN~~ TWICE (Each '?' is equivalent to a 'press enter/return' )
There is a long-standing bug for this problem here: http://code.google.com/p/android/issues/detail?id=6191
Looks like it started around Android 2.1 and has been present in all of the Android 2.x releases since. I'm not sure if it is still a problem in Android 3.x or 4.x though.
Anyway, this StackOverflow post explains how to workaround the problem correctly (it doesn't look relevant by the URL but I promise it is)
I was having the same issue, I made the table fixed and then specified my td width. If you have th you can do those as well.
table {
table-layout: fixed;
word-wrap: break-word;
}
Template:
<td style="width:10%">content</td>
Please use CSS for structuring any layouts.
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
I solve this the way Below
Animation anim = AnimationUtils.loadAnimation(this, R.anim.slide);
fg.startAnimation(anim);
this.fg.setVisibility(View.VISIBLE); //fg is a View object indicate fragment
numpy.random.seed(0)
numpy.random.randint(10, size=5)
This produces the following output:
array([5, 0, 3, 3, 7])
Again,if we run the same code we will get the same result.
Now if we change the seed value 0 to 1 or others:
numpy.random.seed(1)
numpy.random.randint(10, size=5)
This produces the following output: array([5 8 9 5 0])
but now the output not the same like above.
Rails has recently added this into ActiveRecord. It looks to be released in Rails 5. Committed to master already:
https://github.com/rails/rails/commit/9e42cf019f2417473e7dcbfcb885709fa2709f89
Post.where(column: 'something').or(Post.where(other: 'else'))
# => SELECT * FROM posts WHERE (column = 'something') OR (other = 'else)
I had the same problem and I solved it with get_object_vars mentioned above.
Furthermore, I had to convert my object with json_decode and I had to iterate the array with the oldschool "for" loop (rather then for-each).
An old question but deserves an update as now there is a way.
The correct CSS based answer is to use object-fit: cover
, which works like background-size: cover
. Positioning would be taken care of by object-position
attribute, which defaults to centering.
But there is no support for it in any IE / Edge browsers, or Android < 4.4.4. Also, object-position
is not supported by Safari, iOS or OSX. Polyfills do exist, object-fit-images seems to give best support.
For more details on how the property works, see CSS Tricks article on object-fit
for explanation and demo.
\d{1,2}[\,\.]{1}\d{1,2}
EDIT: update to meet the new requirements (comments) ;)
EDIT: remove unnecesary qtfier as per Bryan
^[0-9]{1,2}([,.][0-9]{1,2})?$
Here's the YUI version if anyone's interested:
http://developer.yahoo.com/yui/docs/YAHOO.util.Number.html
var str = YAHOO.util.Number.format(12345, { thousandsSeparator: ',' } );
The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1
.
(("$#" < 1)) && ( (("$1" != 1)) || (("$1" -ne 0q)) )
Your boolean logic is also a bit confused:
(( "$#" < 1 && # If the number of arguments is less than one…
"$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?
This is probably what you want:
(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1
I think these is the two most simple ways to run Redis on Windows
As described here on Option 3) Running Microsoft's native port of Redis:
- Download the redis-latest.zip native 64bit Windows port of redis
wget https://github.com/ServiceStack/redis-windows/raw/master/downloads/redis-latest.zip
Extract redis64-latest.zip in any folder, e.g. in c:\redis
Run the redis-server.exe using the local configuration
cd c:\redis
redis-server.exe redis.conf
- Run redis-cli.exe to connect to your redis instance
cd c:\redis
redis-cli.exe
You can use Redis on Windows with Vagrant, as described here:
Install Vagrant on Windows
Download the vagrant-redis.zip vagrant configuration
wget https://raw.github.com/ServiceStack/redis-windows/master/downloads/vagrant-redis.zip
Extract vagrant-redis.zip in any folder, e.g. in c:\vagrant-redis
Launch the Virtual Box VM with vagrant up:
cd c:\vagrant-redis
vagrant up
This will launch a new Ubuntu VM instance inside Virtual Box that will automatically install and start the latest stable version of redis.
The most Pythonic idiom is to clearly document what the function expects and then just try to use whatever gets passed to your function and either let exceptions propagate or just catch attribute errors and raise a TypeError
instead. Type-checking should be avoided as much as possible as it goes against duck-typing. Value testing can be OK – depending on the context.
The only place where validation really makes sense is at system or subsystem entry point, such as web forms, command line arguments, etc. Everywhere else, as long as your functions are properly documented, it's the caller's responsibility to pass appropriate arguments.
Note: This answer is really old and things may have changed in WordPress land since.
I am guessing that you need to detect the WordPress root from your plugin or theme. I use the following code in FireStats to detect the root WordPress directory where FireStats is installed a a WordPress plugin.
function fs_get_wp_config_path()
{
$base = dirname(__FILE__);
$path = false;
if (@file_exists(dirname(dirname($base))."/wp-config.php"))
{
$path = dirname(dirname($base))."/wp-config.php";
}
else
if (@file_exists(dirname(dirname(dirname($base)))."/wp-config.php"))
{
$path = dirname(dirname(dirname($base)))."/wp-config.php";
}
else
$path = false;
if ($path != false)
{
$path = str_replace("\\", "/", $path);
}
return $path;
}
If you dont want to query for it just create an entity, and then delete it.
Customer customer = new Customer() { Id = 1 } ;
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();
I don't think there is a general purpose tuple class in Java but a custom one might be as easy as the following:
public class Tuple<X, Y> {
public final X x;
public final Y y;
public Tuple(X x, Y y) {
this.x = x;
this.y = y;
}
}
Of course, there are some important implications of how to design this class further regarding equality, immutability, etc., especially if you plan to use instances as keys for hashing.
you can change the file executable by using chmod
like this
chmod 755 file.sh
and use this command for execute
./file.sh
Just use percentage widths and fixed table layout:
<table>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
with
table { table-layout: fixed; }
td { width: 33%; }
Fixed table layout is important as otherwise the browser will adjust the widths as it sees fit if the contents don't fit ie the widths are otherwise a suggestion not a rule without fixed table layout.
Obviously, adjust the CSS to fit your circumstances, which usually means applying the styling only to a tables with a given class or possibly with a given ID.
I figured out how to get the Cygwin cron service running automatically when I logged on to Windows 7. Here's what worked for me:
Using Notepad, create file C:\cygwin\bin\Cygwin_launch_crontab_service_input.txt
with content no
on the first line and yes
on the second line (without the quotes). These are your two responses to prompts for cron-config
.
Create file C:\cygwin\Cygwin_launch_crontab_service.bat
with content:
@echo off
C:
chdir C:\cygwin\bin
bash cron-config < Cygwin_launch_crontab_service_input.txt
Add a Shortcut to the following in the Windows Startup folder:
Cygwin_launch_crontab_service.bat
See http://www.sevenforums.com/tutorials/1401-startup-programs-change.html if you need help on how to add to Startup. BTW, you can optionally add these in Startup if you would like:
Cygwin
XWin Server
The first one executes
C:\cygwin\Cygwin.bat
and the second one executes
C:\cygwin\bin\run.exe /usr/bin/bash.exe -l -c /usr/bin/startxwin.exe
Tried this out quickly in the interactive shell:
>>> l = ['a', 'ab', 'abc', 'bac']
>>> [x for x in l if 'ab' in x]
['ab', 'abc']
>>>
Why does this work? Because the in
operator is defined for strings to mean: "is substring of".
Also, you might want to consider writing out the loop as opposed to using the list comprehension syntax used above:
l = ['a', 'ab', 'abc', 'bac']
result = []
for s in l:
if 'ab' in s:
result.append(s)
On onItemClick :
String text = parent.getItemAtPosition(position).toString();
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
You can also do:
array = numpy.append(array, value)
Note that the numpy.append()
method returns a new object, so if you want to modify your initial array, you have to write: array = ...
Depending on the size of your array, I have found
$array = array_values( array_flip( array_flip( $array ) ) );
can be faster than array_unique.