To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
You can write like below given code.
HTML
<input type="checkbox" id="estado_cat" class="ibtn">
jQuery
$(document).ready(function(){
$(".ibtn").click(function(){
$(".ibtn").attr("checked", "checked");
});
});
Hope it work for you.
Here is way to avoid absolute divs and tables if you know parent's height:
<div class="parent">
<div class="child"> <a href="#">Home</a>
</div>
</div>
CSS:
.parent {
line-height:80px;
border: 1px solid black;
}
.child {
line-height:normal;
display: inline-block;
vertical-align:bottom;
border: 1px solid red;
}
JsFiddle:
I could not get this working with the accepted answer, mainly because I did not know where to enter that code. I looked everywhere for some explanation of the URL Rewrite tool that made sense, but could not find any. I ended up using the HTTP Redirect tool in IIS.
Hope this helps.
According to the documentation on here http://angularjs.blogspot.co.uk/2017/03/angular-400-now-available.html you 'should' just be able to run...
npm install @angular/{common,compiler,compiler-cli,core,forms,http,platform-browser,platform-browser-dynamic,platform-server,router,animations}@latest typescript@latest --save
I tried it and got a couple of errors due to my zone.js and ngrx/store libraries being older versions.
Updating those to the latest versions npm install zone.js@latest --save
and npm install @ngrx/store@latest -save
, then running the angular install again worked for me.
Put quotes around the <?php echo $cname; ?>
to make sure Javascript accepts it as a string, also consider escaping.
The response is a bit late - but in case anyone has the issue in the future...
From the screenshot above - it seems that you are adding the url data (username, password, grant_type) to the header and not to the body element.
Clicking on the body tab, and then select "x-www-form-urlencoded" radio button, there should be a key-value list below that where you can enter the request data
Further reading for any of the topics here: The Definitive Guide to Linux System Calls
I verified these using GNU Assembler (gas) on Linux.
x86-32 aka i386 Linux System Call convention:
In x86-32 parameters for Linux system call are passed using registers. %eax
for syscall_number. %ebx, %ecx, %edx, %esi, %edi, %ebp are used for passing 6 parameters to system calls.
The return value is in %eax
. All other registers (including EFLAGS) are preserved across the int $0x80
.
I took following snippet from the Linux Assembly Tutorial but I'm doubtful about this. If any one can show an example, it would be great.
If there are more than six arguments,
%ebx
must contain the memory location where the list of arguments is stored - but don't worry about this because it's unlikely that you'll use a syscall with more than six arguments.
For an example and a little more reading, refer to http://www.int80h.org/bsdasm/#alternate-calling-convention. Another example of a Hello World for i386 Linux using int 0x80
: Hello, world in assembly language with Linux system calls?
There is a faster way to make 32-bit system calls: using sysenter
. The kernel maps a page of memory into every process (the vDSO), with the user-space side of the sysenter
dance, which has to cooperate with the kernel for it to be able to find the return address. Arg to register mapping is the same as for int $0x80
. You should normally call into the vDSO instead of using sysenter
directly. (See The Definitive Guide to Linux System Calls for info on linking and calling into the vDSO, and for more info on sysenter
, and everything else to do with system calls.)
x86-32 [Free|Open|Net|DragonFly]BSD UNIX System Call convention:
Parameters are passed on the stack. Push the parameters (last parameter pushed first) on to the stack. Then push an additional 32-bit of dummy data (Its not actually dummy data. refer to following link for more info) and then give a system call instruction int $0x80
http://www.int80h.org/bsdasm/#default-calling-convention
(Note: x86-64 Mac OS X is similar but different from Linux. TODO: check what *BSD does)
Refer to section: "A.2 AMD64 Linux Kernel Conventions" of System V Application Binary Interface AMD64 Architecture Processor Supplement. The latest versions of the i386 and x86-64 System V psABIs can be found linked from this page in the ABI maintainer's repo. (See also the x86 tag wiki for up-to-date ABI links and lots of other good stuff about x86 asm.)
Here is the snippet from this section:
- User-level applications use as integer registers for passing the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9. The kernel interface uses %rdi, %rsi, %rdx, %r10, %r8 and %r9.
- A system-call is done via the
syscall
instruction. This clobbers %rcx and %r11 as well as the %rax return value, but other registers are preserved.- The number of the syscall has to be passed in register %rax.
- System-calls are limited to six arguments, no argument is passed directly on the stack.
- Returning from the syscall, register %rax contains the result of the system-call. A value in the range between -4095 and -1 indicates an error, it is
-errno
.- Only values of class INTEGER or class MEMORY are passed to the kernel.
Remember this is from the Linux-specific appendix to the ABI, and even for Linux it's informative not normative. (But it is in fact accurate.)
This 32-bit int $0x80
ABI is usable in 64-bit code (but highly not recommended). What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code? It still truncates its inputs to 32-bit, so it's unsuitable for pointers, and it zeros r8-r11.
x86-32 Function Calling convention:
In x86-32 parameters were passed on stack. Last parameter was pushed first on to the stack until all parameters are done and then call
instruction was executed. This is used for calling C library (libc) functions on Linux from assembly.
Modern versions of the i386 System V ABI (used on Linux) require 16-byte alignment of %esp
before a call
, like the x86-64 System V ABI has always required. Callees are allowed to assume that and use SSE 16-byte loads/stores that fault on unaligned. But historically, Linux only required 4-byte stack alignment, so it took extra work to reserve naturally-aligned space even for an 8-byte double
or something.
Some other modern 32-bit systems still don't require more than 4 byte stack alignment.
x86-64 System V passes args in registers, which is more efficient than i386 System V's stack args convention. It avoids the latency and extra instructions of storing args to memory (cache) and then loading them back again in the callee. This works well because there are more registers available, and is better for modern high-performance CPUs where latency and out-of-order execution matter. (The i386 ABI is very old).
In this new mechanism: First the parameters are divided into classes. The class of each parameter determines the manner in which it is passed to the called function.
For complete information refer to : "3.2 Function Calling Sequence" of System V Application Binary Interface AMD64 Architecture Processor Supplement which reads, in part:
Once arguments are classified, the registers get assigned (in left-to-right order) for passing as follows:
- If the class is MEMORY, pass the argument on the stack.
- If the class is INTEGER, the next available register of the sequence %rdi, %rsi, %rdx, %rcx, %r8 and %r9 is used
So %rdi, %rsi, %rdx, %rcx, %r8 and %r9
are the registers in order used to pass integer/pointer (i.e. INTEGER class) parameters to any libc function from assembly. %rdi is used for the first INTEGER parameter. %rsi for 2nd, %rdx for 3rd and so on. Then call
instruction should be given. The stack (%rsp
) must be 16B-aligned when call
executes.
If there are more than 6 INTEGER parameters, the 7th INTEGER parameter and later are passed on the stack. (Caller pops, same as x86-32.)
The first 8 floating point args are passed in %xmm0-7, later on the stack. There are no call-preserved vector registers. (A function with a mix of FP and integer arguments can have more than 8 total register arguments.)
Variadic functions (like printf
) always need %al
= the number of FP register args.
There are rules for when to pack structs into registers (rdx:rax
on return) vs. in memory. See the ABI for details, and check compiler output to make sure your code agrees with compilers about how something should be passed/returned.
Note that the Windows x64 function calling convention has multiple significant differences from x86-64 System V, like shadow space that must be reserved by the caller (instead of a red-zone), and call-preserved xmm6-xmm15. And very different rules for which arg goes in which register.
One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing
For example
Smoothing at five sample points A, B, C, D, E
ATOTAL = SUM of distances AB AC AD AE
BTOTAL = SUM of distances AB BC BD BE
CTOTAL = SUM of distances AC BC CD CE
DTOTAL = SUM of distances DA DB DC DE
ETOTAL = SUM of distances EA EB EC DE
If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }
This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.
Use a conversion function of MYSQL :
SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05'
This should work
If you need a dynamic choice field in django admin; This works for django >=2.1.
class CarAdminForm(forms.ModelForm):
class Meta:
model = Car
def __init__(self, *args, **kwargs):
super(CarForm, self).__init__(*args, **kwargs)
# Now you can make it dynamic.
choices = (
('audi', 'Audi'),
('tesla', 'Tesla')
)
self.fields.get('car_field').choices = choices
car_field = forms.ChoiceField(choices=[])
@admin.register(Car)
class CarAdmin(admin.ModelAdmin):
form = CarAdminForm
Hope this helps.
You can refer to the proxy documentation here.
If you need to use a proxy, you can configure individual requests with the proxies argument to any request method:
import requests
proxies = {
"http": "http://10.10.1.10:3128",
"https": "https://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)
To use HTTP Basic Auth with your proxy, use the http://user:[email protected]/ syntax:
proxies = {
"http": "http://user:[email protected]:3128/"
}
if you want integer x value change if 1 to 0 and if 0 to 1 you can use (x + 1) % 2
Running a from class inside your JAR file load.jar
is possible via
java -jar load.jar
When doing so, you have to define the application entry point. Usually this is done by providing a manifest file that contains the Main-Class
tag. For documentation and examples have a look at this page.
The argument load=2
can be supplied like in a normal Java applications:
java -jar load.jar load=2
Having also the current directory contained in the classpath, required to also make use of the Class-Path
tag. See here for more information.
The Bootstrap version will be stated at the top of the CSS file. Simply open it and look at the top of the file.
e.g.
/*!
* Bootstrap v2.3.0
*
* Copyright 2012 Twitter, Inc
* Licensed under the Apache License v2.0
* http://www.apache.org/licenses/LICENSE-2.0
*
* Designed and built with all the love in the world @twitter by @mdo and @fat.
*/
$mail = new PHPMailer();
$mail->AddAddress($email);
$mail->From = $from;
$mail->Subject = $subject;
$mail->Body = $body;
if($mail->Send()){
echo 'Email Successfully Sent!';
}else{
echo 'Email Sending Failed!';
}
the simplest way to handle email sending successful or failed...
They must have included this as a feature, because now setting a different @JsonProperty
for a getter and setter results in exactly what you would expect (different property name during serialization and deserialization for the same field). Jackson version 2.6.7
How about something like
CREATE TABLE testRequest (
wardNo nchar(5),
BHTNo nchar(5),
testID nchar(5),
reqDateTime datetime,
PRIMARY KEY (wardNo, BHTNo, testID)
);
Have a look at this example
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
You could also use a URI template. If you structured your request into a restful URL Spring could parse the provided value from the url.
HTML
<li>
<a id="byParameter"
class="textLink" href="<c:url value="/mapping/parameter/bar />">By path, method,and
presence of parameter</a>
</li>
Controller
@RequestMapping(value="/mapping/parameter/{foo}", method=RequestMethod.GET)
public @ResponseBody String byParameter(@PathVariable String foo) {
//Perform logic with foo
return "Mapped by path + method + presence of query parameter! (MappingController)";
}
You can use:
Sub returnname(ByVal TableName As String)
MsgBox (Range("Table15").Rows.count)
End Sub
and call the function as below
Sub called()
returnname "Table15"
End Sub
(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).
First you can subclass urllib2.BaseHandler
or urllib2.HTTPBasicAuthHandler
, and implement http_request
so that each request has the appropriate Authorization
header.
import urllib2
import base64
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Then if you are lazy like me, install the handler globally
api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
realm=None, # default realm.
uri=api_url,
user=api_username,
passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
Yes lists and tuples are always ordered while dictionaries are not
In short, []
operator is more efficient for updating values because it involves calling default constructor of the value type and then assigning it a new value, while insert()
is more efficient for adding values.
The quoted snippet from Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers, Item 24 might help.
template<typename MapType, typename KeyArgType, typename ValueArgType>
typename MapType::iterator
insertKeyAndValue(MapType& m, const KeyArgType&k, const ValueArgType& v)
{
typename MapType::iterator lb = m.lower_bound(k);
if (lb != m.end() && !(m.key_comp()(k, lb->first))) {
lb->second = v;
return lb;
} else {
typedef typename MapType::value_type MVT;
return m.insert(lb, MVT(k, v));
}
}
You may decide to choose a generic-programming-free version of this, but the point is that I find this paradigm (differentiating 'add' and 'update') extremely useful.
nan = float('nan')
And now you have the constant, nan
.
You can similarly create NaN values for decimal.Decimal.:
dnan = Decimal('nan')
If you do an "Add" it will add it to the bottom of the list. You need to do an "Insert" if you want the item added to the top of the list.
Based on an earlier reply by @dmckee
make | tee makelog.txt
This gives you real-time scrolling output while compiling, and simultaneously write to the makelog.txt file.
Try Javascript .NET. It is hosted on GitHub It was originally hosted on CodePlex, here)
Project discussions: http://javascriptdotnet.codeplex.com/discussions
It implements Google V8. You can compile and run JavaScript directly from .NET code with it, and supply CLI objects to be used by the JavaScript code as well. It generates native code from JavaScript.
I implemented some code to do it manually:
using System.Security.Principal;
public bool IsUserAdministrator()
{
bool isAdmin;
try
{
WindowsIdentity user = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(user);
isAdmin = principal.IsInRole(WindowsBuiltInRole.Administrator);
}
catch (UnauthorizedAccessException ex)
{
isAdmin = false;
}
catch (Exception ex)
{
isAdmin = false;
}
return isAdmin;
}
The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.
To get around this I created a empty Div right at the top of my HTML(outside my main container)
<div id="max-width"></div>
In css I set this div to display none
#max-width {
display: none;
}
In my JS created a function
var hasSwitched = function () {
var maxWidth = parseInt($('#max-width').css('max-width'), 10);
return !isNaN(maxWidth);
};
So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following
if (!hasSwitched()) { Your code
}
else{ your code
}
By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.
To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys
Another example is, you have class like :
@obc class Album: NSObject {
let name:String
let singer:Singer
let artwork:URL
let playingSong:Song
// ...
class func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
}
you will also get the same type of error like :
instance member x cannot be used on type x.
It's because you assign your method with "class" keyword (which makes your method a type method) and using like :
Album.getCurrentlyPlayingSongLyric(duration: 5)
but who set the playingSong variable before? Ok. You shouldn't use class keyword for that case :
// ...
func getCurrentlyPlayingSongLyric(duration: Int = 0) -> String {
// ...
return playingSong.lyric
}
// ...
Now you're free to go.
I tried to remove the Image of the ImageView too by using ImageView.setImageRessource(0)
but it didn't work for me.
Luckily I got this message in the logs:
Caused by: java.lang.IllegalStateException: The specified child already has a parent.
You must call removeView() on the child's parent first.
So let's say, layoutmanager
is your instance for the layout, than you need to do that:
RelativeLayout layoutManager = new RelativeLayout(this);
ImageView image = new ImageView(this);
// this line worked for me
layoutManager.removeView(image);
If you are only doing insertions, and want one from the same session, do as per peirix's answer. If you are doing modifications, you will need to modify your database schema to store which entry was most recently updated.
If you want the id from the last modification, which may have been from a different session (i.e. not the one that was just done by the PHP code running at present, but one done in response to a different request), you can add a TIMESTAMP column to your table called last_modified (see http://dev.mysql.com/doc/refman/5.1/en/datetime.html for information), and then when you update, set last_modified=CURRENT_TIME.
Having set this, you can then use a query like: SELECT id FROM table ORDER BY last_modified DESC LIMIT 1; to get the most recently modified row.
For me I removed whole data
folder from xampp\mysql\
and pasted data
folder of previous one here which solved my problem...
If you're using Spring Boot 1.4, it has an awesome way of doing this. Just use new brand @SpringBootTest
on your class and @MockBean
on the field and Spring Boot will create a mock of this type and it will inject it into the context (instead of injecting the original one):
@RunWith(SpringRunner.class)
@SpringBootTest
public class MyTests {
@MockBean
private RemoteService remoteService;
@Autowired
private Reverser reverser;
@Test
public void exampleTest() {
// RemoteService has been injected into the reverser bean
given(this.remoteService.someCall()).willReturn("mock");
String reverse = reverser.reverseSomeCall();
assertThat(reverse).isEqualTo("kcom");
}
}
On the other hand, if you're not using Spring Boot or are you using a previous version, you'll have to do a bit more work:
Create a @Configuration
bean that injects your mocks into Spring context:
@Configuration
@Profile("useMocks")
public class MockConfigurer {
@Bean
@Primary
public MyBean myBeanSpy() {
return mock(MyBean.class);
}
}
Using @Primary
annotation you're telling spring that this bean has priority if no qualifier are specified.
Make sure you annotate the class with @Profile("useMocks")
in order to control which classes will use the mock and which ones will use the real bean.
Finally, in your test, activate userMocks
profile:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
@ActiveProfiles(profiles={"useMocks"})
public class YourIntegrationTestIT {
@Inject
private MyBean myBean; //It will be the mock!
@Test
public void test() {
....
}
}
If you don't want to use the mock but the real bean, just don't activate useMocks
profile:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = {Application.class})
@WebIntegrationTest
public class AnotherIntegrationTestIT {
@Inject
private MyBean myBean; //It will be the real implementation!
@Test
public void test() {
....
}
}
You could use an XPath, too. A bit old fashioned but still effective:
using System.Xml;
...
XmlDocument xmlDocument;
xmlDocument = new XmlDocument();
xmlDocument.LoadXml(xml);
foreach (XmlElement xmlElement in
xmlDocument.DocumentElement.SelectNodes("word[category='verb']"))
{
Console.Out.WriteLine(xmlElement.OuterXml);
}
String s1 = "HelloSuresh";
String m = s1.replace("Hello","");
System.out.println(m);
If you happen to use Rundeck for scheduling your tasks, or any other platform where you ask for a mylogin.cnf
file, I have successfully used the following shell code to provide a new location for the file before proceeding with sql calls:
if test -f "$CUSTOM_MY_LOGINS_FILE_PATH"; then
chmod 600 $CUSTOM_MY_LOGINS_FILE_PATH
export MYSQL_TEST_LOGIN_FILE="$CUSTOM_MY_LOGINS_FILE_PATH"
fi
...
result=$(mysql --login-path=production -NBA -D $schema -e "$query")
Where MYSQL_TEST_LOGIN_FILE
is an environment variable that can be set to a different file path than the default one.
This is especially useful if you are running in a forked process and can't move or copy files to the $HOME
directory.
A couple of wires are crossed here. The various autoplay
settings that you're working with only affect whether the SWF's root timeline starts out paused or not. So if your SWF had a timeline animation, or if it had an embedded video on the root timeline, then these settings would do what you're after.
However, the SWF you're working with almost certainly has only one frame on its timeline, so these settings won't affect playback at all. That one frame contains some flavor of video playback component, which contains ActionScript that controls how the video behaves. To get that player component to start of paused, you'll have to change the settings of the component itself.
Without knowing more about where the content came from it's hard to say more, but when one publishes from Flash, video player components normally include a parameter for whether to autoplay. If your SWF is being published by an application other than Flash (Captivate, I suppose, but I'm not up on that) then your best bet would be to check the settings for that app. Anyway it's not something you can control from the level of the HTML page. (Unless you were talking to the SWF from JavaScript, and for that to work the video component would have to be designed to allow it.)
Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.
I found this thread that provides a solution:
https://github.com/twbs/bootstrap/issues/1411
One of the post suggests the use of
<ul class="dropdown-menu" style="right: 0; left: auto;">
I tested and it works.
Hope to know whether Bootstrap provides config for doing this, not via the above css.
Cheers.
This means that Table A can have one or more records relating to a single record in Table B.
If you already have the tables in place, use the ALTER TABLE statement to create the foreign key constraint:
ALTER TABLE A ADD CONSTRAINT fk_b FOREIGN KEY (b_id) references b(id)
fk_b
: Name of the foreign key constraint, must be unique to the databaseb_id
: Name of column in Table A you are creating the foreign key relationship onb
: Name of table, in this case bid
: Name of column in Table B2015 answer: we have this out of the box on modern browsers, just use the HTML5 CheckValidity API from jQuery. I've also made a jquery-html5-validity module to do this:
npm install jquery-html5-validity
Then:
var $ = require('jquery')
require("jquery-html5-validity")($);
then you can run:
$('.some-class').isValid()
true
concatenated_list = list_1 + list_2
Here's a real simple one:
#include <vector>
#include <string>
using namespace std;
vector<string> split(const char *str, char c = ' ')
{
vector<string> result;
do
{
const char *begin = str;
while(*str != c && *str)
str++;
result.push_back(string(begin, str));
} while (0 != *str++);
return result;
}
I was taught that for arrays, length is not retrieved through a method due to the following fear: programmers would just assign the length to a local variable before entering a loop (think a for loop where the conditional uses the array's length.) The programmer would supposedly do so to trim down on function calls (and thereby improve performance.) The problem is that the length might change during the loop, and the variable wouldn't.
Just follow these steps i can assure pdf file will be generated
<html>
<head>
<title>Exporting table data to pdf Example</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script>
<script type="text/javascript" src="js/jspdf.js"></script>
<script type="text/javascript" src="js/from_html.js"></script>
<script type="text/javascript" src="js/split_text_to_size.js"></script>
<script type="text/javascript" src="js/standard_fonts_metrics.js"></script>
<script type="text/javascript" src="js/cell.js"></script>
<script type="text/javascript" src="js/FileSaver.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#exportpdf").click(function() {
var pdf = new jsPDF('p', 'pt', 'ledger');
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#yourTableIdName')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme' : function(element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top : 80,
bottom : 60,
left : 60,
width : 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width' : margins.width, // max width of content on PDF
'elementHandlers' : specialElementHandlers
},
function(dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
pdf.save('fileNameOfGeneretedPdf.pdf');
}, margins);
});
});
</script>
</head>
<body>
<div id="yourTableIdName">
<table style="width: 1020px;font-size: 12px;" border="1">
<thead>
<tr align="left">
<th>Country</th>
<th>State</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
<tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr><tr align="left">
<td>India</td>
<td>Telangana</td>
<td>Nirmal</td>
</tr>
</tbody>
</table></div>
<input type="button" id="exportpdf" value="Download PDF">
</body>
</html>
Output:
Html file output:
Pdf file output:
I would use:
child.center = CGPointMake(parent.bounds.height / 2, parent.bounds.width / 2)
This is simple, short, and sweet. If you use @Hejazi's answer above and parent.center
is set to anything other than (0,0)
your subview will not be centered!
I tried the options in the existing answers, mainly the one marked correct which did not work in my scenario. However, what did work was using phpMyAdmin. Select the database and then select the table, from the bottom drop down menu select "Repair table".
You need moment.lang (WARNING: lang()
is deprecated since moment 2.8.0
, use locale()
instead):
moment.lang("de").format('LLL');
http://momentjs.com/docs/#/i18n/
As of v2.8.1, moment.locale('de')
sets the localization, but does not return a moment
. Some examples:
var march = moment('2017-03')
console.log(march.format('MMMM')) // 'March'
moment.locale('de') // returns the new locale, in this case 'de'
console.log(march.format('MMMM')) // 'March' still, since the instance was before the locale was set
var deMarch = moment('2017-03')
console.log(deMarch.format('MMMM')) // 'März'
// You can, however, change just the locale of a specific moment
march.locale('es')
console.log(march.format('MMMM')) // 'Marzo'
In summation, calling locale
on the global moment
sets the locale for all future moment
instances, but does not return an instance of moment
. Calling locale
on an instance, sets it for that instance AND returns that instance.
Also, as Shiv said in the comments, make sure you use "moment-with-locales.min.js" and not "moment.min.js", otherwise it won't work.
I encountered the same issue few days ago. My audio MediaPlayer works fine on devices with high processing power, but for slow devices, the media player just did not play some time and from LogCat it had many complain about called in wrong state. So I resolved it by calling putting the call to start(), pause(),... in onPrepared() method of OnPreparedListener() as below:
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
........
mediaPlayer.start();
....
songControlBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
} else {
mediaPlayer.start();
}
}
});
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
............
}
});
}
});
Also try to release any media player that you do not need any more. For example, if you do not want to play the audio or video on background then you should call mediaPlayer.release() in onPause().
I tried restarting Xcode (7) and nothing (the have you tried switching it off and on again of iOS development for me :-)). I then tried by restarting my box and that worked.
In my case the script was failing when copying a file from a location to another one. I think it could have been related to Finder screwing with writing rights over certain folders.
Alternatively, you could create a regular Mac OS X application from your script using Platypus
On MacOSX High Sierra the solution for me was:
brew install git-lfs
and my repository was cloned without any errors.
Implement onFocusChange
of setOnFocusChangeListener
and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.
EditText txtEdit = (EditText) findViewById(R.id.edittxt);
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
}
}
});
You can do it manually. (I know, that that isn't great solution, but..)
use while
loop till the result
hasn't a value
kickOff().then(function(result) {
while(true){
if (result === undefined) continue;
else {
$("#output").append(result);
return;
}
}
});
Have to add this based on @Joseph's answer. If someone want to create image object:
var image = new Image();
image.onload = function(){
console.log(image.width); // image is loaded and we have image width
}
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);
I'm using reactive forms in angular 4 and this approach works for me:
this.profileEditForm.reset(this.profileEditForm.value);
see reset the form flags in the Fundamentals doc
For what it's worth, here's a solution I came up with using the dom4j library. (I did check that it works.)
Read the XML fragment into a org.dom4j.Document
(note: all the XML classes used below are from org.dom4j; see Appendix):
String newNode = "<node>value</node>"; // Convert this to XML
SAXReader reader = new SAXReader();
Document newNodeDocument = reader.read(new StringReader(newNode));
Then get the Document into which the new node is inserted, and the parent Element (to be) from it. (Your org.w3c.dom.Document would need to be converted to org.dom4j.Document here.) For testing purposes, I created one like this:
Document originalDoc =
new SAXReader().read(new StringReader("<root><given></given></root>"));
Element givenNode = originalDoc.getRootElement().element("given");
Adding the new child element is very simple:
givenNode.add(newNodeDocument.getRootElement());
Done. Outputting originalDoc
now yields:
<?xml version="1.0" encoding="utf-8"?>
<root>
<given>
<node>value</node>
</given>
</root>
Appendix: Because your question talks about org.w3c.dom.Document
, here's how to convert between that and org.dom4j.Document
.
// dom4j -> w3c
DOMWriter writer = new DOMWriter();
org.w3c.dom.Document w3cDoc = writer.write(dom4jDoc);
// w3c -> dom4j
DOMReader reader = new DOMReader();
Document dom4jDoc = reader.read(w3cDoc);
(If you'd need both kind of Document
s regularly, it might make sense to put these in neat utility methods, maybe in a class called XMLUtils
or something like that.)
Maybe there are better ways to do this, even without any 3rd party libraries. But out of the solutions presented so far, in my view this is the easiest way, even if you need to do the dom4j <-> w3c conversions.
Update (2011): before adding dom4j dependency to your code, note that it is not an actively maintained project, and has some other problems too. Improved version 2.0 has been in the works for ages, but there's only an alpha version available. You may want to consider an alternative, like XOM, instead; read more in the question linked above.
Your question asks about "unix shell scripting", but is tagged bash
. Those are two different answers.
The POSIX specification for shells does not have anything to say about arrays, as the original Bourne shell did not support them. Even today, on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh
does not have array support. So if you want your script to work in different Bourne-compatible shells, you shouldn't use them. Alternatively, if you are assuming a specific shell, then be sure to put its full name in the shebang line, e.g. #!/usr/bin/env bash
.
If you are using bash or zsh, or a modern version of ksh, you can create an array like this:
myArray=(first "second element" 3rd)
and access elements like this
$ echo "${myArray[1]}"
second element
You can get all the elements via "${myArray[@]}"
. You can use the slice notation ${array[@]:start:length} to restrict the portion of the array referenced, e.g. "${myArray[@]:1}"
to leave off the first element.
The length of the array is ${#myArray[@]}
. You can get a new array containing all the indexes from an existing array with "${!myArray[@]}"
.
Older versions of ksh before ksh93 also had arrays, but not the parenthesis-based notation, nor did they support slicing. You could create an array like this, though:
set -A myArray -- first "second element" 3rd
Request.Form is a NameValueCollection. In NameValueCollection you can find the GetAllValues() method.
By the way the LINQ method also works.
Copy the cell. Paste special as link. Will update with original. No formula though.
A continue
statement without a label will re-execute from the condition the innermost while
or do
loop, and from the update expression of the innermost for
loop. It is often used to early-terminate a loop's processing and thereby avoid deeply-nested if
statements. In the following example continue
will get the next line, without processing the following statement in the loop.
while (getNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}
With a label, continue
will re-execute from the loop with the corresponding label, rather than the innermost loop. This can be used to escape deeply-nested loops, or simply for clarity.
Sometimes continue
is also used as a placeholder in order to make an empty loop body more clear.
for (count = 0; foo.moreData(); count++)
continue;
The same statement without a label also exists in C and C++. The equivalent in Perl is next
.
This type of control flow is not recommended, but if you so choose you can also use continue
to simulate a limited form of goto
. In the following example the continue
will re-execute the empty for (;;)
loop.
aLoopName: for (;;) {
// ...
while (someCondition)
// ...
if (otherCondition)
continue aLoopName;
Same question as @Dan - why not StringReader ?
If it has to be InputStreamReader, then:
String charset = ...; // your charset
byte[] bytes = string.getBytes(charset);
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
InputStreamReader isr = new InputStreamReader(bais);
It's suggested that you do not use return false
, as 3 things occur as a result:
So in this type of situation, you should really only use event.preventDefault();
Archive of article - jQuery Events: Stop (Mis)Using Return False
Remove the multiple="multiple" attribute and add SIZE=6 with the number of elements you want
you may want to check this site
Interestingly, you can also use the using/IDisposable pattern for other interesting things (such as the other point of the way that Rhino Mocks uses it). Basically, you can take advantage of the fact that the compiler will always call .Dispose on the "used" object. If you have something that needs to happen after a certain operation ... something that has a definite start and end ... then you can simply make an IDisposable class that starts the operation in the constructor, and then finishes in the Dispose method.
This allows you to use the really nice using syntax to denote the explicit start and end of said operation. This is also how the System.Transactions stuff works.
This question has been already answered in Unicode characters in Windows command line - how?
You missed one step -> you need to use Lucida console fonts in addition to executing chcp 65001 from cmd console.
Try this function...
function calculate_age(birth_month,birth_day,birth_year)
{
today_date = new Date();
today_year = today_date.getFullYear();
today_month = today_date.getMonth();
today_day = today_date.getDate();
age = today_year - birth_year;
if ( today_month < (birth_month - 1))
{
age--;
}
if (((birth_month - 1) == today_month) && (today_day < birth_day))
{
age--;
}
return age;
}
OR
function getAge(dateString)
{
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate()))
{
age--;
}
return age;
}
margin does not work unfortunately on individual cells, however you could add extra columns between the two cells you want to put a space between... another option is to use a border with the same colour as the background...
It won't be exactly refering to the given problem, but I wanna share my mistake here, maybe some1 will make simmilar one and will also land with his/her problem here:
Ive got Unexpected token ILLEGAL
error because I named a function with a number as 1st char.
It was 3x3check()
.
Changing it to check3x3()
solved my problem.
If you want access to a Docker container where there is a DB, you have to add a bash:
docker exec -it postgresql bash
postgresql is the container name.
Once inside, from the bash, access to DB e.g:
$psql -U postgres
It was discussed before here.
In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.
Just to build on VisioN's answer above, if you are using the jQuery validation plugin you could use this:
$(document).ready(function() {
$.validator.addMethod('integer', function(value, element, param) {
return (value >>> 0 === parseFloat(value) && value > 0);
}, 'Please enter a non zero integer value!');
}
Then you could use in your normal rules set or add it dynamically this way:
$("#positiveIntegerField").rules("add", {required:true, integer:true});
In the situation explained below, client side will throw such an exception:
The server is asked to authenticate client certificate, but the client provides a certificate which Extended Key Usage doesn't support client auth, so the server doesn't accept the client's certificate, and then it closes the connection.
I want to point out that it has been my experience that if throwing an HttpResponseException instead of returning an HttpResponseMessage in a webapi 2 method, that if a call is made immediately to IIS Express it will timeout or return a 200 but with a html error in the response.
Easiest way to test this is to make $.ajax call to a method that throws a HttpResponseException and in the errorCallBack in ajax make an immediate call to another method or even a simple http page. You will notice the imediate call will fail. If you add a break point or a settimeout() in the error call back to delay the second call a second or two giving the server time to recover it works correctly. This makes no since but its almost like the throw HttpResponseException causes the server side listener thread to exit and restart causing a split second of no server accepting connections or something.
Update: The root cause of the wierd Ajax connection Timeout is if an ajax call is made quick enough the same tcp connection is used. I was raising a 401 error ether by returning a HttpResonseMessage or throwing a HTTPResponseException which was returned to the browser ajax call. But along with that call MS was returning a Object Not Found Error because in Startup.Auth.vb app.UserCookieAuthentication was enabled so it was trying to return intercept the response and add a redirect but it errored with Object not Instance of an Object. This Error was html but was appended to the response after the fact so only if the ajax call was made quick enough and the same tcp connection used did it get returned to the browser and then it got appended to the front of the next call. For some reason Chrome just timedout, fiddler pucked becasue of the mix of json and htm but firefox rturned the real error. So wierd but packet sniffer or firefox was the only way to track this one down.
Also it should be noted that if you are using Web API help to generate automatic help and you return HttpResponseMessage then you should add a
[System.Web.Http.Description.ResponseType(typeof(CustomReturnedType))]
attribute to the method so the help generates correctly. Then
return Request.CreateResponse<CustomReturnedType>(objCustomeReturnedType)
or on error
return Request.CreateErrorResponse( System.Net.HttpStatusCode.InternalServerError, new Exception("An Error Ocurred"));
Hope this helps someone else who may be getting random timeout or server not available immediately after throwing a HttpResponseException.
Also returning an HttpResponseException has the added benefit of not causing Visual Studio to break on an Un-handled exception usefull when the error being returned is the AuthToken needs to be refreshed in a single page app.
Update: I am retracting my statement about IIS Express timing out, this happened to be a mistake in my client side ajax call back it turns out since Ajax 1.8 returning $.ajax() and returning $.ajax.().then() both return promise but not the same chained promise then() returns a new promise which caused the order of execution to be wrong. So when the then() promise completed it was a script timeout. Weird gotcha but not an IIS express issue a problem between the Keyboard and chair.
Provide the source image (img) size as the first rectangle:
ctx.drawImage(img, 0, 0, img.width, img.height, // source rectangle
0, 0, canvas.width, canvas.height); // destination rectangle
The second rectangle will be the destination size (what source rectangle will be scaled to).
Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas
Updates an old config with new/changed/removed options.
Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.
function truncateOnWord(str, limit) {
var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
var reg = new RegExp('(?=[' + trimmable + '])');
var words = str.split(reg);
var count = 0;
return words.filter(function(word) {
count += word.length;
return count <= limit;
}).join('');
}
You can use AlarmManager in coop with notification mechanism Something like this:
Intent intent = new Intent(ctx, ReminderBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) ctx.getSystemService(Activity.ALARM_SERVICE);
// time of of next reminder. Unix time.
long timeMs =...
if (Build.VERSION.SDK_INT < 19) {
am.set(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
} else {
am.setExact(AlarmManager.RTC_WAKEUP, timeMs, pendingIntent);
}
It starts alarm.
public class ReminderBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(...)
.setContentTitle(..)
.setContentText(..);
Intent intentToFire = new Intent(context, Activity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intentToFire, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
NotificationManagerCompat.from(this);.notify((int) System.currentTimeMillis(), builder.build());
}
}
Solution:
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5','your text')),3,32)
Calling stopPropagation
on the event prevents propagation:
(event)="doSomething($event); $event.stopPropagation()"
For preventDefault
just return false
(event)="doSomething($event); false"
Event binding allows to execute multiple statements and expressions to be executed sequentially (separated by ;
like in *.ts
files.
The result of last expression will cause preventDefault
to be called if falsy. So be cautious what the expression returns (even when there is only one)
As pointed out by Brani, vector() is a solution, e.g.
newVector <- vector(mode = "numeric", length = 50)
will return a vector named "newVector" with 50 "0"'s as initial values. It is also fairly common to just add the new scalar to an existing vector to arrive at an expanded vector, e.g.
aVector <- c(aVector, newScalar)
don't forget this to add this below in your template:
<router-outlet></router-outlet>
The secret is you need to copy msvcr100.dll to the path where the installation says msvcr100.dll is missing (dialog box) and then try to install the sql developer.
For me I had to create bin folder in
C:\sqldeveloper\jdk\bin
and Copy msvcr100.dll to it.
If still not working! Try this!
You might also need to change the config file settings found in
C:\sqldeveloper\sqldeveloper\bin
Download and install 32 bit JDK (Windows) and set the path in config file as
SetJavaHome C:/Program Files (x86)/Java/jdk1.7.0_01
If you're testing for all zeros to avoid a warning on another numpy function then wrapping the line in a try, except block will save having to do the test for zeros before the operation you're interested in i.e.
try: # removes output noise for empty slice
mean = np.mean(array)
except:
mean = 0
tooltips can be used as alerts. These can be timed to appear and disappear.
CSS can be used to create tooltips and menus. More info on this can be found in 'Javascript for Dummies'. Sorry about the label of this book... Not infuring anything.
Reading other peoples answers here, I realized the answer to my own thoughts/questions. SetTimeOut could be applied to tooltips. Javascript could trigger them.
I got this error briefly after renaming the App_Code folder. Actually, I accidentally dragged the whole folder to the App_data folder. VS 2015 didn't complain it was difficult to spot what had gone wrong.
You can avoid the BasicResponseHandler, but use the HttpResponse itself to get both status and response as a String.
HttpResponse response = httpClient.execute(get);
// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();
// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());
Position the element as relative and then use z-index, it worked for me :)
I found how to automate the build and archive process from the comand line, I just wrote a blog article explaining how you can achieve that.
The command you have to use is xcrun
:
/usr/bin/xcrun -sdk iphoneos PackageApplication \
-v "${RELEASE_BUILDDIR}/${APPLICATION_NAME}.app" \
-o "${BUILD_HISTORY_DIR}/${APPLICATION_NAME}.ipa" \
--sign "${DEVELOPER_NAME}" \
--embed "${PROVISONING_PROFILE}"
You will find all the details in the article. If you have any questions dont hesitate to ask.
I also faced the same issue with a self signed certificate . By referring to few of the above solutions , i tried regenerating the certificate with the correct CN i.e the IP Address of the server .But still it didn't work for me . Finally i tried regenerating the certificate by adding the SAN address to it via the below mentioned command
**keytool -genkey -keyalg RSA -keystore keystore.jks -keysize 2048 -alias <IP_ADDRESS> -ext san=ip:<IP_ADDRESS>**
After that i started my server and downloaded the client certificates via the below mentioned openssl command
**openssl s_client -showcerts -connect <IP_ADDRESS>:443 < /dev/null | openssl x509 -outform PEM > myCert.pem**
Then i imported this client certificate to the java default keystore file (cacerts) of my client machine by the below mentioned command
**keytool -import -trustcacerts -keystore /home/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.242.b08-1.el7.x86_64/jre/lib/security/cacerts -alias <IP_ADDRESS> -file ./mycert.pem**
Replace the string
value = value.replace(/'/g, "\\'");
where value is your string which is going to store in your Database.
Further,
NPM package for this, you can have look into it
Always remember that in case of checked exception you can catch only after throwing the exception(either you throw or any inbuilt method used in your code can throw) ,but in case of unchecked exception You an catch even when you have not thrown that exception.
I found a second really strange corner case that beats my first one by a long shot.
String.Equals Method (String, String, StringComparison) is not actually side effect free.
I was working on a block of code that had this on a line by itself at the top of some function:
stringvariable1.Equals(stringvariable2, StringComparison.InvariantCultureIgnoreCase);
Removing that line lead to a stack overflow somewhere else in the program.
The code turned out to be installing a handler for what was in essence a BeforeAssemblyLoad event and trying to do
if (assemblyfilename.EndsWith("someparticular.dll", StringComparison.InvariantCultureIgnoreCase))
{
assemblyfilename = "someparticular_modified.dll";
}
By now I shouldn't have to tell you. Using a culture that hasn't been used before in a string comparison causes an assembly load. InvariantCulture is not an exception to this.
I found that I needed to wrap my datetime string like this:
"startdate": "\/Date(" + date() + ")\/"
Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD
I have a solution to a problem that may also apply to you. My database was in a state where a DROP TABLE
failed because it couldn't find the table... but a CREATE TABLE
also failed because MySQL thought the table existed. (This state could easily mess with your IF NOT EXISTS clause).
I eventually found this solution:
sudo mysqladmin flush-tables
For me, without the sudo
, I got the following error:
mysqladmin: refresh failed; error: 'Access denied; you need the RELOAD privilege for this operation'
(Running on OS X 10.6)
You would use it if you are using RenderAction
in any of your views, usually to render a partial view.
The reason for marking it with [ChildActionOnly]
is that you need the controller method to be public so you can call it with RenderAction
but you don't want someone to be able to navigate to a URL (e.g. /Controller/SomeChildAction) and see the results of that action directly.
for me best solotion this is
Thread.CurrentThread.Abort();
and force close app.
You can use the border and box-shadow properties along with CSS pseudo elements to achieve a triple-border sort of effect. See the example below for an idea of how to create three borders at the bottom of a div:
.triple-border:after {_x000D_
content: " ";_x000D_
display: block;_x000D_
width: 100%;_x000D_
background: #FFE962;_x000D_
height: 9px;_x000D_
padding-bottom: 8px;_x000D_
border-bottom: 9px solid #A3C662;_x000D_
box-shadow: -2px 11px 0 -1px #34b6af;_x000D_
}
_x000D_
<div class="triple-border">Triple border bottom with multiple colours</div>
_x000D_
You'll have to play around with the values to get the alignment correct. However, you can also achieve more flexibility, e.g. 4 borders if you put some of the attributes in the proper element rather than the pseudo selector.
QT can be as simple as that of Windows. The equivalent code is
if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec())
{
}
In some websites, XMLHttpRequest
may send you something like <script src="#"></srcipt>
. In that case, try using a HTML document like the script under:
<html>
<body>
<iframe src="website.com"></iframe>
<script src="your_JS"></script>
</body>
</html>
Now you can use JS to get some text out of the HTML, such as getElementbyId
.
But this may not work for some websites with cross-domain blocking.
Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):
SC STOP shortservicename
SC DELETE shortservicename
Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc
is aliased to set-content
. So sc delete service
will actually create a file called delete
with the content service
. To do this in Powershell, use sc.exe delete service
instead
If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:
SC QUERY state= all >"C:\Service List.txt"
For a more concise list, execute this command:
SC QUERY state= all | FIND "_NAME"
The short service name will be listed just above the display name, like this:
SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service
And thus to delete that service:
SC STOP MyService
SC DELETE MyService
var object = { "a": 1, "b": 2};_x000D_
$.each(object, function(key, value){_x000D_
console.log(key + ": " + object[key]);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
_x000D_
//output
a: 1
b: 2
Multiprogramming: More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.
Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.
You can concatenate strings using strcat
. If you plan on concatenating numbers as strings, you must first use num2str
to convert the numbers to strings.
Also, strings can't be stored in a vector or matrix, so f
must be defined as a cell array, and must be indexed using {
and }
(instead of normal round brackets).
f = cell(N, 1);
for i=1:N
f{i} = strcat('f', num2str(i));
end
If you are working with heavy queries, you better move the request for the latest row in the where clause. It is a lot faster and looks cleaner.
SELECT c.*,
FROM client AS c
LEFT JOIN client_calling_history AS cch ON cch.client_id = c.client_id
WHERE
cch.cchid = (
SELECT MAX(cchid)
FROM client_calling_history
WHERE client_id = c.client_id AND cal_event_id = c.cal_event_id
)
public static void main(String[] args) {
String value = " Chlamydia_spp. IgG, IgM & IgA Abs (8006) ";
System.out.println(value.replaceAll("[^A-Za-z0-9]", ""));
}
output: ChlamydiasppIgGIgMIgAAbs8006
Github: https://github.com/AlbinViju/Learning/blob/master/StripNonAlphaNumericFromString.java
I just found how.
I delete the first occurrence of lombok @Slf4j
or log
where the compiler complains, and wait for the warning(the red bubble) of IDEA, suggesting "add the lombok.extern.Slf4j.jar to classpath". Since then all goes well. It seems IDEA likes to complain about lombok.
Well, the error message says it all: NumPy arrays do not have an append()
method. There's a free function numpy.append()
however:
numpy.append(M, a)
This will create a new array instead of mutating M
in place. Note that using numpy.append()
involves copying both arrays. You will get better performing code if you use fixed-sized NumPy arrays.
upstream
in the github example is just the name they've chosen to refer to that repository. You may choose any that you like when using git remote add
. Depending on what you select for this name, your git pull
usage will change. For example, if you use:
git remote add upstream git://github.com/somename/original-project.git
then you would use this to pull changes:
git pull upstream master
But, if you choose origin for the name of the remote repo, your commands would be:
To name the remote repo in your local config: git remote add origin git://github.com/somename/original-project.git
And to pull: git pull origin master
What is the difference between Git and GitHub?
Git is a version control system; think of it as a series of snapshots (commits) of your code. You see a path of these snapshots, in which order they where created. You can make branches to experiment and come back to snapshots you took.
GitHub, is a web-page on which you can publish your Git repositories and collaborate with other people.
Is Git saving every repository locally (in the user's machine) and in GitHub?
No, it's only local. You can decide to push (publish) some branches on GitHub.
Can you use Git without GitHub? If yes, what would be the benefit for using GitHub?
Yes, Git runs local if you don't use GitHub. An alternative to using GitHub could be running Git on files hosted on Dropbox, but GitHub is a more streamlined service as it was made especially for Git.
How does Git compare to a backup system such as Time Machine?
It's a different thing, Git lets you track changes and your development process. If you use Git with GitHub, it becomes effectively a backup. However usually you would not push all the time to GitHub, at which point you do not have a full backup if things go wrong. I use git in a folder that is synchronized with Dropbox.
Is this a manual process, in other words if you don't commit you won't have a new version of the changes made?
Yes, committing and pushing are both manual.
If are not collaborating and you are already using a backup system why would you use Git?
If you encounter an error between commits you can use the command git diff
to see the differences between the current code and the last working commit, helping you to locate your error.
You can also just go back to the last working commit.
If you want to try a change, but are not sure that it will work. You create a branch to test you code change. If it works fine, you merge it to the main branch. If it does not you just throw the branch away and go back to the main branch.
You did some debugging. Before you commit you always look at the changes from the last commit. You see your debug print statement that you forgot to delete.
Make sure you check gitimmersion.com.
There's a built-in .NET utility for this: HttpUtility.ParseQueryString
// C#
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
' VB.NET
Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring)
You may need to replace querystring
with new Uri(fullUrl).Query
.
When passing by value:
void func(Object o);
and then calling
func(a);
you will construct an Object
on the stack, and within the implementation of func
it will be referenced by o
. This might still be a shallow copy (the internals of a
and o
might point to the same data), so a
might be changed. However if o
is a deep copy of a
, then a
will not change.
When passing by reference:
void func2(Object& o);
and then calling
func2(a);
you will only be giving a new way to reference a
. "a
" and "o
" are two names for the same object. Changing o
inside func2
will make those changes visible to the caller, who knows the object by the name "a
".
In case of MySQL
or SQLite
the correct keyword is IFNULL
(not ISNULL
).
SELECT iar.Description,
IFNULL(iai.Quantity,0) as Quantity,
IFNULL(iai.Quantity * rpl.RegularPrice,0) as 'Retail',
iar.Compliance
FROM InventoryAdjustmentReason iar
LEFT OUTER JOIN InventoryAdjustmentItem iai on (iar.Id = iai.InventoryAdjustmentReasonId)
LEFT OUTER JOIN Item i on (i.Id = iai.ItemId)
LEFT OUTER JOIN ReportPriceLookup rpl on (rpl.SkuNumber = i.SkuNo)
WHERE iar.StoreUse = 'yes'
I had a fully working project to which I was doing a minor change when this occured after updateting the SDK. Eclipse updated the SDK and the ADT but I could still not build the project. Exlipse said there were no further updates available.
The problem persisted until I manually uninstalled the ADT from eclipse and re-installed it. Only then would my project build. I had restarted eclipse inbetween each step.
Say, you have the following:
std::vector<myObject>::const_iterator first = vObj.begin();
Then the first object in the vector is: *first
. To get the address, use: &(*first)
.
However, in keeping with the STL design, I'd suggest return an iterator instead if you plan to pass it around later on to STL algorithms.
#pragma mark
is used to tag the group of methods so you may easily find and detect methods from the Jump Bar. It may help you when your code files reach about 1000 lines and you want to find methods quickly through the category from Jump box.
In a long program it becomes difficult to remember and find a method name. So pragma mark allows you to categorize methods according to the work they do. For example, you tagged some tag for Table View Protocol Methods, AlertView Methods, Init Methods, Declaration etc.
#pragma mark
is the facility for XCode but it has no impact on your code. It merely helps to make it easier to find methods while coding.
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
I've been struggling recently with the implementation of complex parameter switches in a batch file so here is the result of my research. None of the provided answers are fully safe, examples:
"%1"=="-?"
will not match if the parameter is enclosed in quotes (needed for file names etc.) or will crash if the parameter is in quotes and has spaces (again often seen in file names)
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
rem echo First parameter is %1
if "%1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -?
starting parameter test...
Condition is true, param=-?
C:\>test.bat "-?"
starting parameter test...
Condition is false, param="-?"
Any combination with square brackets [%1]==[-?]
or [%~1]==[-?]
will fail in case the parameter has spaces within quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if [%~1]==[-?] (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat "long file name"
starting parameter test...
First parameter is "long file name"
file was unexpected at this time.
The proposed safest solution "%~1"=="-?"
will crash with a complex parameter that includes text outside the quotes and text with spaces within the quotes:
@ECHO OFF
SETLOCAL
echo.
echo starting parameter test...
echo.
echo First parameter is %1
if "%~1"=="-?" (echo Condition is true, param=%1) else (echo Condition is false, param=%1)
C:\>test.bat -source:"long file name"
starting parameter test...
First parameter is -source:"long file name"
file was unexpected at this time.
The only way to ensure all above scenarios are covered is to use EnableDelayedExpansion and to pass the parameters by reference (not by value) using variables. Then even the most complex scenario will work fine:
@ECHO OFF
SETLOCAL EnableDelayedExpansion
echo.
echo starting parameter test...
echo.
echo First parameter is %1
:: we assign the parameter to a variable to pass by reference with delayed expansion
set "var1=%~1"
echo var1 is !var1!
:: we assign the value to compare with to a second variable to pass by reference with delayed expansion
set "var2=-source:"c:\app images"\image.png"
echo var2 is !var2!
if "!var1!"=="!var2!" (echo Condition is true, param=!var1!) else (echo Condition is false, param=!var1!)
C:\>test.bat -source:"c:\app images"\image.png
starting parameter test...
First parameter is -source:"c:\app images"\image.png
var1 is -source:"c:\app images"\image.png
var2 is -source:"c:\app images"\image.png
Condition is true, param=-source:"c:\app images"\image.png
C:\>test.bat -source:"c:\app images"\image1.png
starting parameter test...
First parameter is -source:"c:\app images"\image1.png
var1 is -source:"c:\app images"\image1.png
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images"\image1.png
C:\>test.bat -source:"c:\app images\image.png"
starting parameter test...
First parameter is -source:"c:\app images\image.png"
var1 is -source:"c:\app images\image.png"
var2 is -source:"c:\app images"\image.png
Condition is false, param=-source:"c:\app images\image.png"
It basically means that the object implements the __getitem__()
method. In other words, it describes objects that are "containers", meaning they contain other objects. This includes strings, lists, tuples, and dictionaries.
I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.
Solution:
First of all find the application which is causing heavy memory usage.
You can find this in the Details section of the Task Manager.
Next.
If this solution works for you please add a comment so that I can know.
A predicate in T is a delegate that takes in a T and returns a bool. List<T>.RemoveAll will remove all elements in a list where calling the predicate returns true. The easiest way to supply a simple predicate is usually a lambda expression, but you can also use anonymous methods or actual methods.
{
List<Vehicle> vehicles;
// Using a lambda
vehicles.RemoveAll(vehicle => vehicle.EnquiryID == 123);
// Using an equivalent anonymous method
vehicles.RemoveAll(delegate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
});
// Using an equivalent actual method
vehicles.RemoveAll(VehiclePredicate);
}
private static bool VehiclePredicate(Vehicle vehicle)
{
return vehicle.EnquiryID == 123;
}
You can use a defaultdict for this.
from collections import defaultdict
d = defaultdict(list)
d['key'].append('mykey')
This is slightly more efficient than setdefault
since you don't end up creating new lists that you don't end up using. Every call to setdefault
is going to create a new list, even if the item already exists in the dictionary.
Also very helpful, while investigating the Environment.SpecialFolder
enum. Use LINQPad or create a solution and execute this code:
Enum.GetValues(typeof(Environment.SpecialFolder))
.Cast<Environment.SpecialFolder>()
.Select(specialFolder => new
{
Name = specialFolder.ToString(),
Path = Environment.GetFolderPath(specialFolder)
})
.OrderBy(item => item.Path.ToLower())
This is the result on my machine:
MyComputer
LocalizedResources
CommonOemLinks
ProgramFiles C:\Program Files (x86)
ProgramFilesX86 C:\Program Files (x86)
CommonProgramFiles C:\Program Files (x86)\Common Files
CommonProgramFilesX86 C:\Program Files (x86)\Common Files
CommonApplicationData C:\ProgramData
CommonStartMenu C:\ProgramData\Microsoft\Windows\Start Menu
CommonPrograms C:\ProgramData\Microsoft\Windows\Start Menu\Programs
CommonAdminTools C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Administrative Tools
CommonStartup C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
CommonTemplates C:\ProgramData\Microsoft\Windows\Templates
UserProfile C:\Users\fisch
LocalApplicationData C:\Users\fisch\AppData\Local
CDBurning C:\Users\fisch\AppData\Local\Microsoft\Windows\Burn\Burn
History C:\Users\fisch\AppData\Local\Microsoft\Windows\History
InternetCache C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCache
Cookies C:\Users\fisch\AppData\Local\Microsoft\Windows\INetCookies
ApplicationData C:\Users\fisch\AppData\Roaming
NetworkShortcuts C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Network Shortcuts
PrinterShortcuts C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Printer Shortcuts
Recent C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Recent
SendTo C:\Users\fisch\AppData\Roaming\Microsoft\Windows\SendTo
StartMenu C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu
Programs C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs
AdminTools C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Administrative Tools
Startup C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
Templates C:\Users\fisch\AppData\Roaming\Microsoft\Windows\Templates
Desktop C:\Users\fisch\Desktop
DesktopDirectory C:\Users\fisch\Desktop
Favorites C:\Users\fisch\Favorites
MyMusic C:\Users\fisch\Music
MyDocuments C:\Users\fisch\OneDrive\Documents
MyDocuments C:\Users\fisch\OneDrive\Documents
MyPictures C:\Users\fisch\OneDrive\Pictures
MyVideos C:\Users\fisch\Videos
CommonDesktopDirectory C:\Users\Public\Desktop
CommonDocuments C:\Users\Public\Documents
CommonMusic C:\Users\Public\Music
CommonPictures C:\Users\Public\Pictures
CommonVideos C:\Users\Public\Videos
Windows C:\Windows
Fonts C:\Windows\Fonts
Resources C:\Windows\resources
System C:\Windows\system32
SystemX86 C:\Windows\SysWoW64
("fisch" is the first 5 letters of my last name. This is the user name assigned when signing in with a Microsoft Account.)
As far as i know, writing multiple matches is logical AND operation; so what your rule means is if the destination port is "59100" AND "3000" then reject connection with tcp-reset; Workaround is using -mport option. Look out for the man page.
I assume X
and Y
are arrays? If so, there's a very simple way to do this:
x = [1, 1, 2, 4]
y = [1, 2, 2, 2]
# intersection
x & y # => [1, 2]
# union
x | y # => [1, 2, 4]
# difference
x - y # => [4]
if you need to limit download rate, use this code !!
<?php
$local_file = 'file.zip';
$download_file = 'name.zip';
// set the download rate limit (=> 20,5 kb/s)
$download_rate = 20.5;
if(file_exists($local_file) && is_file($local_file))
{
header('Cache-control: private');
header('Content-Type: application/octet-stream');
header('Content-Length: '.filesize($local_file));
header('Content-Disposition: filename='.$download_file);
flush();
$file = fopen($local_file, "r");
while(!feof($file))
{
// send the current file part to the browser
print fread($file, round($download_rate * 1024));
// flush the content to the browser
flush();
// sleep one second
sleep(1);
}
fclose($file);}
else {
die('Error: The file '.$local_file.' does not exist!');
}
?>
For more information click here
Use the preprocessor:
#define VISIT_ERROR(FIRST, MIDDLE, LAST) \
FIRST(ErrorA) MIDDLE(ErrorB) /* MIDDLE(ErrorB2) */ LAST(ErrorC)
enum Errors
{
#define ENUMFIRST_ERROR(E) E=0,
#define ENUMMIDDLE_ERROR(E) E,
#define ENUMLAST_ERROR(E) E
VISIT_ERROR(ENUMFIRST_ERROR, ENUMMIDDLE_ERROR, ENUMLAST_ERROR)
// you might undefine the 3 macros defined above
};
std::string toString(Error e)
{
switch(e)
{
#define CASERETURN_ERROR(E) case E: return #E;
VISIT_ERROR(CASERETURN_ERROR, CASERETURN_ERROR, CASERETURN_ERROR)
// you might undefine the above macro.
// note that this will produce compile-time error for synonyms in enum;
// handle those, if you have any, in a distinct macro
default:
throw my_favourite_exception();
}
}
The advantage of this approach is that: - it's still simple to understand, yet - it allows for various visitations (not just string)
If you're willing to drop the first, craft yourself a FOREACH() macro, then #define ERROR_VALUES() (ErrorA, ErrorB, ErrorC)
and write your visitors in terms of FOREACH(). Then try to pass a code review :).
You are comparing a jQuery object (jQuery('input:first')
) to strings (the elements of the array).
Change the code in order to compare the input's value (wich is a string) to the array elements:
if (jQuery.inArray(jQuery("input:first").val(), ar) != -1)
The inArray
method returns -1
if the element wasn't found in the array, so as your bonus answer to how to determine if an element is not in an array, use this :
if(jQuery.inArray(el,arr) == -1){
// the element is not in the array
};
I am a bit extending provided answers (since so far they concentrate on their "own"/artificial terminology focusing on programming a particular language instead of taking care of the bigger picture behind the scene of creating the programming languages, in general, i.e. when things like type-safety vs. memory considerations make the difference):
int is not boolean
Consider
boolean bar = true;
System.out.printf("Bar is %b\n", bar);
System.out.printf("Bar is %d\n", (bar)?1:0);
int baz = 1;
System.out.printf("Baz is %d\n", baz);
System.out.printf("Baz is %b\n", baz);
with output
Bar is true
Bar is 1
Baz is 1
Baz is true
Java code on 3rd line (bar)?1:0
illustrates that bar (boolean) cannot be implicitly converted (casted) into an int. I am bringing this up not to illustrate the details of implementation behind JVM, but to point out that in terms of low level considerations (as memory size) one does have to prefer values over type safety. Especially if that type safety is not truly/fully used as in boolean types where checks are done in form of
if value \in {0,1} then cast to boolean type, otherwise throw an exception.
All just to state that {0,1} < {-2^31, .. , 2^31 -1}. Seems like an overkill, right? Type safety is truly important in user defined types, not in implicit casting of primitives (although last are included in the first).
Bytes are not types or bits
Note that in memory your variable from range of {0,1} will still occupy at least a byte or a word (xbits depending on the size of the register) unless specially taken care of (e.g. packed nicely in memory - 8 "boolean" bits into 1 byte - back and forth).
By preferring type safety (as in putting/wrapping value into a box of a particular type) over extra value packing (e.g. using bit shifts or arithmetic), one does effectively chooses writing less code over gaining more memory. (On the other hand one can always define a custom user type which will facilitate all the conversion not worth than Boolean).
keyword vs. type
Finally, your question is about comparing keyword vs. type. I believe it is important to explain why or how exactly you will get performance by using/preferring keywords ("marked" as primitive) over types (normal composite user-definable classes using another keyword class) or in other words
boolean foo = true;
vs.
Boolean foo = true;
The first "thing" (type) can not be extended (subclassed) and not without a reason. Effectively Java terminology of primitive and wrapping classes can be simply translated into inline value (a LITERAL or a constant that gets directly substituted by compiler whenever it is possible to infer the substitution or if not - still fallback into wrapping the value).
Optimization is achieved due to trivial:
"Less runtime casting operations => more speed."
That is why when the actual type inference is done it may (still) end up in instantiating of wrapping class with all the type information if necessary (or converting/casting into such).
So, the difference between boolean and Boolean is exactly in Compilation and Runtime (a bit far going but almost as instanceof vs. getClass()).
Finally, autoboxing is slower than primitives
Note the fact that Java can do autoboxing is just a "syntactic sugar". It does not speed up anything, just allows you to write less code. That's it. Casting and wrapping into type information container is still performed. For performance reasons choose arithmetics which will always skip extra housekeeping of creating class instances with type information to implement type safety. Lack of type safety is the price you pay to gain performance. For code with boolean-valued expressions type safety (when you write less and hence implicit code) would be critical e.g. for if-then-else flow controls.
try this
Bitmap mBitmap = Bitmap.createScaledBitmap(Bitmap src, int dstWidth, int dstHeight, boolean filter);
protected void onDraw(Canvas canvas) {
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
}
Negative numbers mean that you count from the right instead of the left. So, list[-1]
refers to the last element, list[-2]
is the second-last, and so on.
try this. If you do like this you don't need to fire always any command You need to fire only one time
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
cat /proc/sys/fs/inotify/max_user_watches
fs.inotify.max_user_watches=524288
You can create an interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result to Activity
if Activity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
1) Open tool which is on top.
2) Choose options from Picklist.
3) Now Comes the popup and you can now select designers option from the list of menus on the left side.
4) Now prevent saving changes need to be unchecked that needed table re-creation. Now Click OK.
You want .children()
instead (documentation here):
$(this).closest('tr').children('td.two').text();
The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault()
. However as the OP alluded to, if you always call it preventDefault()
you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.
Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.
// Bind keydown event to this function. Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){
// Use jquery's constants rather than an unintuitive magic number.
// $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
if (e.keyCode == $.ui.keyCode.BACKSPACE) {
// Filters out events coming from any of the following tags so Backspace
// will work when typing text, but not take the page back otherwise.
var rx = /INPUT|SELECT|TEXTAREA/i;
if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
e.preventDefault();
}
// Add your code here.
}
});
Here's my attempt. To disable a tab:
Code:
var toggleTabs = function(state) {
disabledTabs = ['#tab2', '#tab3'];
$.each(disabledTabs, $.proxy(function(idx, tabSelector) {
tab = $(tabSelector);
if (tab.length) {
if (state) {
// Enable tab click.
$(tab).toggleClass('disabled', false);
$('a', tab).attr('data-toggle', 'tab').off('click');
} else {
// Disable tab click.
$(tab).toggleClass('disabled', true);
$('a', tab).removeAttr('data-toggle').on('click', function(e){
e.preventDefault();
});
}
}
}, this));
};
toggleTabs.call(myTabContainer, true);
Found the answer. What I did was was first
sudo apt-get install aptitude
sudo aptitude install libglib2.0-0
sudo aptitude install gcc-4.7 make linux-headers-`uname -r` -y
and tried it but it didn't work so I continued and did
sudo apt-get install build-essential
sudo apt-get install gcc-4.7 linux-headers-`uname -r`
after doing these two steps and trying again, it worked.
What about normal encoded white-space character?
 
numpy.full((2,2), True, dtype=bool)
try below code
Directory.GetFiles(txtFolderPath.Text, "*ProfileHandler.cs",SearchOption.AllDirectories)
In case anyone is trying to apply the above solutions to a .scatter() instead of a .subplot(),
I tried running the following code
y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]
fig, ax = plt.scatter(z, y)
for i, txt in enumerate(n):
ax.annotate(txt, (z[i], y[i]))
But ran into errors stating "cannot unpack non-iterable PathCollection object", with the error specifically pointing at codeline fig, ax = plt.scatter(z, y)
I eventually solved the error using the following code
plt.scatter(z, y)
for i, txt in enumerate(n):
plt.annotate(txt, (z[i], y[i]))
I didn't expect there to be a difference between .scatter() and .subplot() I should have known better.
I had the exact same situation. It was caused by not having a PropertySourcesPlaceholderConfigurer in the Spring context, which resolves values against the @Value
annotation inside of classes.
Include a property placeholder to solve the problem, no need to use Spring expressions for integers (the property file does not have to exist if you use ignore-resource-not-found="true"
):
<context:property-placeholder location="/path/to/my/app.properties"
ignore-resource-not-found="true" />
list.ForEach(x=>Console.WriteLine(x));
An interesting look here, the code given by kelly works well,
$nmonth = date("m", strtotime($month));
but for the month of february, it won't work as expected when the current day is 30 or 31 on leap year and 29,30,31 on non-leap year.It will return 3 as month number. Ex:
$nmonth = date("m", strtotime("february"));
The solution is, add the year with the month like this:
$nmonth = date("m", strtotime("february-2012"));
I got this from this comment in php manual.
To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.
I hope I'm not late to the party.. Here is my answer. I like using Pattern/Matcher because it uses regex which should be more efficient. Yet, I think this answer could be enhanced:
Matcher matcher = Pattern.compile("is").matcher("I think there is a smarter solution, isn't there?");
int numOfOcurrences = 2;
for(int i = 0; i < numOfOcurrences; i++) matcher.find();
System.out.println("Index: " + matcher.start());
I would prefer to store the image in a directory, then store a reference to the image file in the database.
However, if you do store the image in the database, you should partition your database so the image column resides in a separate file.
You can read more about using filegroups here http://msdn.microsoft.com/en-us/library/ms179316.aspx.
try
raw_input('Enter your input:') # If you use Python 2
input('Enter your input:') # If you use Python 3
and if you want to have a numeric value just convert it:
try:
mode=int(raw_input('Input:'))
except ValueError:
print "Not a number"
See these test cases http://jsperf.com/last-item-method The most effective way is throug .pop method (in V8), but loses the last element of the array
Always use double quotes when using a variable inside a string and backslash any other double quotes except the starting and ending ones. You could also use the brackets like below so it's easier to find your variables inside the strings and make them look cleaner.
$var = 'my variable';
echo "I love ${var}";
or
$var = 'my variable';
echo "I love {$var}";
Above would return the following: I love my variable
with python2
pip show tensorflow
to check install
python test.py
to run test
with python3
pip3 show tensorflow
to check install
python3 test.py
to run test
test.py
import tensorflow as tf
import numpy as np
c = np.array([[3.,4], [5.,6], [6.,7]])
step = tf.reduce_mean(c, 1)
with tf.Session() as sess:
print(sess.run(step))
Or, if you haven't install tensorflow yet, try the offical document
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
Here's a quick way to do it, won't require anything besides sys
.. though functionality is limited:
flag = "--flag" in sys.argv[1:]
[1:]
is in case if the full file name is --flag
Is this what you're after?
I added :text-align:center
to the div and image
Note that COLUMNS
is:
SIGWINCH
signal.That second point usually means that your COLUMNS
variable will only be set in your interactive shell, not in a bash script.
If your script's stdin
is connected to your terminal you can manually look up the width of your terminal by asking your terminal:
tput cols
And to use this in your SVN command:
svn diff "$@" --diff-cmd /usr/bin/diff -x "-y -w -p -W $(tput cols)"
(Note: you should quote "$@"
and stay away from eval
;-))
Another way to do it:
testSpace.Style.Add("display", "none");
or
testSpace.Style["background-image"] = "url(images/foo.png)";
in vb.net you can do it this way:
testSpace.Style.Item("display") = "none"
Building upon Anthony and Anton's answers I incorporated the ability to rotate the generated circle without affecting it's overall appearance. This is useful if you're using the path for an animation and you need to control where it begins.
function(cx, cy, r, deg){
var theta = deg*Math.PI/180,
dx = r*Math.cos(theta),
dy = -r*Math.sin(theta);
return "M "+cx+" "+cy+"m "+dx+","+dy+"a "+r+","+r+" 0 1,0 "+-2*dx+","+-2*dy+"a "+r+","+r+" 0 1,0 "+2*dx+","+2*dy;
}
Semantically I think makes more sense as is a container for a single element and if you need to nest them then that suggests more than element will be inside of the outer one.
/<b>(.*?)<\/b>/g
Add g
(global) flag after:
/<b>(.*?)<\/b>/g.exec(str)
//^-----here it is
However if you want to get all matched elements, then you need something like this:
var str = "<b>Bob</b>, I'm <b>20</b> years old, I like <b>programming</b>.";
var result = str.match(/<b>(.*?)<\/b>/g).map(function(val){
return val.replace(/<\/?b>/g,'');
});
//result -> ["Bob", "20", "programming"]
If an element has attributes, regexp will be:
/<b [^>]+>(.*?)<\/b>/g.exec(str)
By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-
For example color is: #000
a:visited, a:hover, a:focus {
text-decoration: none;
color: #000;
}
If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code
a:hover {
color: red;
}
a:visited {
color: green;
}
a:focus {
color: yellow;
}
NB: good practice is to use color code.
Bootstrap 4 progress bar
<div class="progress">
<div class="progress-bar" role="progressbar" style="" aria-valuenow="" aria-valuemin="0" aria-valuemax="100"></div>
</div>
Javascript
change progress bar on next/previous page actions
var count = Number(document.getElementById('count').innerHTML); //set this on page load in a hidden field after an ajax call
var total = document.getElementById('total').innerHTML; //set this on initial page load
var pcg = Math.floor(count/total*100);
document.getElementsByClassName('progress-bar').item(0).setAttribute('aria-valuenow',pcg);
document.getElementsByClassName('progress-bar').item(0).setAttribute('style','width:'+Number(pcg)+'%');
Now in c++11 we have
#include <string>
string s = std::to_string(123);
Link to reference: http://en.cppreference.com/w/cpp/string/basic_string/to_string
In react 16, I use
<Input id="number"
type="time"
onChange={(evt) => { console.log(evt.target.value); }} />
If your input rows are lists rather than dictionaries, then the following is a simple solution:
import pandas as pd
list_of_lists = []
list_of_lists.append([1,2,3])
list_of_lists.append([4,5,6])
pd.DataFrame(list_of_lists, columns=['A', 'B', 'C'])
# A B C
# 0 1 2 3
# 1 4 5 6
I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.
In my case the solution was as follows:
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: mycontrolleraction,
data: JSON.stringify(things)
});
[HttpPost]
public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
{
return Ok();
}
Naming the content
data: { content: nodes }, // Server error 500
Not having the contentType = Server error 500
dataType
is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).List<Thing>
also works in the controller methodThe logcat shows the error, you should call super.onCreate(savedInstanceState)
:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//... your code
}
puts
call the to_s
of each argument and adds a new line to each string, if it does not end with new line.
print
just output each argument by calling their to_s
.
for example:
puts "one two"
:
one two
{new line}
puts "one two\n"
:
one two
{new line} #puts will not add a new line to the result, since the string ends with a new line
print "one two"
:
one two
print "one two\n"
:
one two
{new line}
And there is another way to output: p
For each object, directly writes obj.inspect followed by a newline to the program’s standard output.
It is helpful to output debugging message.
p "aa\n\t"
: aa\n\t
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
This may have changed since the question was asked, but there is a difference between stopping an instance and terminating an instance.
If your instance is EBS-based, it can be stopped. It will remain in your account, but you will not be charged for it (you will continue to be charged for EBS storage associated with the instance and unused Elastic IP addresses). You can re-start the instance at any time.
If the instance is terminated, it will be deleted from your account. You’ll be charged for any remaining EBS volumes, but by default the associated EBS volume will be deleted. This can be configured when you create the instance using the command-line EC2 API Tools.
const arr = Array.from({ length: 10 }).fill(0)
_x000D_
Start with this:
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
msg = path & " exists."
Else
msg = path & " doesn't exist."
End If
Taken from the documentation.
The original question on this post was: How to get Keras and Tensorflow to run with an AMD GPU.
The answer to this question is as followed:
1.) Keras will work if you can make Tensorflow work correctly (optionally within your virtual/conda environment).
2.) To get Tensorflow to work on an AMD GPU, as others have stated, one way this could work is to compile Tensorflow to use OpenCl. To do so read the link below. But for brevity I will summarize the required steps here:
You will need AMDs proprietary drivers. These are currently only available on Ubuntu 14.04 (the version before Ubuntu decided to change the way the UI is rendered). Support for Ubuntu 16.04 is at the writing of this post limited to a few GPUs through AMDProDrivers. Readers who want to do deep learning on AMD GPUs should be aware of this!
Compiling Tensorflow with OpenCl support also requires you to obtain and install the following prerequisites: OpenCl headers, ComputeCpp.
After the prerequisites are fulfilled, configure your build. Note that there are 3 options for compiling Tensorflow: Std Tensorflow (stable), Benoits Steiner's Tensorflow-opencl (developmental), and Luke Iwanski's Tensorflow-opencl (highly experimental) which you can pull from github. Also note that if you decide to build from any of the opencl versions, the question to use opencl will be missing because it is assumed that you are using it. Conversely, this means that if you configure from the standard tensorflow, you will need to select "Yes" when the configure script asks you to use opencl and "NO" for CUDA.
Then run tests like so:
$ bazel test --config=sycl -k --test_timeout 1600 -- //tensorflow/... -//tensorflow/contrib/... -//tensorflow/java/... -//tensorflow /compiler/...
Update: Doing this on my setup takes exceedingly long on my setup. The part that takes long are all the tests running. I am not sure what this means but a lot of my tests are timeing out at 1600 seconds. The duration can probably be shortened at the expense of more tests timeing out. Alternatively, you can just build tensor flow without tests. At the time of this writing, running the tests has taken 2 days already.
Or just build the pip package like so:
bazel build --local_resources 2048,.5,1.0 -c opt --config=sycl //tensorflow/tools/pip_package:build_pip_package
Please actually read the blog post over at Codeplay: Lukas Iwansky posted a comprehensive tutorial post on how to get Tensorflow to work with OpenCl just on March 30th 2017. So this is a very recent post. There are also some details which I did not write about here.
As indicated in the many posts above, little bits of information are spread throughout the interwebs. What Lukas' post adds in terms of value is that all the information was put together into one place which should make setting up Tensforflow and OpenCl a bit less daunting. I will only provide a link here:
https://www.codeplay.com/portal/03-30-17-setting-up-tensorflow-with-opencl-using-sycl
A slightly more complete walk-through has been posted here:
http://deep-beta.co.uk/setting-up-tensorflow-with-opencl-using-sycl/
It differs mainly by explicitly telling the user that he/she needs to:
Note an alternative approach was mentioned above using tensorflow-cl:
https://github.com/hughperkins/tensorflow-cl
I am unable to discern which approach is better at this time though it appears that this approach is less active. Fewer issues are posted, and fewer conversations to resolve those issues are happening. There was a major push last year. Additional pushes have ebbed off since November 2016 although Hugh seems to have pushed some updates a few days ago as of the writing of this post. (Update: If you read some of the documentation readme, this version of tensorflowo now only relies on community support as the main developer is busy with life.)
UPDATE (2017-04-25): I have some notes based on testing tensorflow-opencl below.
Following are some numbers for calculating 1 epoch using the CIFAR10 data set for MY SETUP (A10-7850 with iGPU). Your mileage will almost certainly vary!
You can see that in this particular case performance is worse. I attribute this to the following factors:
If you are using an AMD GPU with more VRAM and more stream processors, you are certain to get much better performance numbers. I would be interested to read what numbers people are achieving to know what's possible.
I will continue to maintain this answer if/when updates get pushed.
3.) An alternative way is currently being hinted at which is using AMD's RocM initiative, and miOpen (cuDNN equivalent) library. These are/will be open-source libraries that enable deep learning. The caveat is that RocM support currently only exists for Linux, and that miOpen has not been released to the wild yet, but Raja (AMD GPU head) has said in an AMA that using the above, it should be possible to do deep learning on AMD GPUs. In fact, support is planned for not only Tensorflow, but also Cafe2, Cafe, Torch7 and MxNet.
You may have to go from DateTime to LocalDate.
Using Joda Time:
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern("yyyy-MMM-dd");
DateTime dateTime = FORMATTER.parseDateTime("2005-nov-12");
LocalDate localDate = dateTime.toLocalDate();
Run cmd
and then run node server.js
. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)
I'm quite a beginner in Python and I found the answer of Anand was very good but quite complicated to me, so I try to reformulate :
1) insert
and append
methods are not specific to sys.path
and as in other languages they add an item into a list or array and :
* append(item)
add item
to the end of the list,
* insert(n, item)
inserts the item
at the nth position in the list (0
at the beginning, 1
after the first element, etc ...).
2) As Anand said, python search the import files in each directory of the path in the order of the path, so :
* If you have no file name collisions, the order of the path has no impact,
* If you look after a function already defined in the path and you use append
to add your path, you will not get your function but the predefined one.
But I think that it is better to use append
and not insert
to not overload the standard behaviour of Python, and use non-ambiguous names for your files and methods.
CheckBoxFor
takes a bool
, you're passing a List<CheckBoxes>
to it. You'd need to do:
@for (int i = 0; i < Model.EmploymentType.Count; i++)
{
@Html.CheckBoxFor(m => m.EmploymentType[i].Checked, new { id = "employmentType_" + i })
@Html.HiddenFor(m => m.EmploymentType[i].Text)
@Html.DisplayFor(m => m.EmploymentType[i].Text)
}
Notice I've added a HiddenFor
for the Text
property too, otherwise you'd lose that when you posted the form, so you wouldn't know which items you'd checked.
Edit, as shown in your comments, your EmploymentType
list is null
when the view is served. You'll need to populate that too, by doing this in your action method:
public ActionResult YourActionMethod()
{
CareerForm model = new CareerForm();
model.EmploymentType = new List<CheckBox>
{
new CheckBox { Text = "Fulltime" },
new CheckBox { Text = "Partly" },
new CheckBox { Text = "Contract" }
};
return View(model);
}
How about simply (Please note, come up with a better name for the class name this is simply an example):
.centerText{
text-align: center;
}
<div>
<table style="width:100%">
<tbody>
<tr>
<td class="centerText">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td class="centerText">Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
Example here
You can place the css
in a separate file, which is recommended.
In my example, I created a file called styles.css
and placed my css
rules in it.
Then include it in the html document in the <head>
section as follows:
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
The alternative, not creating a seperate css file, not recommended at all...
Create <style>
block in your <head>
in the html document. Then just place your rules there.
<head>
<style type="text/css">
.centerText{
text-align: center;
}
</style>
</head>
In DEV C++, I used pure C with WIN32, with this given piece of code:
case IDC_IP:
gethostname(szHostName, 255);
host_entry=gethostbyname(szHostName);
szLocalIP = inet_ntoa (*(struct in_addr *)*host_entry->h_addr_list);
//WSACleanup();
writeInTextBox("\n");
writeInTextBox("IP: ");
writeInTextBox(szLocalIP);
break;
When I click the button 'show ip', it works. But on the second time, the program quits (without warning or error). When I do:
//WSACleanup();
The program does not quit, even clicking the same button multiple times with fastest speed. So WSACleanup() may not work well with Dev-C++..
The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this :
mysql --help | grep Default -A 1
And the output:
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
--
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
--
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
--
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
--
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
literal_eval
, a somewhat safer version of eval
(will only evaluate literals ie strings, lists etc):
from ast import literal_eval
python_dict = literal_eval("{'a': 1}")
json.loads
but it would require your string to use double quotes:
import json
python_dict = json.loads('{"a": 1}')
For our team, nothing helped. We have spend a couple of days and tried out every step that was mentioned here above in answers and comments. We tried with XCode 10 and even XCode 9.2 on an App, that is on the App store since many years.
The issue began after upgrading to MacOS Mojave. Unfortunately, going back to HighSierra didn't help then.
At least we was able again to ship into App store after we've created new certificate and provisioning profile. But we still are not able any more to test our App in release mode on real device, which is necessary to test InApp-purchases.
In short: Archiving and submission works well, running on real device not!
Several developers, several devices, macbooks, XCode versions....
At the end we had to change the AppID for being able again to test on real device.
Therefor we run two different projects now: one for shipping to TestFlight/AppStore with the real AppID and one for development purposes with another AppID.
Although this only happens on ONE particular App of our company and not all the others, we expect to run into similar issues in the future as things get more worse with Apple's development tools...
Assign a int -1
to an unsigned
: As -1
does not fit in the range [0...UINT_MAX]
, multiples of UINT_MAX+1
are added until the answer is in range. Evidently UINT_MAX
is pow(2,32)-1 or 429496725
on OP's machine so a
has the value of 4294967295.
unsigned int a = -1;
The "%x"
, "%u"
specifier expects a matching unsigned
. Since these do not match, "If a conversion specification is invalid, the behavior is undefined.
If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined." C11 §7.21.6.1 9. The printf specifier does not change b
.
printf("%x\n", b); // UB
printf("%u\n", b); // UB
The "%d"
specifier expects a matching int
. Since these do not match, more UB.
printf("%d\n", a); // UB
Given undefined behavior, the conclusions are not supported.
both cases, the bytes are the same (ffffffff).
Even with the same bit pattern, different types may have different values. ffffffff
as an unsigned
has the value of 4294967295. As an int
, depending signed integer encoding, it has the value of -1, -2147483647 or TBD. As a float
it may be a NAN.
what is unsigned word for?
unsigned
stores a whole number in the range [0 ... UINT_MAX]
. It never has a negative value. If code needs a non-negative number, use unsigned
. If code needs a counting number that may be +, - or 0, use int
.
Update: to avoid a compiler warning about assigning a signed int
to unsigned
, use the below. This is an unsigned
1u
being negated - which is well defined as above. The effect is the same as a -1
, but conveys to the compiler direct intentions.
unsigned int a = -1u;
I would not make the primary key of the "info" table a composite of the two values from other tables.
Others can articulate the reasons better, but it feels wrong to have a column that is really made up of two pieces of information. What if you want to sort on the ID from the second table for some reason? What if you want to count the number of times a value from either table is present?
I would always keep these as two distinct columns. You could use a two-column primay key in mysql ...PRIMARY KEY(id_a, id_b)... but I prefer using a two-column unique index, and having an auto-increment primary key field.
This answer may be late but I hope it helps someone.
For me, these 2 lines of code worked:
textView.isScrollEnabled = false
textView.sizeToFit()
But don't set height constraint for your Textview
If you are using the Git Bash shell, you can use the following trick:
> webpage.html
This is actually the same as:
echo "" > webpage.html
Then, you can use git add webpage.html
to stage the file.
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
I've yet another answer that builds upon all previous ones that describe npm install @types/node
and including node
in tsconfig.json / compilerOptions / types
.
In my case, I have a base tsConfig.json
and a separate one in the Angular application that extends this one:
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "../out-tsc/app",
"types": []
},
My problem was the empty types
in this tsconfi.app.json
- it clobbers the one in the base configuration.
When you use a const
string, the compiler embeds the string's value at compile-time.
Therefore, if you use a const
value in a different assembly, then update the original assembly and change the value, the other assembly won't see the change until you re-compile it.
A static readonly
string is a normal field that gets looked up at runtime. Therefore, if the field's value is changed in a different assembly, the changes will be seen as soon as the assembly is loaded, without recompiling.
This also means that a static readonly
string can use non-constant members, such as Environment.UserName
or DateTime.Now.ToString()
. A const
string can only be initialized using other constants or literals.
Also, a static readonly
string can be set in a static constructor; a const
string can only be initialized inline.
Note that a static string
can be modified; you should use static readonly
instead.
You can use this example and change it's implementation like this:
[self enumerateAttribute:NSParagraphStyleAttributeName
inRange:NSMakeRange(0, self.length)
options:0
usingBlock:^(id _Nullable value, NSRange range, BOOL * _Nonnull stop) {
NSMutableParagraphStyle *paragraphStyle = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
//add your specific settings for paragraph
//...
//...
[self removeAttribute:NSParagraphStyleAttributeName range:range];
[self addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:range];
}];
You can use parameter expansion, e.g.
read -p "Enter your name [Richard]: " name
name=${name:-Richard}
echo $name
Including the default value in the prompt between brackets is a fairly common convention
What does the :-Richard
part do? From the bash manual:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
Also worth noting that...
In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
So if you use webpath=${webpath:-~/httpdocs}
you will get a result of /home/user/expanded/path/httpdocs
not ~/httpdocs
, etc.
I find this easier
https://superuser.com/questions/170795/how-can-i-select-and-delete-lines-of-text-in-vi
From the C# language specification (PDF page 287 - or 300th page of the PDF):
Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.
I tried with every answer avobe, but couldn't make it.
Did this and worked
sudo apt-get purge python-virtualenv
sudo pip install pip -U
After that I just installed virtualenv with pip
sudo pip install virtualenv
I built the virtualenv that I was working on and
the package was installed easily.
Get into the virtualenv by using source /bin/activate
and try to install your package, for example:
pip install terminado
It worked for me, although I was using python2.7 not python3