First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
A quick gotcha that I learned the hard way (basically spending 4 hours on Google), you can use PageMethods in your ASPX file to return JSON (with the [ScriptMethod()] marker) for a static method, however if you decide to move your static methods to an asmx file, it cannot be a static method.
Also, you need to tell the web service Content-Type: application/json in order to get JSON back from the call (I'm using jQuery and the 3 Mistakes To Avoid When Using jQuery article was very enlightening - its from the same website mentioned in another answer here).
Based from Google documentation,
If you want to test your app on the emulator, expand the directory for Android 4.2.2 (API 17) or a higher version, select Google APIs, and install it. Then create a new AVD with Google APIs as the platform target.
Try to navigate to settings--> apps in your emulator and then find Google Play Services. Check the version number and use it in you build.gradle. To update it with the latest version, you can see it in these documentation and SO question.
To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:
import warnings
with warnings.catch_warnings():
warnings.filterwarnings('error')
try:
answer = 1 / 0
except Warning as e:
print('error found:', e)
You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.
Step by step self explaining commands for update of feature branch with the latest code from origin "develop" branch:
git checkout develop
git pull -p
git checkout feature_branch
git merge develop
git push origin feature_branch
First off, if you want to extract count features and apply TF-IDF normalization and row-wise euclidean normalization you can do it in one operation with TfidfVectorizer
:
>>> from sklearn.feature_extraction.text import TfidfVectorizer
>>> from sklearn.datasets import fetch_20newsgroups
>>> twenty = fetch_20newsgroups()
>>> tfidf = TfidfVectorizer().fit_transform(twenty.data)
>>> tfidf
<11314x130088 sparse matrix of type '<type 'numpy.float64'>'
with 1787553 stored elements in Compressed Sparse Row format>
Now to find the cosine distances of one document (e.g. the first in the dataset) and all of the others you just need to compute the dot products of the first vector with all of the others as the tfidf vectors are already row-normalized.
As explained by Chris Clark in comments and here Cosine Similarity does not take into account the magnitude of the vectors. Row-normalised have a magnitude of 1 and so the Linear Kernel is sufficient to calculate the similarity values.
The scipy sparse matrix API is a bit weird (not as flexible as dense N-dimensional numpy arrays). To get the first vector you need to slice the matrix row-wise to get a submatrix with a single row:
>>> tfidf[0:1]
<1x130088 sparse matrix of type '<type 'numpy.float64'>'
with 89 stored elements in Compressed Sparse Row format>
scikit-learn already provides pairwise metrics (a.k.a. kernels in machine learning parlance) that work for both dense and sparse representations of vector collections. In this case we need a dot product that is also known as the linear kernel:
>>> from sklearn.metrics.pairwise import linear_kernel
>>> cosine_similarities = linear_kernel(tfidf[0:1], tfidf).flatten()
>>> cosine_similarities
array([ 1. , 0.04405952, 0.11016969, ..., 0.04433602,
0.04457106, 0.03293218])
Hence to find the top 5 related documents, we can use argsort
and some negative array slicing (most related documents have highest cosine similarity values, hence at the end of the sorted indices array):
>>> related_docs_indices = cosine_similarities.argsort()[:-5:-1]
>>> related_docs_indices
array([ 0, 958, 10576, 3277])
>>> cosine_similarities[related_docs_indices]
array([ 1. , 0.54967926, 0.32902194, 0.2825788 ])
The first result is a sanity check: we find the query document as the most similar document with a cosine similarity score of 1 which has the following text:
>>> print twenty.data[0]
From: [email protected] (where's my thing)
Subject: WHAT car is this!?
Nntp-Posting-Host: rac3.wam.umd.edu
Organization: University of Maryland, College Park
Lines: 15
I was wondering if anyone out there could enlighten me on this car I saw
the other day. It was a 2-door sports car, looked to be from the late 60s/
early 70s. It was called a Bricklin. The doors were really small. In addition,
the front bumper was separate from the rest of the body. This is
all I know. If anyone can tellme a model name, engine specs, years
of production, where this car is made, history, or whatever info you
have on this funky looking car, please e-mail.
Thanks,
- IL
---- brought to you by your neighborhood Lerxst ----
The second most similar document is a reply that quotes the original message hence has many common words:
>>> print twenty.data[958]
From: [email protected] (Robert Seymour)
Subject: Re: WHAT car is this!?
Article-I.D.: reed.1993Apr21.032905.29286
Reply-To: [email protected]
Organization: Reed College, Portland, OR
Lines: 26
In article <[email protected]> [email protected] (where's my
thing) writes:
>
> I was wondering if anyone out there could enlighten me on this car I saw
> the other day. It was a 2-door sports car, looked to be from the late 60s/
> early 70s. It was called a Bricklin. The doors were really small. In
addition,
> the front bumper was separate from the rest of the body. This is
> all I know. If anyone can tellme a model name, engine specs, years
> of production, where this car is made, history, or whatever info you
> have on this funky looking car, please e-mail.
Bricklins were manufactured in the 70s with engines from Ford. They are rather
odd looking with the encased front bumper. There aren't a lot of them around,
but Hemmings (Motor News) ususally has ten or so listed. Basically, they are a
performance Ford with new styling slapped on top.
> ---- brought to you by your neighborhood Lerxst ----
Rush fan?
--
Robert Seymour [email protected]
Physics and Philosophy, Reed College (NeXTmail accepted)
Artificial Life Project Reed College
Reed Solar Energy Project (SolTrain) Portland, OR
Both r+
and w+
can read and write to a file. However, r+
doesn't delete the content of the file and doesn't create a new file if such file doesn't exist, whereas w+
deletes the content of the file and creates it if it doesn't exist.
Create a breakpoint as you normally would, right click the red dot and select "condition".
Most UNIX-like operating systems have a basename
executable for a very similar purpose (and dirname
for the path):
pax> a=/tmp/file.txt
pax> b=$(basename $a)
pax> echo $b
file.txt
That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.
So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.
One way to do that (and this is a bash
-only solution, needing no other executables):
pax> a=/tmp/xx/file.tar.gz
pax> xpath=${a%/*}
pax> xbase=${a##*/}
pax> xfext=${xbase##*.}
pax> xpref=${xbase%.*}
pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}
path=/tmp/xx
pref=file.tar
ext=gz
That little snippet sets xpath
(the file path), xpref
(the file prefix, what you were specifically asking for) and xfext
(the file extension).
Use this:
android:scrollbarAlwaysDrawHorizontalTrack="true"
Example:
<Gallery android:id="@+id/gallery"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:scrollbarAlwaysDrawHorizontalTrack="true" />
Itemgetter lets you to sort by multiple criteria / columns:
sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))
What about:
datetime.now().strftime('%M:%S.%f')[:-4]
I'm not sure what you mean by "Milliseconds only 2 digits", but this should keep it to 2 decimal places. There may be a more elegant way by manipulating the strftime format string to cut down on the precision as well -- I'm not completely sure.
EDIT
If the %f
modifier doesn't work for you, you can try something like:
now=datetime.now()
string_i_want=('%02d:%02d.%d'%(now.minute,now.second,now.microsecond))[:-4]
Again, I'm assuming you just want to truncate the precision.
Hi We sort of had the same problem if I understand you well. So check what pysftp version you're using. If it's the latest one which is 0.2.9 downgrade to 0.2.8. Check this out. https://github.com/Yenthe666/auto_backup/issues/47
In Visual Studio 2015: I changed UseIIS in .csproj file to false and it worked for me.
<UseIIS>False</UseIIS>
Deploy your application in the IIS with the default port. Try to debug it using visual studio. It's a good practice. If you use visual studio, it will keep changing the port number most of the time. So better deploy the application in the IIS first and Open the same in visual studio and Debug it.
There is one simple answer for this: You have been output something else, like text, or anything related to output from your page before you send your header. This affect why you get that error.
Just check your code for posible output or you can put the header on top of your method so it will be send first.
DECLARE @Seconds INT = 86200;
SELECT
CONVERT(VARCHAR(15),
CAST(CONVERT(VARCHAR(12), @Seconds / 60 / 60 % 24)
+':'+ CONVERT(VARCHAR(2), @Seconds / 60 % 60)
+':'+ CONVERT(VARCHAR(2), @Seconds % 60) AS TIME), 100) AS [HH:MM:SS (AM/PM)]
Another map() way to remove list of keys from dictionary
and avoid raising KeyError exception
dic = {
'key1': 1,
'key2': 2,
'key3': 3,
'key4': 4,
'key5': 5,
}
keys_to_remove = ['key_not_exist', 'key1', 'key2', 'key3']
k = list(map(dic.pop, keys_to_remove, keys_to_remove))
print('k=', k)
print('dic after = \n', dic)
**this will produce output**
k= ['key_not_exist', 1, 2, 3]
dic after = {'key4': 4, 'key5': 5}
Duplicate keys_to_remove
is artificial, it needs to supply defaults values for dict.pop() function.
You can add here any array with len_ = len(key_to_remove)
For example
dic = {
'key1': 1,
'key2': 2,
'key3': 3,
'key4': 4,
'key5': 5,
}
keys_to_remove = ['key_not_exist', 'key1', 'key2', 'key3']
k = list(map(dic.pop, keys_to_remove, np.zeros(len(keys_to_remove))))
print('k=', k)
print('dic after = ', dic)
** will produce output **
k= [0.0, 1, 2, 3]
dic after = {'key4': 4, 'key5': 5}
You do not need to do it. In C (not C++) you were required to use enum Enumname to refer to a data element of the enumerated type. To simplify it you were allowed to typedef it to a single name data type.
typedef enum MyEnum {
//...
} MyEnum;
allowed functions taking a parameter of the enum to be defined as
void f( MyEnum x )
instead of the longer
void f( enum MyEnum x )
Note that the name of the typename does not need to be equal to the name of the enum. The same happens with structs.
In C++, on the other hand, it is not required, as enums, classes and structs can be accessed directly as types by their names.
// C++
enum MyEnum {
// ...
};
void f( MyEnum x ); // Correct C++, Error in C
Solution with awk:
awk '{if ($1 ~ /^all/) print $0, "anotherthing"; else print $0}' file
Simply: if the row starts with all
print the row plus "anotherthing", else print just the row.
Take a peek at underscore.js which provides many linq like functions. In the example you give you would use the map function.
Get value of one column:
Table_Name::find($id)->column_name;
you can use this method with where clause:
Table_Name::where('id',$id)->first()->column_name;
or use this method for bypass PhpStorm "Method where not found in App\Models":
Table_Name::query()->where('id','=',$id)->first()->column_name;
in query builder:
DB::table('table_names')->find($id)->column_name;
with where cluase:
DB::table('table_names')->where('id',$id)->first()->column_name;
or
DB::table('table_names')->where('id',$id)->first('column_name');
last method result is array
Let's try this
select convert(varchar, getdate(), 108)
Just try a few moment ago
Try this code:
For Each aSheet In Worksheets
Select Case aSheet.Name
Case "ID Sheet", "Summary"
Application.DisplayAlerts = False
aSheet.Delete
Application.DisplayAlerts = True
End Select
Next aSheet
I've tryied all answers of this topic, but just this below worked fine on my project.
Angular 7 and AGM Core 1.0.0-beta.7
<agm-map [latitude]="lat" [longitude]="long" [zoom]="zoom" [fitBounds]="true">
<agm-marker latitude="{{localizacao.latitude}}" longitude="{{localizacao.longitude}}" [agmFitBounds]="true"
*ngFor="let localizacao of localizacoesTec">
</agm-marker>
</agm-map>
The properties [agmFitBounds]="true"
at agm-marker
and [fitBounds]="true"
at agm-map
does the job
I always prefer pre-increment, however ...
I wanted to point out that even in the case of calling the operator++ function, the compiler will be able to optimize away the temporary if the function gets inlined. Since the operator++ is usually short and often implemented in the header, it is likely to get inlined.
So, for practical purposes, there likely isn't much of a difference between the performance of the two forms. However, I always prefer pre-increment since it seems better to directly express what I"m trying to say, rather than relying on the optimizer to figure it out.
Also, giving the optmizer less to do likely means the compiler runs faster.
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
If you want to change anything else instead of 'default', then just add these additional lines to your Vagrantfile:
config.vm.define "tendo" do |tendo|
end
Where "tendo" will be the name that will appear instead of default
It means if "OperationURL[1]" evaluates to "GET" then return "GetRequestSignature()" else return "". I'm guessing "GetRequestSignature()" here returns a string. The syntax CONDITION ? A : B basically stands for an if-else where A is returned when CONDITION is true and B is returned when CONDITION is false.
For MacOS users:
Just do this and easily it will solve your problem:
brew install cocoapods
1) Backup your htdocs folder
2) export your databases (follow this tutorial)
3) uninstall xampp
4) install the new version of xampp
5) replace the htdocs folder that you have backed up
6) Import your databases you had exported before
Note: In case you have changed config files like PHP (php.ini), Apache (httpd.conf) or any other, please take back up of those files as well and replace them with newly installed version.
If other whitespace characters are possible, then you'd want:
testString.split("\\s+");
@Min
and @Max
are used for validating numeric fields which could be String
(representing number), int
, short
, byte
etc and their respective primitive wrappers.
@Size
is used to check the length constraints on the fields.
As per documentation @Size
supports String
, Collection
, Map
and arrays
while @Min
and @Max
supports primitives and their wrappers. See the documentation.
If you have a class on your element, then you can try the following:
if( $('.exists_content').hasClass('exists_content') ){
//element available
}
Instead of NOW()
you can use UNIX_TIMESTAMP()
also:
$update_query = "UPDATE db.tablename
SET insert_time=UNIX_TIMESTAMP()
WHERE username='$somename'";
$.ajax({
url: 'http://url.of.my.server/submit',
dataType: "jsonp",
jsonp: 'callback',
jsonpCallback: 'jsonp_callback'
});
jsonp is the querystring parameter name that is defined to be acceptable by the server while the jsonpCallback is the javascript function name to be executed at the client.
When you use such url:
url: 'http://url.of.my.server/submit?callback=?'
the question mark ? at the end instructs jQuery to generate a random function while the predfined behavior of the autogenerated function will just invoke the callback -the sucess function in this case- passing the json data as a parameter.
$.ajax({
url: 'http://url.of.my.server/submit?callback=?',
success: function (data, status) {
mySurvey.closePopup();
},
error: function (xOptions, textStatus) {
mySurvey.closePopup();
}
});
The same goes here if you are using $.getJSON with ? placeholder it will generate a random function while the predfined behavior of the autogenerated function will just invoke the callback:
$.getJSON('http://url.of.my.server/submit?callback=?',function(data){
//process data here
});
2019 update:
html
<form class="fr" method='POST' enctype="multipart/form-data"> {% csrf_token %}
<textarea name='text'>
<input name='example_image'>
<button type="submit">
</form>
js
$(document).on('submit', '.fr', function(){
$.ajax({
type: 'post',
url: url, <--- you insert proper URL path to call your views.py function here.
enctype: 'multipart/form-data',
processData: false,
contentType: false,
data: new FormData(this) ,
success: function(data) {
console.log(data);
}
});
return false;
});
views.py
form = ThisForm(request.POST, request.FILES)
if form.is_valid():
text = form.cleaned_data.get("text")
example_image = request.FILES['example_image']
I had a similar problem on opening Razor Views
The real behavior of a sticky element is:
A stickily positioned element is treated as relatively positioned until its containing block crosses a specified threshold (such as setting top to value other than auto) within its flow root (or the container it scrolls within), at which point it is treated as "stuck" until meeting the opposite edge of its containing block.
The element is positioned according to the normal flow of the document, and then offset relative to its nearest scrolling ancestor and containing block (nearest block-level ancestor), including table-related elements, based on the values of top, right, bottom, and left. The offset does not affect the position of any other elements.
This value always creates a new stacking context. Note that a sticky element "sticks" to its nearest ancestor that has a "scrolling mechanism" (created when overflow is hidden, scroll, auto, or overlay), even if that ancestor isn't the nearest actually scrolling ancestor.
This example will help you understand:
This can help without rounding
declare @test float(25)
declare @test1 decimal(10,5)
select @test = 34.0387597207
select @test
set @test1 = convert (decimal(10,5), @test)
select cast((@test1) as varchar(12))
Select LEFT(cast((@test1) as varchar(12)),LEN(cast((@test1) as varchar(12)))-1)
CultureInfo.CurrentCulture.TextInfo.ToTitleCase ("my name");
returns ~ My Name
But the problem still exists with names like McFly as stated earlier.
This problem can be caused by requests for certain files that don't exist. For example, requests for files in wp-content/uploads/ where the file does not exist.
If this is the situation you're seeing, you can solve the problem by going to .htaccess and changing this line:
RewriteRule ^(wp-(content|admin|includes).*) $1 [L]
to:
RewriteRule ^(wp-(content|admin|includes).*) - [L]
The underlying issue is that the rule above triggers a rewrite to the exact same url with a slash in front and because there was a rewrite, the newly rewritten request goes back through the rules again and the same rule is triggered. By changing that line's "$1" to "-", no rewrite happens and so the rewriting process does not start over again with the same URL.
It's possible that there's a difference in how apache 2.2 and 2.4 handle this situation of only-difference-is-a-slash-in-front and that's why the default rules provided by WordPress aren't working perfectly.
This should do the trick:
...
select: function(event, ui){
ui.tab.attr('class');
} ,
...
For more info about the ui.tab see http://jqueryui.com/demos/tabs/#Events
Scanner scan = new Scanner(System.in);
int i = scan.nextInt();
Double d = scan.nextDouble();
String newStr = "";
Scanner charScanner = new Scanner( System.in ).useDelimiter( "(\\b|\\B)" ) ;
while( charScanner.hasNext() ) {
String c = charScanner.next();
if (c.equalsIgnoreCase("\r")) {
break;
}
else {
newStr += c;
}
}
System.out.println("String: " + newStr);
System.out.println("Int: " + i);
System.out.println("Double: " + d);
This code works fine
The action occurs when you attempt to call an object which is not a function, as with ()
. For instance, this will produce the error:
>>> a = 5
>>> a()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Class instances can also be called if they define a method __call__
One common mistake that causes this error is trying to look up a list or dictionary element, but using parentheses instead of square brackets, i.e. (0)
instead of [0]
Update new solution: check index
let a = ['a', 'a', 'b', 'a'];
let a = ['a', 'a', 'a', 'a'];
let check = (list) => list.every(item => list.indexOf(item) === 0);
check(a); // false;
check(b); // true;
Updated with ES6:
Use list.every
is the fastest way:
let a = ['a', 'a', 'b', 'a'];
let check = (list) => list.every(item => item === list[0]);
old version:
var listTrue = ['a', 'a', 'a', 'a'];
var listFalse = ['a', 'a', 'a', 'ab'];
function areWeTheSame(list) {
var sample = list[0];
return (list.every((item) => item === sample));
}
Trident provides the ::-ms-check
pseudo-element for checkbox and radio button controls. For example:
<input type="checkbox">
<input type="radio">
::-ms-check {
color: red;
background: black;
padding: 1em;
}
This displays as follows in IE10 on Windows 8:
You can download in the current directory with a .
:
cd # by default, goes to $HOME
scp me@host:/path/to/file .
or in you HOME
directly with :
scp me@host:/path/to/file ~
When you run composer update
, composer
generates a file called composer.lock
which lists all your packages and the currently installed versions. This allows you to later run composer install
, which will install the packages listed in that file, recreating the environment that you were last using.
It appears from your log that some of the versions of packages that are listed in your composer.lock
file are no longer available. Thus, when you run composer install
, it complains and fails. This is usually no big deal - just run composer update
and it will attempt to build a set of packages that work together and write a new composer.lock
file.
However, you're running into a different problem. It appears that, in your composer.json
file, the original developer has added some pre- or post- update actions that are failing, specifically a php artisan migrate
command. This can be avoided by running the following: composer update --no-scripts
This will run the composer update but will skip over the scripts added to the file. You should be able to successfully run the update this way.
However, this does not solve the problem long-term. There are two problems:
A migration is for database changes, not random stuff like compiling assets. Go through the migrations and remove that code from there.
Assets should not be compiled each time you run composer update
. Remove that step from the composer.json
file.
From what I've read, best practice seems to be compiling assets on an as-needed basis during development (ie. when you're making changes to your LESS files - ideally using a tool like gulp.js) and before deployment.
You can use node package, if you often need to restore databases in development process.
Install:
npm install -g sql-bak-restore
Usage:
sql-bak-restore <bakPath> <dbName> <oldDbName> <owner>
Arguments:
!! sqlcmd command line utility should be in your PATH variable.
In case you're using a UITabBarController
:
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.tabBarController?.navigationItem.hidesBackButton = true
}
One from a couple of hours that I wasted:
If you've applied all these tips and are only going on 500 errors because you don't have access to the server error log, maybe the problem isn't in the .htaccess but in the files it redirects to.
After I had fixed my .htaccess-problem I spent two more hours trying to fix it some more, even though I simply had forgotten about some permissions.
Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..
if (command.equals("w"))
{
FileConverter fc = new FileConverter();
btnConvertDocuments.setEnabled(false);
}
When you do the for/in loop you put up first, i is the property name. So you have the property name, i, and access the value by doing myObject[i].
C++
The first one is good for beginners and the second one requires more advanced level in C++.
Read this https://docs.djangoproject.com/en/dev/howto/static-files/:
For local development, if you are using runserver or adding staticfiles_urlpatterns to your URLconf, you’re done with the setup – your static files will automatically be served at the default (for newly created projects) STATIC_URL of /static/.
And try:
~/tmp$ django-admin.py startproject myprj
~/tmp$ cd myprj/
~/tmp/myprj$ chmod a+x manage.py
~/tmp/myprj$ ./manage.py startapp myapp
Then add 'myapp'
to INSTALLED_APPS
(myprj/settings.py
).
~/tmp/myprj$ cd myapp/
~/tmp/myprj/myapp$ mkdir static
~/tmp/myprj/myapp$ echo 'alert("hello!");' > static/hello.js
~/tmp/myprj/myapp$ mkdir templates
~/tmp/myprj/myapp$ echo '<script src="{{ STATIC_URL }}hello.js"></script>' > templates/hello.html
Edit myprj/urls.py
:
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
class HelloView(TemplateView):
template_name = "hello.html"
urlpatterns = patterns('',
url(r'^$', HelloView.as_view(), name='hello'),
)
And run it:
~/tmp/myprj/myapp$ cd ..
~/tmp/myprj$ ./manage.py runserver
It works!
Actually, this is the proper way to get what you want, unless you can use MS SQL 2014 (which finally enables custom format strings for date times).
To get yyyymm
instead of yyyym
, you can use this little trick:
select
right('0000' + cast(datepart(year, getdate()) as varchar(4)), 4)
+ right('00' + cast(datepart(month, getdate()) as varchar(2)), 2)
It's faster and more reliable than gettings parts of convert(..., 112)
.
This answer optimizes one of the suggestions from @Adail-Junior by adding the -D
option, which is helpful when neither of the directories being compared are git repositories:
git diff -D --no-index dir1/ dir2/
If you use -D
then you won't see comparisons to /dev/null
:
text
Binary files a/whatever and /dev/null differ
Why don't you use a QSpinBox
for this purpose ? You can set the up/down buttons invisible with the following line of codes:
// ...
QSpinBox* spinBox = new QSpinBox( this );
spinBox->setButtonSymbols( QAbstractSpinBox::NoButtons ); // After this it looks just like a QLineEdit.
//...
For completeness:
https://developer.chrome.com/multidevice/android/installtohomescreen
Does Add to homescreen work on Chrome for iOS?
No.
Although there won't be any remaining transaction in the case, as @Johan said, you can see the current transaction list in InnoDB with the query below if you want.
SELECT * FROM information_schema.innodb_trx\G
From the document:
The INNODB_TRX table contains information about every transaction (excluding read-only transactions) currently executing inside InnoDB, including whether the transaction is waiting for a lock, when the transaction started, and the SQL statement the transaction is executing, if any.
Solution for Windows (Windows 10) is:
Build time: 2020-11-16 17:09:24 UTC Revision: 2972ff02f3210d2ceed2f1ea880f026acfbab5c0
Kotlin: 1.3.72 Groovy: 2.5.12 Ant: Apache Ant(TM) version 1.10.8 compiled on May 10 2020 JVM: 1.8.0_144 (Oracle Corporation 25.144-b01) OS: Windows 10 10.0 x86
C:>
Finally, run [Cordova environments] to check that all is set for development.
C:\Users\opiyog\AndroidStudioProjects\IONIC\SecondApp>cordova requirements
Requirements check results for android: Java JDK: installed 1.8.0 Android SDK: installed true Android target: installed android-30,android-29,android-28,android-27,android-26,android-25,android-24,android-23,android-22,android-21,android-19 Gradle: installed C:\Gradle\gradle-6.7.1\bin\gradle.BAT
Try:
-webkit-transition: all .2s linear, background-position 0;
This worked for me on something similar..
[1-9]\.\d{1,2}|0\.((0?[1-9])|([1-9]0?)){1,2}\b
tray this:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
inside onCreate()
;
If you have Visual Studio, run the Visual Studio Command prompt from the Start menu, change to the directory containing Makefile.win
and type this:
nmake -f Makefile.win
You can also use the normal command prompt and run vsvars32.bat (c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools for VS2008). This will set up the environment to run nmake and find the compiler tools.
<?php
$variable1 = "foo";
$variable2 = "bar";
header('Location: http://linkhere.com?fieldname1=$variable1&fieldname2=$variable2&fieldname3=$variable3);
?>
This works without any quotations.
[How can I] Change the password, so I can share it with others and let them sign
Using keytool:
keytool -storepasswd -keystore /path/to/keystore
Enter keystore password: changeit
New keystore password: new-password
Re-enter new keystore password: new-password
You can also set DirectoryIndex in apache's httpd.conf file.
CentOS keeps this file in /etc/httpd/conf/httpd.conf
Debian: /etc/apache2/apache2.conf
Open the file in your text editor and find the line starting with DirectoryIndex
To load landing.html as a default (but index.html if that's not found) change this line to read:
DirectoryIndex landing.html index.html
The problem is that you are not specifying the name of the remote: Instead of
git remote add https://github.com/username/project.git
you should use:
git remote add origin https://github.com/username/project.git
For texts in utf-8, it worked for me mb_convert_encoding. To process everything regardless of errors, make sure you use the "@".
The basic code I use is:
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'));
$body = $dom->getElementsByTagName('body')->item(0);
echo $body->textContent;
If you want something more advanced, you can iteratively analyze the nodes, but you will encounter many problems with whitespaces.
I have implemented a converter based on what I say here. If you are interested, you can download it from git https://github.com/kranemora/html2text
It may serve as a reference to make yours
You can use it like this:
$html = <<<EOF
<p>Welcome to <strong>html2text<strong></p>
<p>It's <em>works</em> for you?</p>
EOF;
$html2Text = new \kranemora\Html2Text\Html2Text;
$text = $html2Text->convert($html);
I think the best answer in 2017 is to use the javax.json APIs. Use javax.json.JsonBuilderFactory to create your json objects, then write the objects out using javax.json.JsonWriterFactory. Very nice builder/writer combination.
There is a LARGE collection of attributes you can't set in IE using .setAttribute() which includes every inline event handler.
See here for details:
http://webbugtrack.blogspot.com/2007/08/bug-242-setattribute-doesnt-always-work.html
You could also use GenerationType.TABLE instead of IDENTITY which is only available after the insert.
Should be something to do with your Platform Settings. Try the below steps
Ctrl + End works for me on Visual C++ 2010 Express.
I've seen occasional problems with Eclipse forgetting that built-in classes (including Object
and String
) exist. The way I've resolved them is to:
This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.
ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]
This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.
Use getColorStateList
like this
setTextColor(resources.getColorStateList(R.color.button_states_color))
instead of getColor
setTextColor(resources.getColor(R.color.button_states_color))
public static void copyInputStreamToFile(InputStream input, File file) {
try (OutputStream output = new FileOutputStream(file)) {
input.transferTo(output);
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
java.io.InputStream#transferTo is available since Java 9.
All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.
i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.
I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:
function getFormattedDate(date) {_x000D_
var year = date.getFullYear();_x000D_
_x000D_
var month = (1 + date.getMonth()).toString();_x000D_
month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
var day = date.getDate().toString();_x000D_
day = day.length > 1 ? day : '0' + day;_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Update for ES2017 using String.padStart(), supported by all major browsers except IE.
function getFormattedDate(date) {_x000D_
let year = date.getFullYear();_x000D_
let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
let day = date.getDate().toString().padStart(2, '0');_x000D_
_x000D_
return month + '/' + day + '/' + year;_x000D_
}
_x000D_
Make sure you die()
after your redirection, and make sure you do your redirect AS SOON AS POSSIBLE while your script executes. It makes sure that no more database queries (if some) are not wasted for nothing. That's the one tip I can give you
For search engines, 301 is the best response code
This isn't on the code parter it's on the server side Contact your Server Manager or fix it from server if you own it If you use CPANEL/WHM GO TO WHM/SMTP RESTRICTIONS AND DISABLE IT
Here's the answer that I found for my question:
urlList1.FocusedItem.Index
And I am getting selected item value by:
urlList1.Items(urlList1.FocusedItem.Index).SubItems(0).Text
You can use pandas library and reference the rows and columns like this:
import pandas as pd
input = pd.read_csv("path_to_file");
#for accessing ith row:
input.iloc[i]
#for accessing column named X
input.X
#for accessing ith row and column named X
input.iloc[i].X
I am not sure I understand what you want, but based on what I understood
the x scale seems to be the same, it is the y scale that is not the same, and that is because you specified scales ="free"
you can specify scales = "free_x" to only allow x to be free (in this case it is the same as pred has the same range by definition)
p <- ggplot(plot, aes(x = pred, y = value)) + geom_point(size = 2.5) + theme_bw()
p <- p + facet_wrap(~variable, scales = "free_x")
worked for me, see the picture
I think you were making it too difficult - I do seem to remember one time defining the limits based on a formula with min and max and if faceted I think it used only those values, but I can't find the code
For better performance you can use
$('div.a.b')
This will look only through the div elements instead of stepping through all the html elements that you have on your page.
If you want to get it aligned to the right after the text looses focus you can try to use the direction modifier. This will show the right part of the text after loosing focus. e.g. useful if you want to show the file name in a large path.
input.rightAligned {_x000D_
direction:ltr;_x000D_
overflow:hidden;_x000D_
}_x000D_
input.rightAligned:not(:focus) {_x000D_
direction:rtl;_x000D_
text-align: left;_x000D_
unicode-bidi: plaintext;_x000D_
text-overflow: ellipsis;_x000D_
}
_x000D_
<form>_x000D_
<input type="text" class="rightAligned" name="name" value="">_x000D_
</form>
_x000D_
The not selector is currently well supported : Browser support
The following example will make it clear:
let contactJSON = '{"name":"John Doe","age":"11"}';
let contact = JSON.parse(contactJSON);
console.log(contact.name + ", " + contact.age);
// Output: John Doe, 11
I tryed what hgmnz saids on SQL Server 2012.
Management created to me:
EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'MyDataBase'
GO
USE [master]
GO
/****** Object: Database [MyDataBase] Script Date: 09/09/2014 15:58:46 ******/
DROP DATABASE [MyDataBase]
GO
If you're using Python 2.5, this won't work, but for people using 2.6 or 2.7, try
from __future__ import print_function
print("abcd", end='')
print("efg")
results in
abcdefg
For those using 3.x, this is already built-in.
Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:
....
<string>software</string>
<key>title</key>
<string>Your App Name</string>
...
Open DDMS than in DATA>DATA>"Select your package like com.example.foo"> than select your database folder than pull that data in eclipse you can see the pull an push icon on top right side ...
ChkAsm will show you all the dependencies of a particular assembly at once, including the versions, and easily let you search for assemblies in the list. Works much better for this purpose than ILSpy (http://ilspy.net/), which is what I used to use for this task.
Try this:
@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)
in your code should be,
@Html.ActionLink("Search", "List", "Search", new{@class="btn btn-info", @id="addressSearch"})
To run the batch file when the VM
user logs in:
Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.
Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\
.
As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:
start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"
But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.
Override the handleIntent
Method of the FirebaseMessageService
works for me.
here the code in C# (Xamarin)
public override void HandleIntent(Intent intent)
{
try
{
if (intent.Extras != null)
{
var builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
foreach (string key in intent.Extras.KeySet())
{
builder.AddData(key, intent.Extras.Get(key).ToString());
}
this.OnMessageReceived(builder.Build());
}
else
{
base.HandleIntent(intent);
}
}
catch (Exception)
{
base.HandleIntent(intent);
}
}
and thats the Code in Java
public void handleIntent(Intent intent)
{
try
{
if (intent.getExtras() != null)
{
RemoteMessage.Builder builder = new RemoteMessage.Builder("MyFirebaseMessagingService");
for (String key : intent.getExtras().keySet())
{
builder.addData(key, intent.getExtras().get(key).toString());
}
onMessageReceived(builder.build());
}
else
{
super.handleIntent(intent);
}
}
catch (Exception e)
{
super.handleIntent(intent);
}
}
First, unzip the APK and extract the file /META-INF/ANDROID_.RSA (this file may also be CERT.RSA, but there should only be one .RSA file).
Then issue this command:
keytool -printcert -file ANDROID_.RSA
You will get certificate fingerprints like this:
MD5: B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
SHA1: 16:59:E7:E3:0C:AA:7A:0D:F2:0D:05:20:12:A8:85:0B:32:C5:4F:68
Signature algorithm name: SHA1withRSA
Then use the keytool again to print out all the aliases of your signing keystore:
keytool -list -keystore my-signing-key.keystore
You will get a list of aliases and their certificate fingerprint:
android_key, Jan 23, 2010, PrivateKeyEntry,
Certificate fingerprint (MD5): B3:4F:BE:07:AA:78:24:DC:CA:92:36:FF:AE:8C:17:DB
Voila! we can now determined the apk has been signed with this keystore, and with the alias 'android_key'.
Keytool is part of Java, so make sure your PATH has Java installation dir in it.
For several cases, or even just a few cases involving a lot of criteria, consider using a switch.
switch( true ){
case ( !empty($youtube) && !empty($link) ):{
// Nothing is empty...
break;
}
case ( !empty($youtube) && empty($link) ):{
// One is empty...
break;
}
case ( empty($youtube) && !empty($link) ):{
// The other is empty...
break;
}
case ( empty($youtube) && empty($link) ):{
// Everything is empty
break;
}
default:{
// Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
// That way if you change it, or miss a case, you have some default handler.
break;
}
}
If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.
Note that the { } around the cases aren't required, but they are nice for readability and code folding.
More about switch: http://php.net/manual/en/control-structures.switch.php
If you're not too bothered about the width of the padding, this solution will actually keep the padding in percentages too..
textarea
{
border:1px solid #999999;
width:98%;
margin:5px 0;
padding:1%;
}
Not perfect, but you'll get some padding and the width adds up to 100% so its all good
Your EditText
should be wrapped in a TextInputLayout
<android.support.design.widget.TextInputLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tilEmail">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="@+id/etEmail"
android:hint="Email"
android:layout_marginTop="10dp"
/>
</android.support.design.widget.TextInputLayout>
To get an error message like you wanted, set error to TextInputLayout
TextInputLayout tilEmail = (TextInputLayout) findViewById(R.id.tilEmail);
if (error){
tilEmail.setError("Invalid email id");
}
You should add design support library dependency. Add this line in your gradle dependencies
compile 'com.android.support:design:22.2.0'
I have downloaded some HTML template that comes with custom js files and jquery. I had to attach those js to my app. and continue with Vue.
Found this plugin, it's a clean way to add external scripts both via CDN and from static files https://www.npmjs.com/package/vue-plugin-load-script
// local files
// you have to put your scripts into the public folder.
// that way webpack simply copy these files as it is.
Vue.loadScript("/js/jquery-2.2.4.min.js")
// cdn
Vue.loadScript("https://maps.googleapis.com/maps/api/js")
I had this problem too. It turned out I forgot to include one of the components in app.module.ts
I think that the easiest solution is to use Apache Common Codec:
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);
For a start the first select has 6 columns and the second has 4 columns. Perhaps make both have the same number of columns (adding nulls?).
One practical reason to choose one over the other is if you're going to use the result in another environment, for example JavaScript.
In PHP urlencode('test 1')
returns 'test+1'
while rawurlencode('test 1')
returns 'test%201'
as result.
But if you need to "decode" this in JavaScript using decodeURI() function then decodeURI("test+1")
will give you "test+1"
while decodeURI("test%201")
will give you "test 1"
as result.
In other words the space (" ") encoded by urlencode to plus ("+") in PHP will not be properly decoded by decodeURI in JavaScript.
In such cases the rawurlencode PHP function should be used.
Neither one. Use final class for Constants
declare them as public static final
and static import all constants wherever necessary.
public final class Constants {
private Constants() {
// restrict instantiation
}
public static final double PI = 3.14159;
public static final double PLANCK_CONSTANT = 6.62606896e-34;
}
Usage :
import static Constants.PLANCK_CONSTANT;
import static Constants.PI;//import static Constants.*;
public class Calculations {
public double getReducedPlanckConstant() {
return PLANCK_CONSTANT / (2 * PI);
}
}
See wiki link : http://en.wikipedia.org/wiki/Constant_interface
Following is my proposed solution.
A) Following is my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="schneider.carouseladventure.MainActivity">
<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/viewpager"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RelativeLayout
android:id="@+id/viewPagerIndicator"
android:layout_width="match_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:layout_marginTop="5dp"
android:gravity="center">
<LinearLayout
android:id="@+id/viewPagerCountDots"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
android:gravity="center"
android:orientation="horizontal" />
</RelativeLayout>
</RelativeLayout>
B) pager_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/imageView" />
</LinearLayout>
C) MainActivity.java
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class MainActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {
int[] mResources = {R.drawable.nature1, R.drawable.nature2, R.drawable.nature3, R.drawable.nature4,
R.drawable.nature5, R.drawable.nature6
};
ViewPager mViewPager;
private CustomPagerAdapter mAdapter;
private LinearLayout pager_indicator;
private int dotsCount;
private ImageView[] dots;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mViewPager = (ViewPager) findViewById(R.id.viewpager);
pager_indicator = (LinearLayout) findViewById(R.id.viewPagerCountDots);
mAdapter = new CustomPagerAdapter(this, mResources);
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(0);
mViewPager.setOnPageChangeListener(this);
setPageViewIndicator();
}
private void setPageViewIndicator() {
Log.d("###setPageViewIndicator", " : called");
dotsCount = mAdapter.getCount();
dots = new ImageView[dotsCount];
for (int i = 0; i < dotsCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(4, 0, 4, 0);
final int presentPosition = i;
dots[presentPosition].setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
mViewPager.setCurrentItem(presentPosition);
return true;
}
});
pager_indicator.addView(dots[i], params);
}
dots[0].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
}
@Override
public void onClick(View v) {
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d("###onPageSelected, pos ", String.valueOf(position));
for (int i = 0; i < dotsCount; i++) {
dots[i].setImageDrawable(getResources().getDrawable(R.drawable.nonselecteditem_dot));
}
dots[position].setImageDrawable(getResources().getDrawable(R.drawable.selecteditem_dot));
if (position + 1 == dotsCount) {
} else {
}
}
@Override
public void onPageScrollStateChanged(int state) {
}
}
D) CustomPagerAdapter.java
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
LayoutInflater mLayoutInflater;
private int[] mResources;
public CustomPagerAdapter(Context context, int[] resources) {
mContext = context;
mLayoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mResources = resources;
}
@Override
public Object instantiateItem(ViewGroup container, int position) {
View itemView = mLayoutInflater.inflate(R.layout.pager_item,container,false);
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
imageView.setImageResource(mResources[position]);
/* LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(950, 950);
imageView.setLayoutParams(layoutParams);*/
container.addView(itemView);
return itemView;
}
@Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
@Override
public int getCount() {
return mResources.length;
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
E) selecteditem_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" android:useLevel="true"
android:dither="true">
<size android:height="12dip" android:width="12dip"/>
<solid android:color="#7e7e7e"/>
</shape>
F) nonselecteditem_dot.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval" android:useLevel="true"
android:dither="true">
<size android:height="12dip" android:width="12dip"/>
<solid android:color="#d3d3d3"/>
</shape>
You can use a file browser with an backup function, for example the ES File Explorer Long tap a item and select create backup
I'll offer this in case (like me) you have a column of month numbers in a dataframe:
df['monthName'] = df['monthNumer'].apply(lambda x: calendar.month_name[x])
Here's a pure javascript version:
location.hash = '#123';
It'll scroll automatically. Remember to add the "#" prefix.
The message you received is common when you have ruby 2.0.0p0 (2013-02-24)
on top of Windows.
The message "DL is deprecated, please use Fiddle
" is not an error; it's only a warning.
The source is the Deprecation notice for DL introduced some time ago in dl.rb
( see revisions/37910 ).
On Windows the lib/ruby/site_ruby/2.0.0/readline.rb
file still requires dl.rb
so the warning message comes out when you require 'irb'
( because irb requires 'readline'
) or when anything else wants to require 'readline'
.
You can open readline.rb
with your favorite text editor and look up the code ( near line 4369 ):
if RUBY_VERSION < '1.9.1'
require 'Win32API'
else
require 'dl'
class Win32API
DLL = {}
We can always hope for an improvement to work out this deprecation in future releases of Ruby.
EDIT: For those wanting to go deeper about Fiddle vs DL, let it be said that their purpose is to dynamically link external libraries with Ruby; you can read on the ruby-doc website about DL or Fiddle.
You must use %ld
to print a long int
, and %lld
to print a long long int
.
Note that only long long int
is guaranteed to be large enough to store the result of that calculation (or, indeed, the input values you're using).
You will also need to ensure that you use your compiler in a C99-compatible mode (for example, using the -std=gnu99
option to gcc). This is because the long long int
type was not introduced until C99; and although many compilers implement long long int
in C90 mode as an extension, the constant 2147483648
may have a type of unsigned int
or unsigned long
in C90. If this is the case in your implementation, then the value of -2147483648
will also have unsigned type and will therefore be positive, and the overall result will be not what you expect.
It's not possible, sorry. If really needed, you could use a jQuery plugin to have a custom alert.
it's a pure PHP setting. The alternative is to increase the execution time limit only for specific php scripts, by inserting on top of that php file, the following:
ini_set('max_execution_time', 180); //3 minutes
My MySQL says "Incorrect table definition; there can be only one auto column and it must be defined as a key" So when I added primary key as below it started working:
CREATE TABLE book (
id INT AUTO_INCREMENT NOT NULL,
accepted_terms BIT(1) NOT NULL,
accepted_privacy BIT(1) NOT NULL,
primary key (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
command = "ls *"
def execute_state=sh(returnStdout: true, script: command)
but if the command failure the process will terminate
try this one
var query = "{% url accounts.views.instasearch %}?q=" + $('#tags').val().replace(/ /g, '+');
I had a similar issue so I found a workaround (remove hyperlink tags thanks to regular expressions so that only a paragraph tag remains). I posted this solution on https://github.com/python-openxml/python-docx/issues/85 BP
Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).
double sqrt(double x)
{
...
return x;
}
void other(void)
{
double two = sqrt(2.0);
}
Under my thesis, x is the parameter to sqrt()
and 2.0 is the argument.
The terms are often used at least somewhat interchangeably.
It's excerpt for the webpage: http://android.programmerguru.com/android-localization-at-runtime/
It's simple to change the language of your app upon user selects it from list of languages. Have a method like below which accepts the locale as String (like 'en' for English, 'hi' for hindi), configure the locale for your App and refresh your current activity to reflect the change in language. The locale you applied will not be changed until you manually change it again.
public void setLocale(String lang) {
Locale myLocale = new Locale(lang);
Resources res = getResources();
DisplayMetrics dm = res.getDisplayMetrics();
Configuration conf = res.getConfiguration();
conf.locale = myLocale;
res.updateConfiguration(conf, dm);
Intent refresh = new Intent(this, AndroidLocalize.class);
finish();
startActivity(refresh);
}
Make sure you imported following packages:
import java.util.Locale;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.util.DisplayMetrics;
add in manifest to activity android:configChanges="locale|orientation"
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
From above only, but simple implementation
Index Page
@model CMS.Models.IndexViewModel
@{
ViewBag.PageModel = Model;
}
Layout Page
@{
var Model = (CMS.Models.IndexViewModel)ViewBag.PageModel;
}
x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"
require(reshape2)
df <- melt(data.frame(x,y))
colnames(df) <- c(x_name, y_name)
print(df)
UPDATE (2017-02-07): As an answer to @cdaringe comment - there are multiple solutions possible, one of them is below.
library(dplyr)
library(magrittr)
x <- c(1, 2, 3)
y <- c(100, 200, 300)
z <- c(1, 2, 3, 4, 5)
x_name <- "cond"
y_name <- "rating"
# Helper function to create data.frame for the chunk of the data
prepare <- function(name, value, xname = x_name, yname = y_name) {
data_frame(rep(name, length(value)), value) %>%
set_colnames(c(xname, yname))
}
bind_rows(
prepare("x", x),
prepare("y", y),
prepare("z", z)
)
exp(x) = e^x where e= 2.718281(approx)
import numpy as np
ar=np.array([1,2,3])
ar=np.exp(ar)
print ar
outputs:
[ 2.71828183 7.3890561 20.08553692]
If the above solution didn't work for you, you can use import { withRouter } from 'react-router-dom';
Using this you can export your child class as -
class MyApp extends Component{
// your code
}
export default withRouter(MyApp);
And your class with Router -
// your code
<Router>
...
<Route path="/myapp" component={MyApp} />
// or if you are sending additional fields
<Route path="/myapp" component={() =><MyApp process={...} />} />
<Router>
forever might be of interest to you. It will run your .js-File 24/7 with logging options. Here are two snippets from the help text:
[Long Running Process] The forever process will continue to run outputting log messages to the console. ex. forever -o out.log -e err.log my-script.js
and
[Daemon] The forever process will run as a daemon which will make the target process start in the background. This is extremely useful for remote starting simple node.js scripts without using nohup. It is recommended to run start with -o -l, & -e. ex. forever start -l forever.log -o out.log -e err.log my-daemon.js forever stop my-daemon.js
I've found that the best way to debug is to use the microsoft tool called DTCPing
I've had my fare deal of problems in our old company network, and I've got a few tips:
In my experience, if the DTCPing is able to setup a DTC connection initiated from the client and initiated from the server, your transactions are not the problem any more.
For testing on both laptops on the same wireless and across the internet you could use a service like http://localhost.run/ or https://ngrok.com/
The answer marked here suggests using HttpClient directly and the disposing of it. This might work, but it's quite easy to run in to problems with HttpClient if you don't use it correctly.
If you're going to use HttpClient, you're better off handing over the creation/disposal of HttpClients to a third-party library that uses the factory pattern. RestClient.Net is one such library.
It comes with a very basic HttpClient factory so that you don't run in to the socket exhaustion problem,
public class DefaultHttpClientFactory : IHttpClientFactory, IDisposable
{
#region Fields
private bool disposed;
private readonly ConcurrentDictionary<string, Lazy<HttpClient>> _httpClients;
private readonly Func<string, Lazy<HttpClient>> _createClientFunc;
#endregion
#region Constructor
public DefaultHttpClientFactory() : this(null)
{
}
public DefaultHttpClientFactory(Func<string, Lazy<HttpClient>> createClientFunc)
{
_createClientFunc = createClientFunc;
_httpClients = new ConcurrentDictionary<string, Lazy<HttpClient>>();
if (_createClientFunc != null) return;
_createClientFunc = name =>
{
return new Lazy<HttpClient>(() => new HttpClient(), LazyThreadSafetyMode.ExecutionAndPublication);
};
}
#endregion
#region Implementation
public HttpClient CreateClient(string name)
{
if (name == null)
{
throw new ArgumentNullException(nameof(name));
}
return _httpClients.GetOrAdd(name, _createClientFunc).Value;
}
public void Dispose()
{
if (disposed) return;
disposed = true;
foreach (var name in _httpClients.Keys)
{
_httpClients[name].Value.Dispose();
}
}
#endregion
}
But Microsoft's IHttpClientFactory implementation can also be used for the latest and greatest:
var serviceCollection = new ServiceCollection();
var baseUri = new Uri("http://www.test.com");
serviceCollection.AddSingleton(typeof(ISerializationAdapter), typeof(NewtonsoftSerializationAdapter));
serviceCollection.AddSingleton(typeof(ILogger), typeof(ConsoleLogger));
serviceCollection.AddSingleton(typeof(IClient), typeof(Client));
serviceCollection.AddDependencyInjectionMapping();
serviceCollection.AddTransient<TestHandler>();
//Make sure the HttpClient is named the same as the Rest Client
serviceCollection.AddSingleton<IClient>(x => new Client(name: clientName, httpClientFactory: x.GetRequiredService<IHttpClientFactory>()));
serviceCollection.AddHttpClient(clientName, (c) => { c.BaseAddress = baseUri; })
.AddHttpMessageHandler<TestHandler>();
var serviceProvider = serviceCollection.BuildServiceProvider();
var client = serviceProvider.GetService<IClient>();
await client.GetAsync<object>();
RestClient.Net takes in to account dependency injection, mocking, IoC containers, unit testability, and above all is fast. I've hunted around and the only the other client that seems to work in a similar capacity is Flurl.Http.
You need to wrap button click handler to match the pattern
public void klik(object sender, EventArgs e)
This work with almsost all shell.
ncore=0
while read line ;do
[ "$line" ] && [ -z "${line%processor*}" ] && ncore=$((ncore+1))
done </proc/cpuinfo
echo $ncore
4
In order to stay compatible with shell, dash, busybox and others, I've used ncore=$((ncore+1))
instead of ((ncore++))
.
ncore=0
while read -a line ;do
[ "$line" = "processor" ] && ((ncore++))
done </proc/cpuinfo
echo $ncore
4
Yes, your conclusion is correct. socket.recv
is a blocking call.
socket.recv(1024)
will read at most 1024 bytes, blocking if no data is waiting to be read. If you don't read all data, an other call to socket.recv
won't block.
socket.recv
will also end with an empty string if the connection is closed or there is an error.
If you want a non-blocking socket, you can use the select module (a bit more complicated than just using sockets) or you can use socket.setblocking
.
I had issues with socket.setblocking
in the past, but feel free to try it if you want.
To change color of UINavigationBar
title the correct way use this code:
[self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObject:[UIColor whiteColor] forKey:UITextAttributeTextColor]];
UITextAttributeTextColor
is deprecated in lastest ios 7 version. Use NSForegroundColorAttributeName
instead.
To set automatic dimension for row height & estimated row height, ensure following steps to make, auto dimension effective for cell/row height layout.
UITableViewAutomaticDimension
to rowHeight & estimatedRowHeightheightForRowAt
and return a value UITableViewAutomaticDimension
to it)-
Objective C:
// in ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
@property IBOutlet UITableView * table;
@end
// in ViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
self.table.dataSource = self;
self.table.delegate = self;
self.table.rowHeight = UITableViewAutomaticDimension;
self.table.estimatedRowHeight = UITableViewAutomaticDimension;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewAutomaticDimension;
}
Swift:
@IBOutlet weak var table: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Don't forget to set dataSource and delegate for table
table.dataSource = self
table.delegate = self
// Set automatic dimensions for row height
table.rowHeight = UITableViewAutomaticDimension
table.estimatedRowHeight = UITableViewAutomaticDimension
}
// UITableViewAutomaticDimension calculates height of label contents/text
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return UITableViewAutomaticDimension
}
For label instance in UITableviewCell
Note: If you've more than one labels (UIElements) with dynamic length, which should be adjusted according to its content size: Adjust 'Content Hugging and Compression Resistance Priority` for labels which you want to expand/compress with higher priority.
Here in this example I set low hugging and high compression resistance priority, that leads to set more priority/importance for contents of second (yellow) label.
The short story is that it's not possible to do what you want here. There's no CSS rule which is to "ignore some other rule". The only way around it is to write a more-specific CSS rule for the inner elements which reverts it to how it was before, which is a pain in the butt.
Take the example below:
<div class="red"> <!-- ignore the semantics, it's an example, yo! -->
<p class="blue">
Blue text blue text!
<span class="notBlue">this shouldn't be blue</span>
</p>
</div>
<div class="green">
<p class="blue">
Blue text!
<span class="notBlue">blah</span>
</p>
</div>
There's no way to make the .notBlue
class revert to the parent styling. The best you can do is this:
.red, .red .notBlue {
color: red;
}
.green, .green .notBlue {
color: green;
}
This will allow you to see the whole response not just the "responseText" value
error: function(xhr, status, error) {
var acc = []
$.each(xhr, function(index, value) {
acc.push(index + ': ' + value);
});
alert(JSON.stringify(acc));
}
Passed parameter like below,
Param([parameter(Mandatory=$true,
HelpMessage="Enter name and key values")]
$Name,
$Key)
.\script_name.ps1 -Name name -Key key
Your error shows you are not compiling file with the definition of the insert
function. Update your command to include the file which contains the definition of that function and it should work.
Addition to third answer: If you're using non-english Windows, you can find "Credentials Manager" through "Control panel" > "User Accounts" > "Credentials Manager" Icon of Credentials Manager
You can define a base class for A
and B
where you can hold a common methods/properties/fields of those.
After implement C:Base
.
Or in order to simulate multiple inheritance, define a common interface
(s) and implement them in C
Hope this helps.
Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
table.ListRows.Add Position:=1
Set lastRow = table.ListRows(1).Range
Else
Set lastRow = table.ListRows(table.ListRows.Count).Range
End If
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
The best way to read that is the clockwise/spiral rule by David Anderson.
In general, I/O means Input or Output. Those methods throw the IOException
whenever an input or output operation is failed or interpreted. Note that this won't be thrown for reading or writing to memory as Java will be handling it automatically.
Here are some cases which result in IOException
.
git rm --cached FILE
,
git rm -r --cached CVS */CVS
I just spent 3 hours to solve a similar problem. This is what worked for me.
The element that I was attempting to retrieve from my $.get
response was a first child element of the body tag. For some reason when I wrapped a div around this element, it became retrievable through $(response).find('#nameofelement')
.
No idea why but yeah, retrievable element cannot be first child of body... that might be helpful to someone :)
I do this in a more permanent way - instead of installing the APKs each time with adb
, permanently add them to the system image that the emulator uses. You will need Yaffey on Windows, or a similar utility on other systems, to modify YAFFS2 images. Copy GoogleLoginService.apk
, GoogleServicesFramework.apk
, and Phonesky.apk
(or Vending.apk
in older versions of Android) to the /system/app
folder of the system.img
file of the emulator. Afterwards I can start the emulator normally, without messing with adb, and Play Store is always there.
Downloading Google Apps from some Internet site may not be quite legal, but if you have a phone or tablet with a corresponding Android version, just pull them out of your device:
adb -d root
adb -d pull /system/app/GoogleLoginService.apk
adb -d pull /system/app/GoogleServicesFramework.apk
adb -d pull /system/app/Phonesky.apk
You must have root-level access (run adb root) to the device in order to pull these files from it.
Now start yaffey
on Windows or a similar utility on Linux or Mac, and open system.img
for the emulator image you want to modify. I modify most often the one in [...]\android-sdk\system-images\android-17\x86
.
Rename the original system.img
to system-original.img
. Under yaffey, copy the APK files you pulled from your device to /app folder. Save your modified image as system.img
in the original folder. Then start your emulator (in my case it would be Android 4.2 emulator with Intel Atom processor running under Intel HAX, super-fast on Windows machines) and you'll have Play Store there. I did not find it necessary to delete SdkSetup.apk
and SdkSetup.odex
- the Play Store and other services still work fine for me with these files present.
When finished with your testing, to alleviate your conscience guilty of temporarily pirating the Google Apps from your device, you may delete the modified system.img
and restore the original from system-original.img
.
You want to use regexp_substr()
for this. This should work for your example:
select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
Here, by the way, is the SQL Fiddle.
Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace()
for the first part:
select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t
And here is this corresponding SQL Fiddle.
Use Calendar.
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);
Documentation says:
DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. [...] Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first. [...] The DISTINCT ON expression(s) must match the leftmost ORDER BY expression(s).
So you'll have to add the address_id
to the order by.
Alternatively, if you're looking for the full row that contains the most recent purchased product for each address_id
and that result sorted by purchased_at
then you're trying to solve a greatest N per group problem which can be solved by the following approaches:
The general solution that should work in most DBMSs:
SELECT t1.* FROM purchases t1
JOIN (
SELECT address_id, max(purchased_at) max_purchased_at
FROM purchases
WHERE product_id = 1
GROUP BY address_id
) t2
ON t1.address_id = t2.address_id AND t1.purchased_at = t2.max_purchased_at
ORDER BY t1.purchased_at DESC
A more PostgreSQL-oriented solution based on @hkf's answer:
SELECT * FROM (
SELECT DISTINCT ON (address_id) *
FROM purchases
WHERE product_id = 1
ORDER BY address_id, purchased_at DESC
) t
ORDER BY purchased_at DESC
Problem clarified, extended and solved here: Selecting rows ordered by some column and distinct on another
You can use the isSame
function:
var iscurrentDate = startTime.isSame(new Date(), "day");
if(iscurrentDate) {
}
JavaScript Promises actually use callback functions to determine what to do after a Promise has been resolved or rejected, therefore both are not fundamentally different. The main idea behind Promises is to take callbacks - especially nested callbacks where you want to perform a sort of actions, but it would be more readable.
If you prefer a non-object-oriented approach, move plt.xticks(rotation=70)
to right before the two avail_plot
calls, eg
plt.xticks(rotation=70)
avail_plot(axs[0], dates, s1, 'testing', 'green')
avail_plot(axs[1], dates, s1, 'testing2', 'red')
This sets the rotation property before setting up the labels. Since you have two axes here, plt.xticks
gets confused after you've made the two plots. At the point when plt.xticks
doesn't do anything, plt.gca()
does not give you the axes you want to modify, and so plt.xticks
, which acts on the current axes, is not going to work.
For an object-oriented approach not using plt.xticks
, you can use
plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
after the two avail_plot
calls. This sets the rotation on the correct axes specifically.
Try something like the following example, quoted from the output of IF /?
on Windows XP:
IF EXIST filename. ( del filename. ) ELSE ( echo filename. missing. )
You can also check for a missing file with IF NOT EXIST
.
The IF
command is quite powerful. The output of IF /?
will reward careful reading. For that matter, try the /?
option on many of the other built-in commands for lots of hidden gems.
As others have suggested, you can directly write a 2-dimensional array into a Range on sheet, however if your array is single-dimensional then you have two options:
Here is an example depicting both options:
Sub PrintArrayIn1Cell(myArr As Variant, cell As Range) cell = Join(myArr, ",") End Sub Sub PrintArrayAsRange(myArr As Variant, cell As Range) cell.Resize(UBound(myArr, 1), UBound(myArr, 2)) = myArr End Sub Sub TestPrintArrayIntoSheet() '2dArrayToSheet Dim arr As Variant arr = Split("a b c", " ") 'Printing in ONE-CELL: To print all array-elements as a single string separated by comma (a,b,c): PrintArrayIn1Cell arr, [A1] 'Printing in SEPARATE-CELLS: To print array-elements in separate cells: Dim arr2D As Variant arr2D = Application.WorksheetFunction.Transpose(arr) 'convert a 1D array into 2D array PrintArrayAsRange arr2D, Range("B1:B3") End Sub
Note: Transpose will render column-by-column output, to get row-by-row output transpose it again - hope that makes sense.
HTH
Update the master branch, which you need to do regardless.
Then, one of:
Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.
Merge your branch into master, and resolve the merge conflicts.
Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.
None of these is better than the other, they just have different trade-off patterns.
I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.
To rebase and keep the branch you would:
git checkout <branch> && git rebase <target>
In your case, check out the old branch, then
git rebase master
to get it rebuilt against master.
I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:
curl -o <filename-to-save-as> -u <username>:<password> <url>
Although this entry is quite old and most of you probably already know, I think it's worth mention that GWT 2.x includes a new compile flag which speeds up compiles by skipping optimizations. You definitely shouldn't deploy JavaScript compiled that way, but it can be a time saver during non-production continuous builds.
Just include the flag: -draftCompile to your GWT compiler line.
This is my simple way to set default values to a function, using "try":
function z = myfun (a,varargin)
%% Default values
b = 1;
c = 1;
d = 1;
e = 1;
try
b = varargin{1};
c = varargin{2};
d = varargin{3};
e = varargin{4};
end
%% Calculation
z = a * b * c * d * e ;
end
Regards!
Like others said, you can just loop over the array and print out the elements one by one. To make the output show up as numbers instead of "letters and symbols" you were seeing, you need to convert each element to a string. So your code becomes something like this:
public static void write (String filename, int[]x) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (int i = 0; i < x.length; i++) {
// Maybe:
outputWriter.write(x[i]+"");
// Or:
outputWriter.write(Integer.toString(x[i]);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
If you just want to print out the array like [1, 2, 3, ....]
, you can replace the loop with this one liner:
outputWriter.write(Arrays.toString(x));
You CAN ONLY understand Domain driven design by first comprehending what the following are:
What is a domain?
The field for which a system is built. Airport management, insurance sales, coffee shops, orbital flight, you name it.
It's not unusual for an application to span several different domains. For example, an online retail system might be working in the domains of shipping (picking appropriate ways to deliver, depending on items and destination), pricing (including promotions and user-specific pricing by, say, location), and recommendations (calculating related products by purchase history).
What is a model?
"A useful approximation to the problem at hand." -- Gerry Sussman
An Employee class is not a real employee. It models a real employee. We know that the model does not capture everything about real employees, and that's not the point of it. It's only meant to capture what we are interested in for the current context.
Different domains may be interested in different ways to model the same thing. For example, the salary department and the human resources department may model employees in different ways.
What is a domain model?
A model for a domain.
What is Domain-Driven Design (DDD)?
It is a development approach that deeply values the domain model and connects it to the implementation. DDD was coined and initially developed by Eric Evans.
Culled from here
And for vim
7.4+ you can use (preferably on your .vimrc) (thanks to ??? for that last bit of news!):
:set nofixendofline
Now regarding older versions of vim
.
Even if the file was already saved with new lines at the end:
vim -b file
and once in vim:
:set noeol
:wq
done.
alternatively you can open files in vim with :e ++bin file
Yet another alternative:
:set binary
:set noeol
:wq
see more details at Why do I need vim in binary mode for 'noeol' to work?
In more recent browsers code like below may be enough.
<object data="https://www.w3.org/TR/PNG/iso_8859-1.txt" width="300" height="200">_x000D_
Not supported_x000D_
</object>
_x000D_
Although a bit late, I've come across this question while searching the solution for the same problem, so I hope it can be of any help...
Found myself in the same darkness than you. Just found this article, which explains some new hints introduced in NetBeans 7.4, including this one:
https://blogs.oracle.com/netbeansphp/entry/improve_your_code_with_new
The reason why it has been added is because superglobals usually are filled with user input, which shouldn't ever be blindly trusted. Instead, some kind of filtering should be done, and that's what the hint suggests. Filter the superglobal value in case it has some poisoned content.
For instance, where I had:
$_SERVER['SERVER_NAME']
I've put instead:
filter_input(INPUT_SERVER, 'SERVER_NAME', FILTER_SANITIZE_STRING)
You have the filter_input and filters doc here:
Not like the @staticmethod
but class variables are static method of class and are shared with all the instances.
Now you can access it like
instance = MyClass()
print(instance.i)
or
print(MyClass.i)
you have to assign the value to these variables
I was trying
class MyClass:
i: str
and assigning the value in one method call, in that case it will not work and will throw an error
i is not attribute of MyClass
The best way to boost up android studio runtime performance is to use SSD Drive. It will boost the performance as very much. I did all the above things and felt I should go for new laptop, but suddenly I came to know about SSD Drive and I tried it. Its Much Much better.....
In Selenium to get the URL of the active tab try,
from selenium import webdriver
driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)
print driver.current_url
I am here just providing a pseudo code for you.
You can put this in a loop and create your own flow.
I new to Stackoverflow so still learning how to write proper answers.
I also had an issue with multiline strings in this scenario. @Iman's backtick(`) solution worked great in the modern browsers but caused an invalid character error in Internet Explorer. I had to use the following:
'@item.MultiLineString.Replace(Environment.NewLine, "<br />")'
Then I had to put the carriage returns back again in the js function. Had to use RegEx to handle multiple carriage returns.
// This will work for the following:
// "hello\nworld"
// "hello<br>world"
// "hello<br />world"
$("#MyTextArea").val(multiLineString.replace(/\n|<br\s*\/?>/gi, "\r"));
In addition to what the others have said, see my answer to a related question which shows that catching and rethrowing is not a no-op (it's in VB, but some of the code could be C# invoked from VB).
Just escape the "\"
by using + "\\Tasks"
or use a verbatim string like @"\Tasks"
If you are using Typescript 3.7 or newer you can now also do:
const data = change?.after?.data();
if(!data) {
console.error('No data here!');
return null
}
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
Typescript is saying that change
or data
is possibly undefined
(depending on what onUpdate
returns).
So you should wrap it in a null/undefined check:
if(change && change.after && change.after.data){
const data = change.after.data();
const maxLen = 100;
const msgLen = data.messages.length;
const charLen = JSON.stringify(data).length;
const batch = db.batch();
if (charLen >= 10000 || msgLen >= maxLen) {
// Always delete at least 1 message
const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
data.messages.splice(0, deleteCount);
const ref = db.collection("chats").doc(change.after.id);
batch.set(ref, data, { merge: true });
return batch.commit();
} else {
return null;
}
}
If you are 100% sure that your object
is always defined then you can put this:
const data = change.after!.data();
I've created a tool called Rector, that handles instant upgrades. There is also mysql ? mysqli set.
It handles:
function renaming
constant renaming
switched arguments
non-1:1 function calls changes, e.g.
$data = mysql_db_name($result, $row);
?
mysqli_data_seek($result, $row);
$fetch = mysql_fetch_row($result);
$data = $fetch[0];
composer require rector/rector --dev
// or in case of composer conflicts
composer require rector/rector-prefixed --dev
rector.php
in project root directory with the Mysql to Mysqli set<?php
use Rector\Core\Configuration\Option;
use Rector\Set\ValueObject\SetList;
use Symfony\Component\DependencyInjection\Loader\Configurator\ContainerConfigurator;
return static function (ContainerConfigurator $containerConfigurator): void {
$parameters->set(Option::SETS, [
SetList::MYSQL_TO_MYSQLI,
]);
};
vendor/bin/rector process src --dry-run
vendor/bin/rector process src
I've already run it on 2 big PHP projects and it works perfectly.
That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3)
It's important that you set the Content-Type
header to application/json
, too.
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);
// > {"a":1}
Prettified:
var http = require('http');
var app = http.createServer(function(req,res){
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);
// > {
// > "a": 1
// > }
I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\n'
to achieve that.
In express you can do this by changing the options instead.
'json replacer'
JSON replacer callback, null by default
'json spaces'
JSON response spaces for formatting, defaults to 2 in development, 0 in production
Not actually recommended to set to 40
app.set('json spaces', 40);
Then you could just respond with some json.
res.json({ a: 1 });
It'll use the 'json spaces
' configuration to prettify it.
Very nice solutions. Here are some more.
int length ( String s )
{
int length = 0 ;
// iterate through all possible code points
for ( int i = INTEGER . MIN_VALUE ; i <= INTEGER . MAX_VALUE ; i ++ )
{
// count the number of i's in the string
for ( int next = s . indexOf ( i , next ) + 1 ; next != -1 ; next = s . indexOf ( i , next ) + 1 )
{
length ++ ;
}
}
return ( length ) ;
}
Here is a recursive version:
int length ( String s )
{
int length = 0 ;
search :
for ( int i = Integer . MIN_VALUE ; i <= Integer . MAX_VALUE ; i ++ )
{
final int k = s . indexOf ( i ) ;
if ( k != -1 )
{
length = length ( s . substring ( 0 , k ) ) + length ( s . substring ( k ) ) ;
break search ;
}
}
return ( length ) ;
}
And still more
int length ( String s )
{
int length ;
search ;
for ( length = 0 ; true ; length ++ )
{
int [ ] codePoints = new int [ length ] ;
for ( each possible value of codePoints from {MIN_VALUE,MIN_VALUE,...} to {MAX_VALUE,MAX_VALUE,...} )
{
if ( new String ( codePoints ) . equals ( s ) ) { break search ; }
}
}
}
How could I forget one that actually works in a reasonable time? (String#length is still preferred.)
int length ( String s )
{
String t = s . replaceAll ( "." , "A" ) ;
int length ;
String r = "" ;
search :
for ( r = "" , length = 0 ; true ; r += "A" , length ++ )
{
if ( r . equals ( t ) )
{
break search ;
}
}
return ( length ) ;
}
I had to do this in that order:
Install-Module MSOnline
Install-Module AzureAD
Import-Module AzureAD
The best course of action is using PHP's DateTime
(and DateInterval
) objects. Each date is encapsulated in a DateTime
object, and then a difference between the two can be made:
$first_date = new DateTime("2012-11-30 17:03:30");
$second_date = new DateTime("2012-12-21 00:00:00");
The DateTime
object will accept any format strtotime()
would. If an even more specific date format is needed, DateTime::createFromFormat()
can be used to create the DateTime
object.
After both objects were instantiated, you substract one from the other with DateTime::diff()
.
$difference = $first_date->diff($second_date);
$difference
now holds a DateInterval
object with the difference information. A var_dump()
looks like this:
object(DateInterval)
public 'y' => int 0
public 'm' => int 0
public 'd' => int 20
public 'h' => int 6
public 'i' => int 56
public 's' => int 30
public 'invert' => int 0
public 'days' => int 20
To format the DateInterval
object, we'll need check each value and exclude it if it's 0:
/**
* Format an interval to show all existing components.
* If the interval doesn't have a time component (years, months, etc)
* That component won't be displayed.
*
* @param DateInterval $interval The interval
*
* @return string Formatted interval string.
*/
function format_interval(DateInterval $interval) {
$result = "";
if ($interval->y) { $result .= $interval->format("%y years "); }
if ($interval->m) { $result .= $interval->format("%m months "); }
if ($interval->d) { $result .= $interval->format("%d days "); }
if ($interval->h) { $result .= $interval->format("%h hours "); }
if ($interval->i) { $result .= $interval->format("%i minutes "); }
if ($interval->s) { $result .= $interval->format("%s seconds "); }
return $result;
}
All that's left now is to call our function on the $difference
DateInterval
object:
echo format_interval($difference);
And we get the correct result:
20 days 6 hours 56 minutes 30 seconds
The complete code used to achieve the goal:
/**
* Format an interval to show all existing components.
* If the interval doesn't have a time component (years, months, etc)
* That component won't be displayed.
*
* @param DateInterval $interval The interval
*
* @return string Formatted interval string.
*/
function format_interval(DateInterval $interval) {
$result = "";
if ($interval->y) { $result .= $interval->format("%y years "); }
if ($interval->m) { $result .= $interval->format("%m months "); }
if ($interval->d) { $result .= $interval->format("%d days "); }
if ($interval->h) { $result .= $interval->format("%h hours "); }
if ($interval->i) { $result .= $interval->format("%i minutes "); }
if ($interval->s) { $result .= $interval->format("%s seconds "); }
return $result;
}
$first_date = new DateTime("2012-11-30 17:03:30");
$second_date = new DateTime("2012-12-21 00:00:00");
$difference = $first_date->diff($second_date);
echo format_interval($difference);
To resolve, Update Spring Frame Work to 3.2.0 or above!
You can use the eclipse plugin as suggested by Oscar earlier. Or if you are a command line person, you can use Apache Axis WSDL2Java tool from command prompt. You can find more details here http://axis.apache.org/axis/java/reference.html#WSDL2JavaReference
Try this:
@echo off
set run=
tasklist /fi "imagename eq notepad.exe" | find ":" > nul
if errorlevel 1 set run=yes
if "%run%"=="yes" echo notepad is running
if "%run%"=="" echo notepad is not running
pause
UPDATE databaseName.tableName
SET columnName = replace(columnName, '?', '''')
WHERE columnName LIKE '%?%'
There is the option Microsoft Software Licensing and Protection (SLP) Services as well. After reading about it I really wish I could use it.
I really like the idea of blocking parts of code based on the license. Hot stuff, and the most secure for .NET. Interesting read even if you don't use it!
Microsoft® Software Licensing and Protection (SLP) Services is a software activation service that enables independent software vendors (ISVs) to adopt flexible licensing terms for their customers. Microsoft SLP Services employs a unique protection method that helps safeguard your application and licensing information allowing you to get to market faster while increasing customer compliance.
Note: This is the only way I would release a product with sensitive code (such as a valuable algorithm).
Try this:
export PATH=/home/your_username/anaconda3/bin:$PATH
in ~/.bashrc
Then source ~/.bashrc
This works for me for the same problem.
In python 3, you can use:
import locale
locale.setlocale( locale.LC_ALL, 'English_United States.1252' )
locale.currency( 1234.50, grouping = True )
Output
'$1,234.50'
bash your_script.sh 1>file.log 2>&1
1>file.log
instructs the shell to send STDOUT to the file file.log
, and 2>&1
tells it to redirect STDERR (file descriptor 2) to STDOUT (file descriptor 1).
Note: The order matters as liw.fi pointed out, 2>&1 1>file.log
doesn't work.
var element = document;_x000D_
_x000D_
Rx.Observable_x000D_
.merge(_x000D_
Rx.Observable.fromEvent(element, 'mousedown').mapTo(0),_x000D_
Rx.Observable.fromEvent(element, 'mousemove').mapTo(1)_x000D_
)_x000D_
.sample(Rx.Observable.fromEvent(element, 'mouseup'))_x000D_
.subscribe(flag => {_x000D_
console.clear();_x000D_
console.log(flag ? "drag" : "click");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://unpkg.com/@reactivex/[email protected]/dist/global/Rx.js"></script>
_x000D_
This is a direct clone of what @wong2 did in his answer, but converted to RxJs.
Also interesting use of sample
. The sample
operator will take the latest value from the source (the merge
of mousedown
and mousemove
) and emit it when the inner observable (mouseup
) emits.
Another option if you don't wanna mount a volume, but wanna dump a file from your local machine, is to pipe cat yourdump.sql
. Like so:
cat dump.sql | docker exec -i mysql-container mysql -uuser -ppassword db_name
See: https://gist.github.com/spalladino/6d981f7b33f6e0afe6bb
Simply cleaning the project solved it for me.
My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.
The following code works for me.
//escape the double quotes in json string
String payload="{\"jsonrpc\":\"2.0\",\"method\":\"changeDetail\",\"params\":[{\"id\":11376}],\"id\":2}";
String requestUrl="https://git.eclipse.org/r/gerrit/rpc/ChangeDetailService";
sendPostRequest(requestUrl, payload);
method implementation:
public static String sendPostRequest(String requestUrl, String payload) {
try {
URL url = new URL(requestUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
writer.write(payload);
writer.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuffer jsonString = new StringBuffer();
String line;
while ((line = br.readLine()) != null) {
jsonString.append(line);
}
br.close();
connection.disconnect();
return jsonString.toString();
} catch (Exception e) {
throw new RuntimeException(e.getMessage());
}
}
I prefer using atom-beautify, CTRL+ALT+B (in linux, may be in windows also) handles better al kind of formats and it is also customizable per file format.
more details here: https://atom.io/packages/atom-beautify
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
FIDDLE: https://jsfiddle.net/1ytxfcwx/
NPM: https://www.npmjs.com/package/typescript-string-operations
GITHUB: https://github.com/sevensc/typescript-string-operations
I implemented a class for String. Its not perfect but it works for me.
use it i.e. like this:
var getFullName = function(salutation, lastname, firstname) {
return String.Format('{0} {1:U} {2:L}', salutation, lastname, firstname)
}
export class String {
public static Empty: string = "";
public static isNullOrWhiteSpace(value: string): boolean {
try {
if (value == null || value == 'undefined')
return false;
return value.replace(/\s/g, '').length < 1;
}
catch (e) {
return false;
}
}
public static Format(value, ...args): string {
try {
return value.replace(/{(\d+(:.*)?)}/g, function (match, i) {
var s = match.split(':');
if (s.length > 1) {
i = i[0];
match = s[1].replace('}', '');
}
var arg = String.formatPattern(match, args[i]);
return typeof arg != 'undefined' && arg != null ? arg : String.Empty;
});
}
catch (e) {
return String.Empty;
}
}
private static formatPattern(match, arg): string {
switch (match) {
case 'L':
arg = arg.toLowerCase();
break;
case 'U':
arg = arg.toUpperCase();
break;
default:
break;
}
return arg;
}
}
EDIT:
I extended the class and created a repository on github. It would be great if you can help to improve it!
https://github.com/sevensc/typescript-string-operations
or download the npm package
when you want to access images which are in public/images folder and if you want to access it without using laravel functions, use as follows:
<img src={{url('/images/photo.type')}} width="" height="" alt=""/>
This works fine.
You can replace database value in date_default_timezone_set function, date_default_timezone_set(SOME_PHP_VARIABLE); but just needs to take care of exact values relevant to the timezones.
You need to Open the output file for write access rather than using a new StreamReader, which always overwrites the output file.
StreamWriter stm = null;
fi = new FileInfo(@"C:\target.xml");
if (fi.Exists)
stm = fi.OpenWrite();
Of course, you will still have to seek to the correct line in the output file, which will be hard since you can't read from it, so unless you already KNOW the byte offset to seek to, you probably really want read/write access.
FileStream stm = fi.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.
The Corona SDK (Ansca Mobile) uses Lua as its coding language. See lua.org for more about Lua.
While we plan to add further web integration and native-UI elements, our focus will tend to be on graphics-intensive applications, such as game development, as opposed to web-based technologies. In other words, we don't envision people writing Corona apps entirely in Javascript/HTML/CSS.
This doesn't seem to work in Mac Excel 2016. After a bit of digging, it looks like the key combination for entering the array formula has changed from ?+RETURN to CTRL+SHIFT+RETURN.
For an example data in your table such as combinations of
''
, null
and as well as actual value
than if you want to only actual value
and replace to ''
and null
value by #
symbol than execute this query
SELECT Column_Name = (CASE WHEN (Column_Name IS NULL OR Column_Name = '') THEN '#' ELSE Column_Name END) FROM Table_Name
and another way you can use it but this is little bit lengthy and instead of this you can also use IsNull
function but here only i am mentioning IIF
function
SELECT IIF(Column_Name IS NULL, '#', Column_Name) FROM Table_Name
SELECT IIF(Column_Name = '', '#', Column_Name) FROM Table_Name
-- and syntax of this query
SELECT IIF(Column_Name IS NULL, 'True Value', 'False Value') FROM Table_Name
string str = "asasdkopaksdpoadks";
byte[] data = Encoding.ASCII.GetBytes(str);
MemoryStream stm = new MemoryStream(data, 0, data.Length);
You need some form of iteration here, as val
(except when called with a function) only works on the first element:
$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));
should be:
$("input[placeholder]").each( function () {
$(this).val( $(this).attr("placeholder") );
});
or
$("input[placeholder]").val(function() {
return $(this).attr("placeholder");
});
val.ToString("".PadLeft(length, '0'))