If you are only concerned with the constant True
, a simple sum
is fine. However, keep in mind that in Python other values evaluate as True
as well. A more robust solution would be to use the bool
builtin:
>>> l = [1, 2, True, False]
>>> sum(bool(x) for x in l)
3
UPDATE: Here's another similarly robust solution that has the advantage of being more transparent:
>>> sum(1 for x in l if x)
3
P.S. Python trivia: True
could be true without being 1. Warning: do not try this at work!
>>> True = 2
>>> if True: print('true')
...
true
>>> l = [True, True, False, True]
>>> sum(l)
6
>>> sum(bool(x) for x in l)
3
>>> sum(1 for x in l if x)
3
Much more evil:
True = False
def match_string(words):
nums = 0
letter = 0
other = 0
for i in words :
if i.isalpha():
letter+=1
elif i.isdigit():
nums+=1
else:
other+=1
return nums,letter,other
x = match_string("Hello World")
print(x)
>>>
(0, 10, 2)
>>>
Unique views is always a hard nut to crack. Checking the IP might work, but an IP can be shared by more than one user. A cookie could be a viable option, but a cookie can expire or be modified by the client.
In your case, it don't seem to be a big issue if the cookie is modified tho, so i would recommend using a cookie in a case like this. When the page is loaded, check if there is a cookie, if there is not, create one and add a +1 to views. If it is set, don't do the +1.
Set the cookies expiration date to whatever you want it to be, week or day if that's what you want, and it will expire after that time. After expiration, it will be a unique user again!
Edit:
Thought it might be a good idea to add this notice here...
Since around the end of 2016 a IP address (static or dynamic) is seen as personal data in the EU.
That means that you are only allowed to store a IP address with a good reason (and I'm not sure if tracking views is a good reason). So if you intend to store the IP address of visitors, I would recommend hashing or encrypting it with a algorithm which can not be reversed, to make sure that you are not breaching any law (especially after the GDPR laws have been implemented).
This approach can be tried if you don't want to use any library and keep it simple and short!
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)
o/p
[4, 4, 2, 1, 2]
Here is a defaultdict
solution that will work with Python versions 2.5 and above:
from collections import defaultdict
L = [1,2,45,55,5,4,4,4,4,4,4,5456,56,6,7,67]
d = defaultdict(int)
for i in L:
d[i] += 1
result = max(d.iteritems(), key=lambda x: x[1])
print result
# (4, 6)
# The number 4 occurs 6 times
Note if L = [1, 2, 45, 55, 5, 4, 4, 4, 4, 4, 4, 5456, 7, 7, 7, 7, 7, 56, 6, 7, 67]
then there are six 4s and six 7s. However, the result will be (4, 6)
i.e. six 4s.
defaultdict to the rescue!
from collections import defaultdict
words = "apple banana apple strawberry banana lemon"
d = defaultdict(int)
for word in words.split():
d[word] += 1
This runs in O(n).
This is what i used!
public class SMSListener extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
String mobile,body;
public void onReceive(Context context, Intent intent) {
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
mobile=senderNum.replaceAll("\\s","");
body=message.replaceAll("\\s","+");
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + body);
// Show Alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context,
"senderNum: "+ mobile+ ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
Following code will create directories (if not exists) & then copy files.
// using System.IO;
// for ex. if you want to copy files from D:\A\ to D:\B\
foreach (var f in Directory.GetFiles(@"D:\A\", "*.*", SearchOption.AllDirectories))
{
var fi = new FileInfo(f);
var di = new DirectoryInfo(fi.DirectoryName);
// you can filter files here
if (fi.Name.Contains("FILTER")
{
if (!Directory.Exists(di.FullName.Replace("A", "B"))
{
Directory.CreateDirectory(di.FullName.Replace("A", "B"));
File.Copy(fi.FullName, fi.FullName.Replace("A", "B"));
}
}
}
--shell flag can also be used for javascript files
mongo --shell /path/to/jsfile/test.js
Yes, you will likely need to add another jar or dependency
javax.persistence.*
is part of the Java Persistence API (JPA). It is only an API, you can think of it as similar to an interface. There are many implementations of JPA and this answer gives a very good elaboration of each, as well as which to use.
If your javax.persistence.*
import cannot be resolved, you will need to provide the jar that implements JPA. You can do that either by manually downloading it (and adding it to your project) or by adding a declaration to a dependency management tool (for eg, Ivy/Maven/Gradle). See here for the EclipseLink implementation (the reference implementation) on Maven repo.
After doing that, your imports should be resolved.
Also see here for what is JPA about. The xml you are referring to could be persistence.xml
, which is explained on page 3 of the link.
That being said, you might just be pointing to the wrong target runtime
If i recall correctly, you don't need to provide a JPA implementation if you are deploying it into a JavaEE app server like JBoss. See here "Note that you typically don't need it when you deploy your application in a Java EE 6 application server (like JBoss AS 6 for example).". Try changing your project's target runtime.
If your local project was setup to point to Tomcat while your remote repo assumes a JavaEE server, this could be the case. See here for the difference between Tomcat and JBoss.
Edit: I changed my project to point to GlassFish instead of Tomcat and javax.persistence.*
resolved fine without any explicit JPA dependency.
localhost:55828/token
(not localhost:55828/API/token
)[email protected]&password=Test123$&grant_type=password
When you use JavaScript to make post request, you may use following:
$http.post("localhost:55828/token",
"userName=" + encodeURIComponent(email) +
"&password=" + encodeURIComponent(password) +
"&grant_type=password",
{headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
).success(function (data) {//...
See screenshots below from Postman:
What about using a StringReader
?
using (System.IO.StringReader reader = new System.IO.StringReader(input)) {
string line = reader.ReadLine();
}
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
document.querySelector('img[name="edit-save"]');
and change the src with
document.querySelector('img[name="edit-save"]').src = "..."
so you could achieve the desired effect with
var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
this.src = "..." // this is the reference to the image itself
};
otherwise, as other suggested, if you're in control of the code, it's better to assign an id
to the image a get a reference with getElementById
(since it's the fastest method to retrieve an element)
In case you need short unique IDs as your filename, try shortuuid
, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22
compared to
>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
You can also write this in mysql -
SELECT DATE_FORMAT(create_date, '%m/%d/%Y')
FROM mytable
WHERE create_date < DATE_ADD(NOW(), INTERVAL -1 MONTH);
FIXED
Simply add a class (on any element) and check inside the interval if it's there. This is more reliable, customisable and cross-language than any other way, I believe.
var i = 0;_x000D_
this.setInterval(function() {_x000D_
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'_x000D_
console.log('Counting...');_x000D_
$('#counter').html(i++); //just for explaining and showing_x000D_
} else {_x000D_
console.log('Stopped counting');_x000D_
}_x000D_
}, 500);_x000D_
_x000D_
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */_x000D_
$('#counter').hover(function() { //mouse enter_x000D_
$(this).addClass('pauseInterval');_x000D_
},function() { //mouse leave_x000D_
$(this).removeClass('pauseInterval');_x000D_
}_x000D_
);_x000D_
_x000D_
/* Other example */_x000D_
$('#pauseInterval').click(function() {_x000D_
$('#counter').toggleClass('pauseInterval');_x000D_
});
_x000D_
body {_x000D_
background-color: #eee;_x000D_
font-family: Calibri, Arial, sans-serif;_x000D_
}_x000D_
#counter {_x000D_
width: 50%;_x000D_
background: #ddd;_x000D_
border: 2px solid #009afd;_x000D_
border-radius: 5px;_x000D_
padding: 5px;_x000D_
text-align: center;_x000D_
transition: .3s;_x000D_
margin: 0 auto;_x000D_
}_x000D_
#counter.pauseInterval {_x000D_
border-color: red; _x000D_
}
_x000D_
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="counter"> </p>_x000D_
<button id="pauseInterval">Pause/unpause</button></p>
_x000D_
Without Self
Create some objects:
class foo(object):
x = 'original class'
c1, c2 = foo(), foo()
I can change the c1 instance, and it will not affect the c2 instance:
c1.x = 'changed instance'
c2.x
>>> 'original class'
But if I change the foo class, all instances of that class will be changed as well:
foo.x = 'changed class'
c2.x
>>> 'changed class'
Please note how Python scoping works here:
c1.x
>>> 'changed instance'
With Self
Changing the class does not affect the instances:
class foo(object):
def __init__(self):
self.x = 'original self'
c1 = foo()
foo.x = 'changed class'
c1.x
>>> 'original self'
I had the similar problem: EOF -warning and only part of data was loading with read.csv(). I tried the quotes="", but it only removed the EOF -warning.
But looking at the first row that was not loading, I found that there was a special character, an arrow ? (hexadecimal value 0x1A) in one of the cells. After deleting the arrow I got the data to load normally.
Starting from API level 8 (Android 2.2), for the debuggable application (the one built by Android Studio all the times unless the release build was requested), you can use the shell run-as
command to run a command or executable as a specific user/application or just switch to the UID of your application so you can access its data directory.
List directory content of yourapp:
run-as com.yourapp ls -l /data/data/com.yourapp
Switch to UID of com.yourapp and run all further commands using that uid (until you call exit
):
run-as com.yourapp
cd /data/data/com.yourapp
ls -l
exit
Note 1: there is a known issue with some HTC Desire phones. Because of a non-standard owner/permissions of the /data/data
directory, run-as
command fails to run on those phones.
Note 2: As pointed in the comments by @Avio:
run-as
has issues also with Samsung Galaxy S phones running Cyanogenmod at any version (from 7 to 10.1) because on this platform /data/data
is a symlink to /datadata
. One way to solve the issue is to replace the symlink with the actual directory (unfortunately this usually requires root access).
The documentation on this is pretty clear. It's a UIView subclass so you use it like any other view. To start/stop the animation you use
[activityIndicator startAnimating];
[activityIndicator stopAnimating];
Here's a very good very simple solution on MSDN:
<TextBox
MouseDoubleClick="SelectAddress"
GotKeyboardFocus="SelectAddress"
PreviewMouseLeftButtonDown="SelectivelyIgnoreMouseButton" />
Here's the code behind:
private void SelectAddress(object sender, RoutedEventArgs e)
{
TextBox tb = (sender as TextBox);
if (tb != null)
{
tb.SelectAll();
}
}
private void SelectivelyIgnoreMouseButton(object sender,
MouseButtonEventArgs e)
{
TextBox tb = (sender as TextBox);
if (tb != null)
{
if (!tb.IsKeyboardFocusWithin)
{
e.Handled = true;
tb.Focus();
}
}
}
This answer is an attempt at a technical answer rather than opinion.
If we want to be POSIX purists, we define a line as:
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206
An incomplete line as:
A sequence of one or more non- <newline> characters at the end of the file.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195
A text file as:
A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397
A string as:
A contiguous sequence of bytes terminated by and including the first null byte.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396
From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).
Case in point: wc -l filename
.
From the wc
's manual we read:
A line is defined as a string of characters delimited by a <newline> character.
What are the implications to JavaScript, HTML, and CSS files then being that they are text files?
In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).
As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.
At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.
We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.
What are we left with then? System level tooling.
This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc
).
Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT
.
Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt
Staying on the tooling track, for all practical intents and purposes, let's consider this:
Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js
$ cat x.js y.js > z.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 x.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 y.js
-rw-r--r-- 1 milanadamovsky 15810 Aug 14 23:18 z.js
Notice the cat
file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.
As someone else mentioned in this thread: what if you want to cat
two files whose output becomes just one line instead of two? In other words, cat
does what it's supposed to do.
The man
of cat
only mentions reading input up to EOF, not <newline>. Note that the -n
switch of cat
will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man
.)
-n Number the output lines, starting at 1.
Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.
Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.
For example, instead of using wc -l filename
one could do awk '{x++}END{ print x}' filename
, and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curl
d) - unless our intent was truly to count lines in the POSIX compliant sense.
Conclusion
There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.
Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.
Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.
Try this jQuery which works in IE9, FF, Chrome and provides a countdown to users:
$("#comments").bind("keyup keydown", function() {
var max = 500;
var value = $(this).val();
var left = max - value.length;
if(left < 0) {
$(this).val( value.slice(0, left) );
left = 0;
}
$("#charcount").text(left);
});
<textarea id="comments" onkeyup="ismaxlength(this,500)"></textarea>
<span class="max-char-limit"><span id="charcount">500</span> characters left</span>
I have created react project locally. This reason of occurring this problem (for me) was that I didn't use sudo
before npm
and it needs root access (
> sudo npm start
PS1: For windows users, the powershell
or command line
should be run as administrator)
PS2: If use want to solve the root access issue, you can see this post.
You can write it more succinctly like the following:
required = [:one, :two, :three]
if required.all? {|k| params.has_key? k}
# here you know params has all the keys defined in required array
else
...
end
Another way of removing dublicated rows without loosing information in one step is like following:
delete from dublicated_table t1 (nolock)
join (
select t2.dublicated_field
, min(len(t2.field_kept)) as min_field_kept
from dublicated_table t2 (nolock)
group by t2.dublicated_field having COUNT(*)>1
) t3
on t1.dublicated_field=t3.dublicated_field
and len(t1.field_kept)=t3.min_field_kept
ECU = EC2 Compute Unit. More from here: http://aws.amazon.com/ec2/faqs/#What_is_an_EC2_Compute_Unit_and_why_did_you_introduce_it
Amazon EC2 uses a variety of measures to provide each instance with a consistent and predictable amount of CPU capacity. In order to make it easy for developers to compare CPU capacity between different instance types, we have defined an Amazon EC2 Compute Unit. The amount of CPU that is allocated to a particular instance is expressed in terms of these EC2 Compute Units. We use several benchmarks and tests to manage the consistency and predictability of the performance from an EC2 Compute Unit. One EC2 Compute Unit provides the equivalent CPU capacity of a 1.0-1.2 GHz 2007 Opteron or 2007 Xeon processor. This is also the equivalent to an early-2006 1.7 GHz Xeon processor referenced in our original documentation. Over time, we may add or substitute measures that go into the definition of an EC2 Compute Unit, if we find metrics that will give you a clearer picture of compute capacity.
OK, my answer is super nice:
<style>
#wrapper {
display:flex;
width:100%;
align-content: streach;
justify-content: space-between;
}
#wrapper div {
height:100px;
}
.static240 {
flex: 0 0 240px;
}
.static160 {
flex: 0 0 160px;
}
.growMax {
flex-grow: 1;
}
</style>
<div id="wrapper">
<div class="static240" style="background:red;" > </div>
<div class="static160" style="background: green;" > </div>
<div class="growMax" style="background:yellow;" ></div>
</div>
if you wanna support for all browser, use https://github.com/10up/flexibility
I'm super late to this but I didn't like the other answers
For brew run
"$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
You SHOULD NOT use brew
to install node and npm.
I've seen a few places suggested that you should use Homebrew to install Node (like alexpods answer and in this Team Treehouse blog Post) but installing this way you're more prone to run into issues as npm
and brew
are both package managers and you should have a package manager manage another package manager this leads to problems, like this bug offical npm issues Error: Refusing to delete: /usr/local/bin/npm or this Can't uninstall npm module on OSX
You can read more on the topic in DanHerbert's post Fixing npm On Mac OS X for Homebrew Users, where he goes on to say
Also, using the Homebrew installation of npm will require you to use sudo when installing global packages. Since one of the core ideas behind Homebrew is that apps can be installed without giving them root access, this is a bad idea.
I'd use npm; but you really should just follow the install instruction for each modules following the directions on there website as they will be more aware of any issue or bug they have than anyone else
The approach you're looking for is FillDown
. Another way so you don't have to kick your head off every time is to store formulas in an array of strings. Combining them gives you a powerful method of inputting formulas by the multitude. Code follows:
Sub FillDown()
Dim strFormulas(1 To 3) As Variant
With ThisWorkbook.Sheets("Sheet1")
strFormulas(1) = "=SUM(A2:B2)"
strFormulas(2) = "=PRODUCT(A2:B2)"
strFormulas(3) = "=A2/B2"
.Range("C2:E2").Formula = strFormulas
.Range("C2:E11").FillDown
End With
End Sub
Screenshots:
Result as of line: .Range("C2:E2").Formula = strFormulas
:
Result as of line: .Range("C2:E11").FillDown
:
Of course, you can make it dynamic by storing the last row into a variable and turning it to something like .Range("C2:E" & LRow).FillDown
, much like what you did.
Hope this helps!
Here is a little code to accomplish it:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(30, 20, 30, 0);
Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);
If you just want to test a library from the command line, you could do:
cat somelibrary.js mytestfile.js | node
In Swift try this,
navigationController?.isNavigationBarHidden = true //Hide
navigationController?.isNavigationBarHidden = false //Show
or
navigationController?.setNavigationBarHidden(true, animated: true) //Hide
navigationController?.setNavigationBarHidden(false, animated: true) //Show
If you are using JQuery Google map plug-in then below code will work for you -
var markers = $('#map_canvas').gmap('get','markers');
sender
refers to the object that invoked the event that fired the event handler. This is useful if you have many objects using the same event handler.
EventArgs
is something of a dummy base class. In and of itself it's more or less useless, but if you derive from it, you can add whatever data you need to pass to your event handlers.
When you implement your own events, use an EventHandler
or EventHandler<T>
as their type. This guarantees that you'll have exactly these two parameters for all your events (which is a good thing).
Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;
This will work.
Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)
/etc/squid3/squid.conf
instead of the super bloated default config file
auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
# Choose the port you want. Below we set it to default 3128.
http_port 3128
Please note the basic_ncsa_auth program instead of the old ncsa_auth
For squid 2.x you need to edit /etc/squid/squid.conf
file and place:
auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
sudo htpasswd -c /etc/squid3/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid3 restart
sudo htpasswd -c /etc/squid/passwords username_you_like
and enter a password twice for the chosen username then
sudo service squid restart
For the many people that asked me: the 2 tools produce different file formats:
htdigest
stores the password in plain text.htpasswd
stores the password hashed (various hashing algos are available)Despite this difference in format basic_ncsa_auth
will still be able to parse a password file generated with htdigest
. Hence you can alternatively use:
sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like
Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.
On Ubuntu 14.04 htdigest
and htpasswd
are both available in the [apache2-utils][1]
package.
Similar as above applies, but file paths are different.
Install squid
brew install squid
Start squid service
brew services start squid
Squid config file is stored at /usr/local/etc/squid.conf
.
Comment or remove following line:
http_access allow localnet
Then similar to linux config (but with updated paths) add this:
auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated
Note that path to basic_ncsa_auth
may be different since it depends on installed version when using brew
, you can verify this with ls /usr/local/Cellar/squid/
. Also note that you should add the above just bellow the following section:
#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#
Now generate yourself a user:password basic auth credential (note: htpasswd
and htdigest
are also both available on MacOS)
htpasswd -c /usr/local/etc/squid_passwords username_you_like
Restart the squid service
brew services restart squid
The simplest code to align the iframe element:
<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>
The datepicker('setDate') sets the date in the datepicket not in the input.
You should add the date and set it in the input.
var date2 = $('.pickupDate').datepicker('getDate');
var nextDayDate = new Date();
nextDayDate.setDate(date2.getDate() + 1);
$('input').val(nextDayDate);
Use the standard Unix/Linux/BSD/MacOS command logname
to retrieve the logged in user. This ignores the environment as well as sudo, as these are unreliable reporters. It will always print the logged in user's name and then exit. This command has been around since about 1981.
My-Mac:~ devin$ logname
devin
My-Mac:~ devin$ sudo logname
Password:
devin
My-Mac:~ devin$ sudo su -
My-Mac:~ root# logname
devin
My-Mac:~ root# echo $USER
root
Yes, you can change the encoding of a specific file (or see what it has) with this Encoding Support plugin. With this plugin you will be able to handle the different encodings of your files without problems.
Now it is in version 1.4.0 for NetBeans 8.2 and I use it in Windows 10 several time ago.
The operation is very simple, in the status line you can see the encoding of the open file, and from there you can define its new encoding.
$JAVA_HOME/bin/java -version says 'Permission Denied'
If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.
Do an
ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java
to see why you cannot access or run this program,.
Use this library, It is simple and easy.. https://github.com/hotchemi/Android-Rate
by adding the dependency..
dependencies {
compile 'com.github.hotchemi:android-rate:0.5.6'
}
If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:
public static Task<T> RunAsync<T>(Func<T> function)
{
if (function == null) throw new ArgumentNullException(“function”);
var tcs = new TaskCompletionSource<T>();
ThreadPool.QueueUserWorkItem(_ =>
{
try
{
T result = function();
tcs.SetResult(result);
}
catch(Exception exc) { tcs.SetException(exc); }
});
return tcs.Task;
}
To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.
I saw it's also used in the .NET source, e.g. WebClient.cs:
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
{
// Create the task to be returned
var tcs = new TaskCompletionSource<string>(address);
// Setup the callback event handler
UploadStringCompletedEventHandler handler = null;
handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
this.UploadStringCompleted += handler;
// Start the async operation.
try { this.UploadStringAsync(address, method, data, tcs); }
catch
{
this.UploadStringCompleted -= handler;
throw;
}
// Return the task that represents the async operation
return tcs.Task;
}
Finally, I also found the following useful:
I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.
To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).
This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.
Introduction to Async/Await on ASP.NET
If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.
Based on Stack Overflow questions Unix cut, remove first token and https://stackoverflow.com/a/15903654/781312:
(octal=$(echo -n ? | od -t o1 | head -1 | cut -d' ' -f2- | sed -e 's#\([0-9]\+\) *#\\0\1#g')
echo Octal representation is following $octal
echo -e "$octal")
Output is the following.
Octal representation is following \0342\0230\0240
?
Try JsonFormat.printer().print(MessageOrBuilder)
, it looks good for proto3. Yet, it is unclear how to convert the actual protobuf
message (which is provided as the java package of my choice defined in the .proto file) to a com.google.protbuf.Message object.
Pass in the straight XML instead of a dictionary.
You can't stretch a background image (until CSS 3).
You would have to use absolute positioning, so that you can put an image tag inside the cell and stretch it to cover the entire cell, then put the content on top of the image.
table {_x000D_
width: 230px;_x000D_
}_x000D_
_x000D_
.style1 {_x000D_
text-align: center;_x000D_
height: 35px;_x000D_
}_x000D_
_x000D_
.bg {_x000D_
position: relative;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg img {_x000D_
display: block;_x000D_
width: 100%;_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
.bg .linkcontainer {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
overflow: hidden;_x000D_
width: 100%;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" border="10">_x000D_
<tr>_x000D_
<td class="style1">_x000D_
<div class="bg">_x000D_
<img src="http://placekitten.com/20/20" alt="" />_x000D_
<div class="linkcontainer">_x000D_
<a class="link" href="#">_x000D_
<span>Answer</span>_x000D_
</a>_x000D_
</div>_x000D_
</div>_x000D_
</td>_x000D_
</tr>_x000D_
</table>
_x000D_
It is varchar
and not var_char
CREATE DATABASE IF NOT EXISTS courses;
USE courses;
CREATE TABLE IF NOT EXISTS teachers(
id INT(10) UNSIGNED PRIMARY KEY NOT NULL AUTO_INCREMENT,
name VARCHAR(50) NOT NULL,
addr VARCHAR(255) NOT NULL,
phone INT NOT NULL
);
You should use a SQL tool to visualize possbile errors like MySQL Workbench.
Why not try IS?
$('selector').is(':checked') /* result true or false */
Look a FAQ: jQuery .is() enjoin us ;-)
If you need a random number in the range [double.MinValue
; double.MaxValue
]
// Because of:
double.MaxValue - double.MinValue == double.PositiveInfinity
// This will be equals to NaN or PositiveInfinity
random.NextDouble() * (double.MaxValue - double.MinValue)
Use instead:
public static class RandomExtensions
{
public static double NextDoubleInMinMaxRange(this Random random)
{
var bytes = new byte[sizeof(double)];
var value = default(double);
while (true)
{
random.NextBytes(bytes);
value = BitConverter.ToDouble(bytes, 0);
if (!double.IsNaN(value) && !double.IsInfinity(value))
return value;
}
}
}
Although there are several ways to do this the most efficient solution to your problem would probably be to use one of the fstream's predefined method such as good(). With this method you can check whether the file you've specified exist or not.
fstream file("file_name.txt");
if (file.good())
{
std::cout << "file is good." << endl;
}
else
{
std::cout << "file isnt good" << endl;
}
I hope you find this useful.
This will work in jQuery 1.6 (note colon before the opening bracket), but fails on the newer releases (1.10 at the time).
$('#mySelect option:[text=abc]")
If you want system back color in white then you can use this code
<com.google.android.material.appbar.AppBarLayout
android:id="@+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:elevation="0dp"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar_notification"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
app:contentInsetStartWithNavigation="0dp">
<include layout="@layout/action_bar_notification" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
Note:- android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
is key
The paste is in your activity where you want to show back button on action bar
final Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar_notification);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(false);
To go with thelost's Apache Commons answer: using guava-libraries (Google's general-purpose Java utility library which I would argue should now be on the classpath of any non-trivial Java project), this would use CharMatcher:
CharMatcher.is('0').trimLeadingFrom(inputString);
Since in Vue 2.0, no solution seems available, a clean solution that I found is to create a vue-id
attribute, and also set it on the template. Then on created
and beforeDestroy
lifecycle these instances are updated on the global object.
Basically:
created: function() {
this._id = generateUid();
globalRepo[this._id] = this;
},
beforeDestroy: function() {
delete globalRepo[this._id]
},
data: function() {
return {
vueId: this._id
}
}
The Java Communications API (also known as javax.comm) provides applications access to RS-232 hardware (serial ports): http://www.oracle.com/technetwork/java/index-jsp-141752.html
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
Complete example below. I just love the copy/paste :)
HTML
<div class="container">
<div class="row">
<div class="col-md-8 col-md-offset-2">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" method="" action="">
<div class="form-group">
<label class="col-md-4 control-label">Email</label>
<div class="col-md-6">
<input type="email" class="form-control" name="email" value="">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Password</label>
<div class="col-md-6">
<input id="password-field" type="password" class="form-control" name="password" value="secret">
<span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
CSS
.field-icon {
float: right;
margin-right: 8px;
margin-top: -23px;
position: relative;
z-index: 2;
cursor:pointer;
}
.container{
padding-top:50px;
margin: auto;
}
JS
$(".toggle-password").click(function() {
$(this).toggleClass("fa-eye fa-eye-slash");
var input = $($(this).attr("toggle"));
if (input.attr("type") == "password") {
input.attr("type", "text");
} else {
input.attr("type", "password");
}
});
Try it here: https://codepen.io/anon/pen/ZoMQZP
Get-ADGroupMember "Group1" -recursive | Select-Object Name | Export-Csv c:\path\Groups.csv
I got this to work for me... I would assume that you could put "Group1, Group2, etc." or try a wildcard. I did pre-load AD into PowerShell before hand:
Get-Module -ListAvailable | Import-Module
In newer versions of VS Code, you navigate to settings (Ctrl+,), and make sure to select Workspace Settings at the top right.
Then add a files.exclude
option to specify patterns to exclude.
You can also add search.exclude
if you only want to exclude a file from search results, and not from the folder explorer.
l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)
What about using a server-side script to generate the script tag lines? Crudely, something like this (PHP) -
$handle = opendir("scripts/");
while (($file = readdir($handle))!== false) {
echo '<script type="text/javascript" src="' . $file . '"></script>';
}
closedir($handle);
Combine round and ceiling to get a proper round up.
select ceiling(round(984.375000), 0)) => 984
while
select round(984.375000, 0) => 984.000000
and
select ceil (984.375000) => 985
Run below command where pom.xml
is placed:
mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005"
And start your remote java application with debugging option on port 5005
I've been experimenting with Apache Commons Daemon. It's supports windows (Procrun) and unix (Jsvc). Advanced Installer has a Java Service tutorial with an example project to download. If you get their javaservice.jar running as a windows service you can test it by using "telnet 4444". I used their example because my focus was on getting a java windows service running, not writing java.
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
The first example nearly always wins in my book:
if(foo)
{
}
It's shorter and more concise. Why add an extra check to something when it's absolutely not needed? Just wasting cycles...
I do agree, though, that sometimes the more verbose syntax makes things more readable (which is ultimately more important as long as performance is acceptable) in situations where variables are poorly named.
See the thumbnail function of PIL's Image Module. You can use it to save smaller versions of files as various filetypes and if you're wanting to preserve as much quality as you can, consider using the ANTIALIAS
filter when you do.
Other than that, I'm not sure if there's a way to specify a maximum desired size. You could, of course, write a function that might try saving multiple versions of the file at varying qualities until a certain size is met, discarding the rest and giving you the image you wanted.
Although, the below code does the job, BUT its performance takes a big hit, as you deal with a DataFrame with # records 100k or more:
df.fillna(df.mean())
In my experience, one should replace NaN values (be it with Mean or Median), only where it is required, rather than applying fillna() all over the DataFrame.
I had a DataFrame with 20 variables, and only 4 of them required NaN values treatment (replacement). I tried the above code (Code 1), along with a slightly modified version of it (code 2), where i ran it selectively .i.e. only on variables which had a NaN value
#------------------------------------------------
#----(Code 1) Treatment on overall DataFrame-----
df.fillna(df.mean())
#------------------------------------------------
#----(Code 2) Selective Treatment----------------
for i in df.columns[df.isnull().any(axis=0)]: #---Applying Only on variables with NaN values
df[i].fillna(df[i].mean(),inplace=True)
#---df.isnull().any(axis=0) gives True/False flag (Boolean value series),
#---which when applied on df.columns[], helps identify variables with NaN values
Below is the performance i observed, as i kept on increasing the # records in DataFrame
DataFrame with ~100k records
DataFrame with ~200k records
DataFrame with ~1.6 Million records
DataFrame with ~13 Million records
Apologies for a long answer ! Hope this helps !
Although building the URL or using tools is still possible, it is not needed anymore.
https://www.nuget.org/ currently has a download link named "Download package", that is available even if you don't have an account on the site.
(at the bottom of the right column).
Example of EntityFramework's detail page: https://www.nuget.org/packages/EntityFramework/: (Updated after comment of kwitee.)
You can set this programmatically in the controller:-
HttpContext.Current.Server.ScriptTimeout = 300;
Sets the timeout to 5 minutes instead of the default 110 seconds (what an odd default?)
If you only care about using list comprehensions and nothing else matters to you!
from itertools import combinations
from functools import reduce
def get_devisors(n):
f = [f for f,e in list(factorGenerator(n)) for i in range(e)]
fc = [x for l in range(len(f)+1) for x in combinations(f, l)]
devisors = [1 if c==() else reduce((lambda x, y: x * y), c) for c in set(fc)]
return sorted(devisors)
A much faster method on windows (0.05s), call a bat script that does this:
get_latest.bat
@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%
where \\directory\in\question
is the directory you want to investigate.
get_latest.py
from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)
if it finds a file stdout
is the path and stderr
is None.
Use stdout.decode("utf-8").rstrip()
to get the usable string representation of the file name.
I found the cleanest way of doing it is this.
Tested on Django 3.1.5
class MyForm(forms.Form):
my_boolean = forms.BooleanField(required=False, initial=True)
StringListName = ObjectListName.stream().map( m -> m.toString() ).collect( Collectors.toList() );
I think pressing Q should work.
CreateOrReplaceTempView will create a temporary view of the table on memory it is not presistant at this moment but you can run sql query on top of that . if you want to save it you can either persist or use saveAsTable to save.
first we read data in csv format and then convert to data frame and create a temp view
Reading data in csv format
val data = spark.read.format("csv").option("header","true").option("inferSchema","true").load("FileStore/tables/pzufk5ib1500654887654/campaign.csv")
printing the schema
data.printSchema
data.createOrReplaceTempView("Data")
Now we can run sql queries on top the table view we just created
%sql select Week as Date,Campaign Type,Engagements,Country from Data order by Date asc
using DB facade you can perform SQL queries
public function index()
{
return DB::table('table_name')->get();
}
A void*
pointer is used when you want to indicate a pointer to a hunk of memory without specifying the type. C's malloc
returns such a pointer, expecting you to cast it to a particular type immediately. It really isn't useful until you cast it to another pointer type. You're expected to know which type to cast it to, the compiler has no reflection capability to know what the underlying type should be.
If you have a chance to run any project on the 'ineligible' device from other Mac with Xcode, try it and then reconnect the device to your Mac (without restarting Xcode/Mac).
For me, after doing that, the 'ineligible device' section disappears and my device returns to the normal status.
Hope it helps for someone.
json loads -> returns an object from a string representing a json object.
json dumps -> returns a string representing a json object from an object.
load and dump -> read/write from/to file instead of string
This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..
Both should be same ..Java version
mismatched ..Check it
Try to make use of linq to Dataset
(from b in table1.AsEnumerable()
select new { id = b.Field<int>("id")}).Except(
from a in table2.AsEnumerable()
select new {id = a.Field<int>("id")})
Check this article : Comparing DataSets using LINQ
I have an example of doing both by classpath or from external config with log4j2.properties
package org.mmartin.app1;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.LogManager;
public class App1 {
private static Logger logger=null;
private static final String LOG_PROPERTIES_FILE = "config/log4j2.properties";
private static final String CONFIG_PROPERTIES_FILE = "config/config.properties";
private Properties properties= new Properties();
public App1() {
System.out.println("--Logger intialized with classpath properties file--");
intializeLogger1();
testLogging();
System.out.println("--Logger intialized with external file--");
intializeLogger2();
testLogging();
}
public void readProperties() {
InputStream input = null;
try {
input = new FileInputStream(CONFIG_PROPERTIES_FILE);
this.properties.load(input);
} catch (IOException e) {
logger.error("Unable to read the config.properties file.",e);
System.exit(1);
}
}
public void printProperties() {
this.properties.list(System.out);
}
public void testLogging() {
logger.debug("This is a debug message");
logger.info("This is an info message");
logger.warn("This is a warn message");
logger.error("This is an error message");
logger.fatal("This is a fatal message");
logger.info("Logger's name: "+logger.getName());
}
private void intializeLogger1() {
logger = LogManager.getLogger(App1.class);
}
private void intializeLogger2() {
LoggerContext context = (org.apache.logging.log4j.core.LoggerContext) LogManager.getContext(false);
File file = new File(LOG_PROPERTIES_FILE);
// this will force a reconfiguration
context.setConfigLocation(file.toURI());
logger = context.getLogger(App1.class.getName());
}
public static void main(String[] args) {
App1 app1 = new App1();
app1.readProperties();
app1.printProperties();
}
}
--Logger intialized with classpath properties file--
[DEBUG] 2018-08-27 10:35:14.510 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.513 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.513 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.513 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.513 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.514 [main] App1 - Logger's name: org.mmartin.app1.App1
--Logger intialized with external file--
[DEBUG] 2018-08-27 10:35:14.524 [main] App1 - This is a debug message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - This is an info message
[WARN ] 2018-08-27 10:35:14.525 [main] App1 - This is a warn message
[ERROR] 2018-08-27 10:35:14.525 [main] App1 - This is an error message
[FATAL] 2018-08-27 10:35:14.525 [main] App1 - This is a fatal message
[INFO ] 2018-08-27 10:35:14.525 [main] App1 - Logger's name: org.mmartin.app1.App1
-- listing properties --
dbpassword=password
database=localhost
dbuser=user
For Bootstrap 3
we divide the space with the columns, we use 8 small columns (col-xs-8), we leave 4 empty columns (col-xs-offset-4) and we apply the property (center-block)
<!--Footer-->
<div class="modal-footer">
<div class="col-xs-8 col-xs-offset-4 center-block">
<button type="submit" class="btn btn-primary">Enviar</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cerrar</button>
</div>
</div>
For Bootstrap 4
We use Spacing, Bootstrap includes a wide range of abbreviated and padded response margin utility classes to modify the appearance of an element. The classes are named using the format {property}{sides}-{size} for xs and {property}{sides}-{breakpoint}-{size} for sm, md, lg, and xl.
more info here: https://getbootstrap.com/docs/4.1/utilities/spacing/
<!--Footer-->
<div class="modal-footer">
<button type="submit" class="btn btn-primary ml-auto">Enviar</button>
<button type="button" class="btn btn-danger mr-auto" data-dismiss="modal">Cerrar</button>
</div>
This error is coming from the staticfile handler -- which by default doesn't filter any verbs, but probably can only deal with HEAD and GET.
And this is because no other handler stepped up to the plate and said they could handle DELETE.
Since you are using the WEBAPI, which because of routing doesn't have files and therefore extensions, the following additions need to be added to your web.config file:
<system.webserver>
<httpProtocol>
<handlers>
...
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Obviously what is needed depends on classicmode vs integratedmode, and classicmode depends on bitness. In addition, the OPTIONS header has been added for CORS processing, but if you don't do CORS you don't need that.
FYI, your web.config is the local to the application (or application directory) version whose top level is applicationHost.config.
I just ran into the same problem (lack of hashchange event in IE7). A workaround that suited for my purposes was to bind the click event of the hash-changing links.
<a class='hash-changer' href='#foo'>Foo</a>
<script type='text/javascript'>
if (("onhashchange" in window) && !($.browser.msie)) {
//modern browsers
$(window).bind('hashchange', function() {
var hash = window.location.hash.replace(/^#/,'');
//do whatever you need with the hash
});
} else {
//IE and browsers that don't support hashchange
$('a.hash-changer').bind('click', function() {
var hash = $(this).attr('href').replace(/^#/,'');
//do whatever you need with the hash
});
}
</script>
FWIW, I've been doing the same thing as you for years
CAST(CONVERT(VARCHAR, [tstamp], 102) AS DATETIME) = @dateParam
Seems to me like this is one of the better ways to strip off time in terms of flexibility, speed and readabily. (sorry). Some UDF functions as suggested can be useful, but UDFs can be slow with larger result sets.
Here is my function based on @Cd-MaN's approach.
function shorten($string, $width) {
if(strlen($string) > $width) {
$string = wordwrap($string, $width);
$string = substr($string, 0, strpos($string, "\n"));
}
return $string;
}
In my condition when I got an exception " Unable to start embedded Tomcat servlet container",
I opened the debug mode of spring boot by adding debug=true
in the application.properties,
and then rerun the code ,and it told me that java.lang.NoSuchMethodError: javax.servlet.ServletContext.getVirtualServerName()Ljava/lang/String
Thus, we know that probably I'm using a servlet API of lower version, and it conflicts with spring boot version.
I went to my pom.xml, and found one of my dependencies is using servlet2.5, and I excluded it.
Now it works. Hope it helps.
your fadeIn()
function calls the fadeOut()
function, which calls the fadeIn()
function again. the recursion is in the JS.
Simpler way (if your only keyword is "code" ) may be:
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
Use /fonts/ or /font/ before font type name in your CSS stylesheet. I face this error but after that its working fine.
@font-face {
font-family: 'robotoregular';
src: url('../fonts/Roboto-Regular-webfont.eot');
src: url('../fonts/Roboto-Regular-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/Roboto-Regular-webfont.woff') format('woff'),
url('../fonts/Roboto-Regular-webfont.ttf') format('truetype'),
url('../fonts/Roboto-Regular-webfont.svg#robotoregular') format('svg');
font-weight: normal;
font-style: normal;
}
For people using Kotlin you can put this in your MainActivity.kt:
window.navigationBarColor = ContextCompat.getColor(this@MainActivity, R.color.yourColor)
With window
being:
val window: Window = [email protected]
Or you can put this in your themes.xml or styles.xml (requires API level 21):
<item name='android:navigationBarColor'>@color/yourColor</item>
If you don't really need to use curl;
$body = file_get_contents('http://example.com');
var_export($http_response_header);
var_export($body);
Which outputs
array (
0 => 'HTTP/1.0 200 OK',
1 => 'Accept-Ranges: bytes',
2 => 'Cache-Control: max-age=604800',
3 => 'Content-Type: text/html',
4 => 'Date: Tue, 24 Feb 2015 20:37:13 GMT',
5 => 'Etag: "359670651"',
6 => 'Expires: Tue, 03 Mar 2015 20:37:13 GMT',
7 => 'Last-Modified: Fri, 09 Aug 2013 23:54:35 GMT',
8 => 'Server: ECS (cpm/F9D5)',
9 => 'X-Cache: HIT',
10 => 'x-ec-custom-error: 1',
11 => 'Content-Length: 1270',
12 => 'Connection: close',
)'<!doctype html>
<html>
<head>
<title>Example Domain</title>...
See http://php.net/manual/en/reserved.variables.httpresponseheader.php
In general, you can pass any query to mysql
from shell with -e option.
mysql -u username -p -D dbname -e "DROP DATABASE dbname"
Generic way of solving issues like Error inflating class X
:
Resources$NotFoundException
like this:Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0b0066 at android.content.res.ResourcesImpl.getValue(ResourcesImpl.java:190) at android.content.res.Resources.loadXmlResourceParser(Resources.java:2094) at android.content.res.Resources.getLayout(Resources.java:1111) at android.view.LayoutInflater.inflate(LayoutInflater.java:424)
Resource ID
is actually exact integer from generated R.java file.0x7f0b0066
which will point to the xml file which could not be inflated(found).layout
doesn't have this resource, but some layout-XXX
has.layout
.OK it's 2019 now, and from Java 11 you have a constructor with Charset:
FileWriter?(String fileName, Charset charset)
Unfortunately, we still cannot modify the byte buffer size, and it's set to 8192. (https://www.baeldung.com/java-filewriter)
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
I know this is quite a few years later but here are some interesting plugins. I have not tried either of these yet so YMMV.
https://github.com/mikelue/vim-maven-plugin
https://github.com/vim-scripts/maven-ide
EDIT: Oh an BTW, i've tried eclim off and on, but the reason I like vim is its lightness. Executing eclipse even on headless mode is just too much mental lifting for me.
EDIT2: I've been using playframework lately and this will probably work with maven builds too:
For compiling, you can configure VIM's make to run maven or in my case, run a build script, tee that to a file.
autocmd Filetype java setl makeprg=play_compile
autocmd Filetype java setl efm=%A\ %#[error]\ %f:%l:\ %m,%-Z\ %#[error]\ %p^,%-C%.%#
"play_compile" is just a compile script. It uses SBT so Maven should work just fine here. Even direct javac will work. This way, you can use VIM"s quickfix buffer (:cnext, :clist: cprev, etc).
For jumping around the classes, I use ctrl-p. Its beautiful. Use it. Faster than eclipse in jumping around files.
For jumping around methods, I use tagsearch with exuberant c-tags. Jump into method declarations by using ctrl-]. Go back using Ctrl-o. Doesnt work as good as eclipse, but it works good enough.
I use supertab for code completion. Javacomplete is pretty slow, so I stick with omni-complete. Again, not as accurate as eclipse, but its fast and works good enough for me.
The %run
magic has a parameter file_finder
that it uses to get the full path to the file to execute (see here); as you note, it just looks in the current directory, appending ".py" if necessary.
There doesn't seem to be a way to specify which file finder to use from the %run
magic, but there's nothing to stop you from defining your own magic command that calls into %run
with an appropriate file finder.
As a very nasty hack, you could override the default file_finder
with your own:
IPython.core.magics.execution.ExecutionMagics.run.im_func.func_defaults[2] = my_file_finder
To be honest, at the rate the IPython API is changing that's as likely to continue to work as defining your own magic is.
If your existing code is already relying on from datetime import datetime
, you can also simply also import date
from datetime import datetime, timedelta, date
print isinstance(datetime.today().date(), date)
You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.
If this error happens, check if:
maximize()
in node.js, maximize_window()
in Python),executeScript()
in node.js, execute_script()
in Python).You should not use "width" and "height" attributes directly, use the style attribute like style="some css here"
if you want to use inline styling:
<div class="button" style="width:60px;height:30px;">This is a button</div>
Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:
.button {_x000D_
background-color: #000000;_x000D_
color: #FFFFFF;_x000D_
padding: 10px;_x000D_
border-radius: 10px;_x000D_
-moz-border-radius: 10px;_x000D_
-webkit-border-radius: 10px;_x000D_
margin:10px_x000D_
}_x000D_
_x000D_
.small-btn {_x000D_
width: 50px;_x000D_
height: 25px;_x000D_
}_x000D_
_x000D_
.medium-btn {_x000D_
width: 70px;_x000D_
height: 30px;_x000D_
}_x000D_
_x000D_
.big-btn {_x000D_
width: 90px;_x000D_
height: 40px;_x000D_
}
_x000D_
<div class="button big-btn">This is a big button</div>_x000D_
<div class="button medium-btn">This is a medium button</div>_x000D_
<div class="button small-btn">This is a small button</div>_x000D_
_x000D_
Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.
SELECT *
FROM table
WHERE myDtate BETWEEN now()
, DATE_SUB(NOW()
, INTERVAL 1 MONTH)
Delete from BA_CITY_MASTER where CITY_NAME in (select CITY_NAME from BA_CITY_MASTER group by CITY_NAME having count(CITY_NAME)>1);
As some answers have pointed out, sometimes you really want to delete the local repository entirely, for example, there might be some artifacts that can't be purged as they are not anymore referenced by the pom.
If you want to have this deletion embedded in a maven phase, as for example clean
you can use the maven-clean-plugin
and access the repository through the settings, for example:
<plugin>
<inherited>false</inherited>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<phase>clean</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<tasks>
<echo>Base clean is attached to deleting local maven cache</echo>
<echo>${settings.localRepository}</echo>
</tasks>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<inherited>false</inherited>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
<configuration>
<filesets>
<fileset>
<directory>${settings.localRepository}</directory>
</fileset>
</filesets>
</configuration>
</plugin>
It's possible to find the element in Dictionary collection by using ContainsKey or TryGetValue as follows:
class Program
{
protected static Dictionary<string, string> _tags = new Dictionary<string,string>();
static void Main(string[] args)
{
string strValue;
_tags.Add("101", "C#");
_tags.Add("102", "ASP.NET");
if (_tags.ContainsKey("101"))
{
strValue = _tags["101"];
Console.WriteLine(strValue);
}
if (_tags.TryGetValue("101", out strValue))
{
Console.WriteLine(strValue);
}
}
}
You confuse how browsers renders the elements when there are floating elements. If one block element is floating (your inner div in your case), other block elements will ignore it because browser removes floating elements from the normal flow of the web page. Then, because the floated div has been removed from the normal flow, the outside div is filled in, like the inner div isn't there. However, inline elements (images, links, text, blackquotes) will respect the boundaries of the floating element. If you introduce text in the outside div, the text will place arround de inner div.
In other words, block elements (headers, paragraphs, divs, etc) ignore floating elements and fill in, and inline elements (images, links, text, etc) respect boundaries of floating elements.
<body>
<div style="float:right; background-color:blue;width:200px;min-height:400px;margin-right:20px">
floating element
</div>
<h1 style="background-color:red;"> this is a big header</h1>
<p style="background-color:green"> this is a parragraph with text and a big image. The text places arrounds the floating element. Because of the image is wider than space between paragrah and floating element places down the floating element. Try to make wider the viewport and see what happens :D
<img src="http://2.bp.blogspot.com/_nKxzQGcCLtQ/TBYPAJ6xM4I/AAAAAAAAAC8/lG6XemOXosU/s1600/css.png">
</p>
You cannot, due to security reasons.
Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
<input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>
You don't want the websites you visit to be able to do this, do you? =)
Only one proposed solution keeps the default-value
when some-value:null
was set explicitly (POJO readability is lost there and it's clumsy)
Here's how one can keep the default-value
and never set it to null
@JsonProperty("some-value")
public String someValue = "default-value";
@JsonSetter("some-value")
public void setSomeValue(String s) {
if (s != null) {
someValue = s;
}
}
I managed to find the correct one. It is below.
bool val1 = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
EDIT
The credit of this edit goes to @Gianpiero Caretti who suggested this in comment.
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated
Only you want to set default value parameter. This calling third overloading method.
dt.Columns.Add("MyRow", type(System.Int32),0);
You need to use the public properties from Main
, and not try to directly change the internal variables.
private OutputStream outputStream;
private InputStream inStream;
private void init() throws IOException {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if(bondedDevices.size() > 0) {
Object[] devices = (Object []) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[position];
ParcelUuid[] uuids = device.getUuids();
BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
socket.connect();
outputStream = socket.getOutputStream();
inStream = socket.getInputStream();
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public void write(String s) throws IOException {
outputStream.write(s.getBytes());
}
public void run() {
final int BUFFER_SIZE = 1024;
byte[] buffer = new byte[BUFFER_SIZE];
int bytes = 0;
int b = BUFFER_SIZE;
while (true) {
try {
bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
It is certainly possible to access a remote MySQL server from a local instance of phpMyAdmin, as the other answers have pointed out. And for that to work, you have to configure the remote server's MySQL server to accept remote connections, and allow traffic through the firewall for the port number that MySQL is listening to. I prefer a slightly different solution involving SSH Tunnelling.
The following command will set up an SSH tunnel which will forward all requests made to port 3307 from your local machine to port 3306 on the remote machine:
ssh -NL 3307:localhost:3306 root@REMOTE_HOST
When prompted, you should enter the password for the root user on the remote machine. This will open the tunnel. If you want to run this in the background, you'll need to add the -f
argument, and set up Passwordless SSH between your local machine and the remote machine.
After you've got the SSH tunnel working, you can add the remote server to the servers list in your local phpMyAdmin by modifying the /etc/phpmyadmin/config.inc.php
file. Add the following to the end of the file:
$cfg['Servers'][$i]['verbose'] = 'Remote Server 1'; // Change this to whatever you like.
$cfg['Servers'][$i]['host'] = '127.0.0.1';
$cfg['Servers'][$i]['port'] = '3307';
$cfg['Servers'][$i]['connect_type'] = 'tcp';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['compress'] = FALSE;
$cfg['Servers'][$i]['auth_type'] = 'cookie';
$i++;
I wrote a more in-depth blog post about exactly this, in case you need additional help.
I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.
BE MINDFUL, If you use angular.equals()
on objects that have property obj.$something
(property name starts with $) those properties will get ignored in comparison.
Example:
var obj1 = {
$key0: "A",
key1: "value1",
key2: "value2",
key3: {a: "aa", b: "bb"}
}
var obj2 = {
$key0: "B"
key2: "value2",
key1: "value1",
key3: {a: "aa", b: "bb"}
}
angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
Using .data()
will only add data to the jQuery object for that element. In order to add the information to the element itself you need to access that element using jQuery's .attr
or native .setAttribute
$('div').attr('data-info', 1);
$('div')[0].setAttribute('data-info',1);
In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ($('div[data-info="1"]')
), but when you use .data()
you cannot. In order to select based on the .data()
setting, you would need to use jQuery's filter function.
$('div').data('info', 1);_x000D_
//alert($('div').data('info'));//1_x000D_
_x000D_
$('div').filter(function(){_x000D_
return $(this).data('info') == 1; _x000D_
}).text('222');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>1</div>
_x000D_
At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut
is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.
This works on MacOS Mountain Lion (10.8), Solaris 10 (SunOS 5.10) and RHE Linux (Red Hat Enterprise Linux Server release 5.3, Tikanga)...
$ sed 's/{pattern}/\^J/g' foo.txt > foo2.txt
... where the ^J
is done by doing ctrl+v+j. Do mind the \
before the ^J
.
PS, I know the sed in RHEL is GNU, the MacOS sed is FreeBSD based, and although I'm not sure about the Solaris sed, I believe this will work pretty much with any sed. YMMV tho'...
Try this,
this.searchAll = element(by.xpath('path here'));
this.searchAll.sendKeys('');
If you don't need a signed integer, this is an alternative that uses a slightly different approach, is easy to read and doesn't require an import:
def distance(a, b):
if a > 0 and b > 0:
return max(a, b) - min(a, b)
elif a < 0 and b < 0:
return abs(a - b)
elif a == b:
return 0
return abs(a - 0) + abs(b - 0)
The point is to set the token on the interceptors for each request
import axios from "axios";
const httpClient = axios.create({
baseURL: "http://youradress",
// baseURL: process.env.APP_API_BASE_URL,
});
httpClient.interceptors.request.use(function (config) {
const token = localStorage.getItem('token');
config.headers.Authorization = token ? `Bearer ${token}` : '';
return config;
});
Depends what you mean by "post data". You can use the HTML target=""
attribute on a <form />
tag, so it could be as simple as:
<form action="do_stuff.aspx" method="post" target="my_iframe">
<input type="submit" value="Do Stuff!">
</form>
<!-- when the form is submitted, the server response will appear in this iframe -->
<iframe name="my_iframe" src="not_submitted_yet.aspx"></iframe>
If that's not it, or you're after something more complex, please edit your question to include more detail.
There is a known bug with Internet Explorer that only occurs when you're dynamically creating your iframes, etc. using Javascript (there's a work-around here), but if you're using ordinary HTML markup, you're fine. The target attribute and frame names isn't some clever ninja hack; although it was deprecated (and therefore won't validate) in HTML 4 Strict or XHTML 1 Strict, it's been part of HTML since 3.2, it's formally part of HTML5, and it works in just about every browser since Netscape 3.
I have verified this behaviour as working with XHTML 1 Strict, XHTML 1 Transitional, HTML 4 Strict and in "quirks mode" with no DOCTYPE specified, and it works in all cases using Internet Explorer 7.0.5730.13. My test case consist of two files, using classic ASP on IIS 6; they're reproduced here in full so you can verify this behaviour for yourself.
default.asp
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<form action="do_stuff.asp" method="post" target="my_frame">
<input type="text" name="someText" value="Some Text">
<input type="submit">
</form>
<iframe name="my_frame" src="do_stuff.asp">
</iframe>
</body>
</html>
do_stuff.asp
<%@Language="JScript"%><?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC
"-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>Form Iframe Demo</title>
</head>
<body>
<% if (Request.Form.Count) { %>
You typed: <%=Request.Form("someText").Item%>
<% } else { %>
(not submitted)
<% } %>
</body>
</html>
I would be very interested to hear of any browser that doesn't run these examples correctly.
I prefer it explicitly:
if len(li) == 0:
print('the list is empty')
This way it's 100% clear that li
is a sequence (list) and we want to test its size. My problem with if not li: ...
is that it gives the false impression that li
is a boolean variable.
Double-tap only
It is quite easy to detect a double tap on a view by using SimpleOnGestureListener
(as demonstrated in Hannes Niederhausen's answer).
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
I can't see a big advantage to re-inventing the logic for this (like bughi's answer).
Double-tap and Single-tap with delay
You can also use the SimpleOnGestureListener
to differentiate a single-tap and a double-tap as mutually exclusive events. To do that you just override onSingleTapConfirmed
. This will delay running the single-tap code until the system is certain that the user hasn't double-tapped (ie, the delay > ViewConfiguration.getDoubleTapTimeout()
). There is definately no reason to re-invent all the logic for that (as is done in this, this and other answers).
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
Double-tap and Single-tap with no delay
The potential problem with onSingleTapConfirmed
is the delay. Sometimes a noticeable delay is not acceptable. In that case you can replace onSingleTapConfirmed
with onSingleTapUp
.
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public boolean onDoubleTap(MotionEvent e) {
return true;
}
}
You need to realize, though, that both onSingleTapUp
and onDoubleTap
will be called if there is a double-tap. (This is essentially what bughi's answer does and what some of the commenters were complaining about.) You either need to use the delay or call both methods. It's not possible have a single-tap with no delay and at the same time know whether the user is going to tap again.
If the single-tap delay is not acceptable for you then you have a couple options:
onSingleTapUp
and onDoubleTap
will be called for a double-tap. Just divide up your logic appropriately so that it doesn't matter. This is essentially what I did when I implemented a double-tap for caps-lock on a custom keyboard.Don't use a double-tap. It's not an intuitive UI action for most things. As Dave Webb suggests, a long press is probably better. You can also implement that with the SimpleOnGestureListener
:
private class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onDown(MotionEvent e) {
return true;
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
@Override
public void onLongPress(MotionEvent e) {
}
}
Yes, you can merge them using HTML. When I create tables in .md
files from Github, I always like to use HTML code instead of markdown.
Github Flavored Markdown supports basic HTML in .md
file. So this would be the answer:
Markdown mixed with HTML:
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
| <ul><li>item1</li><li>item2</li></ul>| See the list | from the first column|
Or pure HTML:
<table>
<tbody>
<tr>
<th>Tables</th>
<th align="center">Are</th>
<th align="right">Cool</th>
</tr>
<tr>
<td>col 3 is</td>
<td align="center">right-aligned</td>
<td align="right">$1600</td>
</tr>
<tr>
<td>col 2 is</td>
<td align="center">centered</td>
<td align="right">$12</td>
</tr>
<tr>
<td>zebra stripes</td>
<td align="center">are neat</td>
<td align="right">$1</td>
</tr>
<tr>
<td>
<ul>
<li>item1</li>
<li>item2</li>
</ul>
</td>
<td align="center">See the list</td>
<td align="right">from the first column</td>
</tr>
</tbody>
</table>
This is how it looks on Github:
You know, sometimes it's just easier to work with a BackgroundWorker regardless of if you're using Windows Forms, WPF or whatever technology. The neat part about these guys is you get threading without having to worry too much about where you're thread is executing, which is great for simple tasks.
Before using a BackgroundWorker
consider first if you wish to cancel a thread (closing app, user cancellation) then you need to decide if your thread should check for cancellations or if it should be thrust upon the execution itself.
BackgroundWorker.CancelAsync()
will set CancellationPending
to true
but won't do anything more, it's then the threads responsibility to continually check this, keep in mind also that you could end up with a race condition in this approach where your user cancelled, but the thread completed prior to testing for CancellationPending
.
Thread.Abort()
on the other hand will throw an exception within the thread execution which enforces cancellation of that thread, you must be careful about what might be dangerous if this exception was suddenly raised within the execution though.
Threading needs very careful consideration no matter what the task, for some further reading:
Parallel Programming in the .NET Framework Managed Threading Best Practices
You can change configuration file schema back to DotNetConfig.xsd
via properties of the app.config
file. To find destination of needed schema, you can search it by name or create a WinForms application, add to project the configuration file and in it's properties, you'll find full path to file.
Why to use regex? PHP has some built in functionality to do that
<?php
$valid_symbols = array('-', '_');
$string1 = "This is a string*";
$string2 = "this_is-a-string";
if(preg_match('/\s/',$string1) || !ctype_alnum(str_replace($valid_symbols, '', $string1))) {
echo "String 1 not acceptable acceptable";
}
?>
preg_match('/\s/',$username)
will check for blank space
!ctype_alnum(str_replace($valid_symbols, '', $string1))
will check for valid_symbols
Easier still: return a pointer to a string that's been malloc'd with strdup.
#include <ncurses.h>
char * getStr(int length)
{
char word[length];
for (int i = 0; i < length; i++)
{
word[i] = getch();
}
word[i] = '\0';
return strdup(&word[0]);
}
int main()
{
char wordd[10];
initscr();
*wordd = getStr(10);
printw("The string is:\n");
printw("%s\n",*wordd);
getch();
endwin();
return 0;
}
openssl pkcs12 -inkey bob_key.pem -in bob_cert.cert -export -out bob_pfx.pfx
first taking the full path including directory and extracting the directory
//Just for the sake of example
cwd=process.cwd()
filendir=path.resolve(cwd,'_site/assets/text','node.txt')
// Extracting directory name
mkdir=path.dirname(filendir)
Now make the directory, add option recursive:true as stated by @David Weldon
fs.mkdirSync(mkdir,{recursive:true})
Then make the file
data='Some random text'
fs.writeFileSync(filendir,data)
You are correct - here is a fully working example - you'll see that var result
is implicitly a string because the return type is specified on the greet()
function. Change the type to number
and you'll get warnings.
class Greeter {
greeting: string;
constructor (message: string) {
this.greeting = message;
}
greet() : string {
return "Hello, " + this.greeting;
}
}
var greeter = new Greeter("Hi");
var result = greeter.greet();
Here is the number example - you'll see red squiggles in the playground editor if you try this:
greet() : number {
return "Hello, " + this.greeting;
}
I doubt I'd use it in a mission-critical system, but Derby has always been very interesting to me.
Here is a very simple and easy to follow example.
private int CalculateAge()
{
//get birthdate
DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);
int byear = dtBirth.Year;
int bmonth = dtBirth.Month;
int bday = dtBirth.Day;
DateTime dtToday = DateTime.Now;
int tYear = dtToday.Year;
int tmonth = dtToday.Month;
int tday = dtToday.Day;
int age = tYear - byear;
if (bmonth < tmonth)
age--;
else if (bmonth == tmonth && bday>tday)
{
age--;
}
return age;
}
This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.
As pointed out, the lubridate package has nice extraction functions.
For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.
Try inserting this clearing div before the last </div>
<div style="clear: both; line-height: 0;"> </div>
Long count = (Long) session.createQuery("select count(*) from Book").uniqueResult();
It'll be easier (and more "proper", see below) if you just run your script as
myprogram /path/to/file
Then you can access the path within the script as $1
(for argument #1, similarly $2
is argument #2, etc.)
file="$1"
externalprogram "$file" [other parameters]
Or just
externalprogram "$1" [otherparameters]
If you want to extract the path from something like --file=/path/to/file
, that's usually done with the getopts
shell function. But that's more complicated than just referencing $1
, and besides, switches like --file=
are intended to be optional. I'm guessing your script requires a file name to be provided, so it doesn't make sense to pass it in an option.
No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.
Please refer to this discussion about why it's even in .NET.
I guess UnsupportedOperationException
comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there?
Interface segregation or Liskov substitution issues maybe?
If it's work in progress I'd go for ToBeImplementedException
, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.
You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.
You can wait for a file to be ready by using this function in a loop.
Its another way to declare the constructor. You can also use the class name, for ex:
class Cat
{
function Cat()
{
echo 'meow';
}
}
and
class Cat
{
function __construct()
{
echo 'meow';
}
}
Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:
$cat = new Cat();
just in case you are using a remote access and want to dump all database data, you can use:
pg_dump -a -h your_host -U your_user -W -Fc your_database > DATA.dump
it will create a dump with all database data and use
pg_restore -a -h your_host -U your_user -W -Fc your_database < DATA.dump
to insert the same data in your data base considering you have the same structure
I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html
The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...
However, I’m not sure about using canvas to compress images, but you can certainly resize them.
This works for me:
public void updatedatabase()
{
SqlConnection conn = new SqlConnection("Data Source=" + txtserver.Text.Trim() + ";Initial Catalog=" + txtdatabase.Text.Trim() + ";User ID=" + txtuserid.Text.Trim() + ";Password=" + txtpwd.Text.Trim() + "");
try
{
conn.Open();
string script = File.ReadAllText(Server.MapPath("~/Script/DatingDemo.sql"));
// split script on GO command
IEnumerable<string> commandStrings = Regex.Split(script, @"^\s*GO\s*$", RegexOptions.Multiline | RegexOptions.IgnoreCase);
foreach (string commandString in commandStrings)
{
if (commandString.Trim() != "")
{
new SqlCommand(commandString, conn).ExecuteNonQuery();
}
}
lblmsg.Text = "Database updated successfully.";
}
catch (SqlException er)
{
lblmsg.Text = er.Message;
lblmsg.ForeColor = Color.Red;
}
finally
{
conn.Close();
}
}
This can be done even without renaming the local branch in three simple steps:
You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
DateTimePicker1.Format = DateTimePickerFormat.Custom
DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub
Control-C works, although depending on what the process is doing it might not take right away.
If you're on a unix based system, one thing I do is control-z to go back to the command line prompt and then issue a 'kill' to the process ID.
You might have forgotten to auto increment the id field.
WAY-1 : Updated for the shortest and easy way
Below command will give you the path, But it will only work if java command is working in other words if java path is configured.
readlink -f $(which java)
Read more at Where can I find the Java SDK in Linux?
WAY-2 (Better than WAY-1) : Below answer is still working and try it if above command is not working for you.
You need to dig into symbolic links. Below is steps to get Java directory
Step 1:
$ whereis java
java: /usr/bin/java /etc/java /usr/share/java
That tells the command java resides in /usr/bin/java.
Dig again:
Step 2:
$ ls -l /usr/bin/java
lrwxrwxrwx 1 root root 22 2009-01-15 18:34 /usr/bin/java -> /etc/alternatives/java
So, now we know that /usr/bin/java
is actually a symbolic link to /etc/alternatives/java
.
Dig deeper using the same method above:
Step 3:
$ ls -l /etc/alternatives/java
lrwxrwxrwx 1 root root 31 2009-01-15 18:34 /etc/alternatives/java -> /usr/local/jre1.6.0_07/bin/java
So, thats the actual location of java: /usr/local/jre.....
You could still dig deeper to find other symbolic links.
Reference : where is java's home dir?
Add a column to the left so that B10 to B20 is your named range Age.
Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex
.
The 5th element can be then found by using an array formula:
=sum( Age * (1 * (AgeIndex = 5) )
As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:
{=sum( Age * (1 * (AgeIndex = 5) )}
Just press windows button and type %APPDATA% and type enter.
Above is the location where you can find \npm\node_modules folder. This is where global modules sit in your system.
Presumably this would work:
IF(compliment = 'set' OR compliment = 'Y' OR compliment = 1, 'Y', 'N') AS customer_compliment
For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.
For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:
sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now # to exit the container
Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.
string path = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();
This is probably a more "correct" way of getting it.
$ npm run tsc -- --init
This worked for the below package.json
"devDependencies": {
"@types/jasmine": "^3.6.2",
"@types/node": "^14.14.19",
"jasmine": "^3.6.3",
"protractor": "^7.0.0",
"typescript": "^4.1.3"
},
You're over-complicating it - it just needs to be:
void generateArray(int *a, int si)
{
for (int j = 0; j < si; j++)
a[j] = rand() % 9;
}
int main()
{
const int size=5;
int a[size];
generateArray(a, size);
return 0;
}
When you pass an array as a parameter to a function it decays to a pointer to the first element of the array. So there is normally never a need to pass a pointer to an array.
The spring configuration precedence is as follows.
So your configuration will be overridden at the command-line if you wish to do that. But the recommendation is to avoid overriding, though you can use multiple profiles.
read
without any parameters will only continue if you press enter.
The DOS pause
command will continue if you press any key. Use read –n1
if you want this behaviour.
HashMap
is an implementation of Map
. Map is just an interface for any type of map.
The System.Math.Round
method uses the Double
structure, which, as others have pointed out, is prone to floating point precision errors. The simple solution I found to this problem when I encountered it was to use the System.Decimal.Round
method, which doesn't suffer from the same problem and doesn't require redifining your variables as decimals:
Decimal.Round(0.575, 2, MidpointRounding.AwayFromZero)
Result: 0.58
const inpT = document.getElementById("text-box");_x000D_
const inpC = document.getElementById("text-box-content");_x000D_
// swch gets inputs ._x000D_
var swch;_x000D_
// swch if corsur is active in inputs defaulte is false ._x000D_
var isSelect = false;_x000D_
_x000D_
var crnselect;_x000D_
// on focus_x000D_
function setSwitch(e) {_x000D_
swch = e;_x000D_
isSelect = true;_x000D_
console.log("set Switch: " + isSelect);_x000D_
}_x000D_
// on click ev_x000D_
function setEmoji() {_x000D_
if (isSelect) {_x000D_
console.log("emoji added :)");_x000D_
swch.value += ":)";_x000D_
swch.setSelectionRange(2,2 );_x000D_
isSelect = true;_x000D_
}_x000D_
_x000D_
}_x000D_
// on not selected on input . _x000D_
function onout() {_x000D_
// ?????? ??? ?? ?? _x000D_
crnselect = inpC.selectionStart;_x000D_
_x000D_
// return input select not active after 200 ms ._x000D_
var len = swch.value.length;_x000D_
setTimeout(() => {_x000D_
(len == swch.value.length)? isSelect = false:isSelect = true;_x000D_
}, 200);_x000D_
}
_x000D_
<h1> Try it !</h1>_x000D_
_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box" size="20" value="title">_x000D_
<input type="text" onfocus = "setSwitch(this)" onfocusout = "onout()" id="text-box-content" size="20" value="content">_x000D_
<button onclick="setEmoji()">emogi :) </button>
_x000D_
To remove black background only add background-color: white; to the style of
i was using the tkinter messagebox but it would crash my code. i didn't want to find out why so i used the ctypes module instead.
for example:
import ctypes
ctypes.windll.user32.MessageBoxW(0, "Your text", "Your title", 1)
i got that code from Arkelis
i liked that it didn't crash the code so i worked on it and added a threading so the code after would run.
example for my code
import ctypes
import threading
def MessageboxThread(buttonstyle, title, text, icon):
threading.Thread(
target=lambda: ctypes.windll.user32.MessageBoxW(buttonstyle, text, title, icon)
).start()
messagebox(0, "Your title", "Your text", 1)
for button styles and icon numbers:
## Button styles:
# 0 : OK
# 1 : OK | Cancel
# 2 : Abort | Retry | Ignore
# 3 : Yes | No | Cancel
# 4 : Yes | No
# 5 : Retry | No
# 6 : Cancel | Try Again | Continue
## To also change icon, add these values to previous number
# 16 Stop-sign icon
# 32 Question-mark icon
# 48 Exclamation-point icon
# 64 Information-sign icon consisting of an 'i' in a circle
I know this question is tagged as C# but the concepts are pretty generic questions like this redirect here. So I am going to provide my point of view here (a bit biased from java point of view where I am more comfortable).
When we think of Object-oriented nature we always think of Objects, class (objects blueprints) and the relationship between them. Objects are related and interact with each other via methods. In other words the object of one class may use services/methods provided by the object of another class. This kind of relationship is termed as association..
Aggregation and Composition are subsets of association meaning they are specific cases of association.
Confused?
Composition Example : Consider the example of a Car and an engine that is very specific to that car (meaning it cannot be used in any other car). This type of relationship between Car and SpecificEngine class is called Composition. An object of the Car class cannot exist without an object of SpecificEngine class and object of SpecificEngine has no significance without Car class. To put in simple words Car class solely "owns" the SpecificEngine class.
Aggregation Example : Now consider class Car and class Wheel. Car needs a Wheel object to function. Meaning the Car object owns the Wheel object but we cannot say the Wheel object has no significance without the Car Object. It can very well be used in a Bike, Truck or different Cars Object.
Summing it up -
To sum it up association is a very generic term used to represent when a class uses the functionalities provided by another class. We say it's composition if one parent class object owns another child class object and that child class object cannot meaningfully exist without the parent class object. If it can then it is called Aggregation.
More details here. I am the author of http://opensourceforgeeks.blogspot.in and have added a link above to the relevant post for more context.
You should use style instead of background color. Try searching holoeverywhere then I think this one will help you solve your problem
just change some of the 9patch resources to customize the edittext look and feel.
:sp %:h
- directory listing / file-chooser using the current file's directory
(belongs as a comment under rampion's cd
tip, but I don't have commenting-rights yet)
The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.
Passing and returning an integer
The C++ code for a function which takes an integer and adds one to the returned value,
extern "C" int add_one(int i)
{
return i+1;
}
Saved as file test.cpp
, note the required extern "C" (this can be removed for C code).
This is compiled using g++, with arguments similar to Chinmay Kanchi answer,
g++ -shared -o testlib.so -fPIC test.cpp
The Python code uses load_library
from the numpy.ctypeslib
assuming the path to the shared library in the same directory as the Python script,
import numpy.ctypeslib as ctl
import ctypes
libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)
py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)
This prints 6 as expected.
Passing and printing an array
You can also pass arrays as follows, for a C code to print the element of an array,
extern "C" void print_array(double* array, int N)
{
for (int i=0; i<N; i++)
cout << i << " " << array[i] << endl;
}
which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,
import numpy as np
py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64,
flags='aligned, c_contiguous'),
ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)
where we specify the array, the first argument to print_array
, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,
1.4
2.6
3.0
Change only in two line and you are getting actually what you want.
$query = $this->db->get();
$ret = $query->row();
return $ret->campaign_id;
try it.
tried the above methods but mine stopped auto-compile when it felt like it, due to maximum files to watch have passed the limit.
run cat /proc/sys/fs/inotify/max_user_watches
command .
if it's showing fewer files count including node_modules then open the file
/etc/sysctl.conf
in root privilege and append
fs.inotify.max_user_watches=524288
into the file and save
run again the cat command to see the result. It will work! hopefully!
You don't need to - if the favicon is place in the root at favicon.ico, browsers will automatically pick it up.
If you don't see it working, clear your cache etc, it does work without the markup. You only need to use the code if you want to call it something else, or put it on a CDN for instance.
I ran into this problem with templated classes. Here's a more general solution I had to use:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// Friend means operator<< can use private variables
// It needs to be declared as a template, but T is taken
template <class U>
friend std::ostream& operator<<(std::ostream&, const myClass<U> &);
}
// Operator is a non-member and global, so it's not myClass<U>::operator<<()
// Because of how C++ implements templates the function must be
// fully declared in the header for the linker to resolve it :(
template <class U>
std::ostream& operator<<(std::ostream& os, const myClass<U> & obj)
{
obj.toString(os);
return os;
}
Now: * My toString() function can't be inline if it is going to be tucked away in cpp. * You're stuck with some code in the header, I couldn't get rid of it. * The operator will call the toString() method, it's not inlined.
The body of operator<< can be declared in the friend clause or outside the class. Both options are ugly. :(
Maybe I'm misunderstanding or missing something, but just forward-declaring the operator template doesn't link in gcc.
This works too:
template class <T>
class myClass
{
int myField;
// Helper function accessing my fields
void toString(std::ostream&) const;
// For some reason this requires using T, and not U as above
friend std::ostream& operator<<(std::ostream&, const myClass<T> &)
{
obj.toString(os);
return os;
}
}
I think you can also avoid the templating issues forcing declarations in headers, if you use a parent class that is not templated to implement operator<<, and use a virtual toString() method.
You can use a modulus to get the remainder. Though @cnicutar's answer seems cleaner/more direct.
You can just use git diff
to produce a unified diff suitable for git apply
:
git diff tag1..tag2 > mypatch.patch
You can then apply the resulting patch with:
git apply mypatch.patch
To do that, you must remove all '
charachters in your string or use an escape character. Like:
<?php
echo '<?php
echo \'hello world\';
?>';
?>
This way to pass value from Controller to View:
ViewData["ID"] = _obj.ID;
Here is the way to pass value from View to Controller back:
<input type="button" title="Next" value="Next Step" onclick="location.href='@Url.Action("CreatePerson", "Person", new { ID = ViewData["ID"] })'" />
I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.
I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.
var _RemoveBtn = document.getElementsByClassName("remove");
for(var i=0 ; i<_RemoveBtn.length ; i++){
_RemoveBtn[i].addEventListener('click',sample,false);
}
function sample(event){
console.log(event.currentTarget.parentNode);
}
a = 10.1234
print(f"{a:0.2f}")
in 0.2f:
A detailed video on f-string for numbers https://youtu.be/RtKUsUTY6to?t=606
In DBeaver you can use parameters in queries just like you can from code, so this will work:
SELECT *
FROM somewhere
WHERE something = :myvar
When you run the query DBeaver will ask you for the value for :myvar and run the query.
If you don't want to use the Task class (for instance, in .NET 3.5) you can just start all your threads, and then add them to the list and join them in a foreach loop.
Example:
List<Thread> threads = new List<Thread>();
// Start threads
for(int i = 0; i<10; i++)
{
int tmp = i; // Copy value for closure
Thread t = new Thread(() => Console.WriteLine(tmp));
t.Start;
threads.Add(t);
}
// Await threads
foreach(Thread thread in threads)
{
thread.Join();
}
It took me a while to figure this out too. url_for
in Flask looks for endpoints that you specified in the routes.py
script.
So if you have a decorator in your routes.py
file like @blah.route('/folder.subfolder')
then Flask will recognize the command {{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The 'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.
However let us say that you stored your image file, some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flask routes.py
, your route decorator looks like @blah.routes('/folder')
. You then have to ask for your image file this way:
{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
If you have named tuples you can do this:
results = [t.age for t in mylist if t.person_id == 10]
Otherwise use indexes:
results = [t[1] for t in mylist if t[0] == 10]
Or use tuple unpacking as per Nate's answer. Note that you don't have to give a meaningful name to every item you unpack. You can do (person_id, age, _, _, _, _)
to unpack a six item tuple.
This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:
Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).
Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.
A future version of PowerShell Core will have a
Convert-TextFile
cmdlet with a -LineEnding
parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.
In PSv5+, PowerShell-native solutions are now possible, because Set-Content
now supports the -NoNewline
switch, which prevents undesired appending of a platform-native newline[1]
:
# Convert CRLFs to LFs only.
# Note:
# * (...) around Get-Content ensures that $file is read *in full*
# up front, so that it is possible to write back the transformed content
# to the same file.
# * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
# expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
The above relies on Get-Content
's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.
Caveats:
You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding
; without -Encoding
:
The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.
There's a risk of file corruption, if the process of writing back to the input file gets interrupted.
[1] In fact, if there are multiple strings to write, -NoNewline
also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.
I was having this error w/Citect.
Microsoft Visual C++ 2005 Service Pack 1 Redistributable Package MFC Security Update has the missing files.
Put the .jar
files in libs
folder of the Android project.
Then add this line of code in the app's gradle file:
compile fileTree(dir: 'libs', include: ['*.jar'])
For Android gradle plugin 3.0 and later, it is better to use this instead:
implementation fileTree(dir: 'libs', include: ['*.jar'])
I solved the problem by changing windows user access for the project folder:
Here is a screenshot: http://prntscr.com/djdn0g
It appears that TortoiseSVN (TortoiseMerge) requires the line Index: foobar.py
in the diff/patch file. This is what I needed to do to make a non-TortoiseSVN patch file work with TortoiseSVN's right-click Apply Patch command.
Before:
--- foobar.py.org Sat May 08 16:00:56 2010
+++ foobar.py Sat May 08 15:47:48 2010
After:
Index: foobar.py
===================================================================
--- foobar.py
+++ foobar.py (working copy)
Or if you know the specific revision your contributor was working from:
Index: foobar.py
===================================================================
--- foobar.py (revision 1157)
+++ foobar.py (working copy)
I had the same error code when I used @Transaction
on a wrong method/actionlevel.
methodWithANumberOfDatabaseActions() {
methodA( ...)
methodA( ...)
}
@Transactional
void methodA( ...) {
... ERROR message
}
I had to place the @Transactional
just above the method methodWithANumberOfDatabaseActions()
, of course.
That solved the error message in my case.
This code will accept all country code with + sign
<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>
Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.
If you want to extract the files to the respective folder you can try this
find . -name "*.zip" | while read filename; do unzip -o -d "`dirname "$filename"`" "$filename"; done;
A multi-processed version for systems that can handle high I/O:
find . -name "*.zip" | xargs -P 5 -I fileName sh -c 'unzip -o -d "$(dirname "fileName")/$(basename -s .zip "fileName")" "fileName"'
You might want to take a look this:
HotSwap support: the object-oriented architecture of the Java HotSpot VM enables advanced features such as on-the-fly class redefinition, or "HotSwap". This feature provides the ability to substitute modified code in a running application through the debugger APIs. HotSwap adds functionality to the Java Platform Debugger Architecture, enabling a class to be updated during execution while under the control of a debugger. It also allows profiling operations to be performed by hotswapping in versions of methods in which profiling code has been inserted.
For the moment, this only allows for newly compiled method body to be redeployed without restarting the application. All you have to do is to run it with a debugger. I tried it in Eclipse and it works splendidly.
Also, as Emmanuel Bourg mentioned in his answer (JEP 159), there is hope to have support for the addition of supertypes and the addition and removal of methods and fields.
Reference: Java Whitepaper 135217: Reliability, Availability and Serviceability
PS C:\Windows\System32\WindowsPowerShell\v1.0>split-path "H:\Documents\devops\tp-mkt-SPD-38.4.10.msi" -leaf
tp-mkt-SPD-38.4.10.msi
PS C:\Windows\System32\WindowsPowerShell\v1.0> $psversiontable
Name Value
---- -----
CLRVersion 2.0.50727.5477
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
One observation: (though this can be thought of side effect)
boolean being a primitive can either say yes or no.
Boolean is an object (it can refer to either yes or no or 'don't know' i.e. null)
According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.
You can't avoid a server call here, JavaScript simply cannot (for security reasons) save a file to the user's file system. You'll have to submit your data to the server and have it send the .csv
as a link or an attachment directly.
HTML5 has some ability to do this (though saving really isn't specified - just a use case, you can read the file if you want), but there's no cross-browser solution in place now.
I solved it through googling:
var ObjectId = require('mongoose').Types.ObjectId;
var objId = new ObjectId( (param.length < 12) ? "123456789012" : param );
// You should make string 'param' as ObjectId type. To avoid exception,
// the 'param' must consist of more than 12 characters.
User.find( { $or:[ {'_id':objId}, {'name':param}, {'nickname':param} ]},
function(err,docs){
if(!err) res.send(docs);
});
if you are using netbeans you can add a jlabel to the frame and through properties change its icon to your image and remove the text. then move the jlabel to the bottom of the Jframe or any content pane through navigator
Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.
Check out the instanceof operator.
var isJqueryObject = obj instanceof jQuery