Removed and added back in the table using Scaffold-DbContext and the error went away
I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.
var blob = new Blob([s2ab(atob(data))], {
type: ''
});
href = URL.createObjectURL(blob);
The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
All your problems are that you are mixing content type negotiation with parameter passing. They are things at different levels. More specific, for your question 2, you constructed the response header with the media type your want to return. The actual content negotiation is based on the accept media type in your request header, not response header. At the point the execution reaches the implementation of the method getPersonFormat, I am not sure whether the content negotiation has been done or not. Depends on the implementation. If not and you want to make the thing work, you can overwrite the request header accept type with what you want to return.
return new ResponseEntity<>(PersonFactory.createPerson(), httpHeaders, HttpStatus.OK);
In Access VBA I've used this to turn off all the dialogs when running a bunch of updates:
DoCmd.SetWarnings False
After running all the updates, the last step in my VBA script is:
DoCmd.SetWarnings True
Hope this helps.
UPDATE: this is not the solution but it's a workaround for a problem that can cause the exception presented in the question.
I've solved changing from Release Configuration to Debug Configuration.
You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.
For XLS file: HSSFWorkbook
& HSSFSheet
For XLSX file: XSSFSheet
& XSSFSheet
So in place of XSSFWorkbook
use HSSFWorkbook
and in place of XSSFSheet
use HSSFSheet
.
So your code should look like this after the changes are made:
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
Please see Why does the property I want to mock need to be virtual?
You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x)
call.
I encountered a similar problem with glassfish application server and Oracle JDK/JRE but not in Open JDK/JRE.
When connecting to a SSL domain I always ran into:
javax.net.ssl.SSLHandshakeException: Remote host closed connection during handshake
...
Caused by: java.io.EOFException: SSL peer shut down incorrectly
The solution for me was to install the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files because the server only understood certificates that are not included in Oracle JDK by default, only OpenJDK includes them. After installing everything worked like charme.
JCE 7: http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JCE 8: http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
I have just met this problem today: I migrated my Excel project from Office 2007 to 2010. At a certain point, when my macro tried to Insert a new line (e.g. Range("5:5").Insert
), the same error message came. It happens only when previously another sheet has been edited (my macro switches to another sheet).
Thanks to Google, and your discussion, I found the following solution (based on the answer given by "red" at answered Jul 30 '13 at 0:27): after switching to the sheet a Cell has to be edited before inserting a new row. I have added the following code:
'=== Excel bugfix workaround - 2014.08.17
Range("B1").Activate
vCellValue = Range("B1").Value
Range("B1").ClearContents
Range("B1").Value = vCellValue
"B1" can be replaced by any cell on the sheet.
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
The problem for me was that my stream was not set to the origin before download.
Response.Clear();
Response.ContentType = "Application/msword";
Response.AddHeader("Content-Disposition", "attachment; filename=myfile.docx");
//ADDED THIS LINE
myMemoryStream.Seek(0,SeekOrigin.Begin);
myMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.Close();
I have used text/comma-separated-values
for CSV mime-type in accept attribute and it works fine in Opera. Tried text/csv
without luck.
Some others MIME-Types for CSV if the suggested do not work:
In my project with netcore 2.2 I use this code:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
OkObjectResult result = Ok( payload );
// currently result.Formatters is empty but we'd like to ensure it will be so in the future
result.Formatters.Clear();
// force response as xml
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
It forces only one action within a controller to return a xml without effect to other actions. Also this code doesn't contain neither HttpResponseMessage or StringContent or ObjectContent which are disposable objects and hence should be handled appropriately (it is especially a problem if you use any of code analyzers that reminds you about it).
Going further you could use a handy extension like this:
public static class ObjectResultExtensions
{
public static T ForceResultAsXml<T>( this T result )
where T : ObjectResult
{
result.Formatters.Clear();
result.Formatters.Add( new Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter() );
return result;
}
}
And your code will become like this:
[HttpGet]
[Route( "something" )]
public IActionResult GetSomething()
{
string payload = "Something";
return Ok( payload ).ForceResultAsXml();
}
In addition, this solution looks like an explicit and clean way to force return as xml and it is easy to add to your existent code.
P.S. I used fully-qualified name Microsoft.AspNetCore.Mvc.Formatters.XmlSerializerOutputFormatter just to avoid ambiguity.
No. You can't send headers after they were sent. Try to use hooks in wordpress
IMHO the simplest way is to use new control inherited from Hyperlink
:
/// <summary>
/// Opens <see cref="Hyperlink.NavigateUri"/> in a default system browser
/// </summary>
public class ExternalBrowserHyperlink : Hyperlink
{
public ExternalBrowserHyperlink()
{
RequestNavigate += OnRequestNavigate;
}
private void OnRequestNavigate(object sender, RequestNavigateEventArgs e)
{
Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
e.Handled = true;
}
}
I see 2 possible problems:
Problem 1
Solution: assign a callback function to the objects "onreadystatechange" -event and handle the data in that function
xmlhttp.onreadystatechange = callbackFunctionName;
Once the state has reached DONE (4), the response content is ready to be read.
Problem 2
Solution: Either use a try-catch for creating the correct object for correct browser ( ActiveXObject in IE) or use a framework, for example jQuery ajax-method
Note: if you decide to use jQuery ajax-method, you assign the callback-function with jqXHR.done()
AFAIK you cannot use VBA Excel to create custom tab in the Excel ribbon. You can however hide/make visible a ribbon component using VBA. Additionally, the link that you mentioned above is for MS Project and not MS Excel.
I create tabs for my Excel Applications/Add-Ins using this free utility called Custom UI Editor.
Edit: To accommodate new request by OP
Here is a short tutorial as promised:
After you have installed the Custom UI Editor (CUIE), open it and then click on File | Open and select the relevant Excel File. Please ensure that the Excel File is closed before you open it via CUIE. I am using a brand new worksheet as an example.
Right click as shown in the image below and click on "Office 2007 Custom UI Part". It will insert the "customUI.xml"
Next Click on menu Insert | Sample XML | Custom Tab. You will notice that the basic code is automatically generated. Now you are all set to edit it as per your requirements.
Let's inspect the code
label="Custom Tab"
: Replace "Custom Tab" with the name which you want to give your tab. For the time being let's call it "Jerome".
The below part adds a custom button.
<button id="customButton" label="Custom Button" imageMso="HappyFace" size="large" onAction="Callback" />
imageMso
: This is the image that will display on the button. "HappyFace" is what you will see at the moment. You can download more image ID's here.
onAction="Callback"
: "Callback" is the name of the procedure which runs when you click on the button.
With that, let's create 2 buttons and call them "JG Button 1" and "JG Button 2". Let's keep happy face as the image of the first one and let's keep the "Sun" for the second. The amended code now looks like this:
<customUI xmlns="http://schemas.microsoft.com/office/2006/01/customui">
<ribbon startFromScratch="false">
<tabs>
<tab id="MyCustomTab" label="Jerome" insertAfterMso="TabView">
<group id="customGroup1" label="First Tab">
<button id="customButton1" label="JG Button 1" imageMso="HappyFace" size="large" onAction="Callback1" />
<button id="customButton2" label="JG Button 2" imageMso="PictureBrightnessGallery" size="large" onAction="Callback2" />
</group>
</tab>
</tabs>
</ribbon>
</customUI>
Delete all the code which was generated in CUIE and then paste the above code in lieu of that. Save and close CUIE. Now when you open the Excel File it will look like this:
Now the code part. Open VBA Editor, insert a module, and paste this code:
Public Sub Callback1(control As IRibbonControl)
MsgBox "You pressed Happy Face"
End Sub
Public Sub Callback2(control As IRibbonControl)
MsgBox "You pressed the Sun"
End Sub
Save the Excel file as a macro enabled file. Now when you click on the Smiley or the Sun you will see the relevant message box:
Hope this helps!
The error is telling you that POI couldn't find a core part of the OOXML file, in this case the content types part. Your file isn't a valid OOXML file, let alone a valid .xlsx file. It is a valid zip file though, otherwise you'd have got an earlier error
Can Excel really load this file? I'd expect it wouldn't be able to, as the exception is most commonly triggered by giving POI a regular .zip file! I suspect your file isn't valid, hence the exception
.
Update: In Apache POI 3.15 (from beta 1 onwards), there's a more helpful set of Exception messages for the more common causes of this problem. You'll now get more descriptive exceptions in this case, eg ODFNotOfficeXmlFileException and OLE2NotOfficeXmlFileException. This raw form should only ever show up if POI really has no clue what you've given it but knows it's broken or invalid.
The issue for me was that DocumentFormat.OpenXml.dll
existed in the Global Assembly Cache (GAC) on my Win7 development box. So when publishing my project in VS2013, it found the file in the GAC and therefore omitted it from being copied to the publish folder.
Solution: remove the DLL from the GAC.
%windir%\Microsoft.NET\assembly
)OpenXml
There may be a more proper way to remove a GAC file (below), but that is what I did and it worked.
gacutil –u DocumentFormat.OpenXml.dll
Hope that helps!
Without RegEx, with some must-have value checking
public static string ExtractString(string soapMessage, string tag)
{
if (string.IsNullOrEmpty(soapMessage))
return soapMessage;
var startTag = "<" + tag + ">";
int startIndex = soapMessage.IndexOf(startTag);
startIndex = startIndex == -1 ? 0 : startIndex + startTag.Length;
int endIndex = soapMessage.IndexOf("</" + tag + ">", startIndex);
endIndex = endIndex > soapMessage.Length || endIndex == -1 ? soapMessage.Length : endIndex;
return soapMessage.Substring(startIndex, endIndex - startIndex);
}
You should always use below MIME type if you want to serve excel file in xlsx format
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Cannot comment anymore but voted it up and wanted to let folks know that "
works very well for the xml config files when forming regex expressions for RegexTransformer in Solr like so: regex=".*img src="(.*)".*"
using the escaped version instead of double-quotes.
Below is the server side code that would call the handler and recieve the stream data and loads into xml doc
Stream stream = null;
**Create a web request with the specified URL**
WebRequest myWebRequest = WebRequest.Create(@"http://localhost/XMLProvider/XMLProcessorHandler.ashx");
**Senda a web request and wait for response.**
WebResponse webResponse = myWebRequest.GetResponse();
**Get the stream object from response object**
stream = webResponse.GetResponseStream();
XmlDocument xmlDoc = new XmlDocument();
**Load stream data into xml**
xmlDoc.Load(stream);
XML Blueprint also does that; instructions here
http://www.xmlblueprint.com/help/html/topic_170.htm
It's not free, but there's a 10-day free trial; it seems fast and efficient; unfortunately it's Windows only.
One solution for this can be found with find.
$ mkdir foo bar
$ touch foo/a.txt foo/Music.txt
$ find foo -type f ! -name '*Music*' -exec cp {} bar \;
$ ls bar
a.txt
Find has quite a few options, you can get pretty specific on what you include and exclude.
Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.
The bit shift operators are more efficient as compared to the /
or *
operators.
In computer architecture, divide(/) or multiply(*) take more than one time unit and register to compute result, while, bit shift operator, is just one one register and one time unit computation.
(ansible 2.9.6 ansible-lint 4.2.0)
See ansible-lint default rules. The condition below causes E602 Don’t compare to empty string
when: test_myscript.stderr != ""
Correct syntax and also "Ansible Galaxy Warning-Free" option is
when: test_myscript.stderr | length > 0
Quoting from source code
"Use
when: var|length > 0
rather thanwhen: var != ""
(or ' 'converselywhen: var|length == 0
rather thanwhen: var == ""
)"
Notes
- debug:
msg: "Empty string '{{ var }}' evaluates to False"
when: not var
vars:
var: ''
- debug:
msg: "Empty list {{ var }} evaluates to False"
when: not var
vars:
var: []
give
"msg": "Empty string '' evaluates to False"
"msg": "Empty list [] evaluates to False"
ANSIBLE_CONDITIONAL_BARE_VARS=false
the condition works fine but setting ANSIBLE_CONDITIONAL_BARE_VARS=true
the condition will fail - debug:
msg: "String '{{ var }}' evaluates to True"
when: var
vars:
var: 'abc'
gives
fatal: [localhost]: FAILED! =>
msg: |-
The conditional check 'var' failed. The error was: error while
evaluating conditional (var): 'abc' is undefined
Explicit cast to Boolean prevents the error but evaluates to False i.e. will be always skipped (unless var='True'
). When the filter bool
is used the options ANSIBLE_CONDITIONAL_BARE_VARS=true
and ANSIBLE_CONDITIONAL_BARE_VARS=false
have no effect
- debug:
msg: "String '{{ var }}' evaluates to True"
when: var|bool
vars:
var: 'abc'
gives
skipping: [localhost]
- include_tasks: teardown.yml
when: teardown
- include_tasks: provision.yml
when: not teardown
" based on a variable you define as a string (with quotation marks around it):"
In Ansible 2.7 and earlier, the two conditions above evaluated as True and False respectively if teardown: 'true'
In Ansible 2.7 and earlier, both conditions evaluated as False if teardown: 'false'
In Ansible 2.8 and later, you have the option of disabling conditional bare variables, so when: teardown always evaluates as True and when: not teardown always evaluates as False when teardown is a non-empty string (including 'true' or 'false')
"Expect that this setting eventually will be deprecated after 2.12"
The easiest solution would be to use Wireshark and trace the HTTP tcp flow.
You wrote that format can change from YYYY-mm-dd to dd-mm-YYYY you can try to find year there
$parts = explode("-","2068-06-15");
for ($i = 0; $i < count($parts); $i++)
{
if(strlen($parts[$i]) == 4)
{
$year = $parts[$i];
break;
}
}
function(evt) {evt.preventDefault();}
and its opposite
function(evt) {return true;}
cheers!
In Python 3, raw_input()
doesn't exist which was already mentioned by Sven.
In Python 2, the input()
function evaluates your input.
Example:
name = input("what is your name ?")
what is your name ?harsha
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
name = input("what is your name ?")
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In the example above, Python 2.x is trying to evaluate harsha as a variable rather than a string. To avoid that, we can use double quotes around our input like "harsha":
>>> name = input("what is your name?")
what is your name?"harsha"
>>> print(name)
harsha
raw_input()
The raw_input()` function doesn't evaluate, it will just read whatever you enter.
Example:
name = raw_input("what is your name ?")
what is your name ?harsha
>>> name
'harsha'
Example:
name = eval(raw_input("what is your name?"))
what is your name?harsha
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
name = eval(raw_input("what is your name?"))
File "<string>", line 1, in <module>
NameError: name 'harsha' is not defined
In example above, I was just trying to evaluate the user input with the eval
function.
Had several modules complain about patch does not apply. One thing I was missing out was that the branches had become stale. After the git merge master
generated the patch files using git diff master BRANCH > file.patch
. Going to the vanilla branch was able to apply the patch with git apply file.patch
I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat
contains:
"This is the original content"
Then you can simply write:
f = open('myfile.dat', 'w')
f.close()
This would erase all the content. Then you can write the new content to the file:
f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()
In ResourceServerConfigurerAdapter
class, below code snipped worked for me. http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler()).and.csrf()..
did not work. That's why I wrote it as separate call.
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
@Override
public void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler());
http.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS).permitAll()
.antMatchers("/subscribers/**").authenticated()
.antMatchers("/requests/**").authenticated();
}
Implementation of AuthenticationEntryPoint for catching token expiry and missing authorization header.
public class AuthFailureHandler implements AuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
throws IOException, ServletException {
httpServletResponse.setContentType("application/json");
httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
if( e instanceof InsufficientAuthenticationException) {
if( e.getCause() instanceof InvalidTokenException ){
httpServletResponse.getOutputStream().println(
"{ "
+ "\"message\": \"Token has expired\","
+ "\"type\": \"Unauthorized\","
+ "\"status\": 401"
+ "}");
}
}
if( e instanceof AuthenticationCredentialsNotFoundException) {
httpServletResponse.getOutputStream().println(
"{ "
+ "\"message\": \"Missing Authorization Header\","
+ "\"type\": \"Unauthorized\","
+ "\"status\": 401"
+ "}");
}
}
}
The answer probably depends how critical it is for you to receive support and possible customization for this service.
Google can certainly do this. Look into their XML and Geocoding API's. You should be able to craft an XML message asking Google to return Map coordinates for a given address. If the address is not found (invalid), you will receive an appropriate response. Here's a useful page: http://code.google.com/apis/maps/documentation/services.html#XML_Requests
Note that Google's aim in providing the Maps API is to plot addresses on actual maps. While you can certainly use the data for other purposes, you are at the mercy of Google should one of their maps not exactly correspond to your legal or commercial address validation needs. If you paid for one of the services you mentioned, you would likely be able to receive support should certain addresses not resolve the way you expect them to.
In other words, you get what you pay for ;) . If you have the time, though, why not try implementing a Google-based solution then going from there? The API looks pretty slick, and it's free, after all.
modify Romulo BM answer for velocity listening
func scrollViewWillEndDragging(
_ scrollView: UIScrollView,
withVelocity velocity: CGPoint,
targetContentOffset: UnsafeMutablePointer<CGPoint>
) {
targetContentOffset.pointee = scrollView.contentOffset
var indexes = collection.indexPathsForVisibleItems
indexes.sort()
var index = indexes.first!
if velocity.x > 0 {
index.row += 1
} else if velocity.x == 0 {
let cell = self.collection.cellForItem(at: index)!
let position = self.collection.contentOffset.x - cell.frame.origin.x
if position > cell.frame.size.width / 2 {
index.row += 1
}
}
self.collection.scrollToItem(at: index, at: .centeredHorizontally, animated: true )
}
Answer isE
given that the rest are plainly wrong, but ..
Simple fact is, the garbage collector may never decide to garbage collection every single object that is a viable candidate for collection, not unless memory pressure is extremely high. And then there is the fact that Java is just as susceptible to memory leaks as any other language, they are just harder to cause, and thus harder to find when you do cause them!
The following article has many good details on how memory management works and doesn't work and what gets take up by what. How generational Garbage Collectors work and Thanks for the Memory ( Understanding How the JVM uses Native Memory on Windows and Linux )
If you read the links, I think you will get the idea that memory management in Java isn't as simple as a multiple choice question.
During the course of my project I jumped from Kendall's answer to Cliff's answer to solve this problem for images that are loaded from the phone itself.
In the end I ended up using CGImageCreateWithPNGDataProvider
instead:
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"clockdial.png"];
return CGImageCreateWithPNGDataProvider(CGDataProviderCreateWithFilename([imageFileName UTF8String]), NULL, YES, kCGRenderingIntentDefault);
This doesn't suffer from the orientation issues that you would get from getting the CGImage
from a UIImage
and it can be used as the contents of a CALayer
without a hitch.
For MySql WorkBench, Please use below :
update emp as a
inner join department b on a.department_id=b.id
set a.department_name=b.name
where a.emp_id in (10,11,12);
A update version @Chris Wedgwood
's answer for keeping site-packages
(keeping packages installed)
cd ~/.virtualenv/name_of_broken_venv
mv lib/python2.7/site-packages ./
rm -rf .Python bin lib include
virtualenv .
rm -rf lib/python2.7/site-packages
mv ./site-packages lib/python2.7/
If you must create an empty array you can do this:
string[] arr = new string[0];
If you don't know about the size then You may also use List<string>
as well like
var valStrings = new List<string>();
// do stuff...
string[] arrStrings = valStrings.ToArray();
I use 'setAttribute' function:
<input type="text" id="example"> // Setup text field
<script type="text/javascript">
document.getElementById("example").setAttribute('value','My default value');
</script>
The answer is simple: Use a 3rd party product like jwplayer or similar, then set it to the minimal player size which is the audio player size (only shows player controls).
Voila.
Been using this for over 8 years.
You're using a colon instead of a comma. Try:
$(body).css("background-color","blue");
You also need to wrap the id in quotes or it will look for a variable called #co
$("#co").click(change()
There are many more issues here. click
isn't an HTML attribute. You want onclick
(which is redundant). Try this:
<div id="co"> <!-- no onclick method needed -->
<script>
$(document).ready(function() {
$("#co").click(function() {
$("body").css("background-color","blue"); //edit, body must be in quotes!
});
});
</script>
You were trying to call an undefined method. It looks like you were trying to declare it inside the callback statement? I'm not sure. But please compare this to your code and see the differences.
http://jsfiddle.net/CLwE5/ demo fiddle
Take with a grain of salt, didn't test.
- (BOOL)isModal {
if([self presentingViewController])
return YES;
if([[[self navigationController] presentingViewController] presentedViewController] == [self navigationController])
return YES;
if([[[self tabBarController] presentingViewController] isKindOfClass:[UITabBarController class]])
return YES;
return NO;
}
Simple: active the accordion to a class, and then create divs with this, like multiples instances of accordion.
Like this:
JS
$(function() {
$( ".accordion" ).accordion({
collapsible: true,
clearStyle: true,
active: false,
})
});
HTML
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
<div class="accordion">
<h3>Title</h3>
<p>lorem</p>
</div>
.. the array I get is very little randomized. It generates a lot of blocks of successive numbers...
Sequences of random items often contain blocks of successive numbers, see the Gambler's Fallacy. For example:
.. we have just tossed four heads in a row .. Since the probability of a run of five successive heads is only 1/32 .. a person subject to the gambler's fallacy might believe that this next flip was less likely to be heads than to be tails. http://en.wikipedia.org/wiki/Gamblers_fallacy
Feb 2016 version: Admin tab, then select Property in the middle column, click Property Settings, then the Move To Trash Can button at the top right. No need to delete individual views.
you need to cast int to str before concatenating. for that use str(temperature)
. Or you can print the same output using ,
if you don't want to convert like this.
print("the furnace is now",temperature , "degrees!")
It seems that you have to either use a big amount of code to simulate hashes in bash to get linear behavior or stick to the quadratic superlinear versions.
Among those versions, saua's solution is the best (and simplest):
sort -n ip_addresses.txt | uniq -c
I found http://unix.derkeiler.com/Newsgroups/comp.unix.shell/2005-11/0118.html. But it's ugly as hell...
You can do that with cat and that pipe the output to less:
cat -e yourFile | less
This excerpt from man cat
explains what -e
means:
-e equivalent to -vE
-E, --show-ends
display $ at end of each line
-v, --show-nonprinting
use ^ and M- notation, except for LFD and TAB
By default mysqldump
always creates the CREATE DATABASE IF NOT EXISTS db_name;
statement at the beginning of the dump file.
[EDIT] Few things about the mysqldump
file and it's options:
--all-databases
, -A
Dump all tables in all databases. This is the same as using the --databases
option and naming all the databases on the command line.
--add-drop-database
Add a DROP DATABASE
statement before each CREATE DATABASE
statement. This option is typically used in conjunction with the --all-databases
or --databases
option because no CREATE DATABASE
statements are written unless one of those options is specified.
--databases
, -B
Dump several databases. Normally, mysqldump
treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE
and USE
statements are included in the output before each new database.
--no-create-db
, -n
This option suppresses the CREATE DATABASE
statements that are otherwise included in the output if the --databases
or --all-databases
option is given.
Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.
So to answer your question:
--add-drop-database
option in your mysqldump
statement.--databases
or --all-databases
and the CREATE DATABASE
syntax will be added
automaticallyMore information at MySQL Reference Manual
Why not set sample.png
as background image of text
or h2
css class? This will give effect as you have written over an image.
No -- AL is the 8 least significant bits of AX. AX is the 16 least significant bits of EAX.
Perhaps it's easiest to deal with if we start with 04030201h in eax. In this case, AX will contain 0201h, AH wil contain 02h and AL will contain 01h.
Do a git rebase -i FAR_ENOUGH_BACK
and drop the line for the commit you don't want.
this code is tested with pdfminer for python 3 (pdfminer-20191125)
from pdfminer.layout import LAParams
from pdfminer.converter import PDFPageAggregator
from pdfminer.pdfinterp import PDFResourceManager
from pdfminer.pdfinterp import PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.layout import LTTextBoxHorizontal
def parsedocument(document):
# convert all horizontal text into a lines list (one entry per line)
# document is a file stream
lines = []
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
for page in PDFPage.get_pages(document):
interpreter.process_page(page)
layout = device.get_result()
for element in layout:
if isinstance(element, LTTextBoxHorizontal):
lines.extend(element.get_text().splitlines())
return lines
I found this: https://github.com/PHPGangsta/GoogleAuthenticator. I tested it and works fine for me.
You are iterating over one string (word
), but then using the index into that to look up a character in so_far
. There is no guarantee that these two strings have the same length.
I tried researching that too but instead ended up using jsconsole.com by Remy Sharp (he also created jsbin.com). I'm running on Ubuntu 12.10 so I had to create a special icon but if you're on Windows and use Chrome simply go to Tools>Create Application Shortcuts (note this doesn't work very well, or at all in my case, on Ubuntu). This site works very like the Mac jsc
console: actually it has some cool features too (like loading libraries/code from a URL) that I guess jsc
does not.
Hope this helps.
How do I rename a specific column in pandas?
From v0.24+, to rename one (or more) columns at a time,
DataFrame.rename()
with axis=1
or axis='columns'
(the axis
argument was introduced in v0.21
.
Index.str.replace()
for string/regex based replacement.
If you need to rename ALL columns at once,
DataFrame.set_axis()
method with axis=1
. Pass a list-like sequence. Options are available for in-place modification as well.rename
with axis=1
df = pd.DataFrame('x', columns=['y', 'gdp', 'cap'], index=range(5))
df
y gdp cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
With 0.21+, you can now specify an axis
parameter with rename
:
df.rename({'gdp':'log(gdp)'}, axis=1)
# df.rename({'gdp':'log(gdp)'}, axis='columns')
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
(Note that rename
is not in-place by default, so you will need to assign the result back.)
This addition has been made to improve consistency with the rest of the API. The new axis
argument is analogous to the columns
parameter—they do the same thing.
df.rename(columns={'gdp': 'log(gdp)'})
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
rename
also accepts a callback that is called once for each column.
df.rename(lambda x: x[0], axis=1)
# df.rename(lambda x: x[0], axis='columns')
y g c
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
For this specific scenario, you would want to use
df.rename(lambda x: 'log(gdp)' if x == 'gdp' else x, axis=1)
Index.str.replace
Similar to replace
method of strings in python, pandas Index and Series (object dtype only) define a ("vectorized") str.replace
method for string and regex-based replacement.
df.columns = df.columns.str.replace('gdp', 'log(gdp)')
df
y log(gdp) cap
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
The advantage of this over the other methods is that str.replace
supports regex (enabled by default). See the docs for more information.
set_axis
with axis=1
Call set_axis
with a list of header(s). The list must be equal in length to the columns/index size. set_axis
mutates the original DataFrame by default, but you can specify inplace=False
to return a modified copy.
df.set_axis(['cap', 'log(gdp)', 'y'], axis=1, inplace=False)
# df.set_axis(['cap', 'log(gdp)', 'y'], axis='columns', inplace=False)
cap log(gdp) y
0 x x x
1 x x x
2 x x x
3 x x x
4 x x x
Note: In future releases, inplace
will default to True
.
Method Chaining
Why choose set_axis
when we already have an efficient way of assigning columns with df.columns = ...
? As shown by Ted Petrou in this answer set_axis
is useful when trying to chain methods.
Compare
# new for pandas 0.21+
df.some_method1()
.some_method2()
.set_axis()
.some_method3()
Versus
# old way
df1 = df.some_method1()
.some_method2()
df1.columns = columns
df1.some_method3()
The former is more natural and free flowing syntax.
What I would do is comment out the Dockerfile below and including the offending line. Then you can run the container and run the docker commands by hand, and look at the logs in the usual way. E.g. if the Dockerfile is
RUN foo
RUN bar
RUN baz
and it's dying at bar I would do
RUN foo
# RUN bar
# RUN baz
Then
$ docker build -t foo .
$ docker run -it foo bash
container# bar
...grep logs...
Assuming Date is unique for a given UserID, here's some TSQL:
SELECT
UserTest.UserID, UserTest.Value
FROM UserTest
INNER JOIN
(
SELECT UserID, MAX(Date) MaxDate
FROM UserTest
GROUP BY UserID
) Dates
ON UserTest.UserID = Dates.UserID
AND UserTest.Date = Dates.MaxDate
There are many links that lets you know how to handle post values from checkboxes in php. Look at this link: http://www.html-form-guide.com/php-form/php-form-checkbox.html
Single check box
HTML code:
<form action="checkbox-form.php" method="post">
Do you need wheelchair access?
<input type="checkbox" name="formWheelchair" value="Yes" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
PHP Code:
<?php
if (isset($_POST['formWheelchair']) && $_POST['formWheelchair'] == 'Yes')
{
echo "Need wheelchair access.";
}
else
{
echo "Do not Need wheelchair access.";
}
?>
Check box group
<form action="checkbox-form.php" method="post">
Which buildings do you want access to?<br />
<input type="checkbox" name="formDoor[]" value="A" />Acorn Building<br />
<input type="checkbox" name="formDoor[]" value="B" />Brown Hall<br />
<input type="checkbox" name="formDoor[]" value="C" />Carnegie Complex<br />
<input type="checkbox" name="formDoor[]" value="D" />Drake Commons<br />
<input type="checkbox" name="formDoor[]" value="E" />Elliot House
<input type="submit" name="formSubmit" value="Submit" />
/form>
<?php
$aDoor = $_POST['formDoor'];
if(empty($aDoor))
{
echo("You didn't select any buildings.");
}
else
{
$N = count($aDoor);
echo("You selected $N door(s): ");
for($i=0; $i < $N; $i++)
{
echo($aDoor[$i] . " ");
}
}
?>
More precisely, add the code below to the private void InitializeComponent()
method of the Form class:
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
When i tried to make the .java to .class the command Javac didnt work. I got it working by going to C:\Program Files (x86)\Java\jdk1.7.0_04\bin and when i was on that directory I typed Javac.exe C\Test\test.java and it made the class with that tactic. Try that out.
The solution, if your list items can be display: inline
is quite easy:
#footer { text-align: center; }
#footer ul { list-style: none; }
#footer ul li { display: inline; }
However, many times you must use display:block
on your <li>
s. The following CSS will work, in this case:
#footer { width: 100%; overflow: hidden; }
#footer ul { list-style: none; position: relative; float: left; display: block; left: 50%; }
#footer ul li { position: relative; float: left; display: block; right: 50%; }
Solved post but I'd like to mention my preferred solution. Namely, define a generic one-liner script eval_func.sh
:
#!/bin/bash
source $1 && shift && "@a"
Then call any function within any script via:
./eval_func.sh <any script> <any function> <any args>...
An issue I ran into with the accepted solution is that when sourcing my function-containing script within another script, the arguments of the latter would be evaluated by the former, causing an error.
I use Visual Studio git plugin, and I have some websites running on IIS I wanted to move. A simple way that worked for me:
Close Visual Studio.
Move the code (including git folder, etc)
Click on the solution file from the new location
This refreshes the mapping to the new location, using the existing local git files that were moved. Once i was back in Visual Studio, my Team Explorer window showed the repos in the new location.
There are two way
null
private int var;
can be initialized as private Integer var;
Set equal name
attributes to create a group;
<form>_x000D_
<fieldset id="group1">_x000D_
<input type="radio" value="value1" name="group1">_x000D_
<input type="radio" value="value2" name="group1">_x000D_
</fieldset>_x000D_
_x000D_
<fieldset id="group2">_x000D_
<input type="radio" value="value1" name="group2">_x000D_
<input type="radio" value="value2" name="group2">_x000D_
<input type="radio" value="value3" name="group2">_x000D_
</fieldset>_x000D_
</form>
_x000D_
A list in a flask can be easily jsonify using jsonify like:
from flask import Flask,jsonify
app = Flask(__name__)
tasks = [
{
'id':1,
'task':'this is first task'
},
{
'id':2,
'task':'this is another task'
}
]
@app.route('/app-name/api/v0.1/tasks',methods=['GET'])
def get_tasks():
return jsonify({'tasks':tasks}) #will return the json
if(__name__ == '__main__'):
app.run(debug = True)
The default in the php.ini for the session.gc_maxlifetime
directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:
http://www.php.net/manual/en/session.configuration.php
You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:
php_value session.gc_maxlifetime "3600"
Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.
The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.
I think I did encounter the same issue as yours. I created a simple mvn project and used "mvn eclipse:eclipse" to setup a eclipse project.
For example, my source file "Router.java" locates in "java/main/org/jhoh/mvc". And Router.java wants to read file "routes" which locates in "java/main/org/jhoh/mvc/resources"
I run "Router.java" in eclipse, and eclipse's console got NullPointerExeption. I set pom.xml with this setting to make all *.class java bytecode files locate in build directory.
<build>
<defaultGoal>package</defaultGoal>
<directory>${basedir}/build</directory>
<build>
I went to directory "build/classes/org/jhoh/mvc/resources", and there is no "routes". Eclipse DID NOT copy "routes" to "build/classes/org/jhoh/mvc/resources"
I think you can copy your "install.xml" to your *.class bytecode directory, NOT in your source code directory.
For experienced readers:
C:\Program Files\Java\jdkxxxx\bin\
PATH
. Remove old Java paths.PATH
.JAVA_HOME
.Welcome!
You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command...
error message.
In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.
PATH
(If you already understand this, feel free to skip the next three sections.)
When you run javac HelloWorld.java
, cmd must determine where javac.exe
is located. This is accomplished with PATH
, an environment variable.
An environment variable is a special key-value pair (e.g. windir=C:\WINDOWS
). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.
You can see your environment variables like this:
C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\craig\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...
The most important variable is PATH
. It is a list of paths, separated by ;
. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.
On my computer, PATH
is:
C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPower
Shell\v1.0\;C:\ProgramData\Microsoft\Windows\Start Menu\Programs;C:\Users\craig\AppData\
Roaming\Microsoft\Windows\Start Menu\Programs;C:\msys64\usr\bin;C:\msys64\mingw64\bin;C:\
msys64\mingw32\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Yarn\bin\;C:\Users\
craig\AppData\Local\Yarn\bin;C:\Program Files\Java\jdk-10.0.2\bin;C:\ProgramFiles\Git\cmd;
C:\Program Files\Oracle\VirtualBox;C:\Program Files\7-Zip\;C:\Program Files\PuTTY\;C:\
Program Files\launch4j;C:\Program Files (x86)\NSIS\Bin;C:\Program Files (x86)\Common Files
\Adobe\AGL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\iCLS Client\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
(x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\iCLS
Client\;C:\Users\craig\AppData\Local\Microsoft\WindowsApps
When you run javac HelloWorld.java
, cmd, upon realizing that javac
is not an internal command, searches the system PATH
followed by the user PATH
. It mechanically enters every directory in the list, and checks if javac.com
, javac.exe
, javac.bat
, etc. is present. When it finds javac
, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.
You must add the Java executables directory to PATH
.
(If you already understand this, feel free to skip this section.)
When downloading Java, you are offered a choice between:
java
but not javac
.java
and javac
, along with a host of other development tools. The JDK is a superset of the JRE.You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac
because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package's name includes the words "Development Kit" in it.
set
(If you weren't planning to anyway, feel free to skip this section.)
Several other answers recommend executing some variation of:
C:\>:: DON'T DO THIS
C:\>set PATH=C:\Program Files\Java\jdk1.7.0_09\bin
Do not do that. There are several major problems with that command:
PATH
and replaces it with the Java path. After executing this command, you might find various other commands not working.C:\Program Files\Java\jdk1.7.0_09\bin
– you almost definitely have a newer version of the JDK, which would have a different path.PATH
only applies to the current cmd session. You will have to reenter the set
command every time you open Command Prompt.Points #1 and #2 can be solved with this slightly better version:
C:\>:: DON'T DO THIS EITHER
C:\>set PATH=C:\Program Files\Java\<enter the correct Java folder here>\bin;%PATH%
But it is just a bad idea in general.
The right way begins with finding where you have installed Java. This depends on how you have installed Java.
You have installed Java by running a setup program. Oracle's installer places versions of Java under C:\Program Files\Java\
(or C:\Program Files (x86)\Java\
). With File Explorer or Command Prompt, navigate to that directory.
Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk
(as opposed to jre
). Enter the directory.
Then enter the bin
directory of that.
You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.
The resulting Java path should be in the form of (without quotes):
C:\Program Files\Java\jdkxxxx\bin\
You have downloaded a .zip containing the JDK. Extract it to some random place where it won't get in your way; C:\Java\
is an acceptable choice.
Then locate the bin
folder somewhere within it.
You are now in the correct directory. Copy its path. This is the Java path.
Remember to never move the folder, as that would invalidate the path.
That is the dialog to edit PATH
. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.
Try some of these:
control sysdm.cpl,,3
SystemPropertiesAdvanced.exe
» Environment VariablesControl Panel\System and Security\System
» Advanced System Settings (far left, in sidebar) » Environment VariablesAny of these should take you to the right settings dialog.
If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH
. Otherwise, you will see PATH
in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.
PATH
Look at PATH
. You almost definitely have two PATH
variables (because of user vs. system environment variables). You need to look at both of them.
Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH
, in that order, then javac
will invoke the Java 11 compiler, which will create version 55 .class
files, but java
will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH
. And while you're at it, you may as well uninstall old Java versions, too. And remember that you don't need to have both a JDK and a JRE.
If you have C:\ProgramData\Oracle\Java\javapath
, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.
Now is also a good opportunity to perform general housekeeping on PATH
. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).
PATH
Now take the Java path you found three steps ago, and place it in the system PATH
.
It shouldn't matter where in the list your new path goes; placing it at the end is a fine choice.
If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.
There really isn't much else to say here. Simply add the path to PATH
and click OK.
JAVA_HOME
While you're at it, you may as well set JAVA_HOME
as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.
If JAVA_HOME
does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/
directory, i.e. C:\Program Files\Java\jdkxxxx\
.
Remember to edit JAVA_HOME
after upgrading Java, too.
Though you have modified PATH
, all running programs, including cmd, only see the old PATH
. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.
There is no good way to refresh cmd's environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.
Peer authentication means that postgres asks the operating system for your login name and uses this for authentication. To login as user "dev" using peer authentication on postgres, you must also be the user "dev" on the operating system.
You can find details to the authentication methods in the Postgresql documentation.
Hint: If no authentication method works anymore, disconnect the server from the network and use method "trust" for "localhost" (and double check that your server is not reachable through the network while method "trust" is enabled).
Swift 4.0
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
// Creates that folder if not exists
try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}
The ALL_DIRECTORIES
data dictionary view will have information about all the directories that you have access to. That includes the operating system path
SELECT owner, directory_name, directory_path
FROM all_directories
This is a more accurate way to do it. It places decimals behind the seconds giving more precision.
$now = date('Y-m-d\TH:i:s.uP', time());
Notice the .uP
.
More info: https://stackoverflow.com/a/6153162/8662476
You will use the following query:
SELECT * FROM [table] GROUP BY NUMBER;
Where [table]
is the name of the table.
This provides a unique listing for the NUMBER
column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.
You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.
Good answers by Paul Simon and Steve Homer, I shut down team viewer and that did the trick. Skype or other programs may trigger the same glitch, but in this instance, I recalled the problem occurred when I tried to cut n paste a 2MB file from remote system through windows right click rather than using "File Transfer function in TV. An error message appeared, then the problem with Excel "'Cannot empty clipboard' message.
This problem occurs when you are working on a remote system. After copying and pasting a huge amount of data it shows the error. I have found the solution to this problem.
Go to remote systems task manager and perform the following task
Go to Task Manager > Processes Look for "rdpclip.exe" End that process
Your problem will be solved.
Tensor flow on 32 bit machine.
There is no official build out for 32 bit, but still there is a workaround for that, follow the link http://cudamusing.blogspot.in/2015/11/building-tensorflow-for-jetson-tk1.html. I would not suggest doing this big reason is its not possible to follow the process every time there is a change in official tensor flow code.
From the documentation
class
typing.Union
Union type; Union[X, Y] means either X or Y.
Hence the proper way to represent more than one return data type is
from typing import Union
def foo(client_id: str) -> Union[list,bool]
But do note that typing is not enforced. Python continues to remain a dynamically-typed language. The annotation syntax has been developed to help during the development of the code prior to being released into production. As PEP 484 states, "no type checking happens at runtime."
>>> def foo(a:str) -> list:
... return("Works")
...
>>> foo(1)
'Works'
As you can see I am passing a int value and returning a str. However the __annotations__
will be set to the respective values.
>>> foo.__annotations__
{'return': <class 'list'>, 'a': <class 'str'>}
Please Go through PEP 483 for more about Type hints. Also see What are Type hints in Python 3.5?
Kindly note that this is available only for Python 3.5 and upwards. This is mentioned clearly in PEP 484.
you can use the DBMS_SQL.DESCRIBE_COLUMNS2
SET SERVEROUTPUT ON;
DECLARE
STMT CLOB;
CUR NUMBER;
COLCNT NUMBER;
IDX NUMBER;
COLDESC DBMS_SQL.DESC_TAB2;
BEGIN
CUR := DBMS_SQL.OPEN_CURSOR;
STMT := 'SELECT object_name , to_char(object_id), created FROM DBA_OBJECTS where rownum<10';
SYS.DBMS_SQL.PARSE(CUR, STMT, DBMS_SQL.NATIVE);
DBMS_SQL.DESCRIBE_COLUMNS2(CUR, COLCNT, COLDESC);
DBMS_OUTPUT.PUT_LINE('Statement: ' || STMT);
FOR IDX IN 1 .. COLCNT
LOOP
CASE COLDESC(IDX).col_type
WHEN 2 THEN
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': NUMBER');
WHEN 12 THEN
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': DATE');
WHEN 180 THEN
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': TIMESTAMP');
WHEN 1 THEN
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR'||':'|| COLDESC(IDX).col_max_len);
WHEN 9 THEN
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': VARCHAR2');
-- Insert more cases if you need them
ELSE
DBMS_OUTPUT.PUT_LINE('#' || TO_CHAR(IDX) || ': OTHERS (' || TO_CHAR(COLDESC(IDX).col_type) || ')');
END CASE;
END LOOP;
SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(SQLERRM(SQLCODE()) || ': ' || DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
SYS.DBMS_SQL.CLOSE_CURSOR(CUR);
END;
/
full example in the below url
https://www.ibm.com/support/knowledgecenter/sk/SSEPGG_9.7.0/com.ibm.db2.luw.sql.rtn.doc/doc/r0055146.html
Assuming it's faster to just move a pointer / set a byte to null (or however Java implements StringBuilder#setLength), rather than check a condition each time through the loop to see when to append the delimiter, you could use this method:
public static String Intersperse (Collection<?> collection, String delimiter) { StringBuilder sb = new StringBuilder (); for (Object item : collection) { if (item == null) continue; sb.append (item).append (delimiter); } sb.setLength (sb.length () - delimiter.length ()); return sb.toString (); }
I was looking into this just now, and wasn't happy with the readability of the current solution. If you're writing code informally or on a small project, you can just add another item to the end of your enum called "Length". This way, you only need to type:
var namesCount = (int)MyEnum.Length;
Of course if others are going to use your code - or I'm sure under many other circumstances that didn't apply to me in this case - this solution may be anywhere from ill advised to terrible.
Your query should look like
UPDATE table_name
SET column1=value, column2=value2,...
WHERE some_column=some_value
You can check the below question for help
You need to run the script as source
or the shorthand .
source ./myscript.sh
or
. ./myscript.sh
This will run within the existing shell, ensuring any variables created or modified by the script will be available after the script completes.
Running the script just using the filename will execute the script in a separate subshell.
Try RGBA, e.g.
div { background-color: rgba(255, 255, 255, 0.5); }
As always, this won't work in every single browser ever written.
<md-input placeholder="Item name..." [(ngModel)]="name" (keyup)="filterResults()"></md-input>
<div *ngFor="let item of filteredValue">
{{item.name}}
</div>
filterResults() {
if (!this.name) {
this.filteredValue = [...this.items];
} else {
this.filteredValue = [];
this.filteredValue = this.items.filter((item) => {
return item.name.toUpperCase().indexOf(this.name.toUpperCase()) > -1;
});
}
}
Don't do any modification on 'items' array(list of items from which results are filtered). When searched item 'name' is empty return the complete list of 'items', if not compare the 'name' with every 'name' in the 'items ' array and filter out only the name that is present in 'items' array and store it in the 'filteredValue'.
Sometimes you need to reset ADB. To do that, in Eclipse, go:
Window>> Show View >> Android (Might be found in the "Other" option)>>Devices
in the device Tab, click the down arrow, and choose reset adb.
There are errors in your functions, but the first thing you should do, is to set the body tag correctly:
<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
<button id="on" type="button" value="turn on">turn on</button>
<button id="off" type="button" value="turn off">turn off</button>
</p>
</body>
<script>....</script>
The problem sometimes may be, that you call 'var text' and the other vars only once, when the script starts. If you make changements to the DOM, this static solution may be harmful.
So you could try this (this is more flexible approach and using function parameters, so you can call the functions on any element):
<body>
<p><span id="go" class="georgia">go</span> Italian</p>
<p>
<button type="button" value="turn on"
onclick=turnOn("go")>turn on</button>
<button type="button" value="turn off"
onclick=turnOff()>turn off</button>
</p>
</body>
<script type="text/JavaScript">
var interval;
var turnOn = function(elementId){
interval = setInterval(function(){fontChange(elementId);}, 500);
};
var turnOff = function(){
clearInterval(interval);
};
var fontChange = function(elementId) {
var text = document.getElementById(elementId);
switch(text.className) {
case "georgia":
text.className = "arial";
break;
case "arial":
text.className = "courierNew";
break;
case "courierNew":
text.className = "georgia";
break;
}
};
</script>
You don't need this anymore, so delete it:
var text = document.getElementById("go");
var on = document.getElementById("on");
var off = document.getElementById("off");
This is dynamic code, meaning JS code which runs generic and doesn't adress elements directly. I like this approach more than defining an own function for every div element. ;)
The best solution, where en
is the English locale:
fraction.toLocaleString("en", {style: "percent"})
I got the same problem. Just use File->INVALIDATE CACHES AND RESTART
A Javascript version:
function subsetSum(numbers, target, partial) {_x000D_
var s, n, remaining;_x000D_
_x000D_
partial = partial || [];_x000D_
_x000D_
// sum partial_x000D_
s = partial.reduce(function (a, b) {_x000D_
return a + b;_x000D_
}, 0);_x000D_
_x000D_
// check if the partial sum is equals to target_x000D_
if (s === target) {_x000D_
console.log("%s=%s", partial.join("+"), target)_x000D_
}_x000D_
_x000D_
if (s >= target) {_x000D_
return; // if we reach the number why bother to continue_x000D_
}_x000D_
_x000D_
for (var i = 0; i < numbers.length; i++) {_x000D_
n = numbers[i];_x000D_
remaining = numbers.slice(i + 1);_x000D_
subsetSum(remaining, target, partial.concat([n]));_x000D_
}_x000D_
}_x000D_
_x000D_
subsetSum([3,9,8,4,5,7,10],15);_x000D_
_x000D_
// output:_x000D_
// 3+8+4=15_x000D_
// 3+5+7=15_x000D_
// 8+7=15_x000D_
// 5+10=15
_x000D_
In Java 8 you can use the Collection Interface and do this by calling the removeIf method:
yourList.removeIf((A a) -> a.value == 2);
More information can be found here
Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:
Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}
var out = new java.io.PrintWriter(new java.io.File(path), "UTF-8");
text = new java.lang.String( src || "" );
out.print(text);
out.flush();
out.close();
An alternative
N=3
STRING="one two three four"
arr=($STRING)
echo ${arr[N-1]}
Create a function script that is called earlier than all other functions without passing any arguments to it, like this:
! /bin/bash
function init(){ ORIGOPT= "- $@ -" }
Afer that, you can call init and use the ORIGOPT var as needed,as a plus, I always assign a new var and copy the contents of ORIGOPT in my new functions, that way you can keep yourself assured nobody is going to touch it or change it.
I added spaces and dashes to make it easier to parse it with 'sed -E' also bash will not pass it as reference and make ORIGOPT grow as functions are called with more arguments.
You can use the format
method of the DateTime
class:
$date = new DateTime('2000-01-01');
$result = $date->format('Y-m-d H:i:s');
If format
fails for some reason, it will return FALSE
. In some applications, it might make sense to handle the failing case:
if ($result) {
echo $result;
} else { // format failed
echo "Unknown Time";
}
From the best answer I modified to an adapted version using only datetime objects, this avoids having to do the conversion to seconds and makes the calling code more readable:
def roundTime(dt=None, dateDelta=datetime.timedelta(minutes=1)):
"""Round a datetime object to a multiple of a timedelta
dt : datetime.datetime object, default now.
dateDelta : timedelta object, we round to a multiple of this, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
Stijn Nevens 2014 - Changed to use only datetime objects as variables
"""
roundTo = dateDelta.total_seconds()
if dt == None : dt = datetime.datetime.now()
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
Samples with 1 hour rounding & 15 minutes rounding:
print roundTime(datetime.datetime(2012,12,31,23,44,59),datetime.timedelta(hour=1))
2013-01-01 00:00:00
print roundTime(datetime.datetime(2012,12,31,23,44,49),datetime.timedelta(minutes=15))
2012-12-31 23:30:00
This service is the best in online image map editing I found so far : http://www.image-maps.com/
... but it is in fact a bit weak and I personnaly don't use it anymore. I switched to GIMP and it is indeed pretty good.
The answer from mobius is not wrong but in some cases you must use imagemaps even if it seems a bit old and rusty. For instance, in a newsletter, where you can't use HTML/CSS to do what you want.
I'll take the risk of stating the obvious: You call the function, if it's defined in the base class it's automatically available in the derived class (unless it's private
).
If there is a function with the same signature in the derived class you can disambiguate it by adding the base class's name followed by two colons base_class::foo(...)
. You should note that unlike Java and C#, C++ does not have a keyword for "the base class" (super
or base
) since C++ supports multiple inheritance which may lead to ambiguity.
class left {
public:
void foo();
};
class right {
public:
void foo();
};
class bottom : public left, public right {
public:
void foo()
{
//base::foo();// ambiguous
left::foo();
right::foo();
// and when foo() is not called for 'this':
bottom b;
b.left::foo(); // calls b.foo() from 'left'
b.right::foo(); // call b.foo() from 'right'
}
};
Incidentally, you can't derive directly from the same class twice since there will be no way to refer to one of the base classes over the other.
class bottom : public left, public left { // Illegal
};
It can also be done with isinstance
as per Alex Hall's answer :
>>> NoneType = type(None)
>>> x = None
>>> type(x) == NoneType
True
>>> isinstance(x, NoneType)
True
isinstance
is also intuitive but there is the complication that it requires the line
NoneType = type(None)
which isn't needed for types like int
and float
.
I've taken elindeblom's solution and modified it - the use of strings (even if cast to dates) makes me nervous for the different formats of dates used around the world. This avoids that issue.
While not requested, I've also included time so the week ends 1 second before midnight:
DECLARE @WeekNum INT = 12,
@YearNum INT = 2014 ;
SELECT DATEADD(wk,
DATEDIFF(wk, 6,
CAST(RTRIM(@YearNum * 10000 + 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum - 1 ), 6) AS [start_of_week],
DATEADD(second, -1,
DATEADD(day,
DATEDIFF(day, 0,
DATEADD(wk,
DATEDIFF(wk, 5,
CAST(RTRIM(@YearNum * 10000
+ 1 * 100 + 1) AS DATETIME))
+ ( @WeekNum + -1 ), 5)) + 1, 0)) AS [end_of_week] ;
Yes, I know I'm still casting but from a number. It "feels" safer to me.
This results in:
start_of_week end_of_week
----------------------- -----------------------
2014-03-16 00:00:00.000 2014-03-22 23:59:59.000
In my case, this has been resolved by going to control panel > java > security > then add url in the exception site list. Then apply. Test again the site and it should now allow you to run the local java.
Working fiddle:
$.ajax({
url: 'https://api.flightstats.com/flex/schedules/rest/v1/jsonp/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59',
dataType: 'JSONP',
jsonpCallback: 'callback',
type: 'GET',
success: function (data) {
console.log(data);
}
});
I had to manually set the callback to callback
, since that's all the remote service seems to support. I also changed the url to specify that I wanted jsonp.
I know this is an old thread but for the new and the old who visit this page, there is a website called gitignore.io which can generate these files. Search "visualstudio" upon landing on the website and it will generate these files for you, also you can have multiple languages/ides ignore files concatenated into the one document.
Beautiful.
In your image you've putting the padding outside the child. This is not the case. Padding adds to the width of an element, so if you add padding and give it a width of 100% it will have a width of 100% + padding. In order to what you are wanting you just need to either add padding to the parent div, or add a margin to the inner div. Because divs are block-level elements they will automatically expand to the width of their parent.
You should seriously consider dhiller's answer:
new ArrayList(set)
(or a new LinkedList(set)
, whatever).I think that the solution you posted with the NoDuplicatesList
has some issues, mostly with the contains()
method, plus your class does not handle checking for duplicates in the Collection passed to your addAll()
method.
The content is put after the HTTP headers. The format of an HTTP POST is to have the HTTP headers, followed by a blank line, followed by the request body. The POST variables are stored as key-value pairs in the body.
You can see this in the raw content of an HTTP Post, shown below:
POST /path/script.cgi HTTP/1.0
From: [email protected]
User-Agent: HTTPTool/1.0
Content-Type: application/x-www-form-urlencoded
Content-Length: 32
home=Cosby&favorite+flavor=flies
You can see this using a tool like Fiddler, which you can use to watch the raw HTTP request and response payloads being sent across the wire.
It's little too late but this really works for me.
react-native run-android
.react-native start
.First command will build apk
for android and deploy it on your device if its connected. When you open the App it will show red screen with error. Then run second command which will run packager and build app bundle for you.
None of these answers worked for me, when all I had was a list of directories. Then I stumbled upon the solution! You have to add -r
to --files-from
because -a
will not be recursive in this scenario (who knew?!).
rsync -aruRP --files-from=directory.list . ../new/location
Had the same problem.
adding this to my dependency didn't solve
classpath 'com.google.gms:google-services:3.0.0'
Adding this solved for me
classpath 'com.google.gms:google-services:+'
to the root build.gradle.
With this command you will see all changes in the repository path/to/repo
that were committed in revision <revision>
:
svn diff -c <revision> path/to/repo
The -c
indicates that you would like to look at a changeset, but there are many other ways you can look at diffs and changesets. For example, if you would like to know which files were changed (but not how), you can issue
svn log -v -r <revision>
Or, if you would like to show at the changes between two revisions (and not just for one commit):
svn diff -r <revA>:<revB> path/to/repo
A more complete, albeit more verbose, way of doing this would be to use the Character.codePointAt method. This will handle 'high surrogate' characters, that cannot be represented by a single integer within the range that a char
can represent.
In the example you've given this is not strictly necessary - if the (Unicode) character can fit inside a single (Java) char
(such as the registered
local variable) then it must fall within the \u0000
to \uffff
range, and you won't need to worry about surrogate pairs. But if you're looking at potentially higher code points, from within a String/char array, then calling this method is wise in order to cover the edge cases.
For example, instead of
String input = ...;
char fifthChar = input.charAt(4);
int codePoint = (int)fifthChar;
use
String input = ...;
int codePoint = Character.codePointAt(input, 4);
Not only is this slightly less code in this instance, but it will handle detection of surrogate pairs for you.
if (testNum == 0);
else if (testNum % 2 == 0);
else if ((testNum % 2) != 0 );
docker-compose -f [COMPOSE_FILE_NAME].yml restart [SERVICE_NAME]
Use Case #1: If the COMPOSE_FILE_NAME is docker-compose.yml
and service is worker
docker-compose restart worker
Use Case #2: If the file name is sample.yml
and service is worker
docker-compose -f sample.yml restart worker
By default docker-compose looks for the docker-compose.yml
if we run the docker-compose
command, else we have flag to give specific file name with -f [FILE_NAME].yml
The hard truth is: the only good debugger for IE is Visual Studio.
If you don't have money for the real deal, download free Visual Web Developer 2008 Express EditionVisual Web Developer 2010 Express Edition. While the former allows you to attach debugger to already running IE, the latter doesn't (at least previous versions I used didn't allow that). If this is still the case, the trick is to create a simple project with one empty web page, "run" it (it starts the browser), now navigate to whatever page you want to debug, and start debugging.
Microsoft gives away full Visual Studio on different events, usually with license restrictions, but they allow tinkering at home. Check their schedule and the list of freebies.
Another hint: try to debug your web application with other browsers first. I had a great success with Opera. Somehow Opera's emulation of IE and its bugs was pretty close, but the debugger is much better.
If you want to use a the my_helper_method
inside a model, you can write:
ApplicationController.helpers.my_helper_method
You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:
// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")
Here is a sample extension method for the code above:
// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
var url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imagePath));
imgBuilder.MergeAttribute("alt", alt);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
var anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
set <ORACLE_HOME> path variable
example
path ORACLE_HOME
value is C:\oraclexe\app\oracle\product\10.2.0\server
<html>
<head>
<style type="text/css">
#mydiv {
position:absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width:100px;
height:200px;
margin:auto;
border: 1px solid #ccc;
background-color: #f3f3f3;
}
</style>
</head>
<body>
<div id="mydiv">Maitrey</div>
</body>
</html>
Add the "extern" keyword to the function definitions in point.h
The fundamental problem can often be simply solved by changing an =
to IN
, in cases where you've got a one-to-many relationship. For example, if you wanted to update or delete a bunch of accounts for a given customer:
WITH accounts_to_delete AS
(
SELECT account_id
FROM accounts a
INNER JOIN customers c
ON a.customer_id = c.id
WHERE c.customer_name='Some Customer'
)
-- this fails if "Some Customer" has multiple accounts, but works if there's 1:
DELETE FROM accounts
WHERE accounts.guid =
(
SELECT account_id
FROM accounts_to_delete
);
-- this succeeds with any number of accounts:
DELETE FROM accounts
WHERE accounts.guid IN
(
SELECT account_id
FROM accounts_to_delete
);
Have you tried str = str.replace(/\W|_/g,'');
it will return a string without any character and you can specify if any especial character after the pipe bar |
to catch them as well.
var str = "1324567890abc§$)% John Doe #$@'.replace(/\W|_/g, '');
it will return str = 1324567890abcJohnDoe
or look for digits and letters and replace them for empty string (""):
var str = "1324567890abc§$)% John Doe #$@".replace(/\w|_/g, '');
it will return str = '§$)% #$@';
Take a look at cat /proc/stat
grep 'cpu ' /proc/stat | awk '{usage=($2+$4)*100/($2+$4+$5)} END {print usage "%"}'
EDIT please read comments before copy-paste this or using this for any serious work. This was not tested nor used, it's an idea for people who do not want to install a utility or for something that works in any distribution. Some people think you can "apt-get install" anything.
NOTE: this is not the current CPU usage, but the overall CPU usage in all the cores since the system bootup. This could be very different from the current CPU usage. To get the current value top (or similar tool) must be used.
Current CPU usage can be potentially calculated with:
awk '{u=$2+$4; t=$2+$4+$5; if (NR==1){u1=u; t1=t;} else print ($2+$4-u1) * 100 / (t-t1) "%"; }' \
<(grep 'cpu ' /proc/stat) <(sleep 1;grep 'cpu ' /proc/stat)
I think it's important to point out and to know that if the destination slice (the slice you append to) has sufficient capacity, the append will happen "in-place", by reslicing the destination (reslicing to increase its length in order to be able to accommodate the appendable elements).
This means that if the destination was created by slicing a bigger array or slice which has additional elements beyond the length of the resulting slice, they may get overwritten.
To demonstrate, see this example:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground):
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 10
x: [1 2 3 4]
a: [1 2 3 4 0 0 0 0 0 0]
We created a "backing" array a
with length 10
. Then we create the x
destination slice by slicing this a
array, y
slice is created using the composite literal []int{3, 4}
. Now when we append y
to x
, the result is the expected [1 2 3 4]
, but what may be surprising is that the backing array a
also changed, because capacity of x
is 10
which is sufficient to append y
to it, so x
is resliced which will also use the same a
backing array, and append()
will copy elements of y
into there.
If you want to avoid this, you may use a full slice expression which has the form
a[low : high : max]
which constructs a slice and also controls the resulting slice's capacity by setting it to max - low
.
See the modified example (the only difference is that we create x
like this: x = a[:2:2]
:
a := [10]int{1, 2}
fmt.Printf("a: %v\n", a)
x, y := a[:2:2], []int{3, 4}
fmt.Printf("x: %v, y: %v\n", x, y)
fmt.Printf("cap(x): %v\n", cap(x))
x = append(x, y...)
fmt.Printf("x: %v\n", x)
fmt.Printf("a: %v\n", a)
Output (try it on the Go Playground)
a: [1 2 0 0 0 0 0 0 0 0]
x: [1 2], y: [3 4]
cap(x): 2
x: [1 2 3 4]
a: [1 2 0 0 0 0 0 0 0 0]
As you can see, we get the same x
result but the backing array a
did not change, because capacity of x
was "only" 2
(thanks to the full slice expression a[:2:2]
). So to do the append, a new backing array is allocated that can store the elements of both x
and y
, which is distinct from a
.
With Java 7, you can use Path
, Paths
, and Files
:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
On MySQL 5.1.51, both queries have identical execution plans:
mysql> explain select * from table1 a inner join table2 b on a.pid = b.pid;
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |
| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
2 rows in set (0.02 sec)
mysql> explain select * from table1 a, table2 b where a.pid = b.pid;
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
| 1 | SIMPLE | b | ALL | PRIMARY | NULL | NULL | NULL | 986 | |
| 1 | SIMPLE | a | ref | pid | pid | 4 | schema.b.pid | 70 | |
+----+-------------+-------+------+---------------+------+---------+--------------+------+-------+
2 rows in set (0.00 sec)
table1
has 166208 rows; table2
has about 1000 rows.
This is a very simple case; it doesn't by any means prove that the query optimizer wouldn't get confused and generate different plans in a more complicated case.
In addition to excellent Craig Ringer's post and depesz's blog post, if you would like to speed up your inserts through ODBC (psqlodbc) interface by using prepared-statement inserts inside a transaction, there are a few extra things you need to do to make it work fast:
Protocol=-1
in the connection string. By default psqlodbc uses "Statement" level, which creates a SAVEPOINT for each statement rather than an entire transaction, making inserts slower.UseServerSidePrepare=1
in the connection string. Without this option the client sends the entire insert statement along with each row being inserted.SQLSetConnectAttr(conn, SQL_ATTR_AUTOCOMMIT, reinterpret_cast<SQLPOINTER>(SQL_AUTOCOMMIT_OFF), 0);
SQLEndTran(SQL_HANDLE_DBC, conn, SQL_COMMIT);
. There is no need to explicitly open a transaction.Unfortunately, psqlodbc "implements" SQLBulkOperations
by issuing a series of unprepared insert statements, so that to achieve the fastest insert one needs to code up the above steps manually.
Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.
UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE
measure the square distance from one point to the other:
((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)) < d*d
where d is the distance, (x1,y1) are the coordinates of the 'base point' and (x2,y2) the coordinates of the point you want to check.
or if you prefer:
(Math.Pow(x1-x2,2)+Math.Pow(y1-y2,2)) < (d*d);
Noticed that the preferred one does not call Pow at all for speed reasons, and the second one, probably slower, as well does not call Math.Sqrt
, always for performance reasons. Maybe such optimization are premature in your case, but they are useful if that code has to be executed a lot of times.
Of course you are talking in meters and I supposed point coordinates are expressed in meters too.
Add try this code .. Its working grt.......
<body>_x000D_
<?php_x000D_
if (isset($_POST['nav'])) {_x000D_
header("Location: $_POST[nav]");_x000D_
}_x000D_
?>_x000D_
<form id="page-changer" action="" method="post">_x000D_
<select name="nav">_x000D_
<option value="">Go to page...</option>_x000D_
<option value="http://css-tricks.com/">CSS-Tricks</option>_x000D_
<option value="http://digwp.com/">Digging Into WordPress</option>_x000D_
<option value="http://quotesondesign.com/">Quotes on Design</option>_x000D_
</select>_x000D_
<input type="submit" value="Go" id="submit" />_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
<html>_x000D_
<head>_x000D_
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>_x000D_
<script>_x000D_
$(function() {_x000D_
_x000D_
$("#submit").hide();_x000D_
_x000D_
$("#page-changer select").change(function() {_x000D_
window.location = $("#page-changer select option:selected").val();_x000D_
})_x000D_
_x000D_
});_x000D_
</script>_x000D_
</head>
_x000D_
SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;
There is another way without Promise.all() to do it in parallel:
First, we have 2 functions to print numbers:
function printNumber1() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log("Number1 is done");
resolve(10);
},1000);
});
}
function printNumber2() {
return new Promise((resolve,reject) => {
setTimeout(() => {
console.log("Number2 is done");
resolve(20);
},500);
});
}
This is sequential:
async function oneByOne() {
const number1 = await printNumber1();
const number2 = await printNumber2();
}
//Output: Number1 is done, Number2 is done
This is parallel:
async function inParallel() {
const promise1 = printNumber1();
const promise2 = printNumber2();
const number1 = await promise1;
const number2 = await promise2;
}
//Output: Number2 is done, Number1 is done
A simple and great solution is shepherd
Expanding @Martin Thoma's answer
def one_hot_encode(y):
"""Convert an iterable of indices to one-hot encoded labels."""
y = y.flatten() # Sometimes not flattened vector is passed e.g (118,1) in these cases
# the function ends up creating a tensor e.g. (118, 2, 1). flatten removes this issue
nb_classes = len(np.unique(y)) # get the number of unique classes
standardised_labels = dict(zip(np.unique(y), np.arange(nb_classes))) # get the class labels as a dictionary
# which then is standardised. E.g imagine class labels are (4,7,9) if a vector of y containing 4,7 and 9 is
# directly passed then np.eye(nb_classes)[4] or 7,9 throws an out of index error.
# standardised labels fixes this issue by returning a dictionary;
# standardised_labels = {4:0, 7:1, 9:2}. The values of the dictionary are mapped to keys in y array.
# standardised_labels also removes the error that is raised if the labels are floats. E.g. 1.0; element
# cannot be called by an integer index e.g y[1.0] - throws an index error.
targets = np.vectorize(standardised_labels.get)(y) # map the dictionary values to array.
return np.eye(nb_classes)[targets]
Yes, I just hit my first 'PHP Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM'
. My bad, I had a $instance::method()
that should have been $instance->method()
. Silly me.
The odd thing is that this still works just fine on my local machine (running PHP 5.3.8) - nothing, not even a warning with error_reporting = E_ALL - but not at all on the test server, there it just explodes with a syntax error and a white screen in the browser. Since PHP logging was turned off at the test machine, and the hosting company was too busy to turn it on, it was not too obvious.
So, word of warning: apparently, some PHP installations will let you use a $instance::method(), while others don't.
If anybody can expand on why that is, please do.
You can also do something like this...
<input @input="myHandler('foo', 'bar', ...arguments)">
Evan You himself recommended this technique in one post on Vue forum. In general some events may emit more than one argument. Also as documentation states internal variable $event is meant for passing original DOM event.
I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs
tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.
https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
}
Bit of a hack but if you would like to keep the directory, the following can be used.
import os
import shutil
shutil.rmtree('/home/me/test')
os.mkdir('/home/me/test')
Why would you bother? Load your CSV into Excel like this:
$csv = Join-Path $env:TEMP "process.csv"
$xls = Join-Path $env:TEMP "process.xlsx"
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.OpenText($csv)
$wb.SaveAs($xls, 51)
You just need to make sure that the CSV export uses the delimiter defined in your regional settings. Override with -Delimiter
if need be.
Edit: A more general solution that should preserve the values from the CSV as plain text. Code for iterating over the CSV columns taken from here.
$csv = Join-Path $env:TEMP "input.csv"
$xls = Join-Path $env:TEMP "output.xlsx"
$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true
$wb = $xl.Workbooks.Add()
$ws = $wb.Sheets.Item(1)
$ws.Cells.NumberFormat = "@"
$i = 1
Import-Csv $csv | ForEach-Object {
$j = 1
foreach ($prop in $_.PSObject.Properties) {
if ($i -eq 1) {
$ws.Cells.Item($i, $j++).Value = $prop.Name
} else {
$ws.Cells.Item($i, $j++).Value = $prop.Value
}
}
$i++
}
$wb.SaveAs($xls, 51)
$wb.Close()
$xl.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($xl)
Obviously this second approach won't perform too well, because it's processing each cell individually.
From the documentation on expandtab
:
To insert a real tab when
expandtab
is on, useCTRL-V
<Tab>
. See also:retab
and ins-expandtab.
This option is reset when thepaste
option is set and restored when thepaste
option is reset.
So if you have a mapping for toggling the paste
option, e.g.
set pastetoggle=<F2>
you could also do <F2>Tab<F2>
.
Let me expand a bit on a VonC's very comprehensive answer:
First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.
Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".
Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.
HTH
This code might work for non-.NET Core MVC controllers:
this.HttpContext.Response.StatusCode = 418; // I'm a teapot
return Json(new { status = "mer" }, JsonRequestBehavior.AllowGet);
When you use
@GeneratedValue(strategy=GenerationType.AUTO)
or
@GeneratedValue
which is short hand way of the above, Hibernate starts to decide the best
generation strategy for you, in this case it has selected
GenerationType.SEQUENCE
as the strategy and that is why it is looking for
schemaName.hibernate_sequence
which is a table, for sequence based id generation.
When you use GenerationType.SEQUENCE
as the strategy you need to provide the @TableGenerator
as follows.
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator")
@TableGenerator(name = "user_table_generator",
table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE")
@Column(name = "USER_ID")
private long userId;
When you set the strategy it the to
@GeneratedValue(strategy = GenerationType.IDENTITY)
.
original issue get resolved because then Hibernate stop looking for sequence table.
private and protected access modifiers are one and same only that protected members of the base class can be accessed outside the scope of the base class in the child(derived)class. It also applies the same to inheritance . But with the private modifier the members of the base class can only be accessed in the scope or code of the base class and its friend functions only''''
100% robust approach.
In my case, I didn't have access to the XML layout source file, since I get Checkbox from a 3-rd party MaterialDialog lib. So I have to solve this programmatically.
res/color/checkbox_tinit_dark_theme.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/white"
android:state_checked="false"/>
<item android:color="@color/positiveButtonBg"
android:state_checked="true"/>
</selector>
Then apply it to the checkbox:
ColorStateList darkStateList = ContextCompat.getColorStateList(getContext(), R.color.checkbox_tint_dark_theme);
CompoundButtonCompat.setButtonTintList(checkbox, darkStateList);
P.S. In addition if someone is interested, here is how you can get your checkbox from MaterialDialog dialog (if you set it with .checkBoxPromptRes(...)
):
CheckBox checkbox = (CheckBox) dialog.getView().findViewById(R.id.md_promptCheckbox);
Hope this helps.
Ant is already installed on some older versions of Mac OS X, so you should run ant -version
to test if it is installed before attempting to install it.
If it is not already installed, then your best bet is to install Homebrew (brew install ant
) or MacPorts (sudo port install apache-ant
), and use those tools to install Apache Ant.
Alternatively, though I would highly advise using Homebrew or MacPorts instead, you can install Apache Ant manually. To do so, you would need to:
The commands that you would need, assuming apache-ant-1.8.1-bin.tar.gz
(replace 1.8.1 with the actual version) were still in your Downloads directory, would be the following (explanatory comments included):
cd ~/Downloads # Let's get into your downloads folder.
tar -xvzf apache-ant-1.8.1-bin.tar.gz # Extract the folder
sudo mkdir -p /usr/local # Ensure that /usr/local exists
sudo cp -rf apache-ant-1.8.1-bin /usr/local/apache-ant # Copy it into /usr/local
# Add the new version of Ant to current terminal session
export PATH=/usr/local/apache-ant/bin:"$PATH"
# Add the new version of Ant to future terminal sessions
echo 'export PATH=/usr/local/apache-ant/bin:"$PATH"' >> ~/.profile
# Verify new version of ant
ant -version
I'd suggest doing something similar to:
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = parent.getElementsByClassName('sub');
if (sub[0].style.display == 'inline'){
sub[0].style.display = 'none';
}
else {
sub[0].style.display = 'inline';
}
}
}
document.getElementById('cat').onclick = function(){
show_sub(this.id);
};????
Though the above relies on the use of a class
rather than a name
attribute equal to sub
.
As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:
Uncaught TypeError: Object # has no method 'getElementsByName'.
One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName()
, albeit crudely:
function eBCN(elem,classN){
if (!elem || !classN){
return false;
}
else {
var children = elem.childNodes;
for (var i=0,len=children.length;i<len;i++){
if (children[i].nodeType == 1
&&
children[i].className == classN){
var sub = children[i];
}
}
return sub;
}
}
function show_sub(cat) {
if (!cat) {
return false;
}
else if (document.getElementById(cat)) {
var parent = document.getElementById(cat),
sub = eBCN(parent,'sub');
if (sub.style.display == 'inline'){
sub.style.display = 'none';
}
else {
sub.style.display = 'inline';
}
}
}
var D = document,
listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
listElems[i].onclick = function(){
show_sub(this.id);
};
}?
declare
x number;
begin
x := myfunc(myargs);
end;
Alternatively:
select myfunc(myargs) from dual;
Limit the length of characters in a regular expression? ^[a-z]{6,15}$'
Limit length of characters or Numbers in a regular expression? ^[a-z | 0-9]{6,15}$'
You are not supposed to use floats in React Native. React Native leverages the flexbox to handle all that stuff.
In your case, you will probably want the container to have an attribute
justifyContent: 'flex-end'
And about the text taking the whole space, again, you need to take a look at your container.
Here is a link to really great guide on flexbox: A Complete Guide to Flexbox
No, only native iOS applications support push notifications.
UPDATE:
Mac OS X 10.9 & Safari 7 websites can now also send push notifications, but this still does not apply to iOS.
Read the Notification Programming Guide for Websites. Also check out WWDC 2013 Session 614.
If you simply want to restore the remote master, then
git reset --hard origin/master
WARNING: All local changes will be lost, see https://stackoverflow.com/a/8476004/11769765.
I know it has been long since the original question was posted, but for future reference: check this project, https://github.com/gkorland/Eclipse-Fonts I have used it, and it's very simple and efficient.
The move
instruction copies a value from one register to another. The li
instruction loads a specific numeric value into that register.
For the specific case of zero, you can use either the constant zero or the zero register to get that:
move $s0, $zero
li $s0, 0
There's no register that generates a value other than zero, though, so you'd have to use li
if you wanted some other number, like:
li $s0, 12345678
You can use the desc
command.
desc MY_TABLE
This will give you the column names, whether null is valid, and the datatype (and length if applicable)
You should always return the same type on all case condition:
In the first one you have an character and on the else you have an int.
You can use:
Select convert(varchar(11),isnull(totalamount,0))
or if you want with your solution:
Case when total_amount = 0 then '0'
else convert(varchar(11),isnull(total_amount, 0))
end as total_amount
Ad hoc queries are those that are not already defined that are not needed on a regular basis, so they're not included in the typical set of reports or queries
You can use map() function:
a = list(map(lambda x: x - 13, a))
There's no difference, in fact map
is implemented in C as rb_ary_collect
and enum_collect
(eg. there is a difference between map
on an array and on any other enum, but no difference between map
and collect
).
Why do both map
and collect
exist in Ruby? The map
function has many naming conventions in different languages. Wikipedia provides an overview:
The map function originated in functional programming languages but is today supported (or may be defined) in many procedural, object oriented, and multi-paradigm languages as well: In C++'s Standard Template Library, it is called
transform
, in C# (3.0)'s LINQ library, it is provided as an extension method calledSelect
. Map is also a frequently used operation in high level languages such as Perl, Python and Ruby; the operation is calledmap
in all three of these languages. Acollect
alias for map is also provided in Ruby (from Smalltalk) [emphasis mine]. Common Lisp provides a family of map-like functions; the one corresponding to the behavior described here is calledmapcar
(-car indicating access using the CAR operation).
Ruby provides an alias for programmers from the Smalltalk world to feel more at home.
Why is there a different implementation for arrays and enums? An enum is a generalized iteration structure, which means that there is no way in which Ruby can predict what the next element can be (you can define infinite enums, see Prime for an example). Therefore it must call a function to get each successive element (typically this will be the each
method).
Arrays are the most common collection so it is reasonable to optimize their performance. Since Ruby knows a lot about how arrays work it doesn't have to call each
but can only use simple pointer manipulation which is significantly faster.
Similar optimizations exist for a number of Array methods like zip
or count
.
on tomcat v.7 (vanilla installation)
in your conf/server.xml add the following bit towards the end of the file, just before the </Host>
closing tag:
<Context path="" docBase="app_name">
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
Note that docBase attribute. It's the important bit. You either make sure you've deployed app_name before you change your root web app, or just copy your unpacked webapp (app_name) into your tomcat's webapps folder. Startup, visit root, see your app_name there!
You could just add one needed external jar file to the project. Go to your project-->java build path-->libraries, add external JARS.Then add your downloaded file from the formal website. My default name is commons-codec-1.10.jar
If you add:
jquery.form.min.js
You can simply do this:
<script>
$('#myform').ajaxForm(function(response) {
alert(response);
});
// this will register the AJAX for <form id="myform" action="some_url">
// and when you submit the form using <button type="submit"> or $('myform').submit(), then it will send your request and alert response
</script>
You could use simple $('FORM').serialize() as suggested in post above, but that will not work for FILE INPUTS... ajaxForm() will.
Use SSIS to extract and process the information. That way you will have the processing of the XML files separated from SQL Server. You can also do the SSIS transformations on a separate server if needed. Store the phone numbers in a standard format using VARCHAR. NVARCHAR would be unnecessary since we are talking about numbers and maybe a couple of other chars, like '+', ' ', '(', ')' and '-'.
A lot of great answers here. Below is a sample of the stored procedure that I wrote to accomplish this task for a Web App that I am developing:
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON
-- Create Temporary Table
SELECT * INTO #tempTable FROM <YourTable> WHERE Id = Id
--To trigger the auto increment
UPDATE #tempTable SET Id = NULL
--Update new data row in #tempTable here!
--Insert duplicate row with modified data back into your table
INSERT INTO <YourTable> SELECT * FROM #tempTable
-- Drop Temporary Table
DROP TABLE #tempTable
I stumbled across this question while hitting this road block myself. I ended up writing a piece of code real quick to handle this ReDim Preserve
on a new sized array (first or last dimension). Maybe it will help others who face the same issue.
So for the usage, lets say you have your array originally set as MyArray(3,5)
, and you want to make the dimensions (first too!) larger, lets just say to MyArray(10,20)
. You would be used to doing something like this right?
ReDim Preserve MyArray(10,20) '<-- Returns Error
But unfortunately that returns an error because you tried to change the size of the first dimension. So with my function, you would just do something like this instead:
MyArray = ReDimPreserve(MyArray,10,20)
Now the array is larger, and the data is preserved. Your ReDim Preserve
for a Multi-Dimension array is complete. :)
And last but not least, the miraculous function: ReDimPreserve()
'redim preserve both dimensions for a multidimension array *ONLY
Public Function ReDimPreserve(aArrayToPreserve,nNewFirstUBound,nNewLastUBound)
ReDimPreserve = False
'check if its in array first
If IsArray(aArrayToPreserve) Then
'create new array
ReDim aPreservedArray(nNewFirstUBound,nNewLastUBound)
'get old lBound/uBound
nOldFirstUBound = uBound(aArrayToPreserve,1)
nOldLastUBound = uBound(aArrayToPreserve,2)
'loop through first
For nFirst = lBound(aArrayToPreserve,1) to nNewFirstUBound
For nLast = lBound(aArrayToPreserve,2) to nNewLastUBound
'if its in range, then append to new array the same way
If nOldFirstUBound >= nFirst And nOldLastUBound >= nLast Then
aPreservedArray(nFirst,nLast) = aArrayToPreserve(nFirst,nLast)
End If
Next
Next
'return the array redimmed
If IsArray(aPreservedArray) Then ReDimPreserve = aPreservedArray
End If
End Function
I wrote this in like 20 minutes, so there's no guarantees. But if you would like to use or extend it, feel free. I would've thought that someone would've had some code like this up here already, well apparently not. So here ya go fellow gearheads.
I don't think your problem is with the BouncyCastle keystore; I think the problem is with a broken javax.net.ssl package in Android. The BouncyCastle keystore is a supreme annoyance because Android changed a default Java behavior without documenting it anywhere -- and removed the default provider -- but it does work.
Note that for SSL authentication you may require 2 keystores. The "TrustManager" keystore, which contains the CA certs, and the "KeyManager" keystore, which contains your client-site public/private keys. (The documentation is somewhat vague on what needs to be in the KeyManager keystore.) In theory, you shouldn't need the TrustManager keystore if all of your certficates are signed by "well-known" Certifcate Authorities, e.g., Verisign, Thawte, and so on. Let me know how that works for you. Your server will also require the CA for whatever was used to sign your client.
I could not create an SSL connection using javax.net.ssl at all. I disabled the client SSL authentication on the server side, and I still could not create the connection. Since my end goal was an HTTPS GET, I punted and tried using the Apache HTTP Client that's bundled with Android. That sort-of worked. I could make the HTTPS conection, but I still could not use SSL auth. If I enabled the client SSL authentication on my server, the connection would fail. I haven't checked the Apache HTTP Client code, but I suspect they are using their own SSL implementation, and don't use javax.net.ssl.
This solution work for me...
just type
export PATH=$JAVA_HOME/jre/bin:$PATH
in the terminal
then run mvn -version
it will show the same error but with a log like this
which: no javac in (/jre/bin:/sbin:/bin:/usr/sbin:/usr/bin:/opt/puppetlabs/bin)
Warning: JAVA_HOME environment variable is not set.
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T22:59:23+05:30)
Maven home: /opt/apache-maven-3.2.5
Java version: 1.8.0_171, vendor: Oracle Corporation
Java home: /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre
Default locale: en_US, platform encoding: UTF-8
OS name: "linux", version: "3.10.0-693.el7.x86_64", arch: "amd64", family: "unix"
now copy the Java home
path i.e. /usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre
in my case.
now type,
export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.171-8.b10.el7_5.x86_64/jre
and the error gets resolve. NOTE: paste your own path which is shown by your machine in mvn log at export JAVA_HOME.
You could use the same mechanism the XAML reading system uses: Type converters
var converter = new System.Windows.Media.BrushConverter();
var brush = (Brush)converter.ConvertFromString("#FFFFFF90");
Fill = brush;
Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.
string test = "key1=value1&key2=value2&key3=value3";
var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
.Cast<Match>()
.ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);
var count = keyValues.Count - 1;
$(".field-group_name").each(function() {
console.log($(this).text());
});
JS:
function createDateObj(date) {
var day = date.getDate(); // yields
var month = date.getMonth(); // yields month
var year = date.getFullYear(); // yields year
var hour = date.getHours(); // yields hours
var minute = date.getMinutes(); // yields minutes
var second = date.getSeconds(); // yields seconds
var millisec = date.getMilliseconds();
var jsDate = Date.UTC(year, month, day, hour, minute, second, millisec);
return jsDate;
}
JS:
var oRequirementEval = new Object();
var date = new Date($("#dueDate").val());
CS:
requirementEvaluations.DeadLine = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)
.AddMilliseconds(Convert.ToDouble( arrayUpdateRequirementEvaluationData["DeadLine"]))
.ToLocalTime();
ALTER TABLE t_name modify c_name INT(10) AUTO_INCREMENT PRIMARY KEY;
Here a solution that will work with Solaris and AIX as well.
Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.
You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.
echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.
When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:
echo "$(TZ=GMT+30 date +%Y-%m-%d)
$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
Like this:
<c:forEach var="entry" items="${myMap}">
Key: <c:out value="${entry.key}"/>
Value: <c:out value="${entry.value}"/>
</c:forEach>
Yes, a UIGestureRecognizer can be added to a UIImageView. As stated in the other answer, it is very important to remember to enable user interaction on the image view by setting its userInteractionEnabled
property to YES
. UIImageView inherits from UIView, whose user interaction property is set to YES
by default, however, UIImageView's user interaction property is set to NO
by default.
From the UIImageView docs:
New image view objects are configured to disregard user events by default. If you want to handle events in a custom subclass of UIImageView, you must explicitly change the value of the userInteractionEnabled property to YES after initializing the object.
Anyway, on the the bulk of the answer. Here's an example of how to create a UIImageView
with a UIPinchGestureRecognizer
, a UIRotationGestureRecognizer
, and a UIPanGestureRecognizer
.
First, in viewDidLoad
, or another method of your choice, create an image view, give it an image, a frame, and enable its user interaction. Then create the three gestures as follows. Be sure to utilize their delegate property (most likely set to self). This will be required to use multiple gestures at the same time.
- (void)viewDidLoad
{
[super viewDidLoad];
// set up the image view
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"someImage"]];
[imageView setBounds:CGRectMake(0.0, 0.0, 120.0, 120.0)];
[imageView setCenter:self.view.center];
[imageView setUserInteractionEnabled:YES]; // <--- This is very important
// create and configure the pinch gesture
UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
[pinchGestureRecognizer setDelegate:self];
[imageView addGestureRecognizer:pinchGestureRecognizer];
// create and configure the rotation gesture
UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureDetected:)];
[rotationGestureRecognizer setDelegate:self];
[imageView addGestureRecognizer:rotationGestureRecognizer];
// creat and configure the pan gesture
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
[panGestureRecognizer setDelegate:self];
[imageView addGestureRecognizer:panGestureRecognizer];
[self.view addSubview:imageView]; // add the image view as a subview of the view controllers view
}
Here are the three methods that will be called when the gestures on your view are detected. Inside them, we will check the current state of the gesture, and if it is in either the began or changed UIGestureRecognizerState
we will read the gesture's scale/rotation/translation property, apply that data to an affine transform, apply the affine transform to the image view, and then reset the gestures scale/rotation/translation.
- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
UIGestureRecognizerState state = [recognizer state];
if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
{
CGFloat scale = [recognizer scale];
[recognizer.view setTransform:CGAffineTransformScale(recognizer.view.transform, scale, scale)];
[recognizer setScale:1.0];
}
}
- (void)rotationGestureDetected:(UIRotationGestureRecognizer *)recognizer
{
UIGestureRecognizerState state = [recognizer state];
if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
{
CGFloat rotation = [recognizer rotation];
[recognizer.view setTransform:CGAffineTransformRotate(recognizer.view.transform, rotation)];
[recognizer setRotation:0];
}
}
- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer
{
UIGestureRecognizerState state = [recognizer state];
if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
{
CGPoint translation = [recognizer translationInView:recognizer.view];
[recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
[recognizer setTranslation:CGPointZero inView:recognizer.view];
}
}
Finally and very importantly, you'll need to utilize the UIGestureRecognizerDelegate method gestureRecognizer: shouldRecognizeSimultaneouslyWithGestureRecognizer
to allow the gestures to work at the same time. If these three gestures are the only three gestures that have this class assigned as their delegate, then you can simply return YES
as shown below. However, if you have additional gestures that have this class assigned as their delegate, you may need to add logic to this method to determine which gesture is which before allowing them to all work together.
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
return YES;
}
Don't forget to make sure that your class conforms to the UIGestureRecognizerDelegate protocol. To do so, make sure that your interface looks something like this:
@interface MyClass : MySuperClass <UIGestureRecognizerDelegate>
If you prefer to play with the code in a working sample project yourself, the sample project I've created containing this code can be found here.
The message was pretty clear but I didn't get it at first...
I'm working with two Entity Framework DB contexts sysContext
and shardContext
in the same method.
The entity I had modified\updated is from one context but then I tried to save it to the other context like this:
invite.uid = user.uid;
sysContext.Entry(invite).State = EntityState.Modified;
sysContext.SaveChanges(); // Got the exception here
but the correct version should be this:
invite.uid = user.uid;
shardContext.Entry(invite).State = EntityState.Modified;
shardContext.SaveChanges();
After passing the entity to the correct context this error went away.
Sorry but all the answers I see here are either hacky or fail if you sneeze a little harder.
If you use a table you can (if you wish) add a space between the divs, set borders, padding...
<table width="100%" cellspacing="0">
<tr>
<td style="width:50%;">A</td>
<td style="width:50%;">B</td>
</tr>
</table>
Check a more complete example here: http://jsfiddle.net/qPduw/5/
After trying a few things, and coming across PyMySQL Github, this worked:
sudo pip install PyMySQL
And to import use:
import pymysql
The code seems working to me. I think the same with @Iothar.
Check to see if you include the required headers, to compile. If it is compiled, check to see if there is such a file, and everything, names etc, matches, and also check to see that you have a right to read the file.
To make a cross check, check if you can open it with fopen..
FILE *f = fopen("C:/Demo.txt", "r");
if (f)
printf("fopen success\n");
I would do it like this:
Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)
In case you have some more complex formula it will be handy
Parse Error: Adjacent JSX elements must be wrapped in an enclosing tag
This means that you are trying to return multiple sibling JSX elements in an incorrect manner. Remember that you are not writing HTML, but JSX! Your code is transpiled from JSX into JavaScript. For example:
render() {
return (<p>foo bar</p>);
}
will be transpiled into:
render() {
return React.createElement("p", null, "foo bar");
}
Unless you are new to programming in general, you already know that functions/methods (of any language) take any number of parameters but always only return one value. Given that, you can probably see that a problem arises when trying to return multiple sibling components based on how createElement()
works; it only takes parameters for one element and returns that. Hence we cannot return multiple elements from one function call.
So if you've ever wondered why this works...
render() {
return (
<div>
<p>foo</p>
<p>bar</p>
<p>baz</p>
</div>
);
}
but not this...
render() {
return (
<p>foo</p>
<p>bar</p>
<p>baz</p>
);
}
it's because in the first snippet, both <p>
-elements are part of children
of the <div>
-element. When they are part of children
then we can express an unlimited number of sibling elements. Take a look how this would transpile:
render() {
return React.createElement(
"div",
null,
React.createElement("p", null, "foo"),
React.createElement("p", null, "bar"),
React.createElement("p", null, "baz"),
);
}
Depending on which version of React you are running, you do have a few options to address this:
As of React v16.2, React has support for Fragments which is a node-less component that returns its children directly.
Returning the children in an array (see below) has some drawbacks:
- Children in an array must be separated by commas.
- Children in an array must have a key to prevent React’s key warning.
- Strings must be wrapped in quotes.
These are eliminated from the use of fragments. Here's an example of children wrapped in a fragment:
render() {
return (
<>
<ChildA />
<ChildB />
<ChildC />
</>
);
}
which de-sugars into:
render() {
return (
<React.Fragment>
<ChildA />
<ChildB />
<ChildC />
</React.Fragment>
);
}
Note that the first snippet requires Babel v7.0 or above.
As of React v16, React Components can return arrays. This is unlike earlier versions of React where you were forced to wrap all sibling components in a parent component.
In other words, you can now do:
render() {
return [<p key={0}>foo</p>, <p key={1}>bar</p>];
}
this transpiles into:
return [React.createElement("p", {key: 0}, "foo"), React.createElement("p", {key: 1}, "bar")];
Note that the above returns an array. Arrays are valid React Elements since React version 16 and later. For earlier versions of React, arrays are not valid return objects!
Also note that the following is invalid (you must return an array):
render() {
return (<p>foo</p> <p>bar</p>);
}
The other solution involves creating a parent component which wraps the sibling components in its children
. This is by far the most common way to address this issue, and works in all versions of React.
render() {
return (
<div>
<h1>foo</h1>
<h2>bar</h2>
</div>
);
}
Note: Take a look again at the top of this answer for more details and how this transpiles.
I think I found another solution to this question.
Go to Project > Properties > Java Build Path > tab [Order and Export] > Tick Android Version Checkbox Then if your workspace does not build automatically…
Properties again > Build Project
Like this:
>>> s='1\t2\t3\t4\t5'
>>> [x for x in s.split('\t')]
['1', '2', '3', '4', '5']
For a file:
# create test file:
>>> with open('tabs.txt','w') as o:
... s='\n'.join(['\t'.join(map(str,range(i,i+10))) for i in [0,10,20,30]])
... print >>o, s
#read that file:
>>> with open('tabs.txt','r') as f:
... LoL=[x.strip().split('\t') for x in f]
...
>>> LoL
[['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
['10', '11', '12', '13', '14', '15', '16', '17', '18', '19'],
['20', '21', '22', '23', '24', '25', '26', '27', '28', '29'],
['30', '31', '32', '33', '34', '35', '36', '37', '38', '39']]
>>> LoL[2][3]
23
If you want the input transposed:
>>> with open('tabs.txt','r') as f:
... LoT=zip(*(line.strip().split('\t') for line in f))
...
>>> LoT[2][3]
'32'
Or (better still) use the csv module in the default distribution...
The most useful thing you can do here is display/i $pc
, before using stepi
as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi
command.
(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)
Validating email is a very important point while validating an HTML form. In this page we have discussed how to validate an email using JavaScript :
An email is a string (a subset of ASCII characters) separated into two parts by @ symbol. a "personal_info" and a domain, that is personal_info@domain. The length of the personal_info part may be up to 64 characters long and domain name may be up to 253 characters. The personal_info part contains the following ASCII characters.
The domain name [for example com, org, net, in, us, info] part contains letters, digits, hyphens, and dots.
Example of valid email id
Example of invalid email id
mysite.ourearth.com [@ is not present]
[email protected] [ tld (Top Level domain) can not start with dot "." ]
@you.me.net [ No character before @ ]
[email protected] [ ".b" is not a valid tld ]
[email protected] [ tld can not start with dot "." ]
[email protected] [ an email should not be start with "." ]
mysite()*@gmail.com [ here the regular expression only allows character, digit, underscore, and dash ]
[email protected] [double dots are not allowed]
JavaScript code to validate an email id
function ValidateEmail(mail) {
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w {2, 3})+$/.test(myForm.emailAddr.value)) {
return (true)
}
alert("You have entered an invalid email address!")
return (false)
}
To expand upon Mr. Eels comment, you can do it like this:
File file = new File("C:\\A.txt");
FileWriter writer;
try {
writer = new FileWriter(file, true);
PrintWriter printer = new PrintWriter(writer);
printer.append("Sue");
printer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Don't say we ain't good to ya!
empty_string = ""
if not empty_string:
print "Empty string is not set"
=>Empty string is not set
if empty_string is not None:
print "Empty string is not None"
=>Empty string is not None
If you send a PHP array into a function that expects a string like: echo
or print
, then the PHP interpreter will convert your array to the literal string Array
, throw this Notice and keep going. For example:
php> print(array(1,2,3))
PHP Notice: Array to string conversion in
/usr/local/lib/python2.7/dist-packages/phpsh/phpsh.php(591) :
eval()'d code on line 1
Array
In this case, the function print
dumps the literal string: Array
to stdout and then logs the Notice to stderr and keeps going.
Another example in a PHP script:
<?php
$stuff = array(1,2,3);
print $stuff; //PHP Notice: Array to string conversion in yourfile on line 3
?>
$stuff = array(1,2,3);
foreach ($stuff as $value) {
echo $value, "\n";
}
Prints:
1
2
3
Or along with array keys
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
foreach ($stuff as $key => $value) {
echo "$key: $value\n";
}
Prints:
name: Joe
email: [email protected]
Note that array elements could be arrays as well. In this case either use foreach
again or access this inner array elements using array syntax, e.g. $row['name']
In case it's just a plain 1-demensional array, you can simply join all the cells into a string using a delimiter:
<?php
$stuff = array(1,2,3);
print implode(", ", $stuff); //prints 1, 2, 3
print join(',', $stuff); //prints 1,2,3
In case your array has a complex structure but you need to convert it to a string anyway, then use http://php.net/json_encode
$stuff = array('name' => 'Joe', 'email' => '[email protected]');
print json_encode($stuff);
Prints
{"name":"Joe","email":"[email protected]"}
If you want just to inspect the array contents for the debugging purpose, use one of the following functions. Keep in mind that var_dump is most informative of them and thus usually being preferred for the purpose
examples
$stuff = array(1,2,3);
print_r($stuff);
$stuff = array(3,4,5);
var_dump($stuff);
Prints:
Array
(
[0] => 1
[1] => 2
[2] => 3
)
array(3) {
[0]=>
int(3)
[1]=>
int(4)
[2]=>
int(5)
}
I know it's a really old question, but it's the first result on duckduckgo, so I wanted to share what I think it's a better and more modern solution.
You can use background-blend-mode
property to achieve a greyscale image:
#something {
background-color: #fff;
background-image: url("yourimage");
background-blend-mode: luminosity;
}
If you want to remove the effect, just change the blend-mode to initial
.
You may need to play a little bit with the background-color if this element is over something with a background. What I've found is that the greyscale does not depend on the actual color but on the alpha value. So, if you have a blue background on the parent, set the same background on #something
.
You can also use two images, one with color and the other without and set both as background and play with other blend modes.
https://www.w3schools.com/cssref/pr_background-blend-mode.asp
It won't work on Edge though.
EDIT: I've miss the "fade" part of the question.
If you wan't to make it fade from/to grayscale, you can use a css transition on the background color changeing it's alpha value:
#something {
background-color: rgba(255,255,255,1);
background-image: url("yourimage");
background-blend-mode: luminosity;
transition: background-color 1s ease-out;
}
#something:hover {
background-color: rgba(255,255,255,0);
}
I'm also adding a codepen example for completeness https://codepen.io/anon/pen/OBKKVZ
I wrote you 2 classes to show you how it's done; Main and Customer. If you run the Main class you see what's going on:
import java.util.*;
public class Customer {
private String name;
private String email;
public Customer(String name, String email) {
this.name = name;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public String toString() {
return name + " | " + email;
}
public static String toString(Collection<Customer> customers) {
String s = "";
for(Customer customer : customers) {
s += customer + "\n";
}
return s;
}
}
import java.util.*;
public class Main {
public static void main(String[] args) {
List<Customer> customers = new ArrayList<>();
customers.add(new Customer("Bert", "[email protected]"));
customers.add(new Customer("Ernie", "[email protected]"));
System.out.println("customers before email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
customers.get(1).setEmail("[email protected]");
System.out.println("customers after email change - start");
System.out.println(Customer.toString(customers));
System.out.println("end");
}
}
to get this running, make 2 classes, Main and Customer and copy paste the contents from both classes to the correct class; then run the Main class.
Use this in your RelativeLayout
android:gravity="center_vertical"
The only reason to have a return in a void function would be to exit early due to some conditional statement:
void foo(int y)
{
if(y == 0) return;
// do stuff with y
}
As unwind said: when the code ends, it ends. No need for an explicit return at the end.
i had to figure out the right solution the hard way. the below code is part of cyanogenmod7 (the tablet tweaks) and is tested on android 2.3.3 / gingerbread.
methods:
this hopefully answers this issue in all extend (:
private RunningAppProcessInfo getForegroundApp() {
RunningAppProcessInfo result=null, info=null;
if(mActivityManager==null)
mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
List <RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
Iterator <RunningAppProcessInfo> i = l.iterator();
while(i.hasNext()){
info = i.next();
if(info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
&& !isRunningService(info.processName)){
result=info;
break;
}
}
return result;
}
private ComponentName getActivityForApp(RunningAppProcessInfo target){
ComponentName result=null;
ActivityManager.RunningTaskInfo info;
if(target==null)
return null;
if(mActivityManager==null)
mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
List <ActivityManager.RunningTaskInfo> l = mActivityManager.getRunningTasks(9999);
Iterator <ActivityManager.RunningTaskInfo> i = l.iterator();
while(i.hasNext()){
info=i.next();
if(info.baseActivity.getPackageName().equals(target.processName)){
result=info.topActivity;
break;
}
}
return result;
}
private boolean isStillActive(RunningAppProcessInfo process, ComponentName activity)
{
// activity can be null in cases, where one app starts another. for example, astro
// starting rock player when a move file was clicked. we dont have an activity then,
// but the package exits as soon as back is hit. so we can ignore the activity
// in this case
if(process==null)
return false;
RunningAppProcessInfo currentFg=getForegroundApp();
ComponentName currentActivity=getActivityForApp(currentFg);
if(currentFg!=null && currentFg.processName.equals(process.processName) &&
(activity==null || currentActivity.compareTo(activity)==0))
return true;
Slog.i(TAG, "isStillActive returns false - CallerProcess: " + process.processName + " CurrentProcess: "
+ (currentFg==null ? "null" : currentFg.processName) + " CallerActivity:" + (activity==null ? "null" : activity.toString())
+ " CurrentActivity: " + (currentActivity==null ? "null" : currentActivity.toString()));
return false;
}
private boolean isRunningService(String processname){
if(processname==null || processname.isEmpty())
return false;
RunningServiceInfo service;
if(mActivityManager==null)
mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
List <RunningServiceInfo> l = mActivityManager.getRunningServices(9999);
Iterator <RunningServiceInfo> i = l.iterator();
while(i.hasNext()){
service = i.next();
if(service.process.equals(processname))
return true;
}
return false;
}
If is a package then you can get the source for that with:
select text from all_source where name = 'PADCAMPAIGN'
and type = 'PACKAGE BODY'
order by line;
Oracle doesn't store the source for a sub-program separately, so you need to look through the package source for it.
Note: I've assumed you didn't use double-quotes when creating that package, but if you did , then use
select text from all_source where name = 'pAdCampaign'
and type = 'PACKAGE BODY'
order by line;
you can swipe the key and the value. For example
String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
int[] v = {341, 273, 278, 329, 445};
TreeMap<Integer,String>a=new TreeMap();
for (int i = 0; i < k.length; i++)
a.put(v[i],k[i]);
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
a.remove(a.firstEntry().getKey());
System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
Open IIS Setting in your plesk panel and enter default document name first page of website (deafault values are
Index.html
Index.htm
Index.cfm
Index.shtml
Index.shtm
Index.stm
Index.php
Index.php3
Index.asp
Index.aspx
Default.htm
Default.asp
Default.aspx)
This will work properly
CSS Solution:
.h2{
font-size: 2vw
}
@media (min-width: 700px) {
.h2{
/* Minimum font size */
font-size: 14px
}
}
@media (max-width: 1200px) {
.h2{
/* Maximum font size */
font-size: 24px
}
}
Just in case if some need scss mixin:
///
/// Viewport sized typography with minimum and maximum values
///
/// @author Eduardo Boucas (@eduardoboucas)
///
/// @param {Number} $responsive - Viewport-based size
/// @param {Number} $min - Minimum font size (px)
/// @param {Number} $max - Maximum font size (px)
/// (optional)
/// @param {Number} $fallback - Fallback for viewport-
/// based units (optional)
///
/// @example scss - 5vw font size (with 50px fallback),
/// minumum of 35px and maximum of 150px
/// @include responsive-font(5vw, 35px, 150px, 50px);
///
@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
$responsive-unitless: $responsive / ($responsive - $responsive + 1);
$dimension: if(unit($responsive) == 'vh', 'height', 'width');
$min-breakpoint: $min / $responsive-unitless * 100;
@media (max-#{$dimension}: #{$min-breakpoint}) {
font-size: $min;
}
@if $max {
$max-breakpoint: $max / $responsive-unitless * 100;
@media (min-#{$dimension}: #{$max-breakpoint}) {
font-size: $max;
}
}
@if $fallback {
font-size: $fallback;
}
font-size: $responsive;
}
Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.
I've added IDs to html on the total price and on the buttons. Here is the jQuery.
$('#two').click(function(){
$('#count').val('2');
$('#total').text('Product price: $1000');
});
$('#four').click(function(){
$('#count').val('4');
$('#total').text('Product price: $2000');
});
Just add a new datafile for the existing tablespace
ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;
To find out the location and size of your data files:
SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';
Literally you can't do such a thing, but you should try this CSS trick:
box-shadow: inset 0 3vw 6vw rgba(0,0,0,0.6), inset 0 -3vw 6vw rgba(0,0,0,0.6);
Try this header file in your code
stdbool.h
This must work
From the LESS website:
If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:
@import "lib.css"; The directive will just be left as is, and end up in the CSS output.
As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @import
s consuming precious bandwidth.
From the release news of ggplot 2.2.0
: "The main plot title is now left-aligned to better work better with a subtitle". See also the plot.title
argument in ?theme
: "left-aligned by default".
As pointed out by @J_F, you may add theme(plot.title = element_text(hjust = 0.5))
to center the title.
ggplot() +
ggtitle("Default in 2.2.0 is left-aligned")
ggplot() +
ggtitle("Use theme(plot.title = element_text(hjust = 0.5)) to center") +
theme(plot.title = element_text(hjust = 0.5))
Sometime some C# approach makes the life easier in Java world..:
class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;
This can be solved with the mentioned depends_on
directive since it's implemented now (2016):
version: '2'
services:
nginx:
image: nginx
ports:
- "42080:80"
volumes:
- ./config/docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
depends_on:
- php
php:
build: config/docker/php
ports:
- "42022:22"
volumes:
- .:/var/www/html
env_file: config/docker/php/.env.development
depends_on:
- mongo
mongo:
image: mongo
ports:
- "42017:27017"
volumes:
- /var/mongodata/wa-api:/data/db
command: --smallfiles
Successfully tested with:
$ docker-compose version
docker-compose version 1.8.0, build f3628c7
Find more details in the documentation.
There is also a very interesting article dedicated to this topic: Controlling startup order in Compose
Another functional approach which is maybe a little easier to look at than an anonymous function if you go that route is using functools.partial
to utilize the two-parameter operator.mul
with a fixed multiple
>>> from functools import partial
>>> from operator import mul
>>> double = partial(mul, 2)
>>> list(map(double, [1, 2, 3]))
[2, 4, 6]
In addition to the other answers to this question, using an anonymous namespace can also improve performance. As symbols within the namespace do not need any external linkage, the compiler is freer to perform aggressive optimization of the code within the namespace. For example, a function which is called multiple times once in a loop can be inlined without any impact on the code size.
For example, on my system the following code takes around 70% of the run time if the anonymous namespace is used (x86-64 gcc-4.6.3 and -O2; note that the extra code in add_val makes the compiler not want to include it twice).
#include <iostream>
namespace {
double a;
void b(double x)
{
a -= x;
}
void add_val(double x)
{
a += x;
if(x==0.01) b(0);
if(x==0.02) b(0.6);
if(x==0.03) b(-0.1);
if(x==0.04) b(0.4);
}
}
int main()
{
a = 0;
for(int i=0; i<1000000000; ++i)
{
add_val(i*1e-10);
}
std::cout << a << '\n';
return 0;
}
I think your basic requirement is to have a C/C++-like syntax in Python with the least headache possible. Although I liked Alexander Poluektov's answer it doesn't work for classes.
The following should work for classes. It works by distinguishing by the number of non-keyword arguments (but it doesn't support distinguishing by type):
class TestOverloading(object):
def overloaded_function(self, *args, **kwargs):
# Call the function that has the same number of non-keyword arguments.
getattr(self, "_overloaded_function_impl_" + str(len(args)))(*args, **kwargs)
def _overloaded_function_impl_3(self, sprite, start, direction, **kwargs):
print "This is overload 3"
print "Sprite: %s" % str(sprite)
print "Start: %s" % str(start)
print "Direction: %s" % str(direction)
def _overloaded_function_impl_2(self, sprite, script):
print "This is overload 2"
print "Sprite: %s" % str(sprite)
print "Script: "
print script
And it can be used simply like this:
test = TestOverloading()
test.overloaded_function("I'm a Sprite", 0, "Right")
print
test.overloaded_function("I'm another Sprite", "while x == True: print 'hi'")
Output:
This is overload 3
Sprite: I'm a Sprite
Start: 0
Direction: RightThis is overload 2
Sprite: I'm another Sprite
Script:
while x == True: print 'hi'
One correct way to get selected value would be
var selected_value = $('#fruit_name').val()
And then you should do
if(selected_value) { ... }
Your collection class could have a method that returns a collection (a sublist) based on criteria passed in to define the filter. Build a new collection with the foreach loop and pass it out.
Or, have the method and loop modify the existing collection by setting a "filtered" or "active" flag (property). This one could work but could also cause poblems in multithreaded code. If other objects deped on the contents of the collection this is either good or bad depending of how you use the data.
If you want to ensure keyboard events are fired, consider using sendKeys(CharSequence)
.
Example 1:
from selenium.webdriver.common.keys import Keys
# ...
webElement.sendKeys(Keys.CONTROL + "a");
webElement.sendKeys(Keys.DELETE);
Example 2:
from selenium.webdriver.common.keys import Keys
# ...
webElement.sendKeys(Keys.BACK_SPACE); //do repeatedly, e.g. in while loop
There are many ways to get the required WebElement, e.g.:
webElement.clear();
If this element is a text entry element, this will clear the value.
Note that the events fired by this event may not be as you'd expect. In particular, we don't fire any keyboard or mouse events.
To obtain all the rows that contains an empty cell in in a particular column.
DF_new_row=DF_raw.loc[DF_raw['columnname']=='']
This will give the subset of DF_raw, which satisfy the checking condition.