There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.
Here is an example based on the first answer:
@Component({
selector: 'my-app',
template: `
<div>
<input type="file" #file (change)="onChange(file.files)"/>
</div>
`,
providers: [ UploadService ]
})
export class AppComponent {
onChange(files) {
console.log(files);
}
}
Here is an example app to demonstrate this in action.
Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.
If non of above works for you, make sure tomcat has access to manager folder under webapps (chown ...). The message is the exact same message, and It took me 2 hours to figure out the problem. :-)
just for someone else who came here for the same issue as me.
private static void printStar(int x) {
int i, j;
for (int y = 0; y < x; y++) { // number of row of '*'
for (i = y; i < x - 1; i++)
// number of space each row
System.out.print(' ');
for (j = 0; j < y * 2 + 1; j++)
// number of '*' each row
System.out.print('*');
System.out.println();
}
}
You might have not copied the MySQL connector/J
jar file into the lib folder and then this file has to be there in the classpath.
If you have not done so, please let me know I shall elaborate the answer
The most obvious to me would be:
np.any(my_array[:, 0] == value)
Summary
Microsoft Security Updates 896358 & 840315 block display of CHM file contents when opened from a network drive (or a UNC path). This is Windows' attempt to stop attack vectors for viruses/malware from infecting your computer and has blocked out the .chm file that draw data over the "InfoTech" protocol, which this chm file uses.
Microsoft's summary of the problem: http://support.microsoft.com/kb/896054
Solutions
If you are using Windows Server 2008, Windows 7, windows has created a quick fix. Right click the chm file, and you will get the "yourfile.chm Properties" dialog box, at the bottom, a button called "Unblock" appears. Click Unblock and press OK, and try to open the chm file again, it works correctly. This option is not available for earlier versions of Windows before WindowsXP (SP3).
Solve the problem by moving your chm file OFF the network drive. You may be unaware you are using a network drive, double check now: Right click your .chm file, click properties and look at the "location" field. If it starts with two backslashes like this: \\epicserver\blah\
, then you are using a networked drive. So to fix it, Copy the chm file, and paste it into a local drive, like C:\ or E:. Then try to reopen the chm file, windows does not freak out.
Last resort, if you can't copy/move the file off the networked drive. If you must open it where it sits, and you are using a lesser version of windows like XP, Vista, ME or other, you will have to manually tell Windows not to freak out over this .chm file. HHReg (HTML Help Registration Utility) Utility Automates this Task. Basically you download the HHReg utility, load your .chm file, press OK, and it will create the necessary registry keys to tell Windows not to block it. For more info: http://www.winhelponline.com/blog/fix-cannot-view-chm-files-network-xp-2003-vista/
Windows 8 or 10? --> Upgrade to Windows XP.
I have a simpler idea. Use LINQ with a new selection.
public class Fruit
{
public string Name {get; set;}
public int SeedCount {get; set;}
}
void SomeMethod()
{
List<Fruit> originalFruits = new List<Fruit>();
originalFruits.Add(new Fruit {Name="Apple", SeedCount=10});
originalFruits.Add(new Fruit {Name="Banana", SeedCount=0});
//Deep Copy
List<Fruit> deepCopiedFruits = from f in originalFruits
select new Fruit {Name=f.Name, SeedCount=f.SeedCount};
}
I would use Scanner#nextLine
opposed to next
for your address
attribute.
This method returns the rest of the current line, excluding any line separator at the end.
Since this returns the entire line, delimited by a line separator, it will allow the user to enter any address without any constraint.
I usually use git on my linux machine, but at work I have to use Windows. I had the same problem when trying to commit the first commit in a Windows environment.
For those still facing this problem, I was able to resolve it as follows:
$ git commit --allow-empty -n -m "Initial commit".
Add a contextmenu to your form and then assign it in the control's properties under ContextMenuStrip. Hope this helps :).
Hope this helps:
ContextMenu cm = new ContextMenu();
cm.MenuItems.Add("Item 1");
cm.MenuItems.Add("Item 2");
pictureBox1.ContextMenu = cm;
create an empty modal box on the current page and below is the ajax call you can see how to fetch the content in result from another html page.
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
once the call is done you will get the content of the page by the result to then you can insert the code in you modal's content id using.
You can call controller and get the page content and you can show that in your modal.
below is the example of Bootstrap 3 modal in that we are loading content from registration.html page...
index.html
------------------------------------------------
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
function loadme(){
//alert("loadig");
$.ajax({url: "registration.html", success: function(result){
//alert("success"+result);
$("#contentBody").html(result);
$("#myModal").modal('show');
}});
}
</script>
</head>
<body>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" onclick="loadme()">Load me</button>
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content" >
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body" id="contentBody">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</body>
</html>
registration.html
--------------------
<!DOCTYPE html>
<html>
<style>
body {font-family: Arial, Helvetica, sans-serif;}
form {
border: 3px solid #f1f1f1;
font-family: Arial;
}
.container {
padding: 20px;
background-color: #f1f1f1;
width: 560px;
}
input[type=text], input[type=submit] {
width: 100%;
padding: 12px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
box-sizing: border-box;
}
input[type=checkbox] {
margin-top: 16px;
}
input[type=submit] {
background-color: #4CAF50;
color: white;
border: none;
}
input[type=submit]:hover {
opacity: 0.8;
}
</style>
<body>
<h2>CSS Newsletter</h2>
<form action="/action_page.php">
<div class="container">
<h2>Subscribe to our Newsletter</h2>
<p>Lorem ipsum text about why you should subscribe to our newsletter blabla. Lorem ipsum text about why you should subscribe to our newsletter blabla.</p>
</div>
<div class="container" style="background-color:white">
<input type="text" placeholder="Name" name="name" required>
<input type="text" placeholder="Email address" name="mail" required>
<label>
<input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter
</label>
</div>
<div class="container">
<input type="submit" value="Subscribe">
</div>
</form>
</body>
</html>
Make sure that your ORACLE_HOME and ORACLE_SID are correct To see the current values in windows, at the command prompt type
echo %ORACLE_HOME%
Then
echo %ORACLE_SID%
If the values are not your current oracle home and SID you need to correct them. This can be done in Windows environment variables.
Check out this page for more info
You can reuse your confirm:
function doConfirm(body, $_nombrefuncion)
{ var param = undefined;
var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
autoOpen: false,
buttons: {
Yes: function() {
param = true;
$_nombrefuncion(param);
$(this).dialog('close');
},
No: function() {
param = false;
$_nombrefuncion(param);
$(this).dialog('close');
}
}
});
$confirm.html("<h3>"+body+"<h3>");
$confirm.dialog('open');
};
// for this form just u must change or create a new function for to reuse the confirm
function resultadoconfirmresetVTyBFD(param){
$fecha = $("#asigfecha").val();
if(param ==true){
// DO THE CONFIRM
}
}
//Now just u must call the function doConfirm
doConfirm('body message',resultadoconfirmresetVTyBFD);
As several folks have noted, requests doesn't support FTP but Python has other libraries that do. If you want to keep using the requests library, there is a requests-ftp package that adds FTP capability to requests. I've used this library a little and it does work. The docs are full of warnings about code quality though. As of 0.2.0 the docs say "This library was cowboyed together in about 4 hours of total work, has no tests, and relies on a few ugly hacks".
import requests, requests_ftp
requests_ftp.monkeypatch_session()
response = requests.get('ftp://example.com/foo.txt')
I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.
Well, I faced the same issue as soon as I updated my angular cli
version.
Earlier I was using 1.7.4 and just now I upgraded it to angular cli 6.0.8
.
To update Angular Cli global:
npm uninstall -g angular-cli
npm cache clean
npm install -g @angular/cli@latest
To update Angular Cli dev:
npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install
To fix audit issues after npm install:
npm audit fix
To fix the issue related to "angular.json":
ng update @angular/cli --migrate-only --from=1.7.4
An enumerated type is basically a data type that lets you describe each member of a type in a more readable and reliable way.
Here is a simple example to explain why:
Assuming you are writing a method that has something to do with seasons:
First, you declared some int static constants to represent each season.
public static final int SPRING = 0;
public static final int SUMMER = 1;
public static final int FALL = 2;
public static final int WINTER = 2;
Then, you declared a method to print name of the season into the console.
public void printSeason(int seasonCode) {
String name = "";
if (seasonCode == SPRING) {
name = "Spring";
}
else if (seasonCode == SUMMER) {
name = "Summer";
}
else if (seasonCode == FALL) {
name = "Fall";
}
else if (seasonCode == WINTER) {
name = "Winter";
}
System.out.println("It is " + name + " now!");
}
So, after that, you can print a season name like this.
printSeason(SPRING);
printSeason(WINTER);
This is a pretty common (but bad) way to do different things for different types of members in a class. However, since these code involves integers, so you can also call the method like this without any problems.
printSeason(0);
printSeason(1);
or even like this
printSeason(x - y);
printSeason(10000);
The compiler will not complain because these method calls are valid, and your printSeason
method can still work.
But something is not right here. What does a season code of 10000
supposed to mean? What if x - y
results in a negative number? When your method receives an input that has no meaning and is not supposed to be there, your program knows nothing about it.
You can fix this problem, for example, by adding an additional check.
...
else if (seasonCode == WINTER) {
name = "Winter";
}
else {
throw new IllegalArgumentException();
}
System.out.println(name);
Now the program will throw a RunTimeException
when the season code is invalid. However, you still need to decide how you are going to handle the exception.
By the way, I am sure you noticed the code of FALL
and WINTER
are both 2, right?
You should get the idea now. This pattern is brittle. It makes you write condition checks everywhere. If you're making a game, and you want to add an extra season into your imaginary world, this pattern will make you go though all the methods that do things by season, and in most case you will forget some of them.
You might think class inheritance is a good idea for this case. But we just need some of them and no more.
That's when enum
comes into play.
enum
typeIn Java, enum
types are classes that export one instance for each enumeration constant via a public static final field.
Here you can declare four enumeration constants: SPRING, SUMMER, FALL, WINTER
. Each has its own name
.
public enum Season {
SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter");
private String name;
Season(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Now, back to the method.
public void printSeason(Season season) {
System.out.println("It is " + season.getName() + " now!");
}
Instead of using int
, you can now use Season
as input. Instead of a condition check, you can tell Season
to give you its name.
This is how you use this method now:
printSeason(Season.SPRING);
printSeason(Season.WINTER);
printSeason(Season.WHATEVER); <-- compile error
You will get a compile-time error when you use an incorrect input, and you're guaranteed to get a non-null singleton reference of Season
as long as the program compiles.
When we need an additional season, we simply add another constant in Season
and no more.
public enum Season {
SPRING("Spring"), SUMMER("Summer"), FALL("Fall"), WINTER("Winter"),
MYSEASON("My Season");
...
Whenever you need a fixed set of constants, enum
can be a good choice (but not always). It's a more readable, more reliable and more powerful solution.
There is a easy solution for that problem, the solution is removed the certificate the yours Keychain, the previous thing will cause that it asks again to the user and password.
Steps:
Search the certificate gitHub.com.
Remove gitHub.com certificate.
Execute any operation with git in your terminal. this again ask your username and password.
For Windows Users find the key chain by following:
Control Panel >> User Account >> Credential Manager >> Windows Credential >> Generic Credential
To time task in CMD is as simple as
echo %TIME% && your_command && cmd /v:on /c echo !TIME!
To fix/install Android USB driver on Windows 7/8 32bit/64bit:
<sdk>\extras\google\usb_driver\
.)If it still doesn't work try changing from MTP to PTP.
Swift 5
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
Swift 4
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
As Edan Maor explained, the quick and dirty way to do it (for [utc-16] encoded .xml files), which you should not do for the resons Edam Maor explained, can done with the following python 2.7 code in case time constraints do not allow you to learn (propper) XML parses.
Assuming you want to:
It worked in python 2.7 modifying an .xml file named "b.xml" located in folder "a", where "a" was located in the "working folder" of python. It outputs the new modified file as "c.xml" in folder "a", without yielding encoding errors (for me) in further use outside of python 2.7.
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
line_index =0 #set line count to 0 before starting
file = io.open('a/b.xml', 'r', encoding='utf-16')
lines = file.readlines()
outFile = open('a/c.xml', 'w')
for line in lines[0:len(lines)]:
line_index =line_index +1
if line_index == len(lines):
#1. & 2. delete last line and adding another line in its place not writing it
outFile.writelines("Write extra line here" + '\n')
# 4. Close root tag:
outFile.writelines("</phonebook>") # as in:
#http://tizag.com/xmlTutorial/xmldocument.php
else:
#3. Substitue a line if it finds the following substring in a line:
pattern = '<Author>'
subst = ' <Author>' + domain + '\\' + user_name + '</Author>'
if pattern in line:
line = subst
print line
outFile.writelines(line)#just writing/copying all the lines from the original xml except for the last.
#footer:after
{
content: "";
width: 40px;
height: 3px;
background-color: #529600;
left: 0;
position: relative;
display: block;
top: 10px;
}
For small functions like this you could just count by hand how many hops it is to the target, from the instruction under the branch instruction. If it branches backwards make that hop number negative. if that number doesn't require all 16 bits, then for every number to the left of the most significant of your hop number, make them 1's, if the hop number is positive make them all 0's Since most branches are close to they're targets, this saves you a lot of extra arithmetic for most cases.
After applying the top rated solution I've had a problem that it breaks future modals opening properly. I've found my solution which works good
element.on("shown.bs.modal", function () {
if ($(".modal-backdrop").length > 1) {
$(".modal-backdrop").not(':first').remove();
}
element.css('display', 'block');
});
Not only did Matt Trout write an article about a REPL, he actually wrote one - Devel::REPL
I've used it a bit and it works fairly well, and it's under active development.
BTW, I have no idea why someone modded down the person who mentioned using "perl -e" from the console. This isn't really a REPL, true, but it's fantastically useful, and I use it all the time.
I found another server side solution for web dev using PHP to get the size of an iframe.
First is using server script PHP to an external call via internal function: (like a file_get_contents
with but curl and dom).
function curl_get_file_contents($url,$proxyActivation=false) {
global $proxy;
$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.8.1.7) Gecko/20070914 Firefox/2.0.0.7");
curl_setopt($c, CURLOPT_REFERER, $url);
curl_setopt($c, CURLOPT_URL, $url);
curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1);
if($proxyActivation) {
curl_setopt($c, CURLOPT_PROXY, $proxy);
}
$contents = curl_exec($c);
curl_close($c);
$dom = new DOMDocument();
$dom->preserveWhiteSpace = false;
@$dom->loadHTML($contents);
$form = $dom->getElementsByTagName("body")->item(0);
if ($contents) //si on a du contenu
return $dom->saveHTML();
else
return FALSE;
}
$url = "http://www.google.com"; //Exernal url test to iframe
<html>
<head>
<script type="text/javascript">
</script>
<style type="text/css">
#iframe_reserve {
width: 560px;
height: 228px
}
</style>
</head>
<body>
<div id="iframe_reserve"><?php echo curl_get_file_contents($url); ?></div>
<iframe id="myiframe" src="http://www.google.com" scrolling="no" marginwidth="0" marginheight="0" frameborder="0" style="overflow:none; width:100%; display:none"></iframe>
<script type="text/javascript">
window.onload = function(){
document.getElementById("iframe_reserve").style.display = "block";
var divHeight = document.getElementById("iframe_reserve").clientHeight;
document.getElementById("iframe_reserve").style.display = "none";
document.getElementById("myiframe").style.display = "block";
document.getElementById("myiframe").style.height = divHeight;
alert(divHeight);
};
</script>
</body>
</html>
You need to display under the div (iframe_reserve
) the html generated by the function call by using a simple echo curl_get_file_contents("location url iframe","activation proxy")
After doing this a body event function onload with javascript take height of the page iframe just with a simple control of the content div (iframe_reserve
)
So I used divHeight = document.getElementById("iframe_reserve").clientHeight;
to get height of the page external we are going to call after masked the div container (iframe_reserve
). After this we load the iframe with its good height that's all.
Here is what I figured, and this happened recently on Windows 10 after an update was installed. From what I gathered, a Windows Defender update was installed which assumed my "Project.dll"(an asp.net core project) behaved like a virus so it was deleted.
So, one of the first things I suggest you do before you start installing/uninstalling stuffs is to check to confirm your "Project.dll" is where it should be.
Copy it back to the location if it is no longer there.
If you are having difficulty copying the file back add an exclusion to your project folder in windows defender. ( Learn how to do that here. )
This worked for me instantly, and I repeated it across application multiple servers.
this is in pure javascript
document.addEventListener('keypress', function (e) {_x000D_
if (e.keyCode === 13 || e.which === 13) {_x000D_
e.preventDefault();_x000D_
return false;_x000D_
}_x000D_
_x000D_
});
_x000D_
The accepted answer didn't work with my table (thousands of rows, dynamic loading) but the code below works:
- (void)scrollToBottom:(id)sender {
if ([self.sections count] > 0) {
NSInteger idx = [self.sections count] - 1;
CGRect sectionRect = [self.tableView rectForSection:idx];
sectionRect.size.height = self.tableView.frame.size.height;
[self.tableView scrollRectToVisible:sectionRect animated:NO];
}
}
Using ASP.NET's visible="false"
property will set the visibility
attribute where as I think when you call show()
in jQuery it modifies the display
attribute of the CSS style.
So doing the latter won't rectify the former.
You need to do this:
$("#test1").attr("visibility", "visible");
When you say the 'GUI Tool', I assume you're using Git For Windows.
IMPORTANT, I would highly recommend creating a new branch to do this on if you haven't already. That way your master can remain the same while you test out your changes.
With the GUI you need to 'roll back this commit' like you have with the history on the right of your view. Then you will notice you have all the unwanted files as changes to commit on the left. Now you need to right click on the grey title above all the uncommited files and select 'disregard changes'. This will set your files back to how they were in this version.
namedtuple
s are immutable, just like standard tuples. You have two choices:
The former would look like:
class N(object):
def __init__(self, ind, set, v):
self.ind = ind
self.set = set
self.v = v
And the latter:
item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)
Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.
click link get example file upload clint java with apache HttpComponents
and library downalod link
https://hc.apache.org/downloads.cgi
use 4.5.3.zip it's working fine in my code
and my working code..
import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class ClientMultipartFormPost {
public static void main(String[] args) throws Exception {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpPost httppost = new HttpPost("http://localhost:8080/MyWebSite1/UploadDownloadFileServlet");
FileBody bin = new FileBody(new File("E:\\meter.jpg"));
StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin)
.addPart("comment", comment)
.build();
httppost.setEntity(reqEntity);
System.out.println("executing request " + httppost.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httppost);
try {
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
HttpEntity resEntity = response.getEntity();
if (resEntity != null) {
System.out.println("Response content length: " + resEntity.getContentLength());
}
EntityUtils.consume(resEntity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}
I think the same places of them are: all of them can change the this value of a function.The differences of them are: the bind function will return a new function as a result; the call and apply methods will execute the function immediately, but apply can accept a array as params,and it will parse the array separated.And also, the bind function can be Currying.
Here's the list of logger categories:
Category Function
org.hibernate.SQL Log all SQL DML statements as they are executed
org.hibernate.type Log all JDBC parameters
org.hibernate.tool.hbm2ddl Log all SQL DDL statements as they are executed
org.hibernate.pretty Log the state of all entities (max 20 entities) associated with the session at flush time
org.hibernate.cache Log all second-level cache activity
org.hibernate.transaction Log transaction related activity
org.hibernate.jdbc Log all JDBC resource acquisition
org.hibernate.hql.ast.AST Log HQL and SQL ASTs during query parsing
org.hibernate.secure Log all JAAS authorization requests
org.hibernate Log everything (a lot of information, but very useful for troubleshooting)
Formatted for pasting into a log4j XML configuration file:
<!-- Log all SQL DML statements as they are executed -->
<Logger name="org.hibernate.SQL" level="debug" />
<!-- Log all JDBC parameters -->
<Logger name="org.hibernate.type" level="debug" />
<!-- Log all SQL DDL statements as they are executed -->
<Logger name="org.hibernate.tool.hbm2ddl" level="debug" />
<!-- Log the state of all entities (max 20 entities) associated with the session at flush time -->
<Logger name="org.hibernate.pretty" level="debug" />
<!-- Log all second-level cache activity -->
<Logger name="org.hibernate.cache" level="debug" />
<!-- Log transaction related activity -->
<Logger name="org.hibernate.transaction" level="debug" />
<!-- Log all JDBC resource acquisition -->
<Logger name="org.hibernate.jdbc" level="debug" />
<!-- Log HQL and SQL ASTs during query parsing -->
<Logger name="org.hibernate.hql.ast.AST" level="debug" />
<!-- Log all JAAS authorization requests -->
<Logger name="org.hibernate.secure" level="debug" />
<!-- Log everything (a lot of information, but very useful for troubleshooting) -->
<Logger name="org.hibernate" level="debug" />
NB: Most of the loggers use the DEBUG level, however org.hibernate.type uses TRACE. In previous versions of Hibernate org.hibernate.type also used DEBUG, but as of Hibernate 3 you must set the level to TRACE (or ALL) in order to see the JDBC parameter binding logging.
And a category is specified as such:
<logger name="org.hibernate">
<level value="ALL" />
<appender-ref ref="FILE"/>
</logger>
It must be placed before the root element.
I use the following solution, it's quite simple and elegant, can be easily pasted into source, and works on Linux/Bash:
const std::string red("\033[0;31m");
const std::string green("\033[1;32m");
const std::string yellow("\033[1;33m");
const std::string cyan("\033[0;36m");
const std::string magenta("\033[0;35m");
const std::string reset("\033[0m");
std::cout << "Measured runtime: " << yellow << timer.count() << reset << std::endl;
This is quite useful question. I think that my solution on Windows 10 PHP7 is rather useful for people who have yet some UTF-8 conversion trouble.
Here are my steps. The PHP script calling the following function, here named utfsave.php must have UTF-8 encoding itself, this can be easily done by conversion on UltraEdit.
In utfsave.php, we define a function calling PHP fopen($filename, "wb"), ie, it's opened in both w write mode, and especially with b in binary mode.
<?php
//
// UTF-8 ??:
//
// fnc001: save string as a file in UTF-8:
// The resulting file is UTF-8 only if $strContent is,
// with French accents, chinese ideograms, etc..
//
function entSaveAsUtf8($strContent, $filename) {
$fp = fopen($filename, "wb");
fwrite($fp, $strContent);
fclose($fp);
return True;
}
//
// 0. write UTF-8 string in fly into UTF-8 file:
//
$strContent = "My string contains UTF-8 chars ie ???? for un été en France";
$filename = "utf8text.txt";
entSaveAsUtf8($strContent, $filename);
//
// 2. convert CP936 ANSI/OEM - chinese simplified GBK file into UTF-8 file:
//
$strContent = file_get_contents("cp936gbktext.txt");
$strContent = mb_convert_encoding($strContent, "UTF-8", "CP936");
$filename = "utf8text2.txt";
entSaveAsUtf8($strContent, $filename);
?>
The source file cp936gbktext.txt file content:
>>Get-Content cp936gbktext.txt
My string contains UTF-8 chars ie ???? for un été en France 936 (ANSI/OEM - chinois simplifié GBK)
Running utf8save.php on Windows 10 PHP, thus created utf8text.txt, utf8text2.txt files will be automatically saved in UTF-8 format.
With this method, BOM char is not required. BOM solution is bad because it causes troubles when we do sourcing an sql file for MySQL for example.
It's worth noting that I failed making work file_put_contents($filename, utf8_encode($mystring)); for this purpose.
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
If you don't know the encoding of the source file, you can list encodings with PHP:
print_r(mb_list_encodings());
This gives a list like this:
Array
(
[0] => pass
[1] => wchar
[2] => byte2be
[3] => byte2le
[4] => byte4be
[5] => byte4le
[6] => BASE64
[7] => UUENCODE
[8] => HTML-ENTITIES
[9] => Quoted-Printable
[10] => 7bit
[11] => 8bit
[12] => UCS-4
[13] => UCS-4BE
[14] => UCS-4LE
[15] => UCS-2
[16] => UCS-2BE
[17] => UCS-2LE
[18] => UTF-32
[19] => UTF-32BE
[20] => UTF-32LE
[21] => UTF-16
[22] => UTF-16BE
[23] => UTF-16LE
[24] => UTF-8
[25] => UTF-7
[26] => UTF7-IMAP
[27] => ASCII
[28] => EUC-JP
[29] => SJIS
[30] => eucJP-win
[31] => EUC-JP-2004
[32] => SJIS-win
[33] => SJIS-Mobile#DOCOMO
[34] => SJIS-Mobile#KDDI
[35] => SJIS-Mobile#SOFTBANK
[36] => SJIS-mac
[37] => SJIS-2004
[38] => UTF-8-Mobile#DOCOMO
[39] => UTF-8-Mobile#KDDI-A
[40] => UTF-8-Mobile#KDDI-B
[41] => UTF-8-Mobile#SOFTBANK
[42] => CP932
[43] => CP51932
[44] => JIS
[45] => ISO-2022-JP
[46] => ISO-2022-JP-MS
[47] => GB18030
[48] => Windows-1252
[49] => Windows-1254
[50] => ISO-8859-1
[51] => ISO-8859-2
[52] => ISO-8859-3
[53] => ISO-8859-4
[54] => ISO-8859-5
[55] => ISO-8859-6
[56] => ISO-8859-7
[57] => ISO-8859-8
[58] => ISO-8859-9
[59] => ISO-8859-10
[60] => ISO-8859-13
[61] => ISO-8859-14
[62] => ISO-8859-15
[63] => ISO-8859-16
[64] => EUC-CN
[65] => CP936
[66] => HZ
[67] => EUC-TW
[68] => BIG-5
[69] => CP950
[70] => EUC-KR
[71] => UHC
[72] => ISO-2022-KR
[73] => Windows-1251
[74] => CP866
[75] => KOI8-R
[76] => KOI8-U
[77] => ArmSCII-8
[78] => CP850
[79] => JIS-ms
[80] => ISO-2022-JP-2004
[81] => ISO-2022-JP-MOBILE#KDDI
[82] => CP50220
[83] => CP50220raw
[84] => CP50221
[85] => CP50222
)
If you cannot guess, you try one by one, as mb_detect_encoding() cannot do the job easily.
The formula would be (original - discounted)/original
. i.e. (365-165)/365 = 0.5479...
Firstly, double quote character is nothing special in regex - it's just another character, so it doesn't need escaping from the perspective of regex.
However, because java uses double quotes to delimit String constants, if you want to create a string in java with a double quote in it, you must escape them.
This code will test if your String matches:
if (str.matches("\".*\"")) {
// this string starts and end with a double quote
}
Note that you don't need to add start and end of input markers (^
and $
) in the regex, because matches()
requires that the whole input be matched to return true - ^
and $
are implied.
if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:
If x and/or y is 2-dimensional, then the corresponding columns will be plotted.
In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:
np.squeez doc: Remove single-dimensional entries from the shape of an array.
import numpy as np
import matplotlib.pyplot as plt
data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()
But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:
open android location setting programmatically using alert dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(YourActivity.this);
alertDialog.setTitle("Enable Location");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
alertDialog.show();
As of Laravel 5.8, migration stubs use the bigIncrements method on ID columns by default. Previously, ID columns were created using the increments method.
This will not affect any existing code in your project; however, be aware that foreign key columns must be of the same type. Therefore, a column created using the increments method can not reference a column created using the bigIncrements method.
Source: Migrations & bigIncrements
Let's imagine you are building a simple role-based application, and you need to references user_id in the PIVOT table "role_user".
2019_05_05_112458_create_users_table.php
// ...
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('full_name');
$table->string('email');
$table->timestamps();
});
}
2019_05_05_120634_create_role_user_pivot_table.php
// ...
public function up()
{
Schema::create('role_user', function (Blueprint $table) {
// this line throw QueryException "SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint..."
// $table->integer('user_id')->unsigned()->index();
$table->bigInteger('user_id')->unsigned()->index(); // this is working
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
As you can see, the commented line will throw a query exception, because, as mentioned in the upgrade notes, foreign key columns must be of the same type, therefore you need to either change the foreing key (in this example it's user_id) to bigInteger in role_user table or change bigIncrements method to increments method in users table and use the commented line in the pivot table, it's up to you.
I hope i was able to clarify this issue to you.
Hide the body with css then show it after the page is loaded:
CSS:
html { visibility:hidden; }
Javascript
$(document).ready(function() {
document.getElementsByTagName("html")[0].style.visibility = "visible";
});
The page will go from blank to showing all content when the page is loaded, no flash of content, no watching images load etc.
Following will remove all the <none>
images
docker rmi $(docker images | grep none | awk '{print $3}')
You can force removal by changing docker rmi
to docker rmi -f
although I do not recommend doing that.
Some of the <none>
images could be related to other images so to be on safe side don't use -f
tag.
As was suggested in a comment above, if the certificate store on the host is compatible with the guest, you can just mount it directly.
On a Debian host (and container), I've successfully done:
docker run -v /etc/ssl/certs:/etc/ssl/certs:ro ...
To ignore all untracked files in any submodule use the following command to ignore those changes.
git config --global diff.ignoreSubmodules dirty
It will add the following configuration option to your local git config:
[diff]
ignoreSubmodules = dirty
Further information can be found here
Try it
Thread.currentThread().getStackTrace()[1].getClassName()
Or
Thread.currentThread().getStackTrace()[2].getClassName()
I adapted some code to create a TouchImageView that supports multitouch (>2.1). It is inspired by the book Hello, Android! (3rd edition)
It is contained within the following 3 files TouchImageView.java WrapMotionEvent.java EclairMotionEvent.java
TouchImageView.java
import se.robertfoss.ChanImageBrowser.Viewer;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.util.FloatMath;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
public class TouchImageView extends ImageView {
private static final String TAG = "Touch";
// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix savedMatrix = new Matrix();
// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int ZOOM = 2;
int mode = NONE;
// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
Context context;
public TouchImageView(Context context) {
super(context);
super.setClickable(true);
this.context = context;
matrix.setTranslate(1f, 1f);
setImageMatrix(matrix);
setScaleType(ScaleType.MATRIX);
setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent rawEvent) {
WrapMotionEvent event = WrapMotionEvent.wrap(rawEvent);
// Dump touch event to log
if (Viewer.isDebug == true){
dumpEvent(event);
}
// Handle touch events here...
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
Log.d(TAG, "mode=DRAG");
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
Log.d(TAG, "oldDist=" + oldDist);
if (oldDist > 10f) {
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
Log.d(TAG, "mode=ZOOM");
}
break;
case MotionEvent.ACTION_UP:
int xDiff = (int) Math.abs(event.getX() - start.x);
int yDiff = (int) Math.abs(event.getY() - start.y);
if (xDiff < 8 && yDiff < 8){
performClick();
}
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
Log.d(TAG, "mode=NONE");
break;
case MotionEvent.ACTION_MOVE:
if (mode == DRAG) {
// ...
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);
} else if (mode == ZOOM) {
float newDist = spacing(event);
Log.d(TAG, "newDist=" + newDist);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
}
}
break;
}
setImageMatrix(matrix);
return true; // indicate event was handled
}
});
}
public void setImage(Bitmap bm, int displayWidth, int displayHeight) {
super.setImageBitmap(bm);
//Fit to screen.
float scale;
if ((displayHeight / bm.getHeight()) >= (displayWidth / bm.getWidth())){
scale = (float)displayWidth / (float)bm.getWidth();
} else {
scale = (float)displayHeight / (float)bm.getHeight();
}
savedMatrix.set(matrix);
matrix.set(savedMatrix);
matrix.postScale(scale, scale, mid.x, mid.y);
setImageMatrix(matrix);
// Center the image
float redundantYSpace = (float)displayHeight - (scale * (float)bm.getHeight()) ;
float redundantXSpace = (float)displayWidth - (scale * (float)bm.getWidth());
redundantYSpace /= (float)2;
redundantXSpace /= (float)2;
savedMatrix.set(matrix);
matrix.set(savedMatrix);
matrix.postTranslate(redundantXSpace, redundantYSpace);
setImageMatrix(matrix);
}
/** Show an event in the LogCat view, for debugging */
private void dumpEvent(WrapMotionEvent event) {
// ...
String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",
"POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
StringBuilder sb = new StringBuilder();
int action = event.getAction();
int actionCode = action & MotionEvent.ACTION_MASK;
sb.append("event ACTION_").append(names[actionCode]);
if (actionCode == MotionEvent.ACTION_POINTER_DOWN
|| actionCode == MotionEvent.ACTION_POINTER_UP) {
sb.append("(pid ").append(
action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
sb.append(")");
}
sb.append("[");
for (int i = 0; i < event.getPointerCount(); i++) {
sb.append("#").append(i);
sb.append("(pid ").append(event.getPointerId(i));
sb.append(")=").append((int) event.getX(i));
sb.append(",").append((int) event.getY(i));
if (i + 1 < event.getPointerCount())
sb.append(";");
}
sb.append("]");
Log.d(TAG, sb.toString());
}
/** Determine the space between the first two fingers */
private float spacing(WrapMotionEvent event) {
// ...
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}
/** Calculate the mid point of the first two fingers */
private void midPoint(PointF point, WrapMotionEvent event) {
// ...
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}
}
WrapMotionEvent.java
import android.view.MotionEvent;
public class WrapMotionEvent {
protected MotionEvent event;
protected WrapMotionEvent(MotionEvent event) {
this.event = event;
}
static public WrapMotionEvent wrap(MotionEvent event) {
try {
return new EclairMotionEvent(event);
} catch (VerifyError e) {
return new WrapMotionEvent(event);
}
}
public int getAction() {
return event.getAction();
}
public float getX() {
return event.getX();
}
public float getX(int pointerIndex) {
verifyPointerIndex(pointerIndex);
return getX();
}
public float getY() {
return event.getY();
}
public float getY(int pointerIndex) {
verifyPointerIndex(pointerIndex);
return getY();
}
public int getPointerCount() {
return 1;
}
public int getPointerId(int pointerIndex) {
verifyPointerIndex(pointerIndex);
return 0;
}
private void verifyPointerIndex(int pointerIndex) {
if (pointerIndex > 0) {
throw new IllegalArgumentException(
"Invalid pointer index for Donut/Cupcake");
}
}
}
EclairMotionEvent.java
import android.view.MotionEvent;
public class EclairMotionEvent extends WrapMotionEvent {
protected EclairMotionEvent(MotionEvent event) {
super(event);
}
public float getX(int pointerIndex) {
return event.getX(pointerIndex);
}
public float getY(int pointerIndex) {
return event.getY(pointerIndex);
}
public int getPointerCount() {
return event.getPointerCount();
}
public int getPointerId(int pointerIndex) {
return event.getPointerId(pointerIndex);
}
}
decimal is for fixed quantities like money where you want a specific number of decimal places. Floats are for storing ... floating point precision numbers.
You don't need to parse the string, it's defined as a string already.
Just do:
private static String getStringInput (String prompt) {
String input = EZJ.getUserInput(prompt);
return input;
}
Try to put all your <script ...></script>
tags before the </body>
tag. Perhaps the js is trying to access an object of the DOM before it's built up.
Onfous And onblur Text box with javascript
<input type="text" value="A new value" onfocus="if(this.value=='A new value') this.value='';" onblur="if(this.value=='') this.value='A new value';"/>
Maybe a simpler solution is to set an overlay in front of your map using FrameLayout
or RelativeLayout
and treating them as regular buttons in your activity. You should declare your layers in back to front order, e.g., map before buttons. I modified your layout, simplified it a little bit. Try the following layout and see if it works for you:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MapActivity" >
<fragment xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/map"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:scrollbars="vertical"
class="com.google.android.gms.maps.SupportMapFragment"/>
<RadioGroup
android:id="@+id/radio_group_list_selector"
android:layout_width="match_parent"
android:layout_height="48dp"
android:orientation="horizontal"
android:background="#80000000"
android:padding="4dp" >
<RadioButton
android:id="@+id/radioPopular"
android:layout_width="0dp"
android:layout_height="match_parent"
android:text="@string/Popular"
android:gravity="center_horizontal|center_vertical"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioAZ"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/AZ"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioCategory"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/Category"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton2"
android:textColor="@color/textcolor_radiobutton" />
<View
android:id="@+id/VerticalLine"
android:layout_width="1dip"
android:layout_height="match_parent"
android:background="#aaa" />
<RadioButton
android:id="@+id/radioNearBy"
android:layout_width="0dp"
android:layout_height="match_parent"
android:gravity="center_horizontal|center_vertical"
android:text="@string/NearBy"
android:layout_weight="1"
android:background="@drawable/shape_radiobutton3"
android:textColor="@color/textcolor_radiobutton" />
</RadioGroup>
</FrameLayout>
Hey I got the solution. I did not set the category as "Default". Also I was using the Main activity for the intent Data. Now i am using a different activity for the intent data. Thanks for the help. :)
Lalith's answer is correct.
You may also try this approach:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
invalidateOptionsMenu();
}
});
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
MenuItem settingsItem = menu.findItem(R.id.action_settings);
// set your desired icon here based on a flag if you like
settingsItem.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_launcher));
return super.onPrepareOptionsMenu(menu);
}
Sometimes you want to have your GridView as simple as:
<asp:GridView ID="grid" runat="server" />
You don't want to specify any BoundField, you just want to bind your grid to DataReader. The following code helped me to format DateTime in this situation.
protected void Page_Load(object sender, EventArgs e)
{
grid.RowDataBound += grid_RowDataBound;
// Your DB access code here...
// grid.DataSource = cmd.ExecuteReader(CommandBehavior.CloseConnection);
// grid.DataBind();
}
void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType != DataControlRowType.DataRow)
return;
var dt = (e.Row.DataItem as DbDataRecord).GetDateTime(4);
e.Row.Cells[4].Text = dt.ToString("dd.MM.yyyy");
}
The results shown here.
You can simply do it in JavaScript, with the help of the second - index - parameter of the filter
method:
var a = [2,3,4,5,5,4];
a.filter(function(value, index){ return a.indexOf(value) == index });
or in short hand
a.filter((v,i) => a.indexOf(v) == i)
The accepted answer works but can got complicated when I wanted to try adding Accept headers. This is what I ended up with. It seems simpler to me so I think I'll stick with it in the future:
client.DefaultRequestHeaders.Add("Accept", "application/*+xml;version=5.1");
client.DefaultRequestHeaders.Add("Authorization", "Basic " + authstring);
You might want to start with scapy.
Here's how I did it in Python using csv and the MySQL Connector:
import csv
import mysql.connector
credentials = dict(user='...', password='...', database='...', host='...')
connection = mysql.connector.connect(**credentials)
cursor = connection.cursor(prepared=True)
stream = open('filename.csv', 'rb')
csv_file = csv.DictReader(stream, skipinitialspace=True)
query = 'CREATE TABLE t ('
query += ','.join('`{}` VARCHAR(255)'.format(column) for column in csv_file.fieldnames)
query += ')'
cursor.execute(query)
for row in csv_file:
query = 'INSERT INTO t SET '
query += ','.join('`{}` = ?'.format(column) for column in row.keys())
cursor.execute(query, row.values())
stream.close()
cursor.close()
connection.close()
Key points
'rb'
binaryskipinitialspace
option.255
isn't wide enough you'll get errors on INSERT and have to start over.ALTER TABLE t MODIFY `Amount` DECIMAL(11,2);
ALTER TABLE t ADD `id` INT PRIMARY KEY AUTO_INCREMENT;
To Enter into crontab :
crontab -e
write this into the file:
0 */2 * * * python/php/java yourfilepath
Example :0 */2 * * * python ec2-user/home/demo.py
and make sure you have keep one blank line after the last cron job in your crontab file
you need double quotes in all your three if
statements, eg.:
IF "%a%"=="2" (
@echo OFF &SETLOCAL ENABLEDELAYEDEXPANSION
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if "%a%"=="" goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if "!param1!"=="" goto :param1Prompt
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
USB Write is Unlocked!
)
)
pause
You can run chrome with the --unsafely-treat-insecure-origin-as-secure="http://example.com" flag (replacing "example.com" with the origin you actually want to test), which will treat that origin as secure for this session. Note that you also need to include the --user-data-dir=/test/only/profile/dir to create a fresh testing profile for the flag to work.
For example if use Windows, Click Start and run.
chrome --unsafely-treat-insecure-origin-as-secure="http://localhost:8100" --user-data-dir=C:\testprofile
A slight variation...
new File('/path/to/file').eachLine { line ->
println line
}
Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.
e.g. if you do this:
SELECT 1 / 2
you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.
e.g.
SELECT CAST(1 AS DECIMAL) / 2
gives 0.500000
My solution based on Mahdi Hijazi answer, but without any custom views:
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scrollHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:id="@+id/scrollVertical"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<WateverViewYouWant/>
</ScrollView>
</HorizontalScrollView>
final HorizontalScrollView hScroll = (HorizontalScrollView) value.findViewById(R.id.scrollHorizontal);
final ScrollView vScroll = (ScrollView) value.findViewById(R.id.scrollVertical);
vScroll.setOnTouchListener(new View.OnTouchListener() { //inner scroll listener
@Override
public boolean onTouch(View v, MotionEvent event) {
return false;
}
});
hScroll.setOnTouchListener(new View.OnTouchListener() { //outer scroll listener
private float mx, my, curX, curY;
private boolean started = false;
@Override
public boolean onTouch(View v, MotionEvent event) {
curX = event.getX();
curY = event.getY();
int dx = (int) (mx - curX);
int dy = (int) (my - curY);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
if (started) {
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
} else {
started = true;
}
mx = curX;
my = curY;
break;
case MotionEvent.ACTION_UP:
vScroll.scrollBy(0, dy);
hScroll.scrollBy(dx, 0);
started = false;
break;
}
return true;
}
});
You can change the order of the scrollviews. Just change their order in layout and in the code. And obviously instead of WateverViewYouWant you put the layout/views you want to scroll both directions.
For people who are using AppCompatActivity with Toolbar as white background. Do use this code.
Updated: December, 2017
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:theme="@style/ThemeOverlay.AppCompat.Light">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_edit"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:popupTheme="@style/AppTheme.AppBarOverlay"
app:title="Edit Your Profile"/>
</android.support.design.widget.AppBarLayout>
As of Git 2.19 you can simply:
git branch --sort=-committerdate
You can also:
git config branch.sort -committerdate
So whenever you list branches in the current repository, it will be listed sorted by committerdate.
If whenever you list branches, you want them sorted by comitterdate:
git config --global branch.sort -committerdate
Disclaimer: I'm the author of this feature in Git, and I implemented it when I saw this question.
To combine bitmasks you want to use bitwise-or. In the trivial case where every value you combine has exactly 1 bit on (like your example), it's equivalent to adding them. If you have overlapping bits however, or'ing them handles the case gracefully.
To decode the bitmasks you and your value with a mask, like so:
if(val & (1<<1)) SusanIsOn();
if(val & (1<<2)) BobIsOn();
if(val & (1<<3)) KarenIsOn();
shell_exec('mv filename dest_filename');
Try calling setWillNotDraw(false)
from surfaceCreated
:
public void surfaceCreated(SurfaceHolder holder) {
try {
setWillNotDraw(false);
mycam.setPreviewDisplay(holder);
mycam.startPreview();
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG,"Surface not created");
}
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(area, rectanglePaint);
Log.w(this.getClass().getName(), "On Draw Called");
}
and calling invalidate
from onTouchEvent
:
public boolean onTouch(View v, MotionEvent event) {
invalidate();
return true;
}
What's wrong with self.left = None
?
to make UITableView sections header not sticky or sticky:
change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)
if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)
class tile_tree_apple should be defined in a separate .h file.
tta.h:
#include "tile.h"
class tile_tree_apple : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree;};
void onCreate() {health=rand()%5+4; type=TILET_TREE_APPLE;};
tile onUse() {return *new tile_tree;};
};
file tt.h
#include "tile.h"
class tile_tree : public tile
{
public:
tile onDestroy() {return *new tile_grass;};
tile tick() {if (rand()%20==0) return *new tile_tree_apple;};
void onCreate() {health=rand()%5+4; type=TILET_TREE;};
};
another thing: returning a tile and not a tile reference is not a good idea, unless a tile is a primitive or very "small" type.
I think for REST, you just have to make a decision on the behavior for that particular system in which case, I think the "right" answer would be one of a couple answers given here. If you want the request to stop and behave as if the client made a mistake that it needs to fix before continuing, then use 409. If the conflict really isn't that important and want to keep the request going, then respond by redirecting the client to the entity that was found. I think proper REST APIs should be redirecting (or at least providing the location header) to the GET endpoint for that resource following a POST anyway, so this behavior would give a consistent experience.
EDIT: It's also worth noting that you should consider a PUT since you're providing the ID. Then the behavior is simple: "I don't care what's there right now, put this thing there." Meaning, if nothing is there, it'll be created; if something is there it'll be replaced. I think a POST is more appropriate when the server manages that ID. Separating the two concepts basically tells you how to deal with it (i.e. PUT is idempotent so it should always work so long as the payload validates, POST always creates, so if there is a collision of IDs, then a 409 would describe that conflict).
You need to tell the run to wait until the process is finished. Something like:
const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished
In the script itself, start Excel like so. While debugging start visible:
File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true
Sorry for misunderstanding, from what I understood you want your DIV to have three different colors with different heights. This is the output of my code:
,
If this is what you want try this code:
div {_x000D_
height: 100px;_x000D_
width:400px;_x000D_
position: relative;_x000D_
}_x000D_
.c {_x000D_
background: blue; /* Old browsers */_x000D_
}_x000D_
_x000D_
.c:after{_x000D_
content: '';_x000D_
position: absolute;_x000D_
width:20%;_x000D_
left:0;_x000D_
height:110%;_x000D_
background: yellow;_x000D_
}_x000D_
.c:before{_x000D_
content: '';_x000D_
position: absolute;_x000D_
width:40%;_x000D_
left:60%;_x000D_
height:140%;_x000D_
background: green;_x000D_
}
_x000D_
<div class="c"></div>
_x000D_
I want to mention some other scenario when the real-time is much much bigger than user + sys. I've created a simple server which respondes after a long time
real 4.784
user 0.01s
sys 0.01s
the issue is that in this scenario the process waits for the response which is not on the user site nor in the system.
Something similar happens when you run the find
command. In that case, the time is spent mostly on requesting and getting a response from SSD.
I too needed a rounded ImageView, I used the below code, you can modify it accordingly:
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class RoundedImageView extends ImageView {
public RoundedImageView(Context context) {
super(context);
}
public RoundedImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onDraw(Canvas canvas) {
Drawable drawable = getDrawable();
if (drawable == null) {
return;
}
if (getWidth() == 0 || getHeight() == 0) {
return;
}
Bitmap b = ((BitmapDrawable) drawable).getBitmap();
Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);
int w = getWidth();
@SuppressWarnings("unused")
int h = getHeight();
Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
canvas.drawBitmap(roundBitmap, 0, 0, null);
}
public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
Bitmap sbmp;
if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
float factor = smallest / radius;
sbmp = Bitmap.createScaledBitmap(bmp,
(int) (bmp.getWidth() / factor),
(int) (bmp.getHeight() / factor), false);
} else {
sbmp = bmp;
}
Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final String color = "#BAB399";
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, radius, radius);
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(Color.parseColor(color));
canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
radius / 2 + 0.1f, paint);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(sbmp, rect, rect, paint);
return output;
}
}
There's our IDE / engine called Codea.
The runtime is iOS only, but it's open source. The development environment is iPad only at the moment.
Lodash is inspired by Underscore.js, but nowadays it is a superior solution. You can make your custom builds, have a higher performance, support AMD and have great extra features. Check this Lodash vs. Underscore.js benchmarks on jsperf and... this awesome post about Lodash:
One of the most useful feature when you work with collections, is the shorthand syntax:
var characters = [
{ 'name': 'barney', 'age': 36, 'blocked': false },
{ 'name': 'fred', 'age': 40, 'blocked': true }
];
// Using "_.filter" callback shorthand
_.filter(characters, { 'age': 36 });
// Using Underscore.js
_.filter(characters, function(character) { return character.age === 36; } );
// ? [{ 'name': 'barney', 'age': 36, 'blocked': false }]
(taken from Lodash documentation)
?library
and you will see:
library(package)
andrequire(package)
both load the package with namepackage
and put it on the search list.require
is designed for use inside other functions; it returnsFALSE
and gives a warning (rather than an error aslibrary()
does by default) if the package does not exist. Both functions check and update the list of currently loaded packages and do not reload a package which is already loaded. (If you want to reload such a package, calldetach(unload = TRUE)
orunloadNamespace
first.) If you want to load a package without putting it on the search list, userequireNamespace
.
Java allows you to create "ragged arrays" where each "row" has different lengths. If you know you have a square array, you can use your code modified to protect against an empty array like this:
if (row > 0) col = test[0].length;
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
I would simply use scipy.stats.itemfreq in the following manner:
from scipy.stats import itemfreq
a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
freq = itemfreq(a)
a = freq[:,0]
b = freq[:,1]
you may check the documentation here: http://docs.scipy.org/doc/scipy-0.16.0/reference/generated/scipy.stats.itemfreq.html
#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}
Output: "
Your asp.net account {MACHINE}\ASPNET
does not have write access to that location. That is the reason why its failing.
Consider granting access rights to the resource to the ASP.NET request identity.
Right click on downloading folder Properties > Security Tab > Edit > Add > locations > choose your local machine > click OK > Type ASPNET below "Enter the object name to select" > Click Check Names
Check the boxes for the desired access (Full Control
). If it will not work for you do the same with Network Service
Now this should show your local {MACHINENAME}\ASPNET
account, then you set the write permission to this account.
Otherwise if the application is impersonating via <identity impersonate="true"/>
, the identity will be the anonymous user (typically IUSR_MACHINENAME
) or the authenticated request user.
Or just use dedicated location for storing files in ASP.NET which is App_Data
. To create it right click on your ASP.NET Project (in Visual Studio) Add > Add ASP.NET Folder > App_Data
. Then you'll be able to save data to this location:
var path = Server.MapPath("~/App_Data/file.txt");
System.IO.File.WriteAllText(path, "Hello World");
If you're using github you can use the website for this:
github.com/url/to/your/repo/compare/SHA_of_tip_of_one_branch...SHA_of_tip_of_another_branch
That will show you a compare of the two.
I believe the WAVE module does not support recording, just processing existing files. You might want to look at PyAudio for actually recording. WAV is about the world's simplest file format. In paInt16 you just get a signed integer representing a level, and closer to 0 is quieter. I can't remember if WAV files are high byte first or low byte, but something like this ought to work (sorry, I'm not really a python programmer:
from array import array
# you'll probably want to experiment on threshold
# depends how noisy the signal
threshold = 10
max_value = 0
as_ints = array('h', data)
max_value = max(as_ints)
if max_value > threshold:
# not silence
PyAudio code for recording kept for reference:
import pyaudio
import sys
chunk = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=chunk)
print "* recording"
for i in range(0, 44100 / chunk * RECORD_SECONDS):
data = stream.read(chunk)
# check for silence here by comparing the level with 0 (or some threshold) for
# the contents of data.
# then write data or not to a file
print "* done"
stream.stop_stream()
stream.close()
p.terminate()
SQLSTATE[HY093]: Invalid parameter number: parameter was not defined
Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.
These are the possible errors and their solutions:
There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.
You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)
If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.
// Code snippet
$column_names = array();
$stmt->bindParam(':'.$i, $column_names[$i], $param_type);
$stmt->bindValue(':'.$i, $values[$i], $param_type);
$i++;
//.....
When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.
Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.
import
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
One thing to be wary of is mobile devices, since they implement the idea of the viewport in an 'unusual' way:
As such, using position: fixed;
(as i've seen recommended in other places) usually isn't the way to go. Of course, it depends upon the exact behaviour you're after.
What I've used, and has worked well on desktop and mobile, is:
<body>
<div id="footer"></div>
</body>
with
body {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
padding: 0;
margin: 0;
}
#footer {
position: absolute;
bottom: 0;
}
To get the value of my drop down box on page load, I use
document.addEventListener('DOMContentLoaded',fnName);
Hope this helps some one.
The (A==B).all()
solution is very neat, but there are some built-in functions for this task. Namely array_equal
, allclose
and array_equiv
.
(Although, some quick testing with timeit
seems to indicate that the (A==B).all()
method is the fastest, which is a little peculiar, given it has to allocate a whole new array.)
You can try the following code:
background-image:url('url of your image') 10px 10px no-repeat
You can't. See the Git FAQ.
Currently the design of the git index (staging area) only permits files to be listed, and nobody competent enough to make the change to allow empty directories has cared enough about this situation to remedy it.
Directories are added automatically when adding files inside them. That is, directories never have to be added to the repository, and are not tracked on their own.
You can say "
git add <dir>
" and it will add files in there.If you really need a directory to exist in checkouts you should create a file in it. .gitignore works well for this purpose; you can leave it empty, or fill in the names of files you expect to show up in the directory.
Come, let us recurse together.
def locations_of_substring(string, substring):
"""Return a list of locations of a substring."""
substring_length = len(substring)
def recurse(locations_found, start):
location = string.find(substring, start)
if location != -1:
return recurse(locations_found + [location], location+substring_length)
else:
return locations_found
return recurse([], 0)
print(locations_of_substring('this is a test for finding this and this', 'this'))
# prints [0, 27, 36]
No need for regular expressions this way.
you can use lftp, the swish army knife of downloading if you have bigger files you can add --use-pget-n=10
to command
lftp -c 'mirror --parallel=100 https://example.com/files/ ;exit'
Position the cursor inside the class, then press ALT + Ins and select Getters and Setters
from the contextual menu.
There are many ways to check the size, but as a developer we dont have much access to query meta tables, I find this solution very easy (Note: if you are getting error message ORA-01653 ‘The ORA-01653 error is caused because you need to add space to a tablespace.’)
--Size of All Table Space
--1. Used Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "USED SPACE(IN GB)" FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME
--2. Free Space
SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS "FREE SPACE(IN GB)" FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME
--3. Both Free & Used
SELECT USED.TABLESPACE_NAME, USED.USED_BYTES AS "USED SPACE(IN GB)", FREE.FREE_BYTES AS "FREE SPACE(IN GB)"
FROM
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS USED_BYTES FROM USER_SEGMENTS GROUP BY TABLESPACE_NAME) USED
INNER JOIN
(SELECT TABLESPACE_NAME,TO_CHAR(SUM(NVL(BYTES,0))/1024/1024/1024, '99,999,990.99') AS FREE_BYTES FROM USER_FREE_SPACE GROUP BY TABLESPACE_NAME) FREE
ON (USED.TABLESPACE_NAME = FREE.TABLESPACE_NAME);
Thanks
I realize this is a very old question, but I thought I would offer an analogy to help illustrate the fine answers above.
If you walk into a public library, you will find that the books are all arranged in a particular order (most likely the Dewey Decimal System, or DDS). This corresponds to the "clustered index" of the books. If the DDS# for the book you want was 005.7565 F736s
, you would start by locating the row of bookshelves that is labeled 001-099
or something like that. (This endcap sign at the end of the stack corresponds to an "intermediate node" in the index.) Eventually you would drill down to the specific shelf labelled 005.7450 - 005.7600
, then you would scan until you found the book with the specified DDS#, and at that point you have found your book.
But if you didn't come into the library with the DDS# of your book memorized, then you would need a second index to assist you. In the olden days you would find at the front of the library a wonderful bureau of drawers known as the "Card Catalog". In it were thousands of 3x5 cards -- one for each book, sorted in alphabetical order (by title, perhaps). This corresponds to the "non-clustered index". These card catalogs were organized in a hierarchical structure, so that each drawer would be labeled with the range of cards it contained (Ka - Kl
, for example; i.e., the "intermediate node"). Once again, you would drill in until you found your book, but in this case, once you have found it (i.e, the "leaf node"), you don't have the book itself, but just a card with an index number (the DDS#) with which you could find the actual book in the clustered index.
Of course, nothing would stop the librarian from photocopying all the cards and sorting them in a different order in a separate card catalog. (Typically there were at least two such catalogs: one sorted by author name, and one by title.) In principle, you could have as many of these "non-clustered" indexes as you want.
Yes, you could use a transparent div positioned over the iframe area, with a loader gif as only background.
Then you can attach an onload
event to the iframe:
$(document).ready(function() {
$("iframe#id").load(function() {
$("#loader-id").hide();
});
});
we can also calculate the binary for positive or negative numbers as below:
function toBinary(n){
let binary = "";
if (n < 0) {
n = n >>> 0;
}
while(Math.ceil(n/2) > 0){
binary = n%2 + binary;
n = Math.floor(n/2);
}
return binary;
}
console.log(toBinary(7));
console.log(toBinary(-7));
_x000D_
If I'm understanding you correctly, you should be able to do this in one query, joining table1 and table2 together:
INSERT INTO table3 { name, age, sex, city, id, number}
SELECT p.name, p.age, p.sex, p.city, p.id, c.number
FROM table1 p
INNER JOIN table2 c ON c.Id = p.Id
I got this problem when insert wrong file address into .htaccess
php_value auto_prepend_file "/home/user/wrong/address/config.php"
So if you use auto_prepend_file check your file path. It called from .htaccess
so PHP can't determine error file and line.
localStorage.username = 'blah'
If you're guaranteed to be on a modern browser. Though know your values will all be turned into strings.
Also has the handy benefit of being cached between reloads.
You need to use the scrollTop
property.
document.getElementById('box').scrollTop
#An example for counting matched groups
import re
pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"
res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String
While this question appears to already have been solved, the accepted answer didn't solve the problem for me on Firefox. Firefox (and possibly IE, though I haven't tried it) skip whitespaces while reading the contents of the "content" tag. While I completely understand why Mozilla would do that, it does bring its share of problems. The easiest workaround I found was to use non-breakable spaces instead of regular ones as shown below.
.noLineBreaks br:before{
content: '\a0'
}
I have tried pm2 : installation is easy and easy to use too; the result is satisfying. However, we have to take care of which edition of pm2 that we want. pm 2 runtime is the free edition, whereas pm2 plus and pm2 enterprise are not free.
As for Strongloop, my installation failed or was not complete, so I couldn't use it.
For those who are looking for simple answer
if (window.location.hash === "#_=_"){
history.replaceState
? history.replaceState(null, null, window.location.href.split("#")[0])
: window.location.hash = "";
}
How about this?
>>> s = '23.45678'
>>> int(float(s))
23
Or...
>>> int(Decimal(s))
23
Or...
>>> int(s.split('.')[0])
23
I doubt it's going to get much simpler than that, I'm afraid. Just accept it and move on.
It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied
.
One thing you can try is doing a user install of the package with pip install lxml --user
. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)
You can also run pip install
as a superuser with sudo pip install lxml
but it is not generally a good idea because it can cause issues with your system-level packages.
For types you can use is
and if it is your own viewcontroller class then you need to use isKindOfClass
like:
let vcOnTop = self.embeddedNav.viewControllers[self.embeddedNav.viewControllers.count-1]
if vcOnTop.isKindOfClass(VcShowDirections){
return
}
Off the top of my cat's head, make sure the div
you're trying to center is not set to width: 100%
.
If it is, then the rules set on the child divs are what will matter.
Assumptions: x
is the horizontal axis, and increases when moving from left to right.
y
is the vertical axis, and increases from bottom to top. (touch_x, touch_y)
is the
point selected by the user. (center_x, center_y)
is the point at the center of the
screen. theta
is measured counter-clockwise from the +x
axis. Then:
delta_x = touch_x - center_x
delta_y = touch_y - center_y
theta_radians = atan2(delta_y, delta_x)
Edit: you mentioned in a comment that y increases from top to bottom. In that case,
delta_y = center_y - touch_y
But it would be more correct to describe this as expressing (touch_x, touch_y)
in polar coordinates relative to (center_x, center_y)
. As ChrisF mentioned,
the idea of taking an "angle between two points" is not well defined.
"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)
So you can't do anything about it, it is the issue of the server.
But you could use try .. except
block to handle that exception:
from socket import error as SocketError
import errno
try:
response = urllib2.urlopen(request).read()
except SocketError as e:
if e.errno != errno.ECONNRESET:
raise # Not error we are looking for
pass # Handle error here.
You said:
I want them to always come out as Tanzanian time and not in the local times that various collaborator are in.
If this is the case, then you should not use UTC. All you need to do is to use a DATETIME
type in MySQL instead of a TIMESTAMP
type.
MySQL converts
TIMESTAMP
values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such asDATETIME
.)
If you are already using a DATETIME
type, then you must be not setting it by the local time to begin with. You'll need to focus less on the database, and more on your application code - which you didn't show here. The problem, and the solution, will vary drastically depending on language, so be sure to tag the question with the appropriate language of your application code.
This will be inside a function or script tag with custom CSS with classname as Custom
var board = document.createElement('div');
board.className = "Custom";
board.innerHTML = "your data";
console.log(count);
document.getElementById('notification').appendChild(board);
I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:
f (a,b)
previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.
I had the exact same problem, and it was fixed by doing a chmod 777 /dev/ttyUSB0
. I never had this error again, even though previously the only way to get it to work was to reboot the VM or unplug and replug the USB-to-serial adapter. I am running Ubuntu 10.04 (Lucid Lynx) VM on OS X.
I see that neither is faster. The compiler generates the same machine code in each condition with a different value.
if(a < 901)
cmpl $900, -4(%rbp)
jg .L2
if(a <=901)
cmpl $901, -4(%rbp)
jg .L3
My example if
is from GCC on x86_64 platform on Linux.
Compiler writers are pretty smart people, and they think of these things and many others most of us take for granted.
I noticed that if it is not a constant, then the same machine code is generated in either case.
int b;
if(a < b)
cmpl -4(%rbp), %eax
jge .L2
if(a <=b)
cmpl -4(%rbp), %eax
jg .L3
Yet another option would be:
SELECT * FROM mytable
WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');
Dir.new('/my/dir').each do |name|
...
end
For current datetime, you can use now() function in postgresql insert query.
You can also refer following link.
insert statement in postgres for data type timestamp without time zone NOT NULL,.
You can use android:stopWithTask="false"
in manifest as bellow, This means even if user kills app by removing it from tasklist, your service won't stop.
<service android:name=".service.StickyService"
android:stopWithTask="false"/>
You can change your secret special value to 0, and exploit C's default structure-member semantics
struct foo bar = { .id = 42, .current_route = new_route };
update(&bar);
will then pass 0 as members of bar unspecified in the initializer.
Or you can create a macro that will do the default initialization for you:
#define FOO_INIT(...) { .id = -1, .current_route = -1, .quux = -1, ## __VA_ARGS__ }
struct foo bar = FOO_INIT( .id = 42, .current_route = new_route );
update(&bar);
I had the same error message while trying to deploy the application. In Spring, the security configuration xml can be a different one from applicationContext.xml, usually applicationContext-security.xml inside WEB-INF folder. The changes to be applied are for web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
And the applicationContext.xml would look like:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http auto-config='true'>
<intercept-url pattern="/login.jsp" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/**" access="ROLE_USER" />
<form-login login-page='login.jsp'/>
</http>
</beans:beans>
Even after you make these changes, the namespace error will exist. To get rid of this, add the following jar files to the WEB-INF/lib and then to the library:
Just use the function plot
as follows
figure()
...
plot(t, a)
plot(t, b)
plot(t, c)
Alongside nmaier's answer, as he said you'll always receive code 1006. However, if you were to somehow theoretically receive other codes, here is code to display the results (via RFC6455).
var websocket;
if ("WebSocket" in window)
{
websocket = new WebSocket("ws://yourDomainNameHere.org/");
websocket.onopen = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was opened");
};
websocket.onclose = function (event) {
var reason;
alert(event.code);
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
if (event.code == 1000)
reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled.";
else if(event.code == 1001)
reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page.";
else if(event.code == 1002)
reason = "An endpoint is terminating the connection due to a protocol error";
else if(event.code == 1003)
reason = "An endpoint is terminating the connection because it has received a type of data it cannot accept (e.g., an endpoint that understands only text data MAY send this if it receives a binary message).";
else if(event.code == 1004)
reason = "Reserved. The specific meaning might be defined in the future.";
else if(event.code == 1005)
reason = "No status code was actually present.";
else if(event.code == 1006)
reason = "The connection was closed abnormally, e.g., without sending or receiving a Close control frame";
else if(event.code == 1007)
reason = "An endpoint is terminating the connection because it has received data within a message that was not consistent with the type of the message (e.g., non-UTF-8 [http://tools.ietf.org/html/rfc3629] data within a text message).";
else if(event.code == 1008)
reason = "An endpoint is terminating the connection because it has received a message that \"violates its policy\". This reason is given either if there is no other sutible reason, or if there is a need to hide specific details about the policy.";
else if(event.code == 1009)
reason = "An endpoint is terminating the connection because it has received a message that is too big for it to process.";
else if(event.code == 1010) // Note that this status code is not used by the server, because it can fail the WebSocket handshake instead.
reason = "An endpoint (client) is terminating the connection because it has expected the server to negotiate one or more extension, but the server didn't return them in the response message of the WebSocket handshake. <br /> Specifically, the extensions that are needed are: " + event.reason;
else if(event.code == 1011)
reason = "A server is terminating the connection because it encountered an unexpected condition that prevented it from fulfilling the request.";
else if(event.code == 1015)
reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified).";
else
reason = "Unknown reason";
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "The connection was closed for reason: " + reason);
};
websocket.onmessage = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "New message arrived: " + event.data);
};
websocket.onerror = function (event) {
$("#thingsThatHappened").html($("#thingsThatHappened").html() + "<br />" + "There was an error with your websocket.");
};
}
else
{
alert("Websocket is not supported by your browser");
return;
}
websocket.send("Yo wazzup");
websocket.close();
Please note, buttons and other elements in API 21 and greater have a high elevation, and therefore ignore the xml order of elements regardless of parent layout. Took me a while to figure that one out.
For writing any Text to a file.
public static void WriteToFile(string DirectoryPath,string FileName,string Text)
{
//Check Whether directory exist or not if not then create it
if(!Directory.Exists(DirectoryPath))
{
Directory.CreateDirectory(DirectoryPath);
}
string FilePath = DirectoryPath + "\\" + FileName;
//Check Whether file exist or not if not then create it new else append on same file
if (!File.Exists(FilePath))
{
File.WriteAllText(FilePath, Text);
}
else
{
Text = $"{Environment.NewLine}{Text}";
File.AppendAllText(FilePath, Text);
}
}
For reading a Text from file
public static string ReadFromFile(string DirectoryPath,string FileName)
{
if (Directory.Exists(DirectoryPath))
{
string FilePath = DirectoryPath + "\\" + FileName;
if (File.Exists(FilePath))
{
return File.ReadAllText(FilePath);
}
}
return "";
}
For Reference here this is the official microsoft document link.
See this question: Converting data.frame to xts order.by requires an appropriate time-based object, which suggests looking at argument to order.by,
Currently acceptable classes include: ‘Date’, ‘POSIXct’, ‘timeDate’, as well as ‘yearmon’ and ‘yearqtr’ where the index values remain unique.
And further suggests an explicit conversion using order.by = as.POSIXct,
df$Date <- as.POSIXct(strptime(df$Date,format),tz="UTC")
xts(df[, -1], order.by=as.POSIXct(df$Date))
Where your format is assigned elswhere,
format <- "%m/%d/%Y" #see strptime for details
For all the databases you have on the server:
mysql> SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;
Output:
+----------------------------+---------+--------------------+
| database | charset | collation |
+----------------------------+---------+--------------------+
| information_schema | utf8 | utf8_general_ci |
| my_database | latin1 | latin1_swedish_ci |
...
+----------------------------+---------+--------------------+
For a single Database:
mysql> USE my_database;
mysql> show variables like "character_set_database";
Output:
+----------------------------+---------+
| Variable_name | Value |
+----------------------------+---------+
| character_set_database | latin1 |
+----------------------------+---------+
Getting the collation for Tables:
mysql> USE my_database;
mysql> SHOW TABLE STATUS WHERE NAME LIKE 'my_tablename';
OR - will output the complete SQL for create table:
mysql> show create table my_tablename
Getting the collation of columns:
mysql> SHOW FULL COLUMNS FROM my_tablename;
output:
+---------+--------------+--------------------+ ....
| field | type | collation |
+---------+--------------+--------------------+ ....
| id | int(10) | (NULL) |
| key | varchar(255) | latin1_swedish_ci |
| value | varchar(255) | latin1_swedish_ci |
+---------+--------------+--------------------+ ....
execl("/home/vlc",
"/home/vlc", "/home/my movies/the movie i want to see.mkv",
(char*) NULL);
You need to specify all arguments, included argv[0]
which isn't taken from the executable.
Also make sure the final NULL
gets cast to char*
.
Details are here: http://pubs.opengroup.org/onlinepubs/9699919799/functions/exec.html
I had this problem and it was caused by the second level cache:
Hence, because the cache wasn't invalidated, hibernate assumed that it was dealing with a detached instance of the same entity.
Hope this helps :-)
if(isset($_POST['submit'])){
ini_set("post_max_size", "30M");
ini_set("upload_max_filesize", "30M");
ini_set("memory_limit", "20000M");
$fileName='product_demo.png';
if($_FILES['imgproduct']['size'] > 0 &&
(($_FILES["imgproduct"]["type"] == "image/gif") ||
($_FILES["imgproduct"]["type"] == "image/jpeg")||
($_FILES["imgproduct"]["type"] == "image/pjpeg") ||
($_FILES["imgproduct"]["type"] == "image/png") &&
($_FILES["imgproduct"]["size"] < 2097152))){
if ($_FILES["imgproduct"]["error"] > 0){
echo "Return Code: " . $_FILES["imgproduct"]["error"] . "<br />";
} else {
$rnd=rand(100,999);
$rnd=$rnd."_";
$fileName = $rnd.trim($_FILES['imgproduct']['name']);
$tmpName = $_FILES['imgproduct']['tmp_name'];
$fileSize = $_FILES['imgproduct']['size'];
$fileType = $_FILES['imgproduct']['type'];
$target = "upload/";
echo $target = $target .$rnd. basename( $_FILES['imgproduct']['name']) ;
move_uploaded_file($_FILES['imgproduct']['tmp_name'], $target);
}
} else {
echo "Sorry, there was a problem uploading your file.";
}
}
Singleton pattern
public class MyClass() {
private static MyClass instance = null;
/**
* Get instance of my class, Singleton
**/
public static MyClass getInstance() {
if(instance == null) {
instance = new MyClass();
}
return instance;
}
/**
* Private constructor
*/
private MyClass() {
//This will only be called once, by calling getInstanse() method.
}
}
these methods can help setTitle("your new title"); or super("your new title");
A way to replace it with a java 8 stream:
public static void main(String[] args) throws IOException
{
String test = "ab19198zxncvl1308j10923.";
StringBuilder result = new StringBuilder();
test.chars().mapToObj( i-> (char)i ).filter( c -> Character.isDigit(c) || c == '.' ).forEach( c -> result.append(c) );
System.out.println( result ); //returns 19198.130810923.
}
To be more precise, I would use nanoTime()
method rather than currentTimeMillis()
:
long startTime = System.nanoTime();
myCall();
long stopTime = System.nanoTime();
System.out.println(stopTime - startTime);
In Java 8 (output format is ISO-8601):
Instant start = Instant.now();
Thread.sleep(63553);
Instant end = Instant.now();
System.out.println(Duration.between(start, end)); // prints PT1M3.553S
Guava Stopwatch:
Stopwatch stopwatch = Stopwatch.createStarted();
myCall();
stopwatch.stop(); // optional
System.out.println("Time elapsed: "+ stopwatch.elapsed(TimeUnit.MILLISECONDS));
button1, button2 and button3 have same even handler
private void button1_Click(Object sender, EventArgs e)
{
Button btnSender = (Button)sender;
if (btnSender == button1 || btnSender == button2)
{
//some code here
}
else if (btnSender == button3)
//some code here
}
Just in case somebody needs to check the condition from session.Usage of or
<c:if test="${sessionScope['roleid'] == 1 || sessionScope['roleid'] == 4}">
You can use Ra-Ajax and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for anything)
Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this Ajax RSS parser is loading the RSS items in the source which can be downloaded here (Open Source - LGPL)
(Disclaimer; I work with Ra-Ajax...)
First
check if you have both java 32 and 64 bit install then
Setting Path on Windows
Windows 8
Drag the Mouse pointer to the Right bottom corner of the screen
Click on the Search icon and type: Control Panel
Click on -> Control Panel -> System -> Advanced
Click on Environment Variables, under System Variables, find PATH, and click on it.
In the Edit windows, modify PATH by adding the location of the class to the value for PATH, Or simply make sure that the variable name is in ALL CAPS
If you do not have the item PATH, you may select to add a new variable and add PATH as the name and the location of the class as the value.
Close the window.
Reopen Command prompt window, and run your java code.
Because the URL isn't on the same domain as your website, you need to use JSONP.
For example: (In jQuery):
$.getJSON(
'http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?',
function(data) { ... }
);
This works by creating a <script>
tag like this one:
<script src="http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=someFunction" type="text/javascript"></script>
Their server then emits Javascript that calls someFunction
with the data to retrieve.
`someFunction is an internal callback generated by jQuery that then calls your callback.
To do it by using f-string and with control of the number of trailing digits:
print(f'A number -> {my_number:>20.5f}')
(Following is a late but complete answer)
FileReader.readAsBinaryString()
is deprecated. Don't use it! It's no longer in the W3C File API working draft:
void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);
NB: Note that File
is a kind of extended Blob
structure.
Mozilla still implements readAsBinaryString()
and describes it in MDN FileApi documentation:
void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);
The reason behind readAsBinaryString()
deprecation is in my opinion the following: the standard for JavaScript strings are DOMString
which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.
We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob
and typed arrays
(ArrayBuffer
and the not-yet-implemented but not necessary StringView
) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.
XMLHttpRequest.send()
has the following invocations options:
void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
XMLHttpRequest.sendAsBinary()
has the following invocations options:
void sendAsBinary( in DOMString body );
sendAsBinary() is NOT a standard and may not be supported in Chrome.
So you have several options:
send()
the FileReader.result
of FileReader.readAsArrayBuffer ( fileObject )
. It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.send()
the FileReader.result
of FileReader.readAsDataURL( fileObject )
. It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.sendAsBinary()
the FileReader.result
of FileReader.readAsBinaryString( fileObject )
MDN states that:
The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.
You can do it with few lines of CSS code. You can align all div's which you want to appear next to each other to right.
<div class="div_r">First Element</div>
<div class="div_r">Second Element</div>
<style>
.div_r{
float:right;
color:red;
}
</style>
Your problem is that each time you run the method you are assigning a new value to the constant. This is not allowed, as it makes the constant non-constant; even though the contents of the string are the same (for the moment, anyhow), the actual string object itself is different each time the method is called. For example:
def foo
p "bar".object_id
end
foo #=> 15779172
foo #=> 15779112
Perhaps if you explained your use case—why you want to change the value of a constant in a method—we could help you with a better implementation.
Perhaps you'd rather have an instance variable on the class?
class MyClass
class << self
attr_accessor :my_constant
end
def my_method
self.class.my_constant = "blah"
end
end
p MyClass.my_constant #=> nil
MyClass.new.my_method
p MyClass.my_constant #=> "blah"
If you really want to change the value of a constant in a method, and your constant is a String or an Array, you can 'cheat' and use the #replace
method to cause the object to take on a new value without actually changing the object:
class MyClass
BAR = "blah"
def cheat(new_bar)
BAR.replace new_bar
end
end
p MyClass::BAR #=> "blah"
MyClass.new.cheat "whee"
p MyClass::BAR #=> "whee"
I like pospi's suggestion. Why not go all-out any use the 'tag' property of a view (which you can specify in XML - 'android:tag') to specify any additional styling that you can't do in XML. I like JSON so I'd use a JSON string to specify a key/value set. This class does the work - just call Style.setContentView(this, [resource id])
in your activity.
public class Style {
/**
* Style a single view.
*/
public static void apply(View v) {
if (v.getTag() != null) {
try {
JSONObject json = new JSONObject((String)v.getTag());
if (json.has("typeface") && v instanceof TextView) {
((TextView)v).setTypeface(Typeface.createFromAsset(v.getContext().getAssets(),
json.getString("typeface")));
}
}
catch (JSONException e) {
// Some views have a tag without it being explicitly set!
}
}
}
/**
* Style the passed view hierarchy.
*/
public static View applyTree(View v) {
apply(v);
if (v instanceof ViewGroup) {
ViewGroup g = (ViewGroup)v;
for (int i = 0; i < g.getChildCount(); i++) {
applyTree(g.getChildAt(i));
}
}
return v;
}
/**
* Inflate, style, and set the content view for the passed activity.
*/
public static void setContentView(Activity activity, int resource) {
activity.setContentView(applyTree(activity.getLayoutInflater().inflate(resource, null)));
}
}
Obviously you'd want to handle more than just the typeface to make using JSON worthwhile.
A benefit of the 'tag' property is that you can set it on a base style which you use as a theme and thus have it apply to all of your views automatically. EDIT: Doing this results in a crash during inflation on Android 4.0.3. You can still use a style and apply it to text views individually.
One thing you'll see in the code - some views have a tag without one being explicitly set - bizarrely it's the string '?p???p?' - which is 'cut' in greek, according to google translate! What the hell...?
I did a table for changing order of obj in database used .after() .before(), so this is from what i have experiment.
$(obj1).after($(obj2))
Is insert obj1 before obj2 and
$(obj1).before($(obj2))
do the vice versa.
So if obj1 is after obj3 and obj2 after of obj4, and if you want to change place obj1 and obj2 you will do it like
$(obj1).before($(obj4))
$(obj2).before($(obj3))
This should do it BTW you can use .prev() and .next() to find obj3 and obj4 if you didn't have some kind of index for it already.
For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
While this will not (note the leading space before the opening <?
tag)
<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
Also, this will not work either (the echo
will break it):
<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>
I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.
add ob_start ();
at the top and at the end add ob_end_flush();
<?php
ob_start();
require('fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
ob_end_flush();
?>
give me an error as below:
FPDF error: Some data has already been output, can't send PDF
to over come this error:
go to fpdf.php
in that,goto line number 996
function Output($name='', $dest='')
after that make changes like this:
function Output($name='', $dest='') {
ob_clean(); //Output PDF to so
Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.
<?
while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);
?>
cheers :-)
In my case i had set:
ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);
When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off
the display_errors
option, the report was generated successfully.
//go through this code I have made several changes in it//
import java.util.Scanner;
public class addContact {
public static void main(String [] args){
//declare arrays
String [] contactName = new String [12];
String [] contactPhone = new String [12];
String [] contactAdd1 = new String [12];
String [] contactAdd2 = new String [12];
int i=0;
String name = "0";
String phone = "0";
String add1 = "0";
String add2 = "0";
//method of taken input
Scanner input = new Scanner(System.in);
//while name field is empty display prompt etc.
while (i<11)
{
i++;
System.out.println("Enter contacts name: "+ i);
name = input.nextLine();
name += contactName[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline1:");
add1 = input.nextLine();
add1 += contactAdd1[i];
}
while (i<12)
{
i++;
System.out.println("Enter contacts addressline2:");
add2 = input.nextLine();
add2 += contactAdd2[i];
}
while (i<12)
{
i++;
System.out.println("Enter contact phone number: ");
phone = input.nextLine();
phone += contactPhone[i];
}
}
}
Had the same problem. Used display and margin properties and it worked.
.background-image {
background: url('yourimage.jpg') no-repeat;
display: block;
margin-left: auto;
margin-right: auto;
height: whateveryouwantpx;
width: whateveryouwantpx;
}
Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.
In Kotlin language you can do it in this way:
val values = arrayOf(
"cat",
"dog",
"chicken"
)
ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
values
).also {
it.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinner.adapter = it
}
Simply .Contains() would do the work for you.
"Example String".Contains("amp"); //like '%amp%'
This would return true, and performing a select on it would return the desired output.
If you're behind a masquerading NAT (as most home users are these days), there is a limited pool of external ports, and these must be shared among the TCP connections. Therefore masquerading NATs tend to assume a connection has been terminated if no data has been sent for a certain time period.
This and other such issues (anywhere in between the two endpoints) can mean the connection will no longer "work" if you try to send data after a reasonble idle period. However, you may not discover this until you try to send data.
Using keepalives both reduces the chance of the connection being interrupted somewhere down the line, and also lets you find out about a broken connection sooner.
'make' is a command for UNIX/Linux. Instead of it, use 'nmake' command in MS Windows. Or you'd better use an emulator like CYGWIN.
Looking for a one line option:
<div class="jumbotron bg-dark"> got a team? </div>
You can convert groupby
object to tuples
and then to dict
:
df = pd.DataFrame({'Name':list('aabbef'),
'A':[4,5,4,5,5,4],
'B':[7,8,9,4,2,3],
'C':[1,3,5,7,1,0]}, columns = ['Name','A','B','C'])
print (df)
Name A B C
0 a 4 7 1
1 a 5 8 3
2 b 4 9 5
3 b 5 4 7
4 e 5 2 1
5 f 4 3 0
d = dict(tuple(df.groupby('Name')))
print (d)
{'b': Name A B C
2 b 4 9 5
3 b 5 4 7, 'e': Name A B C
4 e 5 2 1, 'a': Name A B C
0 a 4 7 1
1 a 5 8 3, 'f': Name A B C
5 f 4 3 0}
print (d['a'])
Name A B C
0 a 4 7 1
1 a 5 8 3
It is not recommended, but possible create DataFrames by groups:
for i, g in df.groupby('Name'):
globals()['df_' + str(i)] = g
print (df_a)
Name A B C
0 a 4 7 1
1 a 5 8 3
As you say, REST is good enough for banks so should be good enough for you.
There are two main aspects to security: 1) encryption and 2) identity.
Transmitting in SSL/HTTPS provides encryption over the wire. But you'll also need to make sure that both servers can confirm that they know who they are speaking to. This can be via SSL client certificates, shares secrets, etc.
I'm sure one could make the case that SOAP is "more secure" but probably not in any significant way. The nude motorcyclist analogy is cute but if accurate would imply that the whole internet is insecure.
You can try this script. :)
<html>
<head>
<title>Div BG color</title>
<script type="text/javascript">
function Off(idecko)
{
document.getElementById(idecko).style.background="rgba(0,0,0,0)"; <!--- Default --->
}
function cOn(idecko)
{
document.getElementById(idecko).style.background="rgb(0,60,255)"; <!--- New content color --->
}
function hOn(idecko)
{
document.getElementById(idecko).style.background="rgb(60,255,0)"; <!--- New h2 color --->
}
</script>
</head>
<body>
<div id="catestory">
<div class="content" id="myid1" onmouseover="cOn('myid1'); hOn('h21')" onmouseout="Off('myid1'); Off('h21')">
<h2 id="h21">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid2" onmouseover="cOn('myid2'); hOn('h22')" onmouseout="Off('myid2'); Off('h22')">
<h2 id="h22">some title here</h2>
<p>some content here</p>
</div>
<div class="content" id="myid3" onmouseover="cOn('myid3'); hOn('h23')" onmouseout="Off('myid3'); Off('h23')">
<h2 id="h23">some title here</h2>
<p>some content here</p>
</div>
</div>
</body>
<html>
This behaviour is terminal-specific and specified by the terminal emulator you use (e.g. xterm
) and the semantics of terminal that it provides. The terminal behaviour has been very stable for the last 20 years, and you can reasonably rely on the semantics of \b
.
I would like to propose different solution which wasn't mentioned here which is using .URL
files:
set SHRT_LOCA=%userprofile%\Desktop\new_shortcut2.url
set SHRT_DEST=C:\Windows\write.exe
echo [InternetShortcut]> %SHRT_LOCA%
echo URL=file:///%SHRT_DEST%>> %SHRT_LOCA%
echo IconFile=%SHRT_DEST%>> %SHRT_LOCA%
echo IconIndex=^0>> %SHRT_LOCA%
Notes:
.url
files are intended to open web pages but they are working fine for any properly constructed URI.url
file extension even if "Hide extensions for known file types" option in Windows Explorer is disabledIconFile
and IconIndex
are optionalWith arrays in php, the foreach loop is always a pretty solution.
In this case it could be for example:
foreach($my_array as $number => $number_array)
{
foreach($number_array as $data = > $user_data)
{
print "Array number: $number, contains $data with $user_data. <br>";
}
}
Your regex does not work because [] defines a character class, but what you want is a lookahead:
(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)
So try: (?!bush)
If you get this error message from the browser:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access
when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:
<?php header('Access-Control-Allow-Origin: *'); ?>
What you really need to do, especially if you only use JavaScript to do the Ajax request, is an internal proxy who takes your query and send it through to the remote server.
First in your JavaScript, do an Ajax call to your own server, something like:
$.ajax({
url: yourserver.com/controller/proxy.php,
async:false,
type: "POST",
dataType: "json",
data: data,
success: function (result) {
JSON.parse(result);
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr);
}
});
Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:
if (isset($_POST)) {
$apiKey = $_POST['apiKey'];
$cid = $_POST['cid'];
$minorRev = 99;
$url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;
echo json_encode(file_get_contents($url));
}
By doing:
echo json_encode(file_get_contents($url));
You are just doing the same query but on the server side and after that, it should works fine.
The file in question is not using the CP1252
encoding. It's using another encoding. Which one you have to figure out yourself. Common ones are Latin-1
and UTF-8
. Since 0x90 doesn't actually mean anything in Latin-1
, UTF-8
(where 0x90 is a continuation byte) is more likely.
You specify the encoding when you open the file:
file = open(filename, encoding="utf8")
You have to select "Refresh Dependencies" in the "Gradle" context menu that appears when you right-click the project in the Package Explorer.
You could add the time component
WHERE mydate<='2008-11-25 23:59:59'
but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:
WHERE mydate < '2008-11-26 00:00:00'
I use this
def cleaned( aFile ):
for line in aFile:
yield line.strip()
Then I can do things like this.
lines = list( cleaned( open("file","r") ) )
Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.
If you exclude application/
, then everything under it will always be excluded (even if some later negative exclusion pattern (“unignore”) might match something under application/
).
To do what you want, you have to “unignore” every parent directory of anything that you want to “unignore”. Usually you end up writing rules for this situation in pairs: ignore everything in a directory, but not some certain subdirectory.
# you can skip this first one if it is not already excluded by prior patterns
!application/
application/*
!application/language/
application/language/*
!application/language/gr/
Note
The trailing /*
is significant:
dir/
excludes a directory named dir
and (implicitly) everything under it.dir/
, Git will never look at anything under dir
, and thus will never apply any of the “un-exclude” patterns to anything under dir
.dir/*
says nothing about dir
itself; it just excludes everything under dir
.
With dir/*
, Git will process the direct contents of dir
, giving other patterns a chance to “un-exclude” some bit of the content (!dir/sub/
). To get the execution time as a variable in your proc:
DECLARE @EndTime datetime
DECLARE @StartTime datetime
SELECT @StartTime=GETDATE()
-- Write Your Query
SELECT @EndTime=GETDATE()
--This will return execution time of your query
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in millisecs]
AND see this
Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"
Just wanted to point out something about the solution said above several times:
git config credential.helper store
You can use any command that requires a password after this. You don't have to push. (you can also pull for instance) After that, you won't need to type in your username / password again.
Use \overleftarrow
to create a long arrow to the left.
\overleftarrow{blahblahblah}
How would I accomplish the nextsibling and is there an easier way of doing this?
You may use:
tr/td[@class='name']/following-sibling::td
but I'd rather use directly:
tr[td[@class='name'] ='Brand']/td[@class='desc']
This assumes that:
The context node, against which the XPath expression is evaluated is the parent of all tr
elements -- not shown in your question.
Each tr
element has only one td
with class
attribute valued 'name'
and only one td
with class
attribute valued 'desc'
.
Do you want to pass parameters to another page or to the function only?
If only the function, you don't need to add the $.ajax() tvanfosson added. Just add your function content instead. Like:
function DoAction (id, name ) {
// ...
// do anything you want here
alert ("id: "+id+" - name: "+name);
//...
}
This will return an alert box with the id and name values.
SELECT DATEDIFF(NOW(),pickup_date) AS noofday
FROM cir_order
WHERE DATEDIFF(NOW(),pickup_date)>2;
or
SELECT *
FROM cir_order
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )
The notation List<?>
means "a list of something (but I'm not saying what)". Since the code in test
works for any kind of object in the list, this works as a formal method parameter.
Using a type parameter (like in your point 3), requires that the type parameter be declared. The Java syntax for that is to put <T>
in front of the function. This is exactly analogous to declaring formal parameter names to a method before using the names in the method body.
Regarding List<Object>
not accepting a List<String>
, that makes sense because a String
is not Object
; it is a subclass of Object
. The fix is to declare public static void test(List<? extends Object> set) ...
. But then the extends Object
is redundant, because every class directly or indirectly extends Object
.
This one works for me:
<tr style="height: 15px;"/>
As of iOS 10 there is also a new block based Timer factory method which is cleaner than using the selector:
_ = Timer.scheduledTimer(withTimeInterval: 5, repeats: false) { timer in
label.isHidden = true
}
Make use of brackets /^\d{2}[.-/]\d{2}[.-/]\d{4}$/
http://download.oracle.com/javase/tutorial/essential/regex/char_classes.html
It is what it says, you just cannot instantiate an abstract class. You need to implement it first, then instantiate that class.
IUser user = new User();
Provide the following in the search dialog:
Find What: ^$\r\n
Replace With: (Leave it empty)
Click Replace All
HTML5 Validation Work Only When button type will be submit
change --
<button type="button" onclick="submitform()" id="save">Save</button>
To --
<button type="submit" onclick="submitform()" id="save">Save</button>
Try replacing your last line of gulpfile.js
gulp.task('default', ['server', 'watch']);
with
gulp.task('default', gulp.series('server', 'watch'));
You can use MDB Viewer Plus from http://www.alexnolan.net/software/mdb_viewer_plus.htm to view or edit your old version database
Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?
If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--
My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.
You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.
The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.
edit: Just to help you get started you can look here:
In Swift 2 you can do it in this way:
var dictionary: NSDictionary = ...
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedDataWithRootObject(dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObjectWithData(data!) as! NSDictionary
In Swift 3:
/* NSDictionary to NSData */
let data = NSKeyedArchiver.archivedData(withRootObject: dictionary)
/* NSData to NSDictionary */
let unarchivedDictionary = NSKeyedUnarchiver.unarchiveObject(with: data)
Hacking comments is not a very readable way to do it. Also editors will color it as a comment and someone may miss it when looking through the code.
Try something like this:
{{ ''; $hello = 'world' }}
It will compile into:
<?php echo ''; $hello = 'world'; ?>
...and do the assignment and not echo anything.
Same problem with Pipo S1S after upgrading to 4.2.2 stock rom Jun 4.
$ adb devices
List of devices attached
???????????? no permissions
All of the above suggestions, while valid to get your usb device recognised, do not solve the problem for me. (Android Debug Bridge version 1.0.31 running on Mint 15.)
Updating android sdk tools etc resets ~/.android/adb_usb.ini
.
To recognise Pipo VendorID 0x2207 do these steps
Add to line /etc/udev/rules.d/51-android.rules
SUBSYSTEM=="usb", ATTR{idVendor}=="0x2207", MODE="0666", GROUP="plugdev"
Add line to ~/.android/adb_usb.ini
:
0x2207
Then remove the adbkey files
rm -f ~/.android/adbkey ~/.android/adbkey.pub
and reconnect your device to rebuild the key files with a correct adb connection. Some devices will ask to re-authorize.
sudo adb kill-server
sudo adb start-server
adb devices
In my case, I install 32 Bit Python
so I cannot install Tensorflow, After uninstall 32 Bit Python
and install 64 Bit Python
, I can install tensorflow successfully.
After reinstall Python 64 bit
, you need to check your python install folder path is properly set in Windows Environment Path.
You can check Python version by typing python
in cmd.
Seriously this took my much valuable time but not found solution. Basically if you are taking data from sql then you are converting then you can follow these steps.
rows = cursor.fetchall()---- only tried on single column
dataset=[]
for x in rows:
dataset.append(float(x[0]))