Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.
$(function() {_x000D_
var theImage = $('ul#ss li img');_x000D_
var theWidth = theImage.width();_x000D_
//wrap into mother div_x000D_
$('ul#ss').wrap('<div id="mother" />');_x000D_
//assign height width and overflow hidden to mother_x000D_
$('#mother').css({_x000D_
width: function() {_x000D_
return theWidth;_x000D_
},_x000D_
height: function() {_x000D_
return theImage.height();_x000D_
},_x000D_
position: 'relative',_x000D_
overflow: 'hidden'_x000D_
});_x000D_
//get total of image sizes and set as width for ul _x000D_
var totalWidth = theImage.length * theWidth;_x000D_
$('ul').css({_x000D_
width: function() {_x000D_
return totalWidth;_x000D_
}_x000D_
});_x000D_
_x000D_
var ss_timer = setInterval(function() {_x000D_
ss_next();_x000D_
}, 3000);_x000D_
_x000D_
function ss_next() {_x000D_
var a = $(".active");_x000D_
a.removeClass('active');_x000D_
_x000D_
if (a.hasClass('last')) {_x000D_
//last element -- loop_x000D_
a.parent('ul').animate({_x000D_
"margin-left": (0)_x000D_
}, 1000);_x000D_
a.siblings(":first").addClass('active');_x000D_
} else {_x000D_
a.parent('ul').animate({_x000D_
"margin-left": (-(a.index() + 1) * theWidth)_x000D_
}, 1000);_x000D_
a.next().addClass('active');_x000D_
}_x000D_
}_x000D_
_x000D_
// Cancel slideshow and move next manually on click_x000D_
$('ul#ss li img').on('click', function() {_x000D_
clearInterval(ss_timer);_x000D_
ss_next();_x000D_
});_x000D_
_x000D_
});
_x000D_
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
#ss {_x000D_
list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
float: left;_x000D_
}_x000D_
#ss img {_x000D_
width: 200px;_x000D_
height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
<li class="active">_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
</li>_x000D_
<li>_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
</li>_x000D_
<li class="last">_x000D_
<img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
</li>_x000D_
</ul>
_x000D_
Use split and join method
$("#idBut").click(function() {
$("body").children().each(function() {
$(this).html($(this).html().split('@').join("$"));
});
});
here is solution
If you want every column and every row, then just pass in null
for the SQLiteDatabase
column
and selection
parameters.
Cursor cursor = db.query(TABLE_NAME, null, null, null, null, null, null, null);
The other answers use rawQuery
, but you can use Android's built in SQLiteDatabase
. The documentation for query
says that you can just pass in null
to the selection
parameter to get all the rows.
selection
Passing null will return all rows for the given table.
And while you can also pass in null
for the column
parameter to get all of the columns (as in the one-liner above), it is better to only return the columns that you need. The documentation says
columns
Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used.
Example
SQLiteDatabase db = mHelper.getReadableDatabase();
String[] columns = {
MyDatabaseHelper.COLUMN_1,
MyDatabaseHelper.COLUMN_2,
MyDatabaseHelper.COLUMN_3};
String selection = null; // this will select all rows
Cursor cursor = db.query(MyDatabaseHelper.MY_TABLE, columns, selection,
null, null, null, null, null);
I think this is what you want:
$friends = $facebook->api('/me/friends');
I was working with Spring REST, and I solved it adding the AllowedMethods into the WebMvcConfigurer.
@Value( "${app.allow.origins}" )
private String allowOrigins;
@Bean
public WebMvcConfigurer corsConfigurer() {
System.out.println("allow origin: "+allowOrigins);
return new WebMvcConfigurerAdapter() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//.allowedOrigins("http://localhost")
.allowedOrigins(allowOrigins)
.allowedMethods("PUT", "DELETE","GET", "POST");
}
};
}
Use this and it will work:
pip install --upgrade pip
pip install opencv-python
I just had the same problem, what I did, I arranged the library order in sequence, for example there were java.lang.NullPointerException and javacard.lang.NullPointerException. I made the first one as default library and if you needed to use the other you can explicitly specify the full qualified class name.
It is quite easy. Assuming you have a field(dateposted) with the type "timestamp" in your database table already queried and you want to display it, have it formated and also have the AM/PM, all you need do is shown below.
<?php
echo date("F j, Y h:m:s A" ,strtotime($row_rshearing['dateposted']));
?>
Note: Your OUTPUT should look some what like this depending on the date posted
May 21, 2014 03:05:27 PM
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
You probably just need to provide a user name and password in your connectionstring and set Integrated Security=false
In the comments of http://www.php.net/manual/de/function.mysql-db-name.php I found this one from ericpp % bigfoot.com:
If you just need the current database name, you can use MySQL's SELECT DATABASE() command:
<?php
function mysql_current_db() {
$r = mysql_query("SELECT DATABASE()") or die(mysql_error());
return mysql_result($r,0);
}
?>
Use This:
Update Table Set Column = CAST(NULL As Column Type) where Condition
Like This:
Update News Set Title = CAST(NULL As nvarchar(100)) Where ID = 50
A very good solution to this can be found here:
Here's a class that serves as a wrapper to a pyserial object. It allows you to read lines without 100% CPU. It does not contain any timeout logic. If a timeout occurs,
self.s.read(i)
returns an empty string and you might want to throw an exception to indicate the timeout.
It is also supposed to be fast according to the author:
The code below gives me 790 kB/sec while replacing the code with pyserial's readline method gives me just 170kB/sec.
class ReadLine:
def __init__(self, s):
self.buf = bytearray()
self.s = s
def readline(self):
i = self.buf.find(b"\n")
if i >= 0:
r = self.buf[:i+1]
self.buf = self.buf[i+1:]
return r
while True:
i = max(1, min(2048, self.s.in_waiting))
data = self.s.read(i)
i = data.find(b"\n")
if i >= 0:
r = self.buf + data[:i+1]
self.buf[0:] = data[i+1:]
return r
else:
self.buf.extend(data)
ser = serial.Serial('COM7', 9600)
rl = ReadLine(ser)
while True:
print(rl.readline())
You can use a HTML table:
<table>
<tr>
<td>
<div id="bloc1">your content</div>
</td>
<td>
<div id="bloc2">your content</div>
</td>
</tr>
</table>
If you need to do this once just follow Charles' descriptions, but it is also possible to do this with Excel formulas and helper columns in case you want to make the filter dynamic.
Lets assume you data is on the sheet DataSheet and starts in row 2 of the following columns:
You need two helper columns on this sheet.
=if(A2 = "", 1, 0)
, this is the filter column, corresponding to your where condition=if(D2 <> 1, "", sumifs(D$2:D$1048576, A$2:A$1048576, "<"&A2) + sumifs(D$2:D2, A$2:A2, A2))
, this corresponds to the order byCopy down these formulas as far as your data goes.
On the sheet which should display your result create the following columns.
=match(A2, DataSheet!$E$2:$E$1048576, 0)
, this is the row of the corresponding data=iferror(index(DataSheet!A$2:A$1048576, $B2), "")
, this is the actual data or empty if no data existsCopy down the formulas in B2 and C2 and copy-past column C to D and E.
2055786000 + 93552000 = 2149338000, which is greater than 2^31. So if you're using signed integers coded on 4 bytes, the result of the operation doesn't fit and you get an overflow exception.
<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>
Easy as that.
Or without JS
<a href="http://yahoo.com" target="_blank">test</a>
For Android 7, Galaxy S6 Edge:
If Developer Options is not available then
Now perform step 1. Now it should work, if its still not working then perform these steps. It worked for me.
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
The javadoc for Math.atan(double) is pretty clear that the returning value can range from -pi/2 to pi/2. So you need to compensate for that return value.
In windows server 2012, even after installing asp.net you might run into this issue.
Check for "Http activation" feature. This feature is present under Web services as well.
Make sure you add the above and everything should be awesome for you !!!
I think you are looking for this ?
$('#your_id').html('<p>name</p><p><span style="font-size:xx-small;">ajde</span></p><p><em>da</em></p>').text();
Your worst case scenario isn't as bad as you think.
You are already parsing the RSS feed, so you already have the image URLs. Say you have an image URL like http://otherdomain.com/someimage.jpg
. You rewrite this URL as https://mydomain.com/imageserver?url=http://otherdomain.com/someimage.jpg&hash=abcdeafad
. This way, the browser always makes request over https, so you get rid of the problems.
The next part - create a proxy page or servlet that does the following -
This solution has some advantages. You don't have to download the image at the time of creating the html. You don't have to store the images locally. Also, you are stateless; the url contains all the information necessary to serve the image.
Finally, the hash parameter is for security; you only want your servlet to serve images for urls you have constructed. So, when you create the url, compute md5(image_url + secret_key)
and append it as the hash parameter. Before you serve the request, recompute the hash and compare it to what was passed to you. Since the secret_key is only known to you, nobody else can construct valid urls.
If you are developing in java, the Servlet is just a few lines of code. You should be able to port the code below on any other back-end technology.
/*
targetURL is the url you get from RSS feeds
request and response are wrt to the browser
Assumes you have commons-io in your classpath
*/
protected void proxyResponse (String targetURL, HttpServletRequest request,
HttpServletResponse response) throws IOException {
GetMethod get = new GetMethod(targetURL);
get.setFollowRedirects(true);
/*
* Proxy the request headers from the browser to the target server
*/
Enumeration headers = request.getHeaderNames();
while(headers!=null && headers.hasMoreElements())
{
String headerName = (String)headers.nextElement();
String headerValue = request.getHeader(headerName);
if(headerValue != null)
{
get.addRequestHeader(headerName, headerValue);
}
}
/*Make a request to the target server*/
m_httpClient.executeMethod(get);
/*
* Set the status code
*/
response.setStatus(get.getStatusCode());
/*
* proxy the response headers to the browser
*/
Header responseHeaders[] = get.getResponseHeaders();
for(int i=0; i<responseHeaders.length; i++)
{
String headerName = responseHeaders[i].getName();
String headerValue = responseHeaders[i].getValue();
if(headerValue != null)
{
response.addHeader(headerName, headerValue);
}
}
/*
* Proxy the response body to the browser
*/
InputStream in = get.getResponseBodyAsStream();
OutputStream out = response.getOutputStream();
/*
* If the server sends a 204 not-modified response, the InputStream will be null.
*/
if (in !=null) {
IOUtils.copy(in, out);
}
}
You should use the preprocessor macro __LINE__
and __FILE__
. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.
Others preprocessor variables :
__func__
: function name (this is part of C99, not all C++ compilers support it)__DATE__
: a string of form "Mmm dd yyyy"__TIME__
: a string of form "hh:mm:ss"Your code will be :
if(!Logical)
printf("Not logical value at line number %d in file %s\n", __LINE__, __FILE__);
For my specific situation I only care about the equality of the object as far as keys and primitive values go. The solution that worked for me was converting the object to its JSON representation and using that as the hash. There are limitations such as order of key definition potentially being inconsistent; but like I said it worked for me because these objects were all being generated in one place.
var hashtable = {};
var myObject = {a:0,b:1,c:2};
var hash = JSON.stringify(myObject);
// '{"a":0,"b":1,"c":2}'
hashtable[hash] = myObject;
// {
// '{"a":0,"b":1,"c":2}': myObject
// }
Your return is useless if you don't assign it
list=defineAList()
I did it using Extension Functions
in kotlin
fun String.toDate(dateFormat: String = "yyyy-MM-dd HH:mm:ss", timeZone: TimeZone = TimeZone.getTimeZone("UTC")): Date {
val parser = SimpleDateFormat(dateFormat, Locale.getDefault())
parser.timeZone = timeZone
return parser.parse(this)
}
fun Date.formatTo(dateFormat: String, timeZone: TimeZone = TimeZone.getDefault()): String {
val formatter = SimpleDateFormat(dateFormat, Locale.getDefault())
formatter.timeZone = timeZone
return formatter.format(this)
}
Usage:
"2018-09-10 22:01:00".toDate().formatTo("dd MMM yyyy")
Output: "11 Sep 2018"
Note:
Ensure the proper validation.
If you really need "spring-boot-starter-data-jpa" as your project dependency and at the same time you don't want to allow your app to access any database, you can simply exclude auto-configuration classes
@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)
You can use this simple function. number_format ()
$num = 2214.56;
// default english notation
$english_format = number_format($num);
// 2,215
// French notation
$format_francais = number_format($num, 2, ',', ' ');
// 2 214,56
$num1 = 2234.5688;
// English notation with thousands separator
$english_format_number = number_format($num1,2);
// 2,234.57
// english notation without thousands separator
$english_format_number2 = number_format($num1, 2, '.', '');
// 2234.57
App rejection Note:
Finally UIWbView
is dead and Apple will not longer accept it.
Apple started sending email to all the App owner who are still using UIWebView
:
Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView
APIs.
Apple takes User Privacy very seriously and it is obvious that they won’t allow insecure webview.
So do remove UIWebView from your app as soon as possible. don't use try to use UIWebView
in new created app and I Prefer to using WKWebView
if possible
ITMS-90809: Deprecated API Usage - Apple will stop accepting submissions of apps that use UIWebView APIs . See https://developer.apple.com/documentation/uikit/uiwebview for more information.
Example:
import UIKit
import WebKit
class WebInfoController: UIViewController,WKNavigationDelegate {
var webView : WKWebView = {
var webview = WKWebView()
return webview
}()
var _fileName : String!
override func viewDidLoad() {
self.view.addSubview(webView)
webView.fillSuperview()
let url = Bundle.main.url(forResource: _fileName, withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
webView.load(request)
}
func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
print(error.localizedDescription)
}
func webView(webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Strat to load")
}
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
print("finish to load")
}
}
import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;
public class RadioButton extends JRadioButton {
public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
public Object[] getSelectedObjects() {
if ( isSelected() ) {
return new Object[] { RadioButton.this };
} else {
return new Object[0];
}
}
public RadioButton getButton() { return RadioButton.this; }
}
public RadioButton() { super(); setModel(new RadioButtonModel()); }
public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }
public static void main(String[] args) {
RadioButton b1 = new RadioButton("A");
RadioButton b2 = new RadioButton("B");
ButtonGroup group = new ButtonGroup();
group.add(b1);
group.add(b2);
b2.setSelected(true);
RadioButtonModel model = (RadioButtonModel)group.getSelection();
System.out.println(model.getButton().getText());
}
}
Here's an adaptation of CD Sanchez' answer that consistently returns a 6-digit colour code:
var stringToColour = function(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
Usage:
stringToColour("greenish");
// -> #9bc63b
Example:
(An alternative/simpler solution might involve returning an 'rgb(...)'-style colour code.)
In python3.x it can be done using :
# Converting lat/long to cartesian
import numpy as np
def get_cartesian(lat=None,lon=None):
lat, lon = np.deg2rad(lat), np.deg2rad(lon)
R = 6371 # radius of the earth
x = R * np.cos(lat) * np.cos(lon)
y = R * np.cos(lat) * np.sin(lon)
z = R *np.sin(lat)
return x,y,z
Actually, it is
private const int TheAnswer = 42;
At least if you look at the .NET library, which IMO is the best way to decide naming conventions - so your code doesn't look out of place.
You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter
attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter
that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter
attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter
, then specify the date format in the constructor of the subclass. Apply the JsonConverter
attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:
class CustomDateTimeConverter : IsoDateTimeConverter
{
public CustomDateTimeConverter()
{
base.DateTimeFormat = "yyyy-MM-dd";
}
}
If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK
(as seen in the source code).
In response to your first question: Yes, you have to run a server app to send the messages, as well as a client app to receive them.
In response to your second question: Yes, every application needs its own API key. This key is for your server app, not the client.
In a regular expression, you can "capture" parts of the matched string with (brackets)
; in this case, you are capturing the (^|_)
and ([a-z])
parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.
The /e
modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1
) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'
. It then (effectively) runs eval
to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval
in an insecure way).
The preg_replace_callback
function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1'
, you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }
, the first back-reference is $matches[1]
inside that function.
So a /e
argument of
'do_stuff(\\1) . "and" . do_stuff(\\2)'
could become a callback of
function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }
Or in your case
'strtoupper("\\2")'
could become
function($m) { return strtoupper($m[2]); }
Note that $m
and $matches
are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method)
, as with any callback in PHP, e.g.
function stuffy_callback($things) {
return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');
As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use
keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was
'do_stuff(\\1, $foo)'
then the new callback might look like
function($m) use ($foo) { return do_stuff($m[1], $foo); }
preg_replace_callback
is instead of the /e
modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei
would become /blah(.*)blah/mi
./e
modifier used a variant of addslashes()
internally on the arguments, so some replacements used stripslashes()
to remove it; in most cases, you probably want to remove the call to stripslashes
from your new callback.I tried the codes from bootstrap's document as follows:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>tab demo</title>
<link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="span9">
<div class="tabbable"> <!-- Only required for left/right tabs -->
<ul class="nav nav-tabs">
<li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
<li><a href="#tab2" data-toggle="tab">Section 2</a></li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<p>I'm in Section 1.</p>
</div>
<div class="tab-pane" id="tab2">
<p>Howdy, I'm in Section 2.</p>
</div>
</div>
</div>
</div>
<script src="jquery.min.js"></script>
<script src="bootstrap.js"></script>
</body>
</html>
and it works.
But when I switch these two <script src...>
's postion, it do not work. So please remember to load your jquery script before bootstrap.js.
HttpContext.Current.Session.Remove("sessionname");
it works for me
Other way for get a list just local branch is:
git branch -a | grep -v 'remotes'
How about:
dateTime.ToString("tt", CultureInfo.InvariantCulture);
For Visual Studio 2019 (v16.2.4) I was only able to find this file here:
C:\Users\\Documents\IISExpress\config\applicationhost.config
Hope this helps as I wasn't able to find the .vs folder location as mentioned in the above suggestions.
The trick is to
Updated for Numpy 1.7.0:(Hat-tip to @Rolf Bartstra.)
a=np.empty(n); a.fill(5)
is fastest.
In descending speed order:
%timeit a=np.empty(1e4); a.fill(5)
100000 loops, best of 3: 5.85 us per loop
%timeit a=np.empty(1e4); a[:]=5
100000 loops, best of 3: 7.15 us per loop
%timeit a=np.ones(1e4)*5
10000 loops, best of 3: 22.9 us per loop
%timeit a=np.repeat(5,(1e4))
10000 loops, best of 3: 81.7 us per loop
%timeit a=np.tile(5,[1e4])
10000 loops, best of 3: 82.9 us per loop
cvc-elt.1: Cannot find the declaration of element 'Root'. [7]
Your schemaLocation
attribute on the root element should be xsi:schemaLocation
, and you need to fix it to use the right namespace.
You should probably change the targetNamespace
of the schema and the xmlns
of the document to http://myNameSpace.com
(since namespaces are supposed to be valid URIs, which Test.Namespace
isn't, though urn:Test.Namespace
would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.
(though it still won't validate as your <element2>
contains an <element3>
in the document where the schema expects item
)
If your file is a model field within a model, you can also use ".url" in your template tag to get the image.
For example.
If this is your model:
class Foo(models.Model):
foo = models.TextField()
bar = models.FileField(upload_to="foo-pictures", blank = True)
Pass the model in context in your views.
return render (request, "whatever.html", {'foo':Foo.objects.get(pk = 1)})
In your template you could have:
<img src = "{{foo.bar.url}}">
The original answer from https://github.com/philipwalton/flexbugs/issues/231#issuecomment-362790042
.flex-container{
min-height:100px;
display:flex;
align-items:center;
}
.flex-container:after{
content:'';
min-height:inherit;
font-size:0;
}
I answered a similar question here. I looked in a lot of places that always created the same problem. Basically, I did not want to assign a value to the weights, but simply change the weights. The short version of the above answer is:
tf.keras.backend.set_value(tf_var, numpy_weights)
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
In the first instance you are trying to create what is called a jagged array.
double[][] ServicePoint = new double[10][9].
The above statement would have worked if it was defined like below.
double[][] ServicePoint = new double[10][]
what this means is you are creating an array of size 10 ,that can store 10 differently sized arrays inside it.In simple terms an Array of arrays.see the below image,which signifies a jagged array.
http://msdn.microsoft.com/en-us/library/2s05feca(v=vs.80).aspx
The second one is basically a two dimensional array and the syntax is correct and acceptable.
double[,] ServicePoint = new double[10,9];//<-ok (2)
And to access or modify a two dimensional array you have to pass both the dimensions,but in your case you are passing just a single dimension,thats why the error
Correct usage would be
ServicePoint[0][2]
,Refers to an item on the first row ,third column.
Pictorial rep of your two dimensional array
Straight from the php.ini file:
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This directive informs PHP of which errors, warnings and notices you would like
; it to take action for. The recommended way of setting values for this
; directive is through the use of the error level constants and bitwise
; operators. The error level constants are below here for convenience as well as
; some common settings and their meanings.
; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
; those related to E_NOTICE and E_STRICT, which together cover best practices and
; recommended coding standards in PHP. For performance reasons, this is the
; recommend error reporting setting. Your production server shouldn't be wasting
; resources complaining about best practices and coding standards. That's what
; development servers and development settings are for.
; Note: The php.ini-development file has this setting as E_ALL. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
;
; Error Level Constants:
; E_ALL - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
; E_ERROR - fatal run-time errors
; E_RECOVERABLE_ERROR - almost fatal run-time errors
; E_WARNING - run-time warnings (non-fatal errors)
; E_PARSE - compile-time parse errors
; E_NOTICE - run-time notices (these are warnings which often result
; from a bug in your code, but it's possible that it was
; intentional (e.g., using an uninitialized variable and
; relying on the fact it is automatically initialized to an
; empty string)
; E_STRICT - run-time notices, enable to have PHP suggest changes
; to your code which will ensure the best interoperability
; and forward compatibility of your code
; E_CORE_ERROR - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING - warnings (non-fatal errors) that occur during PHP's
; initial startup
; E_COMPILE_ERROR - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR - user-generated error message
; E_USER_WARNING - user-generated warning message
; E_USER_NOTICE - user-generated notice message
; E_DEPRECATED - warn about code that will not work in future versions
; of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
; E_ALL (Show all errors, warnings and notices including coding standards.)
; E_ALL & ~E_NOTICE (Show all errors, except for notices)
; E_ALL & ~E_NOTICE & ~E_STRICT (Show all errors, except for notices and coding standards warnings.)
; E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
For pure development I go for:
error_reporting = E_ALL ^ E_NOTICE ^ E_WARNING
Also don't forget to put display_errors to on
display_errors = On
After that, restart your server for Apache on Ubuntu:
sudo /etc/init.d/apache2 restart
My solution would be create custom filter and use it:
app.filter('with', function() {
return function(items, field) {
var result = {};
angular.forEach(items, function(value, key) {
if (!value.hasOwnProperty(field)) {
result[key] = value;
}
});
return result;
};
});
And in html:
<div ng-repeat="(k,v) in items | with:'secId'">
{{k}} {{v.pos}}
</div>
If it's inside a closure, i'm pretty sure you can't.
Otherwise you just do functionName();
and hit return.
You should use datetime.datetime.strptime
:
import datetime
dt = datetime.datetime.strptime(string_date, fmt)
fmt
will need to be the appropriate format for your string. You'll find the reference on how to build your format here.
The truly terrible way to do it is to execute each INSERT
statement as its own batch:
Batch 1:
INSERT INTO Entries (id, name) VALUES (1, 'Ian Boyd);
Batch 2:
INSERT INTO Entries (id, name) VALUES (2, 'Bottlenecked);
Batch 3:
INSERT INTO Entries (id, name) VALUES (3, 'Marek Grzenkowicz);
Batch 4:
INSERT INTO Entries (id, name) VALUES (4, 'Giorgi);
Batch 5:
INSERT INTO Entries (id, name) VALUES (5, 'AMissico);
Note: Parameterization, error checking, and any other nit-picks elided for expoistory purposes.
This is truly, horrible, terrible way to do things. It gives truely awful performance, because you suffer the network round-trip-time every time.
A much better solution is to batch all the INSERT
statements into one batch:
Batch 1:
INSERT INTO Entries (id, name) VALUES (1, 'Ian Boyd');
INSERT INTO Entries (id, name) VALUES (2, 'Bottlenecked');
INSERT INTO Entries (id, name) VALUES (3, 'Marek Grzenkowicz');
INSERT INTO Entries (id, name) VALUES (4, 'Giorgi');
INSERT INTO Entries (id, name) VALUES (5, 'AMissico');
This way you only suffer one-round trip. This version has huge performance wins; on the order of 5x faster.
Even better is to use the VALUES
clause:
INSERT INTO Entries (id, name)
VALUES
(1, 'Ian Boyd'),
(2, 'Bottlenecked'),
(3, 'Marek Grzenkowicz'),
(4, 'Giorgi'),
(5, 'AMissico');
This gives you some performance improvements over the 5 separate INSERT
s version; it lets the server do what it's good at: operating on sets:
SQL Sever loves to operate on sets of data; it's where it's a viking!
The above T-SQL examples have all the parameteriztion stuff removed for clarity. But in reality you want to parameterize queries
But Bruno has an important point; SQL Server's driver only lets you include 2,100 parameters in a batch. The above query has two values:
@id, @name
If you import 1,051 rows in a single batch, that's 2,102 parameters - you'll get the error:
Too many parameters were provided in this RPC request
That is why i generally insert 5 or 10 rows at a time. Adding more rows per batch doesn't improve performance that much - there's diminishing returns.
It keeps the number of parameters low, it doesn't get anywhere near the T-SQL batch size limit. There's also the fact that a VALUES
clause is limited to 1000 tuples anyway.
Your first approach is good, but you do have the issues of:
So the goal is to generate a string such as:
INSERT INTO Entries (id, name) VALUES
(@p1, @p2),
(@p3, @p4),
(@p5, @p6),
(@p7, @p8),
(@p9, @p10)
I'll change your code by the seat of my pants
IEnumerable<Entry> entries = GetStuffToInsert();
SqlCommand cmd = new SqlCommand();
StringBuilder sql = new StringBuilder();
Int32 batchSize = 0; //how many rows we have build up so far
Int32 p = 1; //the current paramter name (i.e. "@p1") we're going to use
foreach(var entry in entries)
{
//Build the names of the parameters
String pId = String.Format("@p{0}", p); //the "Id" parameter name (i.e. "p1")
String pName = String.Format("@p{0}", p+1); //the "Name" parameter name (i.e. "p2")
p += 2;
//Build a single "(p1, p2)" row
String row = String.Format("({0}, {1})", pId, pName); //a single values tuple
//Add the row to our running SQL batch
if (batchSize > 0)
sb.AppendLine(",");
sb.Append(row);
batchSize += 1;
//Add the parameter values for this row
cmd.Parameters.Add(pID, System.Data.SqlDbType.Int ).Value = entry.Id;
cmd.Parameters.Add(pName, System.Data.SqlDbType.String).Value = entry.Name;
if (batchSize >= 5)
{
String sql = "INSERT INTO Entries (id, name) VALUES"+"\r\n"+
sb.ToString();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
sb.Clear();
batchSize = 0;
p = 1;
}
}
//handle the last few stragglers
if (batchSize > 0)
{
String sql = "INSERT INTO Entries (id, name) VALUES"+"\r\n"+
sb.ToString();
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
}
Use calloc instead of malloc . calloc will initiate all fields to 0.
int *a = (int *)calloc(n,size of(int)) ;
//all cells of a have been initialized to 0
One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.
package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
Name string
Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
return candidate{name, 0} // enforce the default value here
}
Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.
Please see this sample implementation of filter
to understand how it works in Python 3:
def my_filter(function, iterable):
"""my_filter(function or None, iterable) --> filter object
Return an iterator yielding those items of iterable for which function(item)
is true. If function is None, return the items that are true."""
if function is None:
return (item for item in iterable if item)
return (item for item in iterable if function(item))
The following is an example of how you might use filter
or my_filter
generators:
>>> greetings = {'hello'}
>>> spoken = my_filter(greetings.__contains__, ('hello', 'goodbye'))
>>> print('\n'.join(spoken))
hello
I had to run this for a column introduced in the later stages of a product, on 10+ tables. So wrote this quick untidy script to generate the alter command for all 'relevant' tables.
SET @NeighboringColumn = '<YOUR COLUMN SHOULD COME AFTER THIS COLUMN>';
SELECT CONCAT("ALTER TABLE `",t.TABLE_NAME,"` CHANGE COLUMN `",COLUMN_NAME,"`
`",COLUMN_NAME,"` ", c.DATA_TYPE, CASE WHEN c.CHARACTER_MAXIMUM_LENGTH IS NOT
NULL THEN CONCAT("(", c.CHARACTER_MAXIMUM_LENGTH, ")") ELSE "" END ," AFTER
`",@NeighboringColumn,"`;")
FROM information_schema.COLUMNS c, information_schema.TABLES t
WHERE c.TABLE_SCHEMA = '<YOUR SCHEMA NAME>'
AND c.COLUMN_NAME = '<COLUMN TO MOVE>'
AND c.TABLE_SCHEMA = t.TABLE_SCHEMA
AND c.TABLE_NAME = t.TABLE_NAME
AND t.TABLE_TYPE = 'BASE TABLE'
AND @NeighboringColumn IN (SELECT COLUMN_NAME
FROM information_schema.COLUMNS c2
WHERE c2.TABLE_NAME = t.TABLE_NAME);
Don't use print ...,
if you don't want spaces. Use string concatenation or formatting.
Concatenation:
print 'Value is "' + str(value) + '"'
Formatting:
print 'Value is "{}"'.format(value)
The latter is far more flexible, see the str.format()
method documentation and the Formatting String Syntax section.
You'll also come across the older %
formatting style:
print 'Value is "%d"' % value
print 'Value is "%d", but math.pi is %.2f' % (value, math.pi)
but this isn't as flexible as the newer str.format()
method.
For those of you using python3 you can use:
python3 setup.py install
Presumably you're passing the arguments in on the command line as follows:
php /path/to/wwwpublic/path/to/script.php arg1 arg2
... and then accessing them in the script thusly:
<?php
// $argv[0] is '/path/to/wwwpublic/path/to/script.php'
$argument1 = $argv[1];
$argument2 = $argv[2];
?>
What you need to be doing when passing arguments through HTTP (accessing the script over the web) is using the query string and access them through the $_GET superglobal:
Go to http://yourdomain.com/path/to/script.php?argument1=arg1&argument2=arg2
... and access:
<?php
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
?>
If you want the script to run regardless of where you call it from (command line or from the browser) you'll want something like the following:
EDIT: as pointed out by Cthulhu in the comments, the most direct way to test which environment you're executing in is to use the PHP_SAPI constant. I've updated the code accordingly:
<?php
if (PHP_SAPI === 'cli') {
$argument1 = $argv[1];
$argument2 = $argv[2];
}
else {
$argument1 = $_GET['argument1'];
$argument2 = $_GET['argument2'];
}
?>
You need to instantiate the class it is contained within, or make the method static.
So if it is contained within class Foo:
Foo x = new Foo();
List<Integer> stuff = x.myNumbers();
or alternatively shorthand:
List<Integer> stuff = new Foo().myNumbers();
or if you make it static like so:
public static List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
you can call it like so:
List<Integer> stuff = Foo.myNumbers();
Just do the following change
echo off
cls
echo Would you like to do a backup?
pause
copy "\\My_Servers_IP\Shared Drive\FolderName\*" C:\TEST_BACKUP_FOLDER
pause
For List :
List<Integer> intList
= stringList.stream().map(Integer::valueOf).collect(Collectors.toList());
For Array :
int[] intArray = Arrays.stream(stringArray).mapToInt(Integer::valueOf).toArray();
In my case I had looked at some tables in the DB prior to executing this action. My user account was holding an active connection to this DB in SSMS. Once I disconnected from the server in SSMS (leaving the 'Take database offline' dialog box open) the operation succeeded.
If you use Tomcat server I suggest you to put JSTL .jar file to the Tomcat lib folder. By doing this you will have an access to JSTL in all your web projects automatically (with taglib declaration in .jsp files of course).
It is possible of course, use -l:
instead of -l
. For example -l:libXYZ.a
to link with libXYZ.a
. Notice the lib
written out, as opposed to -lXYZ
which would auto expand to libXYZ
.
You can simply return
if you want to skip the current iteration.
Since you're in a function, if you return
before doing anything else, then you have effectively skipped execution of the code below the return
statement.
Python’s wonderful standard library to the rescue…
import codecs
reader = codecs.getreader("utf-8")
obj = json.load(reader(response))
Works with both py2 and py3.
No, this is not directly possible. The hash for every Git commit is also calculated based on the commit message. When you change the commit message, you change the commit hash. If you want to push that commit, you have to force that push (git push -f). But if already someone pulled your old commit and started a work based on that commit, he would have to rebase his work onto your new commit.
you can try adding
$db['db_debug'] = FALSE;
in "your database file".php after that you can modify your database as you like.
Usually git bash here
can be run only on directories so you have to go up a directory and right click on the previous directory then select git bash here
(of course on Windows OS).
Note: context menu inside a directory does not have a git bash here
option.
You can't do without transaction logs in SQL Server, under any circumstances. The engine simply won't function.
You CAN set your recovery model to SIMPLE on your dev machines - that will prevent transaction log bloating when tran log backups aren't done.
ALTER DATABASE MyDB SET RECOVERY SIMPLE;
I had the same problem but it had nothing to do with annotations. The problem happened while indexing beans in my container (Jboss EAP 6.3). One of my beans could not be indexed because it used Java 8 features an I got this sneaky little warning while deploying:
WARN [org.jboss.as.server.deployment] ... Could not index class ... java.lang.IllegalStateException: Unknown tag! pos=20 poolCount = 133
Then at the injection point I got the error:
Unsatisfied dependencies for type ... with qualifiers @Default
The solution is to update the Java annotations index. download new version of jandex (jandex-1.2.3.Final or newer) then put it into
JBOSS_HOME\modules\system\layers\base\org\jboss\jandex\main and then update reference to the new file in module.xml
NOTE: EAP 6.4.x already have this fixed
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.
I used the following code:
// get the video
var video = document.querySelector('video');
// use the whole window and a *named function*
window.addEventListener('touchstart', function videoStart() {
video.play();
console.log('first touch');
// remove from the window and call the function we are removing
this.removeEventListener('touchstart', videoStart);
});
There doesn't seem to be a way to auto-start anymore.
This makes it so that the first time they touch the screen the video will play. It will also remove itself on first run so that you can avoid multiple listeners adding up.
Here is another approach:
You can simply create an ESLint friendly object like this
const modal: IModal = {} as IModal;
Or a default instance based on the interface and with sensible defaults, if any
const defaultModal: IModal = {
content: "",
form: "",
href: "",
$form: {} as JQuery,
$message: {} as JQuery,
$modal: {} as JQuery,
$submits: {} as JQuery
};
Then variations of the default instance simply by overriding some properties
const confirmationModal: IModal = {
...defaultModal, // all properties/values from defaultModal
form: "confirmForm" // override form only
}
What about LineSentence module, it will ignore such lines:
Bases: object
Simple format: one sentence = one line; words already preprocessed and separated by whitespace.
source can be either a string or a file object. Clip the file to the first limit lines (or not clipped if limit is None, the default).
from gensim.models.word2vec import LineSentence
text = LineSentence('text.txt')
I can't find a single reference that state that it's possible without involving the serverside.
MSDN on:
From browserLanguage:
In Microsoft Internet Explorer 4.0 and earlier, the browserLanguage property reflects the language of the installed browser's user interface. For example, if you install a Japanese version of Windows Internet Explorer on an English operating system, browserLanguage would be ja.
In Internet Explorer 5 and later, however, the browserLanguage property reflects the language of the operating system regardless of the installed language version of Internet Explorer. However, if Microsoft Windows 2000 MultiLanguage version is installed, the browserLanguage property indicates the language set in the operating system's current menus and dialogs, as found in the Regional Options of the Control Panel. For example, if you install a Japanese version of Internet Explorer 5 on an English (United Kingdom) operating system, browserLanguage would be en-gb. If you install Windows 2000 MultiLanguage version and set the language of the menus and dialogs to French, browserLanguage would be fr, even though you have a Japanese version of Internet Explorer.
Note This property does not indicate the language or languages set by the user in Language Preferences, located in the Internet Options dialog box.
Furthermore, it looks like browserLanguage
is deprecated cause IE8 doesn't list it
int c;
String raw = "";
do {
c = inputstream.read();
raw+=(char)c;
} while(inputstream.available()>0);
InputStream.available() shows the available bytes only after one byte is read, hence do .. while
As other answer have suggested to perform most of this work in code only one answer actually provided a way to view your changes in the storyboard IB Interface. My answer goes beyond that answer by allowing you to change the cornerRadius of the view, button, image, etc.
Please take a look at the following code. To use this code create a new swift file called RoundedView or whatever you would like to call it then go to your storyboard and change the class to either "RoundedView", "RoundedImageView" or "RoundedButton".
import UIKit
@IBDesignable class RoundedImage: UIImageView
{
override func layoutSubviews() {
super.layoutSubviews()
updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var cornerRadius: CGFloat = 0.1 {
didSet {
updateCornerRadius()
}
}
func updateCornerRadius() {
layer.cornerRadius = rounded ? cornerRadius : 0
layer.masksToBounds = rounded ? true : false
}
}
@IBDesignable class RoundedView: UIView
{
override func layoutSubviews() {
super.layoutSubviews()
updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var cornerRadius: CGFloat = 0.1 {
didSet {
updateCornerRadius()
}
}
func updateCornerRadius() {
layer.cornerRadius = rounded ? cornerRadius : 0
layer.masksToBounds = rounded ? true : false
}
}
@IBDesignable class RoundedButton: UIButton
{
override func layoutSubviews() {
super.layoutSubviews()
updateCornerRadius()
}
@IBInspectable var rounded: Bool = false {
didSet {
updateCornerRadius()
}
}
@IBInspectable var cornerRadius: CGFloat = 0.1 {
didSet {
updateCornerRadius()
}
}
func updateCornerRadius() {
layer.cornerRadius = rounded ? cornerRadius : 0
layer.masksToBounds = rounded ? true : false
}
}
If you want to do it without cli, you can do it fully on Github website.
New pull request
.Create new pull request
.The title of this thread asks how a subquery can be used in an update. Here's an example of that:
update [dbName].[dbo].[MyTable]
set MyColumn = 1
where
(
select count(*)
from [dbName].[dbo].[MyTable] mt2
where
mt2.ID > [dbName].[dbo].[MyTable].ID
and mt2.Category = [dbName].[dbo].[MyTable].Category
) > 0
Just to add to this:
If you also need to prevent the user to manually type a date in the past, this is a possible solution. This is what we ended up doing (based on @Nicola Peluchetti's answer)
var dateToday = new Date();
$("#myDatePickerInput").change(function () {
var updatedDate = $(this).val();
var instance = $(this).data("datepicker");
var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, updatedDate, instance.settings);
if (date < dateToday) {
$(this).datepicker("setDate", dateToday);
}
});
What this does is to change the value to today's date if the user manually types a date in the past.
use Extension
import java.text.NumberFormat
val Int.commaString: String
get() = NumberFormat.getInstance().format(this)
val String.commaString: String
get() = NumberFormat.getNumberInstance().format(this.toDouble())
val Long.commaString: String
get() = NumberFormat.getInstance().format(this)
val Double.commaString: String
get() = NumberFormat.getInstance().format(this)
result
1234.commaString => 1,234
"1234.456".commaString => 1,234.456
1234567890123456789.commaString => 1,234,567,890,123,456,789
1234.456.commaString => 1,234.456
In Python 3.2+, you can use int.to_bytes:
>>> n = 1245427
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x13\x00\xf3'
>>> (1245427).to_bytes(3, byteorder='big')
b'\x13\x00\xf3'
The accepted answer gives an example of using the newest file in a command and then exiting. If you need to do this in a bat file with other complex operations you can use the following to store the file name of the newest file in a variable:
FOR /F "delims=|" %%I IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%%I
Now you can reference %NewestFile% throughout the rest of your bat file.
For example here is what we use to get the latest version of a database .bak file from a directory, copy it to a server, and then restore the db:
:Variables
SET DatabaseBackupPath=\\virtualserver1\Database Backups
echo.
echo Restore WebServer Database
FOR /F "delims=|" %%I IN ('DIR "%DatabaseBackupPath%\WebServer\*.bak" /B /O:D') DO SET NewestFile=%%I
copy "%DatabaseBackupPath%\WebServer\%NewestFile%" "D:\"
sqlcmd -U <username> -P <password> -d master -Q ^
"RESTORE DATABASE [ExampleDatabaseName] ^
FROM DISK = N'D:\%NewestFile%' ^
WITH FILE = 1, ^
MOVE N'Example_CS' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example.mdf', ^
MOVE N'Example_CS_log' TO N'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Example_1.LDF', ^
NOUNLOAD, STATS = 10"
This happened to me when I tried to install a higher MySQL version than the one coming with the distribution.
I erased the old version then installed the new one (rpm -e ... then rpm -i MySQL-server* ) But did not realize that the files in /var/lib/mysql were still from the older version (with differences as explained by Marc Alff - thanks!)
I could have done an mysql_upgrade, but as I wanted to start from scratch I did:
# su - mysql
$ rm -rf /var/lib/mysql/*
$ mysql_install_db
# /etc/init.d/mysql start
Then set root password (/usr/bin/mysqladmin -u root password), and all worked as expected with the GRANT commands...
Here is a plunker showing how you can use it with the ngClass
directive.
I'm demonstrating with div
s instead of img
s though.
Template:
<ul>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
<li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>
TS:
export class App {
selectedIndex = -1;
setSelected(id: number) {
this.selectedIndex = id;
}
}
you can use following code.
file_obj = open('big_file')
open() returns a file object
then use os.stat for getting size
file_size = os.stat('big_file').st_size
for i in range( file_size/1024):
print file_obj.read(1024)
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form. You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
Tail-call optimization is where you are able to avoid allocating a new stack frame for a function because the calling function will simply return the value that it gets from the called function. The most common use is tail-recursion, where a recursive function written to take advantage of tail-call optimization can use constant stack space.
Scheme is one of the few programming languages that guarantee in the spec that any implementation must provide this optimization, so here are two examples of the factorial function in Scheme:
(define (fact x)
(if (= x 0) 1
(* x (fact (- x 1)))))
(define (fact x)
(define (fact-tail x accum)
(if (= x 0) accum
(fact-tail (- x 1) (* x accum))))
(fact-tail x 1))
The first function is not tail recursive because when the recursive call is made, the function needs to keep track of the multiplication it needs to do with the result after the call returns. As such, the stack looks as follows:
(fact 3)
(* 3 (fact 2))
(* 3 (* 2 (fact 1)))
(* 3 (* 2 (* 1 (fact 0))))
(* 3 (* 2 (* 1 1)))
(* 3 (* 2 1))
(* 3 2)
6
In contrast, the stack trace for the tail recursive factorial looks as follows:
(fact 3)
(fact-tail 3 1)
(fact-tail 2 3)
(fact-tail 1 6)
(fact-tail 0 6)
6
As you can see, we only need to keep track of the same amount of data for every call to fact-tail because we are simply returning the value we get right through to the top. This means that even if I were to call (fact 1000000), I need only the same amount of space as (fact 3). This is not the case with the non-tail-recursive fact, and as such large values may cause a stack overflow.
If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.
As of today (2015, Aug., 1st), Apache2
in Debian Jessie
, you need to edit:
root@host:/etc/apache2/mods-enabled$ vi dir.conf
And change the order of that line, bringing index.php to the first position:
DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
You can create a Blob
from your base64 data, and then read it asDataURL
:
var img_b64 = canvas.toDataURL('image/png');
var png = img_b64.split(',')[1];
var the_file = new Blob([window.atob(png)], {type: 'image/png', encoding: 'utf-8'});
var fr = new FileReader();
fr.onload = function ( oFREvent ) {
var v = oFREvent.target.result.split(',')[1]; // encoding is messed up here, so we fix it
v = atob(v);
var good_b64 = btoa(decodeURIComponent(escape(v)));
document.getElementById("uploadPreview").src = "data:image/png;base64," + good_b64;
};
fr.readAsDataURL(the_file);
Full example (includes junk code and console log): http://jsfiddle.net/tTYb8/
Alternatively, you can use .readAsText
, it works fine, and its more elegant.. but for some reason text does not sound right ;)
fr.onload = function ( oFREvent ) {
document.getElementById("uploadPreview").src = "data:image/png;base64,"
+ btoa(oFREvent.target.result);
};
fr.readAsText(the_file, "utf-8"); // its important to specify encoding here
Full example: http://jsfiddle.net/tTYb8/3/
Most answers talks about constructing std::string
.
If already constructed, just use assignment operator.
std::string oString;
char* pStr;
... // Here allocate and get character string (e.g. using fgets as you mentioned)
oString = pStr; // This is it! It copies contents from pStr to oString
Check This Example
Html:
<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>
<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>
Javascript:
$('#showall').click(function(){
$('div').show();
});
$('#showdiv1').click(function(){
$('div[id^=div]').hide();
$('#div1').show();
});
$('#showdiv2').click(function(){
$('div[id^=div]').hide();
$('#div2').show();
});
$('#showdiv3').click(function(){
$('div[id^=div]').hide();
$('#div3').show();
});
$('#showdiv4').click(function(){
$('div[id^=div]').hide();
$('#div4').show();
});
window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});
This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.
EDIT 1:
As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a #something
already in the URL does not work with the above code. Here is another version to handle that:
// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);
// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).
NOTE:
To use jQuery, you could just replace window.addEventListener
with $(window).on
in the examples. Thanks @Neon.
EDIT 2:
As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no hashchange
event to force the offset.
This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity
// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}
// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});
// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);
JSFiddle for this example is here
For what it's worth, this came up on the python-ideas mailing list recently. It turns out that there is an itertools recipe for doing this already:1
def all_equal(iterable):
"Returns True if all the elements are equal to each other"
g = groupby(iterable)
return next(g, True) and not next(g, False)
Supposedly it performs very nicely and has a few nice properties.
1In other words, I can't take the credit for coming up with the solution -- nor can I take credit for even finding it.
Rather than placing an extra scanner.nextLine()
each time you want to read something, since it seems you want to accept each input on a new line, you might want to instead changing the delimiter to actually match only newlines (instead of any whitespace, as is the default)
import java.util.Scanner;
class ScannerTest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
scanner.useDelimiter("\\n");
System.out.print("Enter an index: ");
int index = scanner.nextInt();
System.out.print("Enter a sentence: ");
String sentence = scanner.next();
System.out.println("\nYour sentence: " + sentence);
System.out.println("Your index: " + index);
}
}
Thus, to read a line of input, you only need scanner.next()
that has the same behavior delimiter-wise of next{Int, Double, ...}
The difference with the "nextLine() every time" approach, is that the latter will accept, as an index also <space>3
, 3<space>
and 3<space>whatever
while the former only accepts 3
on a line on its own
In this case it is better to use basename
instead of awk
:
$ basename /home/parent/child1/child2/filename
filename
A solution I found https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (This code taken directly from the comment)
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
If you want or don't mind having all the leading and trailing whitespace from your string removed you can use the strip
method.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
as mentioned here.
edit The original title for this question was different. My answer is for the original question.
You can change your keymap to use eclipse shortcuts. You can see here how to change keymap. https://stackoverflow.com/a/25419358
As addition to the answers above:
If you would like to delete those files
find $dir -size 0 -type f -delete
It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with ""
and your variable will be hidden.
So, you could define the variable with:
{{f = forecast[day.iso]; ""}}
Temporary redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? redirect;
Permanent redirect
rewrite ^ http://www.RedirectToThisDomain.com$request_uri? permanent;
In nginx configuration file for specific site:
server {
server_name www.example.com;
rewrite ^ http://www.RedictToThisDomain.com$request_uri? redirect;
}
string = string.replace(/[\W_]/g, "_");
CNAME'ing a root record is technically not against RFC, but does have limitations meaning it is a practice that is not recommended.
Normally your root record will have multiple entries. Say, 3 for your name servers and then one for an IP address.
Per RFC:
If a CNAME RR is present at a node, no other data should be present;
And Per IETF 'Common DNS Operational and Configuration Errors' Document:
This is often attempted by inexperienced administrators as an obvious way to allow your domain name to also be a host. However, DNS servers like BIND will see the CNAME and refuse to add any other resources for that name. Since no other records are allowed to coexist with a CNAME, the NS entries are ignored. Therefore all the hosts in the podunk.xx domain are ignored as well!
References:
If you are working in Eclipse IDE, that could mean that you haven't close the file in the previous launch of the application. When I had the same error message at trying to delete a file, that was the reason. It seems, Eclipse IDE doesn't close all files after termination of an application.
You can always write the code in VBA that updates similarly. I had this problem too, and my workaround was making a select query, with all the joins, that had all the data I was looking for to be able to update, making that a recordset and running the update query repeatedly as an update query of only the updating table, only searching the criteria you're looking for
Dim updatingItems As Recordset
Dim clientName As String
Dim tableID As String
Set updatingItems = CurrentDb.OpenRecordset("*insert SELECT SQL here*");", dbOpenDynaset)
Do Until updatingItems .EOF
clientName = updatingItems .Fields("strName")
tableID = updatingItems .Fields("ID")
DoCmd.RunSQL "UPDATE *ONLY TABLE TO UPDATE* SET *TABLE*.strClientName= '" & clientName & "' WHERE (((*TABLE*.ID)=" & tableID & "))"
updatingItems.MoveNext
Loop
I'm only doing this to about 60 records a day, doing it to a few thousand could take much longer, as the query is running from start to finish multiple times, instead of just selecting an overall group and making changes. You might need ' ' around the quotes for tableID, as it's a string, but I'm pretty sure this is what worked for me.
In the code snipet below, it is being verified that if the current time (can be any) exists between start and end time or not:
Calendar startTimeCal = Calendar.getInstance();
startTimeCal.setTime(startTime);
int startTimeHour = startTimeCal.get(Calendar.HOUR_OF_DAY);
if (startTimeHour == 0){
startTimeHour = 24;
}
int startTimeMinutes = startTimeCal.get(Calendar.MINUTE);
Calendar curTimeCal = Calendar.getInstance();
curTimeCal.setTime(currentTime);
int curTimeHour = curTimeCal.get(Calendar.HOUR_OF_DAY);
int curTimeMinutes = curTimeCal.get(Calendar.MINUTE);
Calendar endTimeCal = Calendar.getInstance();
endTimeCal.setTime(endTime);
int endTimeHour = endTimeCal.get(Calendar.HOUR_OF_DAY);
if (endTimeHour == 0) {
endTimeHour = 24;
}
int endTimeMinutes = endTimeCal.get(Calendar.MINUTE);
if (((curTimeHour > startTimeHour) || (curTimeHour == startTimeHour && curTimeMinutes >= startTimeMinutes)) &&
((curTimeHour < endTimeHour) || (curTimeHour == endTimeHour && curTimeMinutes <= endTimeHour))) {
//time exists between start and end time
} else {
//time doesn't exist between start and end time
}
There is HTML and URI encodings. &
is &
encoded in HTML while %26
is &
in URI encoding.
So before URI encoding your string you might want to HTML decode and then URI encode it :)
var div = document.createElement('div');
div.innerHTML = '&AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);
result %26AndOtherHTMLEncodedStuff
Hope this saves you some time
Assign the members directly without the .Value
part:
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime;
this.otherdata = myNewDT.otherdata;
}
Use break, as such:
while(choice!=99)
{
cin>>choice;
if (choice==99)
break; //exit here and don't get additional input
cin>>gNum;
}
This works for for loops also, and is the keyword for ending a switch clause. More info here.
Assuming the following method to test:
public boolean doSomething(SomeClass arg);
Mockito documentation says that you should not use captor in this way:
when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));
Because you can just use matcher during stubbing:
when(someObject.doSomething(eq(expected))).thenReturn(true);
But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor
and this is the case for which it is designed:
ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));
We'll git log
sometimes is not good to get all commits detail, so to view this...
For Mac: Get into you git project and type:
$ nano .git/logs/HEAD
to view you all commits in that, or:
$ gedit .git/logs/HEAD
to view you all commits in that,
then you can edit in any of your favourite browser.
PHP file (for example, my_lengthy_script.php)
ini_set('max_execution_time', 300); //300 seconds = 5 minutes
.htaccess file
<IfModule mod_php5.c>
php_value max_execution_time 300
</IfModule>
More configuration options
<IfModule mod_php5.c>
php_value post_max_size 5M
php_value upload_max_filesize 5M
php_value memory_limit 128M
php_value max_execution_time 300
php_value max_input_time 300
php_value session.gc_maxlifetime 1200
</IfModule>
If wordpress, set this in the config.php file,
define('WP_MEMORY_LIMIT', '128M');
If drupal, sites/default/settings.php
ini_set('memory_limit', '128M');
If you are using other frameworks,
ini_set('memory_limit', '128M');
You can increase memory as gigabyte.
ini_set('memory_limit', '3G'); // 3 Gigabytes
259200 means:-
( 259200/(60x60 minutes) ) / 24 hours ===> 3 Days
This code will show an error like
Table[0] can not be found!
because there will not be any table in position 0.
if (ds.Tables[0].Rows.Count == 0)
{
//
}
I'd like to expand a little bit on Pavel Minaev's answer, which you should read before reading my answer. Both solutions presented by Pavel won't compile if the member to be compared (such as id
in the question's code) is private. In this case, VS2013 throws the following error for me:
error C2248: 'Class1::id' : cannot access private member declared in class 'Class1'
As mentioned by SkyWalker in the comments on Pavel's answer, using a friend
declaration helps. If you wonder about the correct syntax, here it is:
class Class1
{
public:
Class1(int id) : id(id) {}
private:
int id;
friend struct Class1Compare; // Use this for Pavel's first solution.
friend struct std::less<Class1>; // Use this for Pavel's second solution.
};
However, if you have an access function for your private member, for example getId()
for id
, as follows:
class Class1
{
public:
Class1(int id) : id(id) {}
int getId() const { return id; }
private:
int id;
};
then you can use it instead of a friend
declaration (i.e. you compare lhs.getId() < rhs.getId()
).
Since C++11, you can also use a lambda expression for Pavel's first solution instead of defining a comparator function object class.
Putting everything together, the code could be writtem as follows:
auto comp = [](const Class1& lhs, const Class1& rhs){ return lhs.getId() < rhs.getId(); };
std::map<Class1, int, decltype(comp)> c2int(comp);
Your error message is pretty explicit about what is going wrong:
laravel/framework v5.2.9 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
Do you have mbstring
installed on your server and is it enabled?
You can install mbstring
as part of the libapache2-mod-php5 package:
sudo apt-get install libapache2-mod-php5
Or standalone with:
sudo apt-get install php-mbstring
Installing it will also enable it, however you can also enable it by editing your php.ini
file and remove the ;
that is commenting it out if it is already installed.
If this is on your local machine, then follow the appropriate steps to install this on your environment.
It seems that Bootstrap doesn't support disabled links. Instead of trying to add a Bootstrap class, you could add a class by your own and add some styling to it, just like this:
a.disabled {_x000D_
/* Make the disabled links grayish*/_x000D_
color: gray;_x000D_
/* And disable the pointer events */_x000D_
pointer-events: none;_x000D_
}
_x000D_
<!-- Make the disabled links unfocusable as well -->_x000D_
<a href="#" class="disabled" tabindex="-1">Link to disable</a><br/>_x000D_
<a href="#">Non-disabled Link</a>
_x000D_
I know this is old, but just thought I would add my solution just in case someone finds it useful.
I wanted to compare the local naive datetime with an aware datetime from a timeserver. I basically created a new naive datetime object using the aware datetime object. It's a bit of a hack and doesn't look very pretty but gets the job done.
import ntplib
import datetime
from datetime import timezone
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=None)
try:
ntpt = ntplib.NTPClient()
response = ntpt.request('pool.ntp.org')
date = utc_to_local(datetime.datetime.utcfromtimestamp(response.tx_time))
sysdate = datetime.datetime.now()
...here comes the fudge...
temp_date = datetime.datetime(int(str(date)[:4]),int(str(date)[5:7]),int(str(date)[8:10]),int(str(date)[11:13]),int(str(date)[14:16]),int(str(date)[17:19]))
dt_delta = temp_date-sysdate
except Exception:
print('Something went wrong :-(')
Goto my blog : retrofit with kotlin
the link below explains everything step by step.
http://loopj.com/android-async-http/
Here are sample apps:
Create a class :
public class HttpUtils {
private static final String BASE_URL = "http://api.twitter.com/1/";
private static AsyncHttpClient client = new AsyncHttpClient();
public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(getAbsoluteUrl(url), params, responseHandler);
}
public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(getAbsoluteUrl(url), params, responseHandler);
}
public static void getByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.get(url, params, responseHandler);
}
public static void postByUrl(String url, RequestParams params, AsyncHttpResponseHandler responseHandler) {
client.post(url, params, responseHandler);
}
private static String getAbsoluteUrl(String relativeUrl) {
return BASE_URL + relativeUrl;
}
}
Call Method :
RequestParams rp = new RequestParams();
rp.add("username", "aaa"); rp.add("password", "aaa@123");
HttpUtils.post(AppConstant.URL_FEED, rp, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
Log.d("asd", "---------------- this is response : " + response);
try {
JSONObject serverResp = new JSONObject(response.toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray timeline) {
// Pull out the first event on the public timeline
}
});
Please grant internet permission in your manifest file.
<uses-permission android:name="android.permission.INTERNET" />
you can add compile 'com.loopj.android:android-async-http:1.4.9'
for Header[]
and compile 'org.json:json:20160212'
for JSONObject
in build.gradle file if required.
<?php
$divStyle=''; // show div
// add condition
if($variable == '1'){
$divStyle='style="display:none;"'; //hide div
}
print'<div '.$divStyle.'>Div to hide</div>';
?>
You can find the list of formats here (in the Double.ToString()-MSDN-Article) as comments in the example section.
The full JSP tag should be something like this, mind the pageEncoding too:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
Some old browsers mess up with the encoding too. you can use the HTML tag
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
Also the file should be recorded in UTF-8 format, if you are using Eclipse left-click on the file->Properties->Check out ->Text file encoding.
Be careful how you define the table for you will get different results on insert. Consider the following
CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
INSERT INTO t1 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title')
ON CONFLICT(a) DO UPDATE SET b=excluded.b;
CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
INSERT INTO t2 (a, b) VALUES
('Alice', 'Some title'),
('Bob', 'Palindromic guy'),
('Charles', 'chucky cheese'),
('Alice', 'Some other title');
$ sqlite3 test.sqlite
SQLite version 3.28.0 2019-04-16 19:49:53
Enter ".help" for usage hints.
sqlite> CREATE TABLE IF NOT EXISTS t1 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT);
sqlite> INSERT INTO t1 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title')
...> ON CONFLICT(a) DO UPDATE SET b=excluded.b;
sqlite> CREATE TABLE IF NOT EXISTS t2 (id INTEGER PRIMARY KEY, a TEXT UNIQUE, b TEXT, UNIQUE(a) ON CONFLICT REPLACE);
sqlite> INSERT INTO t2 (a, b) VALUES
...> ('Alice', 'Some title'),
...> ('Bob', 'Palindromic guy'),
...> ('Charles', 'chucky cheese'),
...> ('Alice', 'Some other title');
sqlite> .mode col
sqlite> .headers on
sqlite> select * from t1;
id a b
---------- ---------- ----------------
1 Alice Some other title
2 Bob Palindromic guy
3 Charles chucky cheese
sqlite> select * from t2;
id a b
---------- ---------- ---------------
2 Bob Palindromic guy
3 Charles chucky cheese
4 Alice Some other titl
sqlite>
While the insert/update effect is the same, the id
changes based on the table definition type (see the second table where 'Alice' now has id = 4
; the first table is doing more of what I expect it to do, keep the PRIMARY KEY the same). Be aware of this effect.
For some fun with linq and string interpolation:
public string ByteArrayToString(byte[] bytes)
{
if ( bytes == null ) return "null";
string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
return $"new byte[] {{ {joinedBytes} }}";
}
Test cases:
byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();
Output:
new byte[] { 1, 2, 3, 4 }
null
new byte[] { }
There are many questions on that and many suggestions. None of them helped me for the recent Opencv 3.4.16 and Python 3.6/3.7. Finally I switched to Pyhon 2.7.15 and installed opencv 3.1.0. The DLL-problem was solved.
When I look in cv2.pyd with dependency walker, the 3.1 has no dependency to one missing dll. Opencv 3.4 has this missing dependency to this dll:
API-MS-WIN-DOWNLEVEL-SHLWAPI-L1-1-0.DLL
may be this is the problem.
P.S.: I have Win7 pofessional 64Bit, 32Bit Python 2.7.15
I was missing C headers solution was to download it for Xcode, this is the best way.
xcode-select --install
Hope it helps.
Mac comes with the JDK, for more information check:
You may also consider using line.rstrip() to remove the whitespaces at the end of your line.
hopefully its work
SET foreign_key_checks = 0;
DROP TABLE table name
;
SET foreign_key_checks = 1;
By default, the below code will NOT generate a checked Check Box as model properties override the html attributes:
@Html.CheckBoxFor(m => m.SomeBooleanProperty, new { @checked = "checked" });
Instead, in your GET Action method, the following needs to be done:
model.SomeBooleanProperty = true;
The above will preserve your selection(If you uncheck the box) even if model is not valid(i.e. some error occurs on posting the form).
However, the following code will certainly generate a checked checkbox, but will not preserve your uncheck responses, instead make the checkbox checked every time on errors in form.
@Html.CheckBox("SomeBooleanProperty", new { @checked = "checked" });
UPDATE
//Get Method
public ActionResult CreateUser(int id)
{
model.SomeBooleanProperty = true;
}
Above code would generate a checked check Box at starting and will also preserve your selection even on errors in form.
Stack frame is the packed information related to a function call. This information generally includes arguments passed to th function, local variables and where to return upon terminating. Activation record is another name for a stack frame. The layout of the stack frame is determined in the ABI by the manufacturer and every compiler supporting the ISA must conform to this standard, however layout scheme can be compiler dependent. Generally stack frame size is not limited but there is a concept called "red/protected zone" to allow system calls...etc to execute without interfering with a stack frame.
There is always a SP but on some ABIs (ARM's and PowerPC's for example) FP is optional. Arguments that needed to be placed onto the stack can be offsetted using the SP only. Whether a stack frame is generated for a function call or not depends on the type and number of arguments, local variables and how local variables are accessed generally. On most ISAs, first, registers are used and if there are more arguments than registers dedicated to pass arguments these are placed onto the stack (For example x86 ABI has 6 registers to pass integer arguments). Hence, sometimes, some functions do not need a stack frame to be placed on the stack, just the return address is pushed onto the stack.
JLabel label = new JLabel("fax", SwingConstants.RIGHT);
C-style solution could be to use itoa
, but better way is to print this number into string by using sprintf
/ snprintf
. Check this question: How to convert an integer to a string portably?
Note that itoa
function is not defined in ANSI-C and is not part of C++, but is supported by some compilers. It's a non-standard function, thus you should avoid using it. Check this question too: Alternative to itoa() for converting integer to string C++?
Also note that writing C-style code while programming in C++ is considered bad practice and sometimes referred as "ghastly style". Do you really want to convert it into C-style char*
string? :)
You can use pg_terminate_backend() to kill a connection. You have to be superuser to use this function. This works on all operating systems the same.
SELECT
pg_terminate_backend(pid)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
pid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = 'database_name'
;
Before executing this query, you have to REVOKE the CONNECT privileges to avoid new connections:
REVOKE CONNECT ON DATABASE dbname FROM PUBLIC, username;
If you're using Postgres 8.4-9.1 use procpid instead of pid
SELECT
pg_terminate_backend(procpid)
FROM
pg_stat_activity
WHERE
-- don't kill my own connection!
procpid <> pg_backend_pid()
-- don't kill the connections to other databases
AND datname = 'database_name'
;
If you have a drawable that's a solid color and you want to change it to a differnet solid color, you can use a ColorMatrixColorFilter
. Transparency is preserved.
int iColor = Color.parseColor(color);
int red = (iColor & 0xFF0000) / 0xFFFF;
int green = (iColor & 0xFF00) / 0xFF;
int blue = iColor & 0xFF;
float[] matrix = { 0, 0, 0, 0, red,
0, 0, 0, 0, green,
0, 0, 0, 0, blue,
0, 0, 0, 1, 0 };
ColorFilter colorFilter = new ColorMatrixColorFilter(matrix);
drawable.setColorFilter(colorFilter);
You (or Joomla) is likely including this file multiple times. Enclose your function in a conditional block:
if (!function_exists('parseDate')) {
// ... proceed to declare your function
}
I was using my OpenWRT enhanced device as a repeater (which adds virtual ethernet and wireless lan capabilities) and found that the /sys/class/net/eth0 carrier and opstate values were unreliable. I played around with /sys/class/net/eth0.1 and /sys/class/net/eth0.2 as well with (at least to my finding) no reliable way to detect that something was physically plugged in and talking on any of the ethernet ports. I figured out a bit crude but seemingly reliable way to detect if anything had been plugged in since the last reboot/poweron state at least (which worked exactly as I needed it to in my case).
ifconfig eth0 | grep -o 'RX packets:[0-9]*' | grep -o '[0-9]*'
You'll get a 0 if nothing has been plugged in and something > 0 if anything has been plugged in (even if it was plugged in and since removed) since the last power on or reboot cycle.
Hope this helps somebody out at least!
I tried all of these suggestions and more, just so I could git clone from my AWS instance. Nothing worked. I finally cheated out of desperation: I copied the contents of id_rsa.pub on my local machine and appended it to ~/.ssh/known_hosts on my AWS instance.
Some pages may require more than login/pass. There may even be hidden fields. The most reliable way is to use inspect tool and look at the network tab while logging in, to see what data is being passed on.
I'm using SSH to authenticate my GitHub account and have a couple dependencies in my project installed as follows:
"dependencies": {
"<dependency name>": "git+ssh://[email protected]/<github username>/<repository name>.git#<release version | branch>"
}
I came across this issue recently. I used PuPHPet to generate a config.
To connect to MySQL through SSH, the "vagrant" password was not working for me, instead I had to authenticate through the SSH key file.
To connect with MySQL Workbench
Connection method
Standard TCP/IP over SSH
SSH
Hostname: 127.0.0.1:2222 (forwarded SSH port)
Username: vagrant
Password: (do not use)
SSH Key File: C:\vagrantpath\puphpet\files\dot\ssh\insecure_private_key
(Locate your insercure_private_key)
MySQL
Server Port: 3306
username: (root, or username)
password: (password)
Test the connection.
You can do it with the code you have, you just need to ensure that html
and body
are set to 100% height.
Demo: http://jsfiddle.net/kevinPHPkevin/a7eGN/
html, body {
height:100%;
}
body {
background-color: white;
background-image: url('http://www.canvaz.com/portrait/charcoal-1.jpg');
background-size: auto 100%;
background-repeat: no-repeat;
background-position: left top;
}
If I understand correctly, you want to get the String of an Editable object, right? If yes, try using toString()
.
To avoid getting expections at run time , do something like this.
There are chances of having empty string sometimes,
string a = "abc,xyz,wer";
string b=string.Empty;
if(!string.IsNullOrEmpty(a ))
{
b = a.Split(',')[0];
}
You can you use permalinks to include code snippets in issues, PRs, etc.
References:
https://help.github.com/en/articles/creating-a-permanent-link-to-a-code-snippet
It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:
#include <iostream.h>
or
#include <iostream>
The former is pre-standard, and you'll be able to just say cout
as opposed to std::cout
without anything additional. You can get the same behavior in standard C++ by adding
using std::cout;
or
using namespace std;
Just one idea, anyway.
I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:
I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit
or /usr/bin/time
result from each of several methods of checksumming a file of approx. 11MB:
$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f /tmp/test.data.300k
real 0m0.043s
user 0m0.032s
sys 0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400
So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum
function (md5sum_read
in the above listing) is pretty similar to Omnifarious's:
import hashlib
def md5sum(filename, blocksize=65536):
hash = hashlib.md5()
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
hash.update(block)
return hash.hexdigest()
Granted, these are from single runs (the mmap
ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize)
after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum
on the command line is not necessarily faster than a Python implementation...
EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32()
call:
import zlib
def adler32sum(filename, blocksize=65536):
checksum = zlib.adler32("")
with open(filename, "rb") as f:
for block in iter(lambda: f.read(blocksize), b""):
checksum = zlib.adler32(block, checksum)
return checksum & 0xffffffff
Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for ""
, which is 1
-- CRC can start with 0
instead. The AND
-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.
If you want to allow the user to browse for a file, you need to have an input type="file"
The closest you could get to your requirement would be to place the input type="file"
on the page and hide it. Then, trigger the click event of the input when the button is clicked:
#myFileInput {
display:none;
}
<input type="file" id="myFileInput" />
<input type="button"
onclick="document.getElementById('myFileInput').click()"
value="Select a File" />
Here's a working fiddle.
Note: I would not recommend this approach. The input type="file"
is the mechanism that users are accustomed to using for uploading a file.
You need to publish the exposed ports by using the following options:
-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.
-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.
The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo
and check which random ports are being used from your host at the Ports section.
Just run the following command:
docker run -it -p 8080:8080 demo
After that your url will work.
Another option is to use the TimeUtils
utility method:
TimeUtils.millisToUnit(System.currentTimeMillis(), TimeUnit.SECONDS)
as you can see on the answer to this question: Conversion of a varchar data type to a datetime data type resulted in an out-of-range value
-- set the dateformat for the current session
set dateformat dmy
-- The conversion of a varchar data type
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31' as datetime)
-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid
-- set the dateformat for the current session
set dateformat ymd
-- this should work
select cast('2017-08-13 16:31:31' as datetime)
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
there's no code smaller than this:
public static boolean palindrome(String x){
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
if you want to check something:
public static boolean palindrome(String x){
if(x==null || x.length()==0){
throw new IllegalArgumentException("Not a valid string.");
}
return (x.charAt(0) == x.charAt(x.length()-1)) &&
(x.length()<4 || palindrome(x.substring(1, x.length()-1)));
}
LOL B-]
cin.clear();
fflush(stdin);
This was the only thing that worked for me when reading from console. In every other case it would either read indefinitely due to lack of \n, or something would remain in the buffer.
EDIT: I found out that the previous solution made things worse. THIS one however, works:
cin.getline(temp, STRLEN);
if (cin.fail()) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
break
will exit the loop completely, continue
will just skip the current iteration.
For example:
for (int i = 0; i < 10; i++) {
if (i == 0) {
break;
}
DoSomeThingWith(i);
}
The break will cause the loop to exit on the first iteration - DoSomeThingWith
will never be executed. This here:
for (int i = 0; i < 10; i++) {
if(i == 0) {
continue;
}
DoSomeThingWith(i);
}
Will not execute DoSomeThingWith
for i = 0
, but the loop will continue and DoSomeThingWith
will be executed for i = 1
to i = 9
.
Note that services and tools for sending emails may be able to inline your CSS for you, allowing CSS in <style>
tags to work in Gmail.
For instance, if you're sending emails with MailChimp, your CSS from <style>
tags will get inlined automatically by default. With Mandrill, you can enable this functionality (although it's disabled by default for performance reasons) by checking the "Inline CSS Styles in HTML Emails" box in the "Sending Defaults" section of the Settings tab:
(copy-paste/adapted from https://stackoverflow.com/a/24048772/1733117).
First you can subclass urllib2.BaseHandler
or urllib2.HTTPBasicAuthHandler
, and implement http_request
so that each request has the appropriate Authorization
header.
import urllib2
import base64
class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
'''Preemptive basic auth.
Instead of waiting for a 403 to then retry with the credentials,
send the credentials if the url is handled by the password manager.
Note: please use realm=None when calling add_password.'''
def http_request(self, req):
url = req.get_full_url()
realm = None
# this is very similar to the code from retry_http_basic_auth()
# but returns a request object.
user, pw = self.passwd.find_user_password(realm, url)
if pw:
raw = "%s:%s" % (user, pw)
auth = 'Basic %s' % base64.b64encode(raw).strip()
req.add_unredirected_header(self.auth_header, auth)
return req
https_request = http_request
Then if you are lazy like me, install the handler globally
api_url = "http://api.foursquare.com/"
api_username = "johndoe"
api_password = "some-cryptic-value"
auth_handler = PreemptiveBasicAuthHandler()
auth_handler.add_password(
realm=None, # default realm.
uri=api_url,
user=api_username,
passwd=api_password)
opener = urllib2.build_opener(auth_handler)
urllib2.install_opener(opener)
sudo apt-get update
For Mysql Database
sudo apt-get install php-mysql
For PostgreSQL Database
sudo apt-get install php-pgsql
Than
php artisan migrate
Try to create a new key store and replace with old one, then rebuild a new signed APK.
Update: Note that if you're using a http connection with server ,you should use SSL.
Take a look at: https://developer.android.com/distribute/best-practices/develop/understand-play-policies
Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there
That agony has been solved for me. I found out that what was taking over port 80 is http api service. I wrote in cmd:
net stop http
Asked me "The following services will be stopped, do you want to continue?" Pressed y
It stopped a number of services actually.
Then wrote localhost
and wallah, Apache is up and running on port 80.
Hope this helps
Important: Skype uses port 80 by default, you can change this in skype options > advanced > connection - and uncheck "use port 80"
LD_LIBRARY_PATH
is the default library path which is accessed to check for available dynamic and shared libraries. It is specific to linux distributions.
It is similar to environment variable PATH
in windows that linker checks for possible implementations during linking time.
Ahh. Because I missed the point of you initial post, here is an example which also ITERATES. The first example did not. In this case, I retreive an ADODB recordset, then load the data into a collection, which is returned by the function to client code:
EDIT: Not sure what I screwed up in pasting the code, but the formatting is a little screwball. Sorry!
Public Function StatesCollection() As Collection
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim colReturn As New Collection
Set colReturn = New Collection
Dim SQL As String
SQL = _
"SELECT tblState.State, tblState.StateName " & _
"FROM tblState"
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
With cn
.Provider = DataConnection.MyADOProvider
.ConnectionString = DataConnection.MyADOConnectionString
.Open
End With
With cmd
.CommandText = SQL
.ActiveConnection = cn
End With
Set rs = cmd.Execute
With rs
If Not .EOF Then
Do Until .EOF
colReturn.Add Nz(!State, "")
.MoveNext
Loop
End If
.Close
End With
cn.Close
Set rs = Nothing
Set cn = Nothing
Set StatesCollection = colReturn
End Function
I tried many different ways and this way is the only one worked for me
//check all images on the page
$('img').each(function(){
var img = new Image();
img.onload = function() {
console.log($(this).attr('src') + ' - done!');
}
img.src = $(this).attr('src');
});
You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/
I recommend using a library called Moment.js.
It is well tested, works cross browser and on server side(I am using it both in Angular and Node projects). It has great support for locale dates.
var threeMonthsAgo = moment().subtract(3, 'months');
console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00
.format()
returns string representation of date formatted in ISO 8601 format. You can also use it with custom date format like this:.format('dddd, MMMM Do YYYY, h:mm:ss a')
I know its not exactly the answer you were searching for but you could pass "null"
as last argument when @include box-shadow
mixin, like this @include box-shadow(12px, 14px, 2px, green, null);
Now, if that argument is only one in that property than that property (and its (default) value) won't get compiled. If there are two or more args on that "line" only ones that you nulled won't get compiled (your case).
CSS output is exactly as you wanted it, but you have to write your null
s :)
@include box-shadow(12px, 14px, 2px, green, null);
// compiles to ...
-webkit-box-shadow: 12px 14px 2px green;
-moz-box-shadow: 12px 14px 2px green;
box-shadow: 12px 14px 2px green;
It's simple...
=CONCATENATE(A1, ",")
Example: if [email protected] is in the A1 cell then write in another cell: =CONCATENATE(A1, ",")
[email protected] After this formula you will get [email protected],
For remove formula: copy that cell and use Alt + E + S + V or paste special value.
For example for 3.6 version type py -3.6
.
If you have also 32bit and 64bit versions, you can just type py -3.6-64
or py -3.6-32
.
To rename a table in SQL Server, use the sp_rename
command:
exec sp_rename 'schema.old_table_name', 'new_table_name'
You can use BinaryReader to read each of the bytes, then use BitConverter.ToString(byte[]) to find out how each is represented in binary.
You can then use this representation and write it to a file.
We solved this problem with deleting .vs folder on project folder and deleting temporary ASP.NET files.
1. Close the Visual Studio.
2. Delete .vs folder on project folder that includes applicationhost.config file.
3. Delete temporary ASP.NET Files located: C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET Files\root
Everything in JavaScript is pass by reference, so if you want a true deep copy of the objects in the array, the best method I can think of is to serialize the entire array to JSON and then de-serialize it back.
Iteration. It creates a state machine "under the covers" that remembers where you were on each additional cycle of the function and picks up from there.
There is this, which I credit to this blog:
@media only screen and (min-device-width: 560px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 2) {
/* iPhone 5 only */
}
Keep in mind it reacts the iPhone 5, not to the particular iOS version installed on said device.
To merge with your existing version, you should be able to comma-delimit them:
@media only screen and (max-device-width: 480px), only screen and (min-device-width: 560px) and (max-device-width: 1136px) and (-webkit-min-device-pixel-ratio: 2) {
/* iPhone only */
}
NB: I haven't tested the above code, but I've tested comma-delimited @media
queries before, and they work just fine.
Note that the above may hit some other devices which share similar ratios, such as the Galaxy Nexus. Here is an additional method which will target only devices which have one dimension of 640px (560px due to some weird display-pixel anomalies) and one of between 960px (iPhone <5) and 1136px (iPhone 5).
@media
only screen and (max-device-width: 1136px) and (min-device-width: 960px) and (max-device-height: 640px) and (min-device-height: 560px),
only screen and (max-device-height: 1136px) and (min-device-height: 960px) and (max-device-width: 640px) and (min-device-width: 560px) {
/* iPhone only */
}
I guess you could open a popup window and call that a dialog box. I'm unsure of the details, but I'm pretty sure you can close a window programmatically that you opened from javascript. Would this suffice?
Use the retainAll()
method of Set
:
Set<String> s1;
Set<String> s2;
s1.retainAll(s2); // s1 now contains only elements in both sets
If you want to preserve the sets, create a new set to hold the intersection:
Set<String> intersection = new HashSet<String>(s1); // use the copy constructor
intersection.retainAll(s2);
The javadoc of retainAll()
says it's exactly what you want:
Retains only the elements in this set that are contained in the specified collection (optional operation). In other words, removes from this set all of its elements that are not contained in the specified collection. If the specified collection is also a set, this operation effectively modifies this set so that its value is the intersection of the two sets.
You can use String arrays to add jComboBox items
String [] items = { "First item", "Second item", "Third item", "Fourth item" };
JComboBox comboOne = new JComboBox (items);
I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between
BEGIN
SELECT MONTH(CURDATE()) INTO @curmonth;
SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
SELECT DAY(@checkweekday) INTO @checkday;
SET @daycount = 0;
SET @workdays = 0;
WHILE(@daycount < @totaldays) DO
IF (WEEKDAY(@checkweekday) < 5) THEN
SET @workdays = @workdays+1;
END IF;
SET @daycount = @daycount+1;
SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
END WHILE;
END
Just for others:
If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query
delimiter ;;
drop procedure if exists test2;;
create procedure test2()
begin
select ‘Hello World’;
end
;;
Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.
The first_day function you need is: How to get first day of every corresponding month in mysql?
Showing the Procedure is working Simply add the following line below END WHILE and above END
SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;
Then use the following code in the SQL Query Window.
call test2 /* or whatever you changed the name of the stored procedure to */
NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).
Run -> Edit configurations -> Select your build configuration -> JRE - change Default to one of actual JDK paths
You could use a sub query...
WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)
But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.
- Can someone give a simple definition of what
Record
is?
A Record<K, T>
is an object type whose property keys are K
and whose property values are T
. That is, keyof Record<K, T>
is equivalent to K
, and Record<K, T>[K]
is (basically) equivalent to T
.
- Is
Record<K,T>
merely a way of saying "all properties on this object will have typeT
"? Probably not all objects, sinceK
has some purpose...
As you note, K
has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>
, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }
.
- Does the
K
generic forbid additional keys on the object that are notK
, or does it allow them and just indicate that their properties are not transformed toT
?
It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:
declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'
and it would treat them as excess properties which are sometimes rejected:
declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties
and sometimes accepted:
const y = {a: "hey", b: "you"};
acceptR(y); // okay
With the given example:
type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
Is it exactly the same as this?:
type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
Yes!
Hope that helps. Good luck!
Have you tried Bananascript? It produces highly compressed and completely unreadable code.
Left, Right and Below tabs were removed from Bootstrap 3, but you can add custom CSS to achieve this..
.tabs-below > .nav-tabs,
.tabs-right > .nav-tabs,
.tabs-left > .nav-tabs {
border-bottom: 0;
}
.tab-content > .tab-pane,
.pill-content > .pill-pane {
display: none;
}
.tab-content > .active,
.pill-content > .active {
display: block;
}
.tabs-below > .nav-tabs {
border-top: 1px solid #ddd;
}
.tabs-below > .nav-tabs > li {
margin-top: -1px;
margin-bottom: 0;
}
.tabs-below > .nav-tabs > li > a {
-webkit-border-radius: 0 0 4px 4px;
-moz-border-radius: 0 0 4px 4px;
border-radius: 0 0 4px 4px;
}
.tabs-below > .nav-tabs > li > a:hover,
.tabs-below > .nav-tabs > li > a:focus {
border-top-color: #ddd;
border-bottom-color: transparent;
}
.tabs-below > .nav-tabs > .active > a,
.tabs-below > .nav-tabs > .active > a:hover,
.tabs-below > .nav-tabs > .active > a:focus {
border-color: transparent #ddd #ddd #ddd;
}
.tabs-left > .nav-tabs > li,
.tabs-right > .nav-tabs > li {
float: none;
}
.tabs-left > .nav-tabs > li > a,
.tabs-right > .nav-tabs > li > a {
min-width: 74px;
margin-right: 0;
margin-bottom: 3px;
}
.tabs-left > .nav-tabs {
float: left;
margin-right: 19px;
border-right: 1px solid #ddd;
}
.tabs-left > .nav-tabs > li > a {
margin-right: -1px;
-webkit-border-radius: 4px 0 0 4px;
-moz-border-radius: 4px 0 0 4px;
border-radius: 4px 0 0 4px;
}
.tabs-left > .nav-tabs > li > a:hover,
.tabs-left > .nav-tabs > li > a:focus {
border-color: #eeeeee #dddddd #eeeeee #eeeeee;
}
.tabs-left > .nav-tabs .active > a,
.tabs-left > .nav-tabs .active > a:hover,
.tabs-left > .nav-tabs .active > a:focus {
border-color: #ddd transparent #ddd #ddd;
*border-right-color: #ffffff;
}
.tabs-right > .nav-tabs {
float: right;
margin-left: 19px;
border-left: 1px solid #ddd;
}
.tabs-right > .nav-tabs > li > a {
margin-left: -1px;
-webkit-border-radius: 0 4px 4px 0;
-moz-border-radius: 0 4px 4px 0;
border-radius: 0 4px 4px 0;
}
.tabs-right > .nav-tabs > li > a:hover,
.tabs-right > .nav-tabs > li > a:focus {
border-color: #eeeeee #eeeeee #eeeeee #dddddd;
}
.tabs-right > .nav-tabs .active > a,
.tabs-right > .nav-tabs .active > a:hover,
.tabs-right > .nav-tabs .active > a:focus {
border-color: #ddd #ddd #ddd transparent;
*border-left-color: #ffffff;
}
Working example: http://bootply.com/74926
UPDATE
If you don't need the exact look of a tab (bordered appropriately on the left or right as each tab is activated), you can simple use nav-stacked
, along with Bootstrap col-*
to float the tabs to the left or right...
nav-stacked
demo: http://codeply.com/go/rv3Cvr0lZ4
<ul class="nav nav-pills nav-stacked col-md-3">
<li><a href="#a" data-toggle="tab">1</a></li>
<li><a href="#b" data-toggle="tab">2</a></li>
<li><a href="#c" data-toggle="tab">3</a></li>
</ul>
In the menu go to : - File - Import - as the filter select 'Existing Projects into Workspace' - click next - browse to the project directory at 'select root directory' - click on 'finish'
To remove all objects in oracle :
1) Dynamic
DECLARE
CURSOR IX IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE ='TABLE'
AND OWNER='SCHEMA_NAME';
CURSOR IY IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE
IN ('SEQUENCE',
'PROCEDURE',
'PACKAGE',
'FUNCTION',
'VIEW') AND OWNER='SCHEMA_NAME';
CURSOR IZ IS
SELECT * FROM ALL_OBJECTS WHERE OBJECT_TYPE IN ('TYPE') AND OWNER='SCHEMA_NAME';
BEGIN
FOR X IN IX LOOP
EXECUTE IMMEDIATE('DROP '||X.OBJECT_TYPE||' SCHEMA_NAME.'||X.OBJECT_NAME|| ' CASCADE CONSTRAINT');
END LOOP;
FOR Y IN IY LOOP
EXECUTE IMMEDIATE('DROP '||Y.OBJECT_TYPE||' SCHEMA_NAME.'||Y.OBJECT_NAME);
END LOOP;
FOR Z IN IZ LOOP
EXECUTE IMMEDIATE('DROP '||Z.OBJECT_TYPE||' SCHEMA_NAME.'||Z.OBJECT_NAME||' FORCE ');
END LOOP;
END;
/
2)Static
SELECT 'DROP TABLE "' || TABLE_NAME || '" CASCADE CONSTRAINTS;' FROM user_tables
union ALL
select 'drop '||object_type||' '|| object_name || ';' from user_objects
where object_type in ('VIEW','PACKAGE','SEQUENCE', 'PROCEDURE', 'FUNCTION')
union ALL
SELECT 'drop '
||object_type
||' '
|| object_name
|| ' force;'
FROM user_objects
WHERE object_type IN ('TYPE');
Update: This got fixed in C# 7.0 with pattern matching
switch (MyObj)
case Type1 t1:
case Type2 t2:
case Type3 t3:
Old answer:
It is a hole in C#'s game, no silver bullet yet.
You should google on the 'visitor pattern' but it might be a little heavy for you but still something you should know about.
Here's another take on the matter using Linq: http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx
Otherwise something along these lines could help
// nasty..
switch(MyObj.GetType.ToString()){
case "Type1": etc
}
// clumsy...
if myObj is Type1 then
if myObj is Type2 then
etc.
You better use array_shift()
. That will return the first element of the array, remove it from the array and re-index the array. All in one efficient method.
Just grep the ID from docker images
:
docker build -t creack/node:latest .
ID="$(docker images | grep 'creak/node' | head -n 1 | awk '{print $3}')"
docker tag "$ID" creack/node:0.10.24
docker tag "$ID" creack/node:latest
Needs no temporary file and gives full build output. You still can redirect it to /dev/null
or a log file.
No, you can not.
You can call a function
from a stored procedure
and debug a stored procedure
(this will step into the function
)
If you have to remove the first few characters that are preceded by a special character like #
, this is a good one:
UPDATE tblInvalidID
SET [ColumnName] =stuff(ColumnName, 1, charindex('#', ColumnName), ' ')
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
If you trust the data source, you can use eval
to convert your string into a dictionary:
eval(your_json_format_string)
Example:
>>> x = "{'a' : 1, 'b' : True, 'c' : 'C'}"
>>> y = eval(x)
>>> print x
{'a' : 1, 'b' : True, 'c' : 'C'}
>>> print y
{'a': 1, 'c': 'C', 'b': True}
>>> print type(x), type(y)
<type 'str'> <type 'dict'>
>>> print y['a'], type(y['a'])
1 <type 'int'>
>>> print y['a'], type(y['b'])
1 <type 'bool'>
>>> print y['a'], type(y['c'])
1 <type 'str'>