I use the following in a batch file:
path = %path%;C:\Windows\Microsoft.NET\Framework\v2.0.50727
regasm httpHelper\bin\Debug\httpHelper.dll /tlb:.\httpHelper.tlb /codebase
pause
You are setting the html of #showresults
of whatever data
is, and then replacing it with itself, which doesn't make much sense ?
I'm guessing you where really trying to find #showresults
in the returned data, and then update the #showresults
element in the DOM with the html from the one from the ajax call :
$('#submitform').click(function () {
$.ajax({
url: "getinfo.asp",
data: {
txtsearch: $('#appendedInputButton').val()
},
type: "GET",
dataType: "html",
success: function (data) {
var result = $('<div />').append(data).find('#showresults').html();
$('#showresults').html(result);
},
error: function (xhr, status) {
alert("Sorry, there was a problem!");
},
complete: function (xhr, status) {
//$('#showresults').slideDown('slow')
}
});
});
I did experience this error when I tried doing an WHERE EXIST where the subquery matched 2 columns that accidentially was different types. The two tables was also different storage engines.
One column was a CHAR (90) and the other was a BIGINT (20).
One table was InnoDB and the other was MEMORY.
Part of query:
[...] AND EXISTS (select objectid from temp_objectids where temp_objectids.objectid = items_raw.objectid );
Changing the column type on the one column from BIGINT to CHAR solved the issue.
You can do something like this instead.
return new DateTime(2010, Month, 1).ToString("MMM");
Where are you jar files? Is there a pattern to find where they are?
For example, foo/a/a.jar
and foo/b/b.jar
are all under the folder foo/
, in this case, you could use find
with grep
:
find foo/ -name "*.jar" | xargs grep Hello.class
Sure, at least you can search them under the root directory /
, but it will be slow.
As @loganaayahee said, you could also use the command locate
. locate
search the files with an index, so it will be faster. But the command should be:
locate "*.jar" | xargs grep Hello.class
Since you want to search the content of the jar files.
Typically, Java will store the paths to find jar files in an environment variable like CLASS_PATH
, I don't know if this is what you want. But if your variable is just like this:CLASS_PATH=/lib:/usr/lib:/bin
, which use a :
to separate the paths, then you could use this commend to search the class:
for P in `echo $CLASS_PATH | sed 's/:/ /g'`; do grep Hello.calss $P/*.jar; done
I use:
var $scrollEl = $.browser.mozilla ? $('html') : $('body');
because read jQuery scrollTop not working in Chrome but working in Firefox
Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;
. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.
The easiest way if you have
<div ng-repeat="person in data | filter: query"></div>
Filtered data length
<div>{{ (data | filter: query).length }}</div>
A one liner would be :
str=str[::-1].replace(".",".-",1)[::-1]
Try this:
HTML:
<input type="submit" value="submit" name="submit" onclick="myfunction()">
jQuery:
<script type="text/javascript">
function myfunction()
{
var url = $(location).attr('href');
$('#spn_url').html('<strong>' + url + '</strong>');
}
</script>
grep is the right tool for extracting.
using your example and your regex:
kent$ echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4
how about something like this...
var directory = new DirectoryInfo("C:\\MyDirectory");
var myFile = (from f in directory.GetFiles()
orderby f.LastWriteTime descending
select f).First();
// or...
var myFile = directory.GetFiles()
.OrderByDescending(f => f.LastWriteTime)
.First();
I use a combination of json.get() and instanceof to read in values that might be either integers or integer strings.
These three test cases illustrate:
int val;
Object obj;
JSONObject json = new JSONObject();
json.put("number", 1);
json.put("string", "10");
json.put("other", "tree");
obj = json.get("number");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
obj = json.get("string");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
System.out.println(val);
try {
obj = json.get("other");
val = (obj instanceof Integer) ? (int) obj : (int) Integer.parseInt((String) obj);
} catch (Exception e) {
// throws exception
}
<html>
<head>
<script type="text/javascript">
function striptag(){
var html = /(<([^>]+)>)/gi;
for (i=0; i < arguments.length; i++)
arguments[i].value=arguments[i].value.replace(html, "")
}
</script>
</head>
<body>
<form name="myform">
<textarea class="comment" title="comment" name=comment rows=4 cols=40></textarea><br>
<input type="button" value="Remove HTML Tags" onClick="striptag(this.form.comment)">
</form>
</body>
</html>
?php
/* Database config */
$db_host = 'localhost';
$db_user = '~';
$db_pass = '~';
$db_database = 'banners';
/* End config */
$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_database);
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
It looks like your TimeStamp is being set to the timezone of the originating system.
This is deprecated, but it should work:
cal.setTimeInMillis(ts_.getTime() - ts_.getTimezoneOffset());
The non-deprecated way is to use
Calendar.get(Calendar.ZONE_OFFSET) + Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000)
but that would need to be done on the client side, since that system knows what timezone it is in.
As akjoshi and Julio say this is about dispatching an Action to update the GUI on the same thread as the GUI item but from the method that is handling the background data. You can see this code in specific form in akjoshi's answer above. This is a general version.
myTextBlock.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(delegate()
{
myTextBlock.Text = Convert.ToString(myDataObject.getMeData());
}));
The critical part is to call the dispatcher of your UI object - that ensures you have the correct thread.
From personal experience it seems much easier to create and use the Action inline like this. Declaring it at class level gave me lots of problems with static/non-static contexts.
Load each query into a datatable:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=143
load both datatables into the dataset:
http://msdn.microsoft.com/en-us/library/aeskbwf7%28v=vs.80%29.aspx
An obfuscated C version:
int IsPalindrome (char *s)
{
char*a,*b,c=0;
for(a=b=s;a<=b;c=(c?c==1?c=(*a&~32)-65>25u?*++a,1:2:c==2?(*--b&~32)-65<26u?3:2:c==3?(*b-65&~32)-(*a-65&~32)?*(b=s=0,a),4:*++a,1:0:*++b?0:1));
return s!=0;
}
var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
//Set content length to 0
authRequest.ContentLength = 0;
WebResponse authResponseTwitter = authRequest.GetResponse();
The ContentLength
property contains the value to send as the Content-length
HTTP header with the request.
Any value other than -1 in the ContentLength
property indicates that the request uploads data and that only methods that upload data are allowed to be set in the Method property.
After the ContentLength
property is set to a value, that number of bytes must be written to the request stream that is returned by calling the GetRequestStream
method or both the BeginGetRequestStream
and the EndGetRequestStream
methods.
for more details click here
I tested "jenv" and other things like setting "JAVA_HOME" without success. Now i and endet up with following solution
function setJava {
export JAVA_HOME="$(/usr/libexec/java_home -v $1)"
launchctl setenv JAVA_HOME $JAVA_HOME
sudo ln -nsf "$(dirname ${JAVA_HOME})/MacOS" /Library/Java/MacOS
java -version
}
(added to ~/.bashrc or ~/.bash.profile or ~/.zshrc)
And calling like that:
setJava 1.8
java_home will handle the wrong input. so you can't do something wrong. Maven and other stuff will pick up the right version now.
As your list is an ArrayList
, it can be assumed that it is unsorted. Therefore, there is no way to search for your element that is faster than O(n).
If you can, you should think about changing your list into a Set
(with HashSet
as implementation) with a specific Comparator
for your sample class.
Another possibility would be to use a HashMap
. You can add your data as Sample
(please start class names with an uppercase letter) and use the string you want to search for as key. Then you could simply use
Sample samp = myMap.get(myKey);
If there can be multiple samples per key, use Map<String, List<Sample>>
, otherwise use Map<String, Sample>
. If you use multiple keys, you will have to create multiple maps that hold the same dataset. As they all point to the same objects, space shouldn't be that much of a problem.
There is no direct function to get yesterday's date.
To get yesterday's date, you need to use Calendar
by subtracting -1
.
Similar to @Wolfram J's answer, here is a method to encrypt your private key with a passphrase:
gpg --output - --armor --export $KEYID | \
gpg --output private_key.asc --armor --symmetric --cipher-algo AES256
And a corresponding method to decrypt:
gpg private_key.asc
I faced the same problem. I restarted the oracle service for that DB instance and the error is gone.
You can use Apply and Lambda to select rows where a column contains any thing in a list. For your scenario :
df[df["col"].apply(lambda x:x not in [word1,word2,word3])]
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
I had the same problem with bootstrap datetimepicker extension. Including moment.js before datetimepicker.js was the solution.
use default_scope in rails 3
ActiveRecord obscures the difference between defaulting defined in the database (schema) and defaulting done in the application (model). During initialization, it parses the database schema and notes any default values specified there. Later, when creating objects, it assigns those schema-specified default values without touching the database.
Well According to a comment on the shuf answer he shuffed 78 000 000 000 lines in under a minute.
Challenge accepted...
EDIT: I beat my own record
$ time ./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null
./powershuf.py -n 10 --file lines_78000000000.txt > /dev/null 0.02s user 0.01s system 80% cpu 0.047 total
The reason it is so fast, well I don't read the whole file and just move the file pointer 10 times and print the line after the pointer.
First I needed a file of 78.000.000.000 lines:
seq 1 78 | xargs -n 1 -P 16 -I% seq 1 1000 | xargs -n 1 -P 16 -I% echo "" > lines_78000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000.txt > lines_78000000.txt
seq 1 1000 | xargs -n 1 -P 16 -I% cat lines_78000000.txt > lines_78000000000.txt
This gives me a a file with 78 Billion newlines ;-)
Now for the shuf part:
$ time shuf -n 10 lines_78000000000.txt
shuf -n 10 lines_78000000000.txt 2171.20s user 22.17s system 99% cpu 36:35.80 total
The bottleneck was CPU and not using multiple threads, it pinned 1 core at 100% the other 15 were not used.
Python is what I regularly use so that's what I'll use to make this faster:
#!/bin/python3
import random
f = open("lines_78000000000.txt", "rt")
count = 0
while 1:
buffer = f.read(65536)
if not buffer: break
count += buffer.count('\n')
for i in range(10):
f.readline(random.randint(1, count))
This got me just under a minute:
$ time ./shuf.py
./shuf.py 42.57s user 16.19s system 98% cpu 59.752 total
I did this on a Lenovo X1 extreme 2nd gen with the i9 and Samsung NVMe which gives me plenty read and write speed.
I know it can get faster but I'll leave some room to give others a try.
Line counter source: Luther Blissett
You could create a basket service. And generally in JS you use objects instead of lots of parameters.
Here's an example: http://jsfiddle.net/2MbZY/
var app = angular.module('myApp', []);
app.factory('basket', function() {
var items = [];
var myBasketService = {};
myBasketService.addItem = function(item) {
items.push(item);
};
myBasketService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
myBasketService.items = function() {
return items;
};
return myBasketService;
});
function MyCtrl($scope, basket) {
$scope.newItem = {};
$scope.basket = basket;
}
Simply type conda update pandas
in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory).
See this document for a detailed instruction.
You can either:
pre { white-space: normal; }
to maintain the monospace font but add word-wrap, or:
pre { overflow: auto; }
which will allow a fixed size with horizontal scrolling for long lines.
Assuming that you meant to write
char *functionname(char *string[256])
Here you are declaring a function that takes an array of 256 pointers to char
as argument and returns a pointer to char. Here, on the other hand,
char functionname(char string[256])
You are declaring a function that takes an array of 256 char
s as argument and returns a char
.
In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.
Below is a fast approach to remove a potential '\n'
from a string saved by fgets()
.
It uses strlen()
, with 2 tests.
char buffer[100];
if (fgets(buffer, sizeof buffer, stdin) != NULL) {
size_t len = strlen(buffer);
if (len > 0 && buffer[len-1] == '\n') {
buffer[--len] = '\0';
}
Now use buffer
and len
as needed.
This method has the side benefit of a len
value for subsequent code. It can be easily faster than strchr(Name, '\n')
. Ref YMMV, but both methods work.
buffer
, from the original fgets()
will not contain in "\n"
under some circumstances:
A) The line was too long for buffer
so only char
preceding the '\n'
is saved in buffer
. The unread characters remain in the stream.
B) The last line in the file did not end with a '\n'
.
If input has embedded null characters '\0'
in it somewhere, the length reported by strlen()
will not include the '\n'
location.
Some other answers' issues:
strtok(buffer, "\n");
fails to remove the '\n'
when buffer
is "\n"
. From this answer - amended after this answer to warn of this limitation.
The following fails on rare occasions when the first char
read by fgets()
is '\0'
. This happens when input begins with an embedded '\0'
. Then buffer[len -1]
becomes buffer[SIZE_MAX]
accessing memory certainly outside the legitimate range of buffer
. Something a hacker may try or found in foolishly reading UTF16 text files. This was the state of an answer when this answer was written. Later a non-OP edited it to include code like this answer's check for ""
.
size_t len = strlen(buffer);
if (buffer[len - 1] == '\n') { // FAILS when len == 0
buffer[len -1] = '\0';
}
sprintf(buffer,"%s",buffer);
is undefined behavior: Ref. Further, it does not save any leading, separating or trailing whitespace. Now deleted.
[Edit due to good later answer] There are no problems with the 1 liner buffer[strcspn(buffer, "\n")] = 0;
other than performance as compared to the strlen()
approach. Performance in trimming is usually not an issue given code is doing I/O - a black hole of CPU time. Should following code need the string's length or is highly performance conscious, use this strlen()
approach. Else the strcspn()
is a fine alternative.
If the autofiltering is part of a subroutine operation, you could use
BioSum.Unprotect "letmein"
'<Your function here>
BioSum.Cells(1, 1).Activate
BioSum.Protect "letmein"
to momentarily unprotect the sheet, filter the cells, and reprotect afterwards.
I just created this js function using the jQuery size function http://api.jquery.com/size/
function classCount(name){
alert($('.'+name).size())
}
It alerts out the number of times the class name occurs in the document.
Note, while the above answers are correct, if you want, you can do something like:
alert("The variable named x1 has value: " + x1);
In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:
Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase
The official answer from Facebook (http://developers.facebook.com/bugs/282710765082535):
Mikhail,
The facebook android sdk no longer supports android 1.5 and 1.6. Please upgrade to the next api version.
Good luck with your implementation.
Here's one from jQuery Validate plugin's additional-methods.js
file...
jQuery.validator.addMethod("zipUS", function(value, element) {
return /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(value);
}, "Please specify a valid US zip code.");
EDIT: Since the above code is part of the jQuery Validate plugin, it depends on the .addMethod()
method.
Remove dependency on plugins and make it more generic....
function checkZip(value) {
return (/(^\d{5}$)|(^\d{5}-\d{4}$)/).test(value);
};
Example Usage: http://jsfiddle.net/5PNcJ/
I have already upvoted the @dasblinkenlight answer since the Median of Medians algorithm in fact solves this problem in O(n) time. I only want to add that this problem could be solved in O(n) time by using heaps also. Building a heap could be done in O(n) time by using the bottom-up. Take a look to the following article for a detailed explanation Heap sort
Supposing that your array has N elements, you have to build two heaps: A MaxHeap that contains the first N/2 elements (or (N/2)+1 if N is odd) and a MinHeap that contains the remaining elements. If N is odd then your median is the maximum element of MaxHeap (O(1) by getting the max). If N is even, then your median is (MaxHeap.max()+MinHeap.min())/2 this takes O(1) also. Thus, the real cost of the whole operation is the heaps building operation which is O(n).
BTW this MaxHeap/MinHeap algorithm works also when you don't know the number of the array elements beforehand (if you have to resolve the same problem for a stream of integers for e.g). You can see more details about how to resolve this problem in the following article Median Of integer streams
There's one really important difference which is not mentioned anywhere.
take(1) emits 1, completes, unsubscribes
first() emits 1, completes, but doesn't unsubscribe.
It means that your upstream observable will still be hot after first() which is probably not expected behavior.
UPD: This referes to RxJS 5.2.0. This issue might be already fixed.
And now for direct answer: one way to check if the value for the field has changed is to fetch original data from database before saving instance. Consider this example:
class MyModel(models.Model):
f1 = models.CharField(max_length=1)
def save(self, *args, **kw):
if self.pk is not None:
orig = MyModel.objects.get(pk=self.pk)
if orig.f1 != self.f1:
print 'f1 changed'
super(MyModel, self).save(*args, **kw)
The same thing applies when working with a form. You can detect it at the clean or save method of a ModelForm:
class MyModelForm(forms.ModelForm):
def clean(self):
cleaned_data = super(ProjectForm, self).clean()
#if self.has_changed(): # new instance or existing updated (form has data to save)
if self.instance.pk is not None: # new instance only
if self.instance.f1 != cleaned_data['f1']:
print 'f1 changed'
return cleaned_data
class Meta:
model = MyModel
exclude = []
If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...
Just add this somewhere in your code:
$(document).ready(
$('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
e.preventDefault();
}),
$('[data-toggle="collapse"]').on('click', function(e) {
e.preventDefault();
$($(this).data('target')).toggleClass('in');
})
);
Any attribute can be selected using [attribute_name=value]
way.
See the sample here:
var value = $("[name='nameofobject']");
You can replace IList<DzieckoAndOpiekun> resultV
with var resultV
.
Short answer:
$ ssh-keygen -p
This will then prompt you to enter the keyfile location, the old passphrase, and the new passphrase (which can be left blank to have no passphrase).
If you would like to do it all on one line without prompts do:
$ ssh-keygen -p [-P old_passphrase] [-N new_passphrase] [-f keyfile]
Important: Beware that when executing commands they will typically be logged in your ~/.bash_history
file (or similar) in plain text including all arguments provided (i.e. the passphrases in this case). It is, therefore, is recommended that you use the first option unless you have a specific reason to do otherwise.
Notice though that you can still use -f keyfile
without having to specify -P
nor -N
, and that the keyfile defaults to ~/.ssh/id_rsa
, so in many cases, it's not even needed.
You might want to consider using ssh-agent, which can cache the passphrase for a time. The latest versions of gpg-agent also support the protocol that is used by ssh-agent.
value = value.setScale(2, RoundingMode.CEILING)
When I have a Store Procedure name, and do not know which database it belongs to, I use the following -
Use [master]
GO
DECLARE @dbname VARCHAR(50)
DECLARE @statement NVARCHAR(max)
DECLARE db_cursor CURSOR
LOCAL FAST_FORWARD
FOR
--Status 48 (mirrored db)
SELECT name FROM MASTER.dbo.sysdatabases WHERE STATUS NOT LIKE 48 AND name NOT IN ('master','model','msdb','tempdb','distribution')
OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @dbname
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @statement = 'SELECT * FROM ['+@dbname+'].INFORMATION_SCHEMA.ROUTINES WHERE [ROUTINE_NAME] LIKE ''%name_of_proc%'''+';'
print @statement
EXEC sp_executesql @statement
FETCH NEXT FROM db_cursor INTO @dbname
END
CLOSE db_cursor
DEALLOCATE db_cursor
From source machine
mysqldump --defaults-extra-file=sql.cnf database | gzip | base64 | mail [email protected]
On Destination machine. Save the received mail body as db.sql.gz.b64; then..
base64 -D -i db.sql.gz.b64 | gzip -d | mysql --defaults-extra-file=sql.cnf
Here is an algorithm finding and printing all paths from s to t using modification of DFS. Also dynamic programming can be used to find the count of all possible paths. The pseudo code will look like this:
AllPaths(G(V,E),s,t)
C[1...n] //array of integers for storing path count from 's' to i
TopologicallySort(G(V,E)) //here suppose 's' is at i0 and 't' is at i1 index
for i<-0 to n
if i<i0
C[i]<-0 //there is no path from vertex ordered on the left from 's' after the topological sort
if i==i0
C[i]<-1
for j<-0 to Adj(i)
C[i]<- C[i]+C[j]
return C[i1]
Here is code for numeric keyboard : keyboardType: TextInputType.phone When you add this code in textfield it will open numeric keyboard.
final _mobileFocus = new FocusNode();
final _mobile = TextEditingController();
TextFormField(
controller: _mobile,
focusNode: _mobileFocus,
maxLength: 10,
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
counterText: "",
counterStyle: TextStyle(fontSize: 0),
hintText: "Mobile",
border: InputBorder.none,
hintStyle: TextStyle(
color: Colors.black,
fontSize: 15.0.
),
),
style: new TextStyle(
color: Colors.black,
fontSize: 15.0,
),
);
There is a trick to have both timestamps, but with a little limitation.
You can use only one of the definitions in one table. Create both timestamp columns like so:
create table test_table(
id integer not null auto_increment primary key,
stamp_created timestamp default '0000-00-00 00:00:00',
stamp_updated timestamp default now() on update now()
);
Note that it is necessary to enter null
into both columns during insert
:
mysql> insert into test_table(stamp_created, stamp_updated) values(null, null);
Query OK, 1 row affected (0.06 sec)
mysql> select * from test_table;
+----+---------------------+---------------------+
| id | stamp_created | stamp_updated |
+----+---------------------+---------------------+
| 2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |
+----+---------------------+---------------------+
2 rows in set (0.00 sec)
mysql> update test_table set id = 3 where id = 2;
Query OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from test_table;
+----+---------------------+---------------------+
| id | stamp_created | stamp_updated |
+----+---------------------+---------------------+
| 3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 |
+----+---------------------+---------------------+
2 rows in set (0.00 sec)
Note that git branch delete only deletes the local copy, not the copy on the server. First, in the Git panel (git icon on left toolbar), look through the branches and see if your branch is still there under "origin/your_branch_name". If so, just select that and you should get your code back (suggest that you immediately copy/paste/save it locally somewhere else).
If you didn't see an "origin/your_branch_name", Install the GitLens extension. This allows you to visually poke around in the server repositories and locate the copy you synced to the server. If you have multiple repositories, note that it might be necessary to have at least one file opened from the desired repository in order to make the repository appear in GitLens. Then:
Open the GitLens panel
Expand the repository
You should see a list of categories: Branches / Contributors / Remotes / Stashes / etc
You should find YourLostTreasure under "Branches" or possibly under "Remotes -> Origins". Hopefully, you will see a branch with the desired name - if you expand it, you should see the files you changed in that branch. Double-click the file names to open them, and immediately back up that code.
If you don't immediately see your lost branch, poke around and if you find something promising, immediately open it and grab the code. I had to poke around quite a bit until I found TheGoldenBranch, and even then the code was missing the last one or two saves (possibly because I failed to sync to server before attempting-a-Branch-Merge-but-accidentally-clicking-Branch-Delete). My search was unnecessarily lengthened because when I first found the branch I wasn't completely sure the name was correct so kept looking, and it took some time to re-find that first branch. (Thus, Carpe Carpum and then keep looking.)
Content is what is passed as children. View is the template of the current component.
The view is initialized before the content and ngAfterViewInit()
is therefore called before ngAfterContentInit()
.
** ngAfterViewInit()
is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild()
hence runs fine inside it.
Example:
@Component({
selector: 'widget-three',
template: `<input #input1 type="text">`
})
export class WidgetThree{
@ViewChild('input1') input1;
constructor(private renderer:Renderer){}
ngAfterViewInit(){
this.renderer.invokeElementMethod(
this.input1.nativeElement,
'focus',
[]
)
}
}
I do not know "right" solution but I can suggest you a fast patch.
String.format("%16s", Integer.toBinaryString(1)).replace(" ", "0");
I have just tried it and saw that it works fine.
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
This is no longer an active API for google, you can try Xignite, although they charge: http://www.xignite.com
CREATE TABLE dbo.tblUsers
(
ID INT IDENTITY(1,1) NOT NULL PRIMARY KEY CLUSTERED,
UserID AS 'UID' + RIGHT('00000000' + CAST(ID AS VARCHAR(8)), 8) PERSISTED,
[Name] VARCHAR(50) NOT NULL,
)
marc_s's Answer Snap
You can also hide again advanced option after reconfigure:
-- show advanced options
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
-- enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
-- hide advanced options
EXEC sp_configure 'show advanced options', 0
GO
RECONFIGURE
GO
@dotjoe It is cheaper to update and check @@rowcount, do an insert after then fact.
Exceptions are expensive && updates are more frequent
Suggestion: If you want to be uber performant in your DAL, make the front end pass in a unique ID for the row to be updated, if null insert.
The DALs should be CRUD, and not need to worry about being stateless.
If you make it stateless, With good indexes, you will not see a diff with the following SQL vs 1 statement. IF (select top 1 * form x where PK=@ID) Insert else update
Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page.
But after adding below code in my server.js
file it is save my day but it's not a proper solution or not a good way .
app.use(function(req, res, next){
var d = res.status(404);
if(d){
res.sendfile('index.html');
}
});
Strings don't encapsulate color information. Are you thinking of setting the color in a console or in the GUI?
There's no special case for String
, because String
is an ordinary referential type on JVM, in contrast with Java primitives (int
, double
, ...) -- storing them in a reference Array<T>
requires boxing them into objects like Integer
and Double
. The purpose of specialized arrays like IntArray
in Kotlin is to store non-boxed primitives, getting rid of boxing and unboxing overhead (the same as Java int[]
instead of Integer[]
).
You can use Array<String>
(and Array<String?>
for nullables), which is equivalent to String[]
in Java:
val stringsOrNulls = arrayOfNulls<String>(10) // returns Array<String?>
val someStrings = Array<String>(5) { "it = $it" }
val otherStrings = arrayOf("a", "b", "c")
See also: Arrays in the language reference
Make sure everything is pushed up to your remote repository (GitHub):
git checkout main
Overwrite "main" with "better_branch":
git reset --hard better_branch
Force the push to your remote repository:
git push -f origin main
I had a mismatch between projects: one with multi-byte character set, the other with Unicode. Correcting these to agree on Unicode corrected the problem.
To find the last non-empty cell you can use INDEX
and MATCH
functions like this:
=DAYS360(A2; INDEX(A:A; MATCH(99^99;A:A; 1)))
I think this is a little bit faster and easier.
To get rid use array_unique()
. To detect if have any use count(array_unique())
and compare to count($array)
.
In that case, it isn't space that is in prefix/suffix.
The 1st row looks OK. Do the following for the contents of 2nd row.
ASCII(RIGHT(ProductAlternateKey, 1))
and
ASCII(LEFT(ProductAlternateKey, 1))
JLS§14.14.1, The basic for Statement, makes it clear that the ForUpdate expression(s) are evaluated and the value(s) are discarded. The effect is to make the two forms identical in the context of a for
statement.
Here's an example in C# (cause that's what I was searching for). I needed to split a 23 GB csv-file with around 175 million lines to be able to look at the files. I split it into files of one million rows each. This code did it in about 5 minutes on my machine:
var list = new List<string>();
var fileSuffix = 0;
using (var file = File.OpenRead(@"D:\Temp\file.csv"))
using (var reader = new StreamReader(file))
{
while (!reader.EndOfStream)
{
list.Add(reader.ReadLine());
if (list.Count >= 1000000)
{
File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);
list = new List<string>();
}
}
}
File.WriteAllLines(@"D:\Temp\split" + (++fileSuffix) + ".csv", list);
It depends.
Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
You get SyntaxError
error exception because Python has no &&
operator. It has and
and &
where the latter one is the correct choice to create boolean expressions on Column
(|
for a logical disjunction and ~
for logical negation).
Condition you created is also invalid because it doesn't consider operator precedence. &
in Python has a higher precedence than ==
so expression has to be parenthesized.
(col("Age") == "") & (col("Survived") == "0")
## Column<b'((Age = ) AND (Survived = 0))'>
On a side note when
function is equivalent to case
expression not WHEN
clause. Still the same rules apply. Conjunction:
df.where((col("foo") > 0) & (col("bar") < 0))
Disjunction:
df.where((col("foo") > 0) | (col("bar") < 0))
You can of course define conditions separately to avoid brackets:
cond1 = col("Age") == ""
cond2 = col("Survived") == "0"
cond1 & cond2
Pass multiple -v
arguments.
For instance:
docker -v /on/my/host/1:/on/the/container/1 \
-v /on/my/host/2:/on/the/container/2 \
...
Some blogs/websites to check out:
Currently, Josh Smith has a "From Russia With Love" article that can be of some use to you.
I suggest Oj as it is waaaaaay faster than the standard JSON library.
For people reading this that use Angular 2 rc4 or later, it appears LocationStrategy has been moved from router to common. You'll have to import it from there.
Also note the curly brackets around the 'provide' line.
main.ts
// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';
// The usual bootstrapping imports
import { bootstrap } from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent } from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
HTTP_PROVIDERS,
{provide: LocationStrategy, useClass: HashLocationStrategy}
]);
It gives you the remainder of a division.
int c=11, d=5;
cout << (c/d) * d + c % d; // gives you the value of c
const styles = theme => ({_x000D_
contentClass:{_x000D_
overflow: 'hidden',_x000D_
textOverflow: 'ellipsis',_x000D_
display: '-webkit-box',_x000D_
WebkitLineClamp:1,_x000D_
WebkitBoxOrient:'vertical'_x000D_
} _x000D_
})
_x000D_
render () {_x000D_
return(_x000D_
<div className={classes.contentClass}>_x000D_
{'content'}_x000D_
</div>_x000D_
)_x000D_
}
_x000D_
A really simple implementation is:
out = "".join(c for c in asking if c not in ('!','.',':'))
and keep adding any other types of punctuation.
A more efficient way would be
import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)
Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python
Sure, simply bind multiple listeners to it.
Short cutting with jQuery
$("#id").bind("click", function() {_x000D_
alert("Event 1");_x000D_
});_x000D_
$(".foo").bind("click", function() {_x000D_
alert("Foo class");_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="foo" id="id">Click</div>
_x000D_
In additions, now it is possible to do with class
and static
'use strict'
class Foo {
static talk() {
console.log('talk')
};
speak() {
console.log('speak')
};
};
will give
var a = new Foo();
Foo.talk(); // 'talk'
a.talk(); // err 'is not a function'
a.speak(); // 'speak'
Foo.speak(); // err 'is not a function'
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new URL("http://example.com:80/docs/books/tutorial"
+ "/index.html?name=networking#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol()); //http
System.out.println("authority = " + aURL.getAuthority()); //example.com:80
System.out.println("host = " + aURL.getHost()); //example.com
System.out.println("port = " + aURL.getPort()); //80
System.out.println("path = " + aURL.getPath()); // /docs/books/tutorial/index.html
System.out.println("query = " + aURL.getQuery()); //name=networking
System.out.println("filename = " + aURL.getFile()); ///docs/books/tutorial/index.html?name=networking
System.out.println("ref = " + aURL.getRef()); //DOWNLOADING
}
}
[C++]
I agree with the "use it when you have to" brigade. Decorating code unnecessarily with this isn't a great idea because the compiler won't warn you when you forget to do it. This introduces potential confusion for people expecting this to always be there, i.e. they'll have to think about it.
So, when would you use it? I've just had a look around some random code and found these examples (I'm not passing judgement on whether these are good things to do or otherwise):
Use CURRENT_TIMESTAMP
when you need it, instead OF NOW()
(which is MySQL)
If you have a string like this: '123456' and you want a list of integers like this: [1,2,3,4,5,6], use this:
>>>s = '123456'
>>>list1 = [int(i) for i in list(s)]
>>>print(list1)
[1,2,3,4,5,6]
or if you want a list of strings like this: ['1','2','3','4','5','6'], use this:
>>>s = '123456'
>>>list1 = list(s)
>>>print(list1)
['1','2','3','4','5','6']
For anyone using entity framework core ending up here. This is how you do it.
# Powershell / Package manager console
Script-Migration
# Cli
dotnet ef migrations script
You can use the -From
and -To
parameter to generate an update script to update a database to a specific version.
Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2
https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts
There are several options to this command.
The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify
0
(this is the default).The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.
An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.
This situation calls for some preprocessor. Because if you write a function (static method) which picks the first not null value, it evaluates all items. It is problem if some items are method calls (may be time expensive method calls). And this methods are called even if any item before them is not null.
Some function like this
public static <T> T coalesce(T ...items) …
should be used but before compiling into byte code there should be a preprocessor which find usages of this „coalesce function“ and replaces it with construction like
a != null ? a : (b != null ? b : c)
Update 2014-09-02:
Thanks to Java 8 and Lambdas there is possibility to have true coalesce in Java! Including the crucial feature: particular expressions are evaluated only when needed – if earlier one is not null, then following ones are not evaluated (methods are not called, computation or disk/network operations are not done).
I wrote an article about it Java 8: coalesce – hledáme neNULLové hodnoty – (written in Czech, but I hope that code examples are understandable for everyone).
You can now use In app review API provided by Google out of the box.
First, in your build.gradle(app)
file, add following dependencies (full setup can be found here)
dependencies {
// This dependency is downloaded from the Google’s Maven repository.
// So, make sure you also include that repository in your project's build.gradle file.
implementation 'com.google.android.play:core:1.8.0'
}
Add this method to your Activity
:
void askRatings() {
ReviewManager manager = ReviewManagerFactory.create(this);
Task<ReviewInfo> request = manager.requestReviewFlow();
request.addOnCompleteListener(task -> {
if (task.isSuccessful()) {
// We can get the ReviewInfo object
ReviewInfo reviewInfo = task.getResult();
Task<Void> flow = manager.launchReviewFlow(this, reviewInfo);
flow.addOnCompleteListener(task2 -> {
// The flow has finished. The API does not indicate whether the user
// reviewed or not, or even whether the review dialog was shown. Thus, no
// matter the result, we continue our app flow.
});
} else {
// There was some problem, continue regardless of the result.
}
});
}
And then you can simply call it using
askRatings();
There is a new NuGet package that contains the System.Windows.Interactivity.dll that is compatible with:
To install Expression.Blend.Sdk, run the following command in the Package Manager Console
PM> Install-Package Expression.Blend.Sdk
I finally figured out the regex to change these all in old Python2 example scripts. Otherwise use 2to3.py.
Try it out on Regexr.com, doesn't work in NP++(?):
find: (?<=print)( ')(.*)(')
replace: ('$2')
for variables:
(?<=print)( )(.*)(\n)
('$2')\n
for label and variable:
(?<=print)( ')(.*)(',)(.*)(\n)
('$2',$4)\n
When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.
You are asking for the value at key 0
of $votes
. It is an array that does not contain that key.
The array $votes
is not set, so when PHP is trying to access the key 0
of the array, it encounters an undefined offset for [0] and [1] and throws the error.
If you have an array:
$votes = array('1','2','3');
We can now access:
$votes[0];
$votes[1];
$votes[2];
If we try and access:
$votes[3];
We will get the error "Notice: Undefined offset: 3"
Note that you can also hit this error if you accidentally type:
#define <stdio.h>
...instead of...
#include <stdio.>
using a function:
function run_command ($command)
{
invoke-expression "$command *>$null"
return $_
}
if (!(run_command "dir *.txt"))
{
if (!(run_command "dir *.doc"))
{
run_command "dir *.*"
}
}
or if you like one-liners:
function run_command ($command) { invoke-expression "$command "|out-null; return $_ }
if (!(run_command "dir *.txt")) { if (!(run_command "dir *.doc")) { run_command "dir *.*" } }
Tried all solutions here but these 2 steps solved the issue:
1) manual update of open-ssl from here:
https://slproweb.com/products/Win32OpenSSL.html
2) update OpenSSL using conda update openssl
command in the Anaconda Prompt
solved the issue!
context.Authors.Where(a => a.Books.Any(b => b.BookID == bookID)).ToList();
a.Books
is the list of books by that author. The property is automatically created by Linq-to-Sql, provided you have a foreign-key relationship set up.
So, a.Books.Any(b => b.BookID == bookID)
translates to "Do any of the books by this author have an ID of bookID", which makes the complete expression "Who are the authors of the book with id bookID?"
That could also be written something like
from a in context.Authors
join b in context.Books on a.AuthorId equal b.AuthorID
where b.BookID == bookID
select a;
UPDATE:
Any()
as far as I know, only returns a bool
. Its effective implementation is:
public Any(this IEnumerable<T> coll, Func<T, bool> predicate)
{
foreach(T t in coll)
{
if (predicte(t))
return true;
}
return false;
}
If you use eclipse (Eclipse can put utf8 code for you even you write utf8 character. You will see normal utf8 character when you programming but background will be utf8 code) ;
P.S : this will ok if you static value in code. For Example String test = "IIIIIiiiiiiççççç";
I had the same error for a different package. My problem was that a dependent project was referencing a different version. I changed them to be the same version and all was good.
If your project uses Guava (14.0 or newer), you can go with Files.getNameWithoutExtension()
.
(Essentially the same as FilenameUtils.removeExtension()
from Apache Commons IO, as the highest-voted answer suggests. Just wanted to point out Guava does this too. Personally I didn't want to add dependency to Commons—which I feel is a bit of a relic—just because of this.)
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
This is a three liner. Just follow the instructions on the boto3 documentation.
import boto3
s3 = boto3.resource(service_name = 's3')
s3.meta.client.upload_file(Filename = 'C:/foo/bar/baz.filetype', Bucket = 'yourbucketname', Key = 'baz.filetype')
Some important arguments are:
Parameters:
str
) -- The path to the file to upload.str
) -- The name of the bucket to upload to.
str
) -- The name of the that you want to assign to your file in your s3 bucket. This could be the same as the name of the file or a different name of your choice but the filetype should remain the same.
Note: I assume that you have saved your credentials in a ~\.aws
folder as suggested in the best configuration practices in the boto3 documentation.
data = pd.read_csv('your_dataset.tsv', delimiter = '\t', quoting = 3)
You can use a delimiter to separate data, quoting = 3 helps to clear quotes in datasst
This little example shows how the $rootScope
emit a event that will be listen by a children scope in another controller.
(function(){
angular
.module('ExampleApp',[]);
angular
.module('ExampleApp')
.controller('ExampleController1', Controller1);
Controller1.$inject = ['$rootScope'];
function Controller1($rootScope) {
var vm = this,
message = 'Hi my children scope boy';
vm.sayHi = sayHi;
function sayHi(){
$rootScope.$broadcast('greeting', message);
}
}
angular
.module('ExampleApp')
.controller('ExampleController2', Controller2);
Controller2.$inject = ['$scope'];
function Controller2($scope) {
var vm = this;
$scope.$on('greeting', listenGreeting)
function listenGreeting($event, message){
alert(['Message received',message].join(' : '));
}
}
})();
http://codepen.io/gpincheiraa/pen/xOZwqa
The answer of @gayathri bottom explain technically the differences of all those methods in the scope angular concept and their implementations $scope
and $rootScope
.
Another script variant avoiding the loop in shell:
#!/bin/bash
grep VmSwap /proc/[0-9]*/status | awk -F':' -v sort="$1" '
{
split($1,pid,"/") # Split first field on /
split($3,swp," ") # Split third field on space
cmdlinefile = "/proc/"pid[3]"/cmdline" # Build the cmdline filepath
getline pname[pid[3]] < cmdlinefile # Get the command line from pid
swap[pid[3]] = sprintf("%6i %s",swp[1],swp[2]) # Store the swap used (with unit to avoid rebuilding at print)
sum+=swp[1] # Sum the swap
}
END {
OFS="\t" # Change the output separator to tabulation
print "Pid","Swap used","Command line" # Print header
if(sort) {
getline max_pid < "/proc/sys/kernel/pid_max"
for(p=1;p<=max_pid;p++) {
if(p in pname) print p,swap[p],pname[p] # print the values
}
} else {
for(p in pname) { # Loop over all pids found
print p,swap[p],pname[p] # print the values
}
}
print "Total swap used:",sum # print the sum
}'
Standard usage is script.sh
to get the usage per program with random order (down to how awk
stores its hashes) or script.sh 1
to sort the output by pid.
I hope I've commented the code enough to tell what it does.
If you're using Python, you can define your environment variables in a .env
file and load them from within a Jupyter notebook using python-dotenv.
Install python-dotenv:
pip install python-dotenv
Load the .env
file in a Jupyter notebook:
%load_ext dotenv
%dotenv
You can use the simple soupparser
from lxml
from lxml.html.soupparser import fromstring
tree = fromstring("<a>Find me!</a>")
print tree.xpath("//a/text()")
When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).
During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information
Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.
A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).
A)whenever getSession() is called on HttpServletRequest object
Step 1: request object is evaluated for incoming session ID.
Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).
Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.
Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.
1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine
2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code
A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.
Simplejson 2.1 and higher has native support for Decimal type:
>>> json.dumps(Decimal('3.9'), use_decimal=True)
'3.9'
Note that use_decimal
is True
by default:
def dumps(obj, skipkeys=False, ensure_ascii=True, check_circular=True,
allow_nan=True, cls=None, indent=None, separators=None,
encoding='utf-8', default=None, use_decimal=True,
namedtuple_as_object=True, tuple_as_array=True,
bigint_as_string=False, sort_keys=False, item_sort_key=None,
for_json=False, ignore_nan=False, **kw):
So:
>>> json.dumps(Decimal('3.9'))
'3.9'
Hopefully, this feature will be included in standard library.
Your code doesn't get the UTF-8 into memory as you read it back into a string again, so its no longer in UTF-8, but back in UTF-16 (though ideally its best to consider strings at a higher level than any encoding, except when forced to do so).
To get the actual UTF-8 octets you could use:
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
var memoryStream = new MemoryStream();
var streamWriter = new StreamWriter(memoryStream, System.Text.Encoding.UTF8);
serializer.Serialize(streamWriter, entry);
byte[] utf8EncodedXml = memoryStream.ToArray();
I've left out the same disposal you've left. I slightly favour the following (with normal disposal left in):
var serializer = new XmlSerializer(typeof(SomeSerializableObject));
using(var memStm = new MemoryStream())
using(var xw = XmlWriter.Create(memStm))
{
serializer.Serialize(xw, entry);
var utf8 = memStm.ToArray();
}
Which is much the same amount of complexity, but does show that at every stage there is a reasonable choice to do something else, the most pressing of which is to serialise to somewhere other than to memory, such as to a file, TCP/IP stream, database, etc. All in all, it's not really that verbose.
It's not good for several reasons:
eval
The simplest thing would be to add a name
attribute to your <a>
element, then you could do:
document.myelement.onclick = function() {
window.popup('/map/', 300, 300, 'map');
return false;
};
although modern best practise would be to use an id
instead of a name, and use addEventListener()
instead of using onclick
since that allows you to bind multiple functions to a single event.
NSString * formattedname;
NSString * firstname;
NSString * middlename;
NSString * lastname;
firstname = @"My First Name";
middlename = @"My Middle Name";
lastname = @"My Last Name";
formattedname = [NSString stringWithFormat:@"My Full Name: %@ %@ %@", firstname, middlename, lastname];
NSLog(@"\n\nHere is the Formatted Name:\n%@\n\n", formattedname);
/*
Result:
Here is the Formatted Name:
My Full Name: My First Name My Middle Name My Last Name
*/
in java when you set a value to variable, it return new value. So
private boolean getValue()
{
return value = !value;
}
I can see it's an old question, if you want to put other HTML inside could use the radiobutton with GroupName propery same in all radiobuttons and in the Text property set something like an image or the html you need.
<asp:RadioButton GroupName="group1" runat="server" ID="paypalrb" Text="<img src='https://www.paypalobjects.com/webstatic/mktg/logo/bdg_secured_by_pp_2line.png' border='0' alt='Secured by PayPal' style='width: 103px; height: 61px; padding:10px;'>" />
<input type="file">
with a <label>
tag;<span>
or <a>
;input[type="file"]
invisible via display: none
.You can try with this code
var result = (from item in List
select new
{
EmpLoc = item.empLoc,
EmpPL= item.empPL,
EmpShift= item.empShift
})
.ToList()
.Distinct();
I don't know why the answer seem so complicated... It seems pretty simple to do this with ps
:
mem()
{
ps -eo rss,pid,euser,args:100 --sort %mem | grep -v grep | grep -i $@ | awk '{printf $1/1024 "MB"; $1=""; print }'
}
Example usage:
$ mem mysql
0.511719MB 781 root /bin/sh /usr/bin/mysqld_safe
0.511719MB 1124 root logger -t mysqld -p daemon.error
2.53516MB 1123 mysql /usr/sbin/mysqld --basedir=/usr --datadir=/var/lib/mysql --plugin-dir=/usr/lib/mysql/plugin --user=mysql --pid-file=/var/run/mysqld/mysqld.pid --socket=/var/run/mysqld/mysqld.sock --port=3306
We can use the following shortcut in the latest version of notepad++ for formatting the code
Alt + Ctrl + Shift + B
Apache FileUtil gives very handy methods to do the conversion
try {
File file = new File(imagefilePath);
byte[] byteArray = new byte[file.length()]();
byteArray = FileUtils.readFileToByteArray(file);
}catch(Exception e){
e.printStackTrace();
}
This would also work but is less eloquent than the plyr solution:
x <- sapply(split(myvec, myvec$name), function(x) length(unique(x[, 2])))
data.frame(names=names(x), number_of_distinct_orders=x, row.names = NULL)
Most of the existing answers here are impractical because they totally ignore the real-world usage of addresses like:
First, a digression into terminology. What are these addresses? Are they valid URLs?
Historically, the answer was "no". According to RFC 3986, from 2005, such addresses are not URIs (and therefore not URLs, since URLs are a type of URIs). Per the terminology of 2005 IETF standards, we should properly call them IRIs (Internationalized Resource Identifiers), as defined in RFC 3987, which are technically not URIs but can be converted to URIs simply by percent-encoding all non-ASCII characters in the IRI.
Per modern spec, the answer is "yes". The WHATWG Living Standard simply classifies everything that would previously be called "URIs" or "IRIs" as "URLs". This aligns the specced terminology with how normal people who haven't read the spec use the word "URL", which was one of the spec's goals.
Per this newer meaning of "URL", what characters are allowed? In many parts of the URL, such as the query string and path, we're allowed to use arbitrary "URL units", which are
What are "URL code points"?
The URL code points are ASCII alphanumeric, U+0021 (!), U+0024 ($), U+0026 (&), U+0027 ('), U+0028 LEFT PARENTHESIS, U+0029 RIGHT PARENTHESIS, U+002A (*), U+002B (+), U+002C (,), U+002D (-), U+002E (.), U+002F (/), U+003A (:), U+003B (;), U+003D (=), U+003F (?), U+0040 (@), U+005F (_), U+007E (~), and code points in the range U+00A0 to U+10FFFD, inclusive, excluding surrogates and noncharacters.
(Note that the list of "URL code points" doesn't include %
, but that %
s are allowed in "URL code units" if they're part of a percent-encoding sequence.)
The only place I can spot where the spec permits the use of any character that's not in this set is in the host, where IPv6 addresses are enclosed in [
and ]
characters. Everywhere else in the URL, either URL units are allowed or some even more restrictive set of characters.
For the sake of history, and since it's not explored fully elsewhere in the answers here, let's examine was allowed under the older pair of specs.
First of all, we have two types of RFC 3986 reserved characters:
:/?#[]@
, which are part of the generic syntax for a URI defined in RFC 3986!$&'()*+,;=
, which aren't part of the RFC's generic syntax, but are reserved for use as syntactic components of particular URI schemes. For instance, semicolons and commas are used as part of the syntax of data URIs, and &
and =
are used as part of the ubiquitous ?foo=bar&qux=baz
format in query strings (which isn't specified by RFC 3986).Any of the reserved characters above can be legally used in a URI without encoding, either to serve their syntactic purpose or just as literal characters in data in some places where such use could not be misinterpreted as the character serving its syntactic purpose. (For example, although /
has syntactic meaning in a URL, you can use it unencoded in a query string, because it doesn't have meaning in a query string.)
RFC 3986 also specifies some unreserved characters, which can always be used simply to represent data without any encoding:
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~
Finally, the %
character itself is allowed for percent-encodings.
That leaves only the following ASCII characters that are forbidden from appearing in a URL:
"<>\^`{|}
Every other character from ASCII can legally feature in a URL.
Then RFC 3987 extends that set of unreserved characters with the following unicode character ranges:
%xA0-D7FF / %xF900-FDCF / %xFDF0-FFEF
/ %x10000-1FFFD / %x20000-2FFFD / %x30000-3FFFD
/ %x40000-4FFFD / %x50000-5FFFD / %x60000-6FFFD
/ %x70000-7FFFD / %x80000-8FFFD / %x90000-9FFFD
/ %xA0000-AFFFD / %xB0000-BFFFD / %xC0000-CFFFD
/ %xD0000-DFFFD / %xE1000-EFFFD
These block choices from the old spec seem bizarre and arbitrary given the latest Unicode block definitions; this is probably because the blocks have been added to in the decade since RFC 3987 was written.
Finally, it's perhaps worth noting that simply knowing which characters can legally appear in a URL isn't sufficient to recognise whether some given string is a legal URL or not, since some characters are only legal in particular parts of the URL. For example, the reserved characters [
and ]
are legal as part of an IPv6 literal host in a URL like http://[1080::8:800:200C:417A]/foo but aren't legal in any other context, so the OP's example of http://example.com/file[/].html
is illegal.
Well, I added
<policy domain="coder" rights="read | write" pattern="PDF" />
just before </policymap>
in /etc/ImageMagick-7/policy.xml
and that makes it work again, but not sure about the security implications of that.
Wait function using timers, no UI locks.
public void wait(int milliseconds)
{
var timer1 = new System.Windows.Forms.Timer();
if (milliseconds == 0 || milliseconds < 0) return;
// Console.WriteLine("start wait timer");
timer1.Interval = milliseconds;
timer1.Enabled = true;
timer1.Start();
timer1.Tick += (s, e) =>
{
timer1.Enabled = false;
timer1.Stop();
// Console.WriteLine("stop wait timer");
};
while (timer1.Enabled)
{
Application.DoEvents();
}
}
Usage: just placing this inside your code that needs to wait:
wait(1000); //wait one second
I ran into this where the scripts would load once, but repeat calls would not run the script.
It turned out to be an issue with using .html() to display a wait indicator and then chaining .load() after it.
// Processes scripts as expected once per page load, but not for repeat calls
$("#id").html("<img src=wait.gif>").load("page.html");
When I made them separate calls, my inline scripts loaded every time as expected.
// Without chaining html and load together, scripts are processed as expected every time
$("#id").html("<img src=wait.gif>");
$("#id").load("page.html");
For further research, note that there are two versions of .load()
A simple .load() call (without a selector after the url) is simply a shorthand for calling $.ajax() with dataType:"html" and taking the return contents and calling .html() to put those contents in the DOM. And the documentation for dataType:"html" clearly states "included script tags are evaluated when inserted in the DOM." http://api.jquery.com/jquery.ajax/ So .load() officially runs inline scripts.
A complex .load() call has a selector such as load("page.html #content"). When used that way, jQuery purposefully filters out script tags as discussed in articles like this one: https://forum.jquery.com/topic/the-load-function-and-script-blocks#14737000000752785 In this case the scripts never run, not even once.
In the command line type service apache2 status
then hit enter. The result should say:
Apache2 is running (pid xxxx)
-(IBAction)SegmentbtnCLK:(id)sender
{ [self sortArryofDictionary];
[self.objtable reloadData];}
-(void)sortArryofDictionary
{ NSSortDescriptor *sorter;
switch (sortcontrol.selectedSegmentIndex)
{case 0:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Name" ascending:YES];
break;
case 1:
sorter=[[NSSortDescriptor alloc]initWithKey:@"Age" ascending:YES];
default:
break; }
NSArray *sortdiscriptor=[[NSArray alloc]initWithObjects:sorter, nil];
[arr sortUsingDescriptors:sortdiscriptor];
}
My guess is that something is either encoding or decoding too often - or that you've got text with multiple lines in.
Base64 strings have to be a multiple of 4 characters in length - every 4 characters represents 3 bytes of input data. Somehow, the view state data being passed back by ASP.NET is corrupted - the length isn't a multiple of 4.
Do you log the user agent when this occurs? I wonder whether it's a badly-behaved browser somewhere... another possibility is that there's a proxy doing naughty things. Likewise try to log the content length of the request, so you can see whether it only happens for large requests.
For some reason, you're re-instantiating the form after you check is_valid()
. Forms only get a cleaned_data
attribute when is_valid()
has been called, and you haven't called it on this new, second instance.
Just get rid of the second form = SearchForm(request.POST)
and all should be well.
If you want to be very permissive, required only two final digits with comma or dot:
^([,.\d]+)([,.]\d{2})$
if variable b has a list then you can simply do the below:
create a new variable "a" as: a=[]
then assign the list to "a" as: a=b
now "a" has all the components of list "b" in array.
so you have successfully converted list to array.
Somebody wrote a blog post about this a few years back. There are examples in several languages, using both WebKit and Mozilla. There's also an example in Ruby.
It boils down to this: decide how wide you want your window to be; put a browser component in the window; wait until the page loads; capture the pixel buffer contents.
In ECMAScript 6 (aka ECMAScript 2015), Set
can be used to filter out duplicates. Then it can be converted back to an array using the spread operator.
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"],
unique = [...new Set(names)];
You can do this with animation-keyframe rather than transition. Change your hover declaration and add the animation keyframe, you might also need to add browser prefixes for -moz- and -webkit-. See https://developer.mozilla.org/en/docs/Web/CSS/@keyframes for more detailed info.
nav.main ul ul {_x000D_
position: absolute;_x000D_
list-style: none;_x000D_
display: none;_x000D_
opacity: 0;_x000D_
visibility: hidden;_x000D_
padding: 10px;_x000D_
background-color: rgba(92, 91, 87, 0.9);_x000D_
-webkit-transition: opacity 600ms, visibility 600ms;_x000D_
transition: opacity 600ms, visibility 600ms;_x000D_
}_x000D_
_x000D_
nav.main ul li:hover ul {_x000D_
display: block;_x000D_
visibility: visible;_x000D_
opacity: 1;_x000D_
animation: fade 1s;_x000D_
}_x000D_
_x000D_
@keyframes fade {_x000D_
0% {_x000D_
opacity: 0;_x000D_
}_x000D_
_x000D_
100% {_x000D_
opacity: 1;_x000D_
}_x000D_
}
_x000D_
<nav class="main">_x000D_
<ul>_x000D_
<li>_x000D_
<a href="">Lorem</a>_x000D_
<ul>_x000D_
<li><a href="">Ipsum</a></li>_x000D_
<li><a href="">Dolor</a></li>_x000D_
<li><a href="">Sit</a></li>_x000D_
<li><a href="">Amet</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>_x000D_
</nav>
_x000D_
Here is an update on your fiddle. https://jsfiddle.net/orax9d9u/1/
List is an Interface . You cant use List to initialize it.
List<String> supplierNames = new ArrayList<String>();
These are the some of List impelemented classes,
ArrayList, LinkedList, Vector
You could use any of this as per your requirement. These each classes have its own features.
I've faced same problem and came across to this thread but my problem was with upstream
. Below git command worked for me.
git checkout {remoteName}/{branch} -- {../path/file.js}
git checkout upstream/develop -- public/js/index.js
String g1="Male";
String g2="Female";
String salutation="";
String gender="Male";
if(gender.toLowerCase().trim().equals(g1.toLowerCase().trim()));
salutation ="Mr.";
if(gender.toLowerCase().trim().equals(g2.toLowerCase().trim()));
salutation ="Ms.";
Always call dispose. It is not worth the risk. Big managed enterprise applications should be treated with respect. No assumptions can be made or else it will come back to bite you.
Don't listen to leppie.
A lot of objects don't actually implement IDisposable, so you don't have to worry about them. If they genuinely go out of scope they will be freed automatically. Also I have never come across the situation where I have had to set something to null.
One thing that can happen is that a lot of objects can be held open. This can greatly increase the memory usage of your application. Sometimes it is hard to work out whether this is actually a memory leak, or whether your application is just doing a lot of stuff.
Memory profile tools can help with things like that, but it can be tricky.
In addition always unsubscribe from events that are not needed. Also be careful with WPF binding and controls. Not a usual situation, but I came across a situation where I had a WPF control that was being bound to an underlying object. The underlying object was large and took up a large amount of memory. The WPF control was being replaced with a new instance, and the old one was still hanging around for some reason. This caused a large memory leak.
In hindsite the code was poorly written, but the point is that you want to make sure that things that are not used go out of scope. That one took a long time to find with a memory profiler as it is hard to know what stuff in memory is valid, and what shouldn't be there.
To get a meaningful/useful view of the two tables, you normally need to determine an identifying field from each table that can then be used in the ON clause in a JOIN.
THen in your view:
SELECT T1.*, T2.* FROM T1 JOIN T2 ON T1.IDFIELD1 = T2.IDFIELD2
You mention no fields are "common", but although the identifying fields may not have the same name or even be the same data type, you could use the convert / cast functions to join them in some way.
Some of the system headers provide a forward declaration of std::stringstream
without the definition. This makes it an 'incomplete type'. To fix that you need to include the definition, which is provided in the <sstream>
header:
#include <sstream>
Using dplyr
:
require(dplyr)
df <- data.frame(A = c(1, 1, 2, 3, 3), B = c(2, 3, 3, 5, 6))
df %>% group_by(A) %>% summarise(B = sum(B))
## Source: local data frame [3 x 2]
##
## A B
## 1 1 5
## 2 2 3
## 3 3 11
With sqldf
:
library(sqldf)
sqldf('SELECT A, SUM(B) AS B FROM df GROUP BY A')
After looking at most of the StackOverflow posts on different ways to achieve this using a TextWatcher
, InputFilter
, or library like CurrencyEditText I've settled on this simple solution using an OnFocusChangeListener
.
The logic is to parse the EditText
to a number when it is focused and to format it back when it loses focus.
amount.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
Number numberAmount = 0f;
try {
numberAmount = Float.valueOf(amount.getText().toString());
} catch (NumberFormatException e1) {
e1.printStackTrace();
try {
numberAmount = NumberFormat.getCurrencyInstance().parse(amount.getText().toString());
} catch (ParseException e2) {
e2.printStackTrace();
}
}
if (hasFocus) {
amount.setText(numberAmount.toString());
} else {
amount.setText(NumberFormat.getCurrencyInstance().format(numberAmount));
}
}
});
I have written a small module to do just that, called timexe:
Install:
npm install timexe
use:
var timexe = require('timexe');
//Every 30 sec
var res1=timexe(”* * * * * /30”, function() console.log(“Its time again”)});
//Every minute
var res2=timexe(”* * * * *”,function() console.log(“a minute has passed”)});
//Every 7 days
var res3=timexe(”* y/7”,function() console.log(“its the 7th day”)});
//Every Wednesdays
var res3=timexe(”* * w3”,function() console.log(“its Wednesdays”)});
// Stop "every 30 sec. timer"
timexe.remove(res1.id);
you can achieve start/stop functionality by removing/re-adding the entry directly in the timexe job array. But its not an express function.
As of .NET Core 2.0, the constructor Dictionary<TKey,TValue>(IEnumerable<KeyValuePair<TKey,TValue>>)
now exists.
You can iterate DataTable
like this:
private void button1_Click(object sender, EventArgs e)
{
for(int i = 0; i< dt.Rows.Count;i++)
for (int j = 0; j <dt.Columns.Count ; j++)
{
object o = dt.Rows[i].ItemArray[j];
//if you want to get the string
//string s = o = dt.Rows[i].ItemArray[j].ToString();
}
}
Depending on the type of the data in the DataTable
cell, you can cast the object to whatever you want.
Here's extension method to convert DataTable to object list:
public static class Extensions
{
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item,day,null);
}
else
{
if(row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
}
usage:
List<Employee> lst = ds.Tables[0].ToList<Employee>();
@itay.b
CODE EXPLAINED:
We first read all the property names from the class T using reflection
then we iterate through all the rows in datatable and create new object of T,
then we set the properties of the newly created object using reflection.
The property values are picked from the row's matching column cell.
PS: class property name and table column names must be same
This is an alternative solution, but one could argue it doesn't add enough value to make it worth it:
import com.google.common.collect.Iterables;
...
Iterator<String> iter = Iterables.cycle(list).iterator();
if(iter.hasNext()) {
str = iter.next();
}
Calling hasNext() will reset the iterator cursor to the beginning if it's a the end.
I just needed a simple testing button for react.js. Here is what I did and it worked.
function Testing(){
var f=function testing(){
console.log("Testing Mode activated");
UserData.authenticated=true;
UserData.userId='123';
};
console.log("Testing Mode");
return (<div><button onClick={f}>testing</button></div>);
}
You can also check user by id
command.
id -u name
gives you the id of that user.
if the user doesn't exist, you got command return value ($?
)1
And as other answers pointed out: if all you want is just to check if the user exists, use if
with id
directly, as if
already checks for the exit code. There's no need to fiddle with strings, [
, $?
or $()
:
if id "$1" &>/dev/null; then
echo 'user found'
else
echo 'user not found'
fi
(no need to use -u
as you're discarding the output anyway)
Also, if you turn this snippet into a function or script, I suggest you also set your exit code appropriately:
#!/bin/bash
user_exists(){ id "$1" &>/dev/null; } # silent, it just sets the exit code
if user_exists "$1"; code=$?; then # use the function, save the code
echo 'user found'
else
echo 'user not found' >&2 # error messages should go to stderr
fi
exit $code # set the exit code, ultimately the same set by `id`
Although the following is not way to do it in GUI but you can get autoincrementing simply using the IDENTITY datatype(start, increment):
CREATE TABLE "dbo"."TableName"
(
id int IDENTITY(1,1) PRIMARY KEY NOT NULL,
name varchar(20),
);
the insert statement should list all columns except the id column (it will be filled with autoincremented value):
INSERT INTO "dbo"."TableName" (name) VALUES ('alpha');
INSERT INTO "dbo"."TableName" (name) VALUES ('beta');
and the result of
SELECT id, name FROM "dbo"."TableName";
will be
id name
--------------------------
1 alpha
2 beta
Something like this?
<div onclick="alert('test');">
</div>
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
There is no way to know unless the particular company reveals the info. The best you can do is find a few companies that are sharing and then extrapolate based on app ranking (which is available publicly). The best you'll get is a ball park estimate.
ES6:
let csv = test_array.map(row=>row.join(',')).join('\n')
//test_array being your 2D array
You can specify the whole day by doing a range, like so:
WHERE bk_date >= TO_DATE('2012-03-18', 'YYYY-MM-DD')
AND bk_date < TO_DATE('2012-03-19', 'YYYY-MM-DD')
More simply you can use TRUNC:
WHERE TRUNC(bk_date) = TO_DATE('2012-03-18', 'YYYY-MM-DD')
TRUNC without parameter removes hours, minutes and seconds from a DATE.
You want to use URL encoding if the strings can have arbitrary data (for example, characters such as ampersands, slashes, etc. will need to be encoded).
Check out urllib.urlencode:
>>> import urllib
>>> urllib.urlencode({'lang':'en','tag':'python'})
'lang=en&tag=python'
In python3:
from urllib import parse
parse.urlencode({'lang':'en','tag':'python'})
check your R directory ...sometimes if a file name is not all lower case and has special characters you can get this error. Im using eclipse and it only accepts file names a-z0-9_.
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source
You can use (char) System.in.read();
.
There is one interesting option in this scenario I haven`t found in answers here.
You can Nack messages with "requeue" feature in one consumer to process them in another. Generally speaking it is not a right way, but maybe it will be good enough for someone.
https://www.rabbitmq.com/nack.html
And beware of loops (when all concumers nack+requeue message)!
If the image size is variable or the design is responsive, in addition to wrapping the text, you can set a min width for the paragraph to avoid it to become too narrow.
Give an invisible CSS pseudo-element with the desired minimum paragraph width. If there isn't enough space to fit this pseudo-element, then it will be pushed down underneath the image, taking the paragraph with it.
#container:before {
content: ' ';
display: table;
width: 10em; /* Min width required */
}
#floated{
float: left;
width: 150px;
background: red;
}
The most common way of doing this is to include the binary as base-64 in an element. However, this is a workaround, and adds a bit of volume to the file.
For example, this is the bytes 00 to 09 (note we needed 16 bytes to encode 10 bytes worth of data):
<xml><image>AAECAwQFBgcICQ==</image></xml>
how you do this encoding varies per architecture. For example, with .NET you might use Convert.ToBase64String
, or XmlWriter.WriteBase64
.
You can submit your jsp page to servlet. For this use <form>
tag.
And to redirect use:
response.sendRedirect("servleturl")
C:\Users\\AppData\Roaming\Microsoft\Microsoft SQL Server\100\Tools\Shell
"validate Email"-Solution for Swift 4: Create this class:
import Foundation
public class EmailAddressValidator {
public init() {
}
public func validateEmailAddress(_ email: String) -> Bool {
let emailTest = NSPredicate(format: "SELF MATCHES %@", String.emailValidationRegEx)
return emailTest.evaluate(with: email)
}
}
private extension String {
static let emailValidationRegEx = "(?:[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}~-]+(?:\\.[\\p{L}0-9!#$%\\&'*+/=?\\^_`{|}" +
"~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\" +
"x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[\\p{L}0-9](?:[a-" +
"z0-9-]*[\\p{L}0-9])?\\.)+[\\p{L}0-9](?:[\\p{L}0-9-]*[\\p{L}0-9])?|\\[(?:(?:25[0-5" +
"]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-" +
"9][0-9]?|[\\p{L}0-9-]*[\\p{L}0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21" +
"-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])"
}
and use it like this:
let validator = EmailAddressValidator()
let isValid = validator.validateEmailAddress("[email protected]")
You need
test.split("\\|");
split
uses regular expression and in regex |
is a metacharacter representing the OR
operator. You need to escape that character using \
(written in String as "\\"
since \
is also a metacharacter in String literals and require another \
to escape it).
You can also use
test.split(Pattern.quote("|"));
and let Pattern.quote
create the escaped version of the regex representing |
.
You will have the duplicate values for name and price here. And ids are duplicate in the drinks_photos table.There is no way you can avoid them.Also what exactly you want the output ?
I know it's old post, but I thought this is a good addition:
You can use List<T>.ConvertAll<TOutput>
List<int> integers = strings.ConvertAll(s => Int32.Parse(s));
So here's what I did to make it dismiss after touching the background or return. I had to add the delegate = self in viewDidLoad and then also the delegate methods later in the .m files.
.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <UITextFieldDelegate>
@property (strong, atomic) UITextField *username;
@end
.m
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = [UIColor blueColor];
self.username = [[UITextField alloc] initWithFrame:CGRectMake(100, 25, 80, 20)];
self.username.placeholder = @"Enter your username";
self.username.backgroundColor = [UIColor whiteColor];
self.username.borderStyle = UITextBorderStyleRoundedRect;
if (self.username.placeholder != nil) {
self.username.clearsOnBeginEditing = NO;
}
self.username.delegate = self;
[self.username resignFirstResponder];
[self.view addSubview:self.username];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
@end
this is very old question, but since I came here while searching worth putting my answer.
SELECT DATEPART(ISO_WEEK,'2020-11-13') AS ISO_8601_WeekNr
In my case none of the above solutions worked. I solved by right clicking on the reference
System.Net.Http.Formatting
from Visual studio and setting the property Copy Local to true.
I hope this is useful somehow.
from time import clock
from random import sample
n = 500
myList = sample(xrange(10000),n)
#print myList
A,B,C,D = [],[],[],[]
for i in xrange(100):
t0 = clock()
ecr =( '\n'.join('{}: {}'.format(*k) for k in enumerate(myList)) )
A.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(str(n) + ": " + str(entry) for (n, entry) in zip(range(0,len(myList)), myList))
B.append(clock()-t0)
t0 = clock()
ecr = '\n'.join(map(lambda x: '%s: %s' % x, enumerate(myList)))
C.append(clock()-t0)
t0 = clock()
ecr = '\n'.join('%s: %s' % x for x in enumerate(myList))
D.append(clock()-t0)
print '\n'.join(('t1 = '+str(min(A))+' '+'{:.1%}.'.format(min(A)/min(D)),
't2 = '+str(min(B))+' '+'{:.1%}.'.format(min(B)/min(D)),
't3 = '+str(min(C))+' '+'{:.1%}.'.format(min(C)/min(D)),
't4 = '+str(min(D))+' '+'{:.1%}.'.format(min(D)/min(D))))
For n=500:
150.8%.
142.7%.
110.8%.
100.0%.
For n=5000:
153.5%.
176.2%.
109.7%.
100.0%.
Oh, I see now: only the solution 3 with map() fits with the title of the question.
Reasoning for my CSS styles not being applied, even though they were being loaded:
The media
attribute on the link
tag which was loading the stylesheet had an incorrect value. I had inadvertently set it to 1
instead of all
. This meant the browser was ignoring those styles in that linked stylesheet.
Broken:
<link rel="stylesheet" type="text/css" href="css/style.css" media="1" />
Corrected:
<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
if you are using RestTemplate than you should use following code to implement timeouts
@Bean
public RestTemplate restTemplate() {
return new RestTemplate(clientHttpRequestFactory());
}
private ClientHttpRequestFactory clientHttpRequestFactory() {
HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
factory.setReadTimeout(2000);
factory.setConnectTimeout(2000);
return factory;
}}
The xml configuration
<bean class="org.springframework.web.client.RestTemplate">
<constructor-arg>
<bean class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory"
p:readTimeout="2000"
p:connectTimeout="2000" />
</constructor-arg>
Consider:
Function GetFolder() As String
Dim fldr As FileDialog
Dim sItem As String
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = Application.DefaultFilePath
If .Show <> -1 Then GoTo NextCode
sItem = .SelectedItems(1)
End With
NextCode:
GetFolder = sItem
Set fldr = Nothing
End Function
This code was adapted from Ozgrid
and as jkf points out, from Mr Excel
Use itertools.islice
, starting at index 17. It will automatically skip the 17 first lines.
import itertools
with open('file.txt') as f:
for line in itertools.islice(f, 17, None): # start=17, stop=None
# process lines
The official docker answer to Run multiple services in a container.
It explains how you can do it with an init system (systemd, sysvinit, upstart) , a script (CMD ./my_wrapper_script.sh
) or a supervisor like supervisord
.
The &&
workaround can work only for services that starts in background (daemons) or that will execute quickly without interaction and release the prompt. Doing this with an interactive service (that keeps the prompt) and only the first service will start.
It is changed to : from PIL.Image import core as image
for new versions.
It might be beneficial to add greedy matching to the end of the string, so you can accept strings > than 10 and the regex will only return up to the first 10 chars. /^[a-z0-9]{0,10}$?/
void show() throws Exception
{
throw new Exception("my.own.Exception");
}
As there is checked exception in show() method , which is not being handled in that method so we use throws keyword for propagating the Exception.
void show2() throws Exception //Why throws is necessary here ?
{
show();
}
Since you are using the show() method in show2() method and you have propagated the exception atleast you should be handling here. If you are not handling the Exception here , then you are using throws keyword. So that is the reason for using throws keyword at the method signature.
The above answer seems good. But another way of doing this is adding the auto commit option along with the db connect. This automatically commits every other operations performed in the db, avoiding the use of mentioning sql.commit()
every time.
mydb = MySQLdb.connect(host='localhost',
user='root',
passwd='',
db='mydb',autocommit=true)
I am going to assume this is a WinForms questions (which it feels like, based on it being a "program" rather than a website/app). In which case you can simple do the following to change the text colour of a label:
myLabel.ForeColor = System.Drawing.Color.Red;
Or any other colour of your choice. If you want to be more specific you can use an RGB value like so:
myLabel.ForeColor = Color.FromArgb(0, 0, 0);//(R, G, B) (0, 0, 0 = black)
Having different colours for different users can be done a number of ways. For example, you could allow each user to specify their own RGB value colours, store these somewhere and then load them when the user "connects".
An alternative method could be to just use 2 colours - 1 for the current user (running the app) and another colour for everyone else. This would help the user quickly identify their own messages above others.
A third approach could be to generate the colour randomly - however you will likely get conflicting values that do not show well against your background, so I would suggest not taking this approach. You could have a pre-defined list of "acceptable" colours and just pop one from that list for each user that joins.
This is a barebones look at what I've done to float one image over another.
img {_x000D_
position: absolute;_x000D_
top: 25px;_x000D_
left: 25px;_x000D_
}_x000D_
.imgA1 {_x000D_
z-index: 1;_x000D_
}_x000D_
.imgB1 {_x000D_
z-index: 3;_x000D_
}
_x000D_
<img class="imgA1" src="https://placehold.it/200/333333">_x000D_
<img class="imgB1" src="https://placehold.it/100">
_x000D_
Not possible.
This a little counter-intuitive.
You're encountering the "Apple is-a fruit" but "Every Fruit is not an Apple"
Go for creating a new map and checking with instance of with String
Despite some other answers: YES it IS possible:
if expression1:
statement1
elif expression2:
statement2
else:
statement3
translates to the following one liner:
statement1 if expression1 else (statement2 if expression2 else statement3)
in fact you can nest those till infinity. Enjoy ;)
<%@ page import = "java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for(String parameter : parameters.keySet()) {
if(parameter.toLowerCase().startsWith("question")) {
String[] values = parameters.get(parameter);
//your code here
}
}
One factor your not taking into account is the robustness of the GetHashcode() function. With a perfect hash function the HashSet will clearly have better searching performance. But as the hash function diminishes so will the HashSet search time.
Try something like:
ffmpeg -i "path to file" -f null /dev/null
It writes the frame number to stderr, so you can retrieve the last frame from this.
Although this is a very old question in Java 8 you could do something like
List<String> a1 = Arrays.asList("2009-05-18", "2009-05-19", "2009-05-21");
List<String> a2 = Arrays.asList("2009-05-18", "2009-05-18", "2009-05-19", "2009-05-19", "2009-05-20", "2009-05-21","2009-05-21", "2009-05-22");
List<String> result = a2.stream().filter(elem -> !a1.contains(elem)).collect(Collectors.toList());
That's the function I wrote to get string in Unicode characters:
function nbUnicodeLength(string){
var stringIndex = 0;
var unicodeIndex = 0;
var length = string.length;
var second;
var first;
while (stringIndex < length) {
first = string.charCodeAt(stringIndex); // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
second = string.charCodeAt(stringIndex + 1);
if (second >= 0xDC00 && second <= 0xDFFF) {
stringIndex += 2;
} else {
stringIndex += 1;
}
} else {
stringIndex += 1;
}
unicodeIndex += 1;
}
return unicodeIndex;
}
Swift 2 or later
You can combine indexOf
and map
to write a "find element" function in a single line.
let array = [T(name: "foo"), T(name: "Foo"), T(name: "FOO")]
let foundValue = array.indexOf { $0.name == "Foo" }.map { array[$0] }
print(foundValue) // Prints "T(name: "Foo")"
Using filter
+ first
looks cleaner, but filter
evaluates all the elements in the array. indexOf
+ map
looks complicated, but the evaluation stops when the first match in the array is found. Both the approaches have pros and cons.
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
float roundUp(float number, float fixedBase) {
if (fixedBase != 0 && number != 0) {
float sign = number > 0 ? 1 : -1;
number *= sign;
number /= fixedBase;
int fixedPoint = (int) ceil(number);
number = fixedPoint * fixedBase;
number *= sign;
}
return number;
}
This works for any float number or base (e.g. you can round -4 to the nearest 6.75). In essence it is converting to fixed point, rounding there, then converting back. It handles negatives by rounding AWAY from 0. It also handles a negative round to value by essentially turning the function into roundDown.
An int specific version looks like:
int roundUp(int number, int fixedBase) {
if (fixedBase != 0 && number != 0) {
int sign = number > 0 ? 1 : -1;
int baseSign = fixedBase > 0 ? 1 : 0;
number *= sign;
int fixedPoint = (number + baseSign * (fixedBase - 1)) / fixedBase;
number = fixedPoint * fixedBase;
number *= sign;
}
return number;
}
Which is more or less plinth's answer, with the added negative input support.
I check for both Wi-fi and Mobile internet as follows...
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
Obviously, It could easily be modified to check for individual specific connection types, e.g., if your app needs the potentially higher speeds of Wi-fi to work correctly etc.
Write this in onclick
event of the button:
var result = confirm("Want to delete?");
if (result) {
//Logic to delete the item
}
You can use list slicing to archive your goal:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
newlist = mylist[n:]
print newlist
Outputs:
[6, 7, 8, 9]
Or del
if you only want to use one list:
n = 5
mylist = [1,2,3,4,5,6,7,8,9]
del mylist[:n]
print mylist
Outputs:
[6, 7, 8, 9]
I think you probably want to view the minification of each set of css as a separate task
task minifyBrandACss(type: com.eriwen.gradle.css.tasks.MinifyCssTask) {
source = "src/main/webapp/css/brandA/styles.css"
dest = "${buildDir}/brandA/styles.css"
}
etc etc
BTW executing your minify tasks in an action of the war task seems odd to me - wouldn't it make more sense to make them a dependency of the war task?
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>
function showButtons () { $('#b1, #b2, #b3').show(); }
</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}
</style>
</head>
<body>
<a href="#" onclick="showButtons();">Show me the money!</a>
<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />
</body>
</html>
This can be done through the youtube player API:
Working example:
<div id="player"></div>
<script src="http://www.youtube.com/player_api"></script>
<script>
// create youtube player
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('player', {
width: '640',
height: '390',
videoId: '0Bmhjf0rKe8',
events: {
onReady: onPlayerReady,
onStateChange: onPlayerStateChange
}
});
}
// autoplay video
function onPlayerReady(event) {
event.target.playVideo();
}
// when video ends
function onPlayerStateChange(event) {
if(event.data === 0) {
alert('done');
}
}
</script>