For the sake of everyone and myself, here is how I use it:
def run_sql(conn_String):
output_connection = engine.create_engine(conn_string, poolclass=NullPool).connect()
rows = output_connection.execute('select * from db1.t1').fetchall()
return [dict(row) for row in rows]
Below is a Swift port of "SAMTextView" ObjC code posted as one of the first handful of replies to the question. I tested it on iOS 8. I tweaked a couple of things, including the bounds offset for the placement of the placeholder text, as the original was too high and too far right (used suggestion in one of the comments to that post).
I know there are a lot of simple solutions, but I like the approach of subclassing UITextView because it's reusable and I don't have to clutter classes utilizing it with the mechanisms.
Swift 2.2:
import UIKit
class PlaceholderTextView: UITextView {
@IBInspectable var placeholderColor: UIColor = UIColor.lightGrayColor()
@IBInspectable var placeholderText: String = ""
override var font: UIFont? {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
override var text: String? {
didSet {
setNeedsDisplay()
}
}
override var attributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
private func setUp() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(PlaceholderTextView.textChanged(_:)),
name: UITextViewTextDidChangeNotification, object: self)
}
func textChanged(notification: NSNotification) {
setNeedsDisplay()
}
func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var x = contentInset.left + 4.0
var y = contentInset.top + 9.0
let w = frame.size.width - contentInset.left - contentInset.right - 16.0
let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0
if let style = self.typingAttributes[NSParagraphStyleAttributeName] as? NSParagraphStyle {
x += style.headIndent
y += style.firstLineHeadIndent
}
return CGRect(x: x, y: y, width: w, height: h)
}
override func drawRect(rect: CGRect) {
if text!.isEmpty && !placeholderText.isEmpty {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let attributes: [ String: AnyObject ] = [
NSFontAttributeName : font!,
NSForegroundColorAttributeName : placeholderColor,
NSParagraphStyleAttributeName : paragraphStyle]
placeholderText.drawInRect(placeholderRectForBounds(bounds), withAttributes: attributes)
}
super.drawRect(rect)
}
}
Swift 4.2:
import UIKit
class PlaceholderTextView: UITextView {
@IBInspectable var placeholderColor: UIColor = UIColor.lightGray
@IBInspectable var placeholderText: String = ""
override var font: UIFont? {
didSet {
setNeedsDisplay()
}
}
override var contentInset: UIEdgeInsets {
didSet {
setNeedsDisplay()
}
}
override var textAlignment: NSTextAlignment {
didSet {
setNeedsDisplay()
}
}
override var text: String? {
didSet {
setNeedsDisplay()
}
}
override var attributedText: NSAttributedString? {
didSet {
setNeedsDisplay()
}
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUp()
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
private func setUp() {
NotificationCenter.default.addObserver(self,
selector: #selector(self.textChanged(notification:)),
name: Notification.Name("UITextViewTextDidChangeNotification"),
object: nil)
}
@objc func textChanged(notification: NSNotification) {
setNeedsDisplay()
}
func placeholderRectForBounds(bounds: CGRect) -> CGRect {
var x = contentInset.left + 4.0
var y = contentInset.top + 9.0
let w = frame.size.width - contentInset.left - contentInset.right - 16.0
let h = frame.size.height - contentInset.top - contentInset.bottom - 16.0
if let style = self.typingAttributes[NSAttributedString.Key.paragraphStyle] as? NSParagraphStyle {
x += style.headIndent
y += style.firstLineHeadIndent
}
return CGRect(x: x, y: y, width: w, height: h)
}
override func draw(_ rect: CGRect) {
if text!.isEmpty && !placeholderText.isEmpty {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = textAlignment
let attributes: [NSAttributedString.Key: Any] = [
NSAttributedString.Key(rawValue: NSAttributedString.Key.font.rawValue) : font!,
NSAttributedString.Key(rawValue: NSAttributedString.Key.foregroundColor.rawValue) : placeholderColor,
NSAttributedString.Key(rawValue: NSAttributedString.Key.paragraphStyle.rawValue) : paragraphStyle]
placeholderText.draw(in: placeholderRectForBounds(bounds: bounds), withAttributes: attributes)
}
super.draw(rect)
}
}
Looks like you need the package from the installation media if you're you're offline (located at D:\sources\sxs
) You could copy this to each machine that you require .NET 3.5 on (so technically you only need the installation media once to get the package) and get each machine to run the command:
Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess
There's a guide on MSDN.
That seems to be an extra image being shown there.
You can try using this
<img src="/images/image_of_video.png" alt="image" />
/* write your code for the video here */
Now using jQuery play the video and hide the image as
$('img').click(function () {
$(this).hide();
// use the parameters to play the video now..
})
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
Copy downloaded color schemes to ~/.vim/colors/Your_Color_Scheme
.
Then write
colo Your_Color_Scheme
or
colorscheme Your_Color_Scheme
into your ~/.vimrc
.
See this link for holokai
This one returns time like youtube videos
function getYoutubeLikeToDisplay(millisec) {
var seconds = (millisec / 1000).toFixed(0);
var minutes = Math.floor(seconds / 60);
var hours = "";
if (minutes > 59) {
hours = Math.floor(minutes / 60);
hours = (hours >= 10) ? hours : "0" + hours;
minutes = minutes - (hours * 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
}
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
if (hours != "") {
return hours + ":" + minutes + ":" + seconds;
}
return minutes + ":" + seconds;
}
Output:
You can use package manager (pm
) over adb shell
to list packages:
adb shell pm list packages | sort
and to display where the .apk
file is:
adb shell pm path com.king.candycrushsaga
package:/data/app/com.king.candycrushsaga-1/base.apk
And adb pull
to download the apk.
adb pull data/app/com.king.candycrushsaga-1/base.apk
I just used the simple line in my code and it works :
myCusstomView.setRotation(45);
Hope it works for you.
Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"
Make a list(your_string).
>>> s = "mep"
>>> list(s)
['m', 'e', 'p']
// Month here is 1-indexed (January is 1, February is 2, etc). This is
// because we're using 0 as the day so that it returns the last day
// of the last month, so you have to add 1 to the month number
// so it returns the correct amount of days
function daysInMonth (month, year) {
return new Date(year, month, 0).getDate();
}
// July
daysInMonth(7,2009); // 31
// February
daysInMonth(2,2009); // 28
daysInMonth(2,2008); // 29
All of these are kinds of indices.
primary: must be unique, is an index, is (likely) the physical index, can be only one per table.
unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.
index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.
fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.
You want the :checkbox:checked
selector and map
to create an array of the values:
var checkedValues = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked')
, or for a common name $('input[name="Foo"]:checked')
- Update -
If you don't need IE support then you can now make the map()
call more succinct by using an arrow function:
var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();
the approved answer does not include the essential return false to prevent touchstart from calling click if click is implemented which will result in running the handler twoce.
do:
$(btn).on('click touchstart', e => {
your code ...
return false;
});
File names are case sensitive - please check your file name. it should be in same case in view folder
Just bumped into this post, by getting the same error, trying to test if two variables are both empty (or non-empty). That turns out to be a compound comparison - 7.3. Other Comparison Operators - Advanced Bash-Scripting Guide; and I thought I should note the following:
-e
-z
for testing empty variable (string)test
s and &&
them: [ ... ] && [ ... ]
-a
operator in a single test
: [ ... -a ... ]
Here is a working command (searching through all txt files in a directory, and dumping those that grep
finds contain both of two words):
find /usr/share/doc -name '*.txt' | while read file; do \
a1=$(grep -H "description" $file); \
a2=$(grep -H "changes" $file); \
[ ! -z "$a1" -a ! -z "$a2" ] && echo -e "$a1 \n $a2" ; \
done
Edit 12 Aug 2013: related problem note:
Note that when checking string equality with classic test
(single square bracket [
), you MUST have a space between the "is equal" operator, which in this case is a single "equals" =
sign (although two equals' signs ==
seem to be accepted as equality operator too). Thus, this fails (silently):
$ if [ "1"=="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] ; then echo A; else echo B; fi
A
$ if [ "1"="" ] && [ "1"="1" ] ; then echo A; else echo B; fi
A
$ if [ "1"=="" ] && [ "1"=="1" ] ; then echo A; else echo B; fi
A
... but add the space - and all looks good:
$ if [ "1" = "" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" ] ; then echo A; else echo B; fi
B
$ if [ "1" = "" -a "1" = "1" ] ; then echo A; else echo B; fi
B
$ if [ "1" == "" -a "1" == "1" ] ; then echo A; else echo B; fi
B
Based on Daniel's answer, I wrote this SASS mixin with interpolation (#{}
) for a youtube video's iframe that is inside a Bootstrap modal dialog:
@mixin responsive-modal-wiframe($height: 9, $width: 16.5,
$max-w-allowed: 90, $max-h-allowed: 60) {
$sides-adjustment: 1.7;
iframe {
width: #{$width / $height * ($max-h-allowed - $sides-adjustment)}vh;
height: #{$height / $width * $max-w-allowed}vw;
max-width: #{$max-w-allowed - $sides-adjustment}vw;
max-height: #{$max-h-allowed}vh;
}
@media only screen and (max-height: 480px) {
margin-top: 5px;
.modal-header {
padding: 5px;
.modal-title {font-size: 16px}
}
.modal-footer {display: none}
}
}
Usage:
.modal-dialog {
width: 95vw; // the modal should occupy most of the screen's available space
text-align: center; // this will center the titles and the iframe
@include responsive-modal-wiframe();
}
HTML:
<div class="modal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Video</h4>
</div>
<div class="modal-body">
<iframe src="https://www.youtube-nocookie.com/embed/<?= $video_id ?>?rel=0" frameborder="0"
allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen></iframe>
</div>
<div class="modal-footer">
<button class="btn btn-danger waves-effect waves-light"
data-dismiss="modal" type="button">Close</button>
</div>
</div>
</div>
</div>
This will always display the video without those black parts that youtube adds to the iframe when the width or height is not proportional to the video. Notes:
$sides-adjustment
is a slight adjustment to compensate a tiny part of these black parts showing up on the sides;.modal-footer
;.modal-dialog
;.modal-header
.After a lot of testing, this is working flawlessly for me now.
File > Add > Existing Project...
will let you add projects to your current solution. Just adding this since none of the above posts point that out. This lets you include the same project in multiple solutions.
Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.
It's not possible to identify the computers accessing a web site without the cooperation of their owners. If they let you, however, you can store a cookie to identify the machine when it visits your site again. The key is, the visitor is in control; they can remove the cookie and appear as a new visitor any time they wish.
The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.
An Error
usually shouldn't be caught, as it indicates an abnormal condition that should never occur.
From the Java API Specification for the Error
class:
An
Error
is a subclass ofThrowable
that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.
As the specification mentions, an Error
is only thrown in circumstances that are
Chances are, when an Error
occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError
)
Although an Error
is a subclass of Throwable
which means that it can be caught by a try-catch
clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error
is thrown by the JVM.
There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.
If you are using PoolingHttpClientConnectionManager procedure above doesn't work, custom SSLContext is ignored. You have to pass socketFactoryRegistry in contructor when creating PoolingHttpClientConnectionManager.
SSLContextBuilder builder = SSLContexts.custom();
builder.loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
return true;
}
});
SSLContext sslContext = builder.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext, new X509HostnameVerifier() {
@Override
public void verify(String host, SSLSocket ssl)
throws IOException {
}
@Override
public void verify(String host, X509Certificate cert)
throws SSLException {
}
@Override
public void verify(String host, String[] cns,
String[] subjectAlts) throws SSLException {
}
@Override
public boolean verify(String s, SSLSession sslSession) {
return true;
}
});
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
.<ConnectionSocketFactory> create().register("https", sslsf)
.build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(
socketFactoryRegistry);
CloseableHttpClient httpclient = HttpClients.custom()
.setConnectionManager(cm).build();
For anyone else who runs into this...
Version 1.2.0 of this plugin (current as of this post) doesn't quite work in all cases as documented with Bootstrap 3.0, but it does with a minor workaround.
Specifically, if using an input with icon, the HTML markup is of course slightly different as class names have changed:
<div class="input-group" data-datepicker="true">
<input name="date" type="text" class="form-control" />
<span class="input-group-addon"><i class="icon-calendar"></i></span>
</div>
It seems because of this, you need to use a selector that points directly to the input element itself NOT the parent container (which is what the auto generated HTML on the demo page suggests).
$('*[data-datepicker="true"] input[type="text"]').datepicker({
todayBtn: true,
orientation: "top left",
autoclose: true,
todayHighlight: true
});
Having done this you will probably also want to add a listener for clicking/tapping on the icon so it sets focus on the text input when clicked (which is the behaviour when using this plugin with TB 2.x by default).
$(document).on('touch click', '*[data-datepicker="true"] .input-group-addon', function(e){
$('input[type="text"]', $(this).parent()).focus();
});
NB: I just use a data-datepicker boolean attribute because the class name 'datepicker' is reserved by the plugin and I already use 'date' for styling elements.
I got exceptions in the linq-code so I do it this way (without a complicated extension):
private static IList<Type> loadAllImplementingTypes(Type[] interfaces)
{
IList<Type> implementingTypes = new List<Type>();
// find all types
foreach (var interfaceType in interfaces)
foreach (var currentAsm in AppDomain.CurrentDomain.GetAssemblies())
try
{
foreach (var currentType in currentAsm.GetTypes())
if (interfaceType.IsAssignableFrom(currentType) && currentType.IsClass && !currentType.IsAbstract)
implementingTypes.Add(currentType);
}
catch { }
return implementingTypes;
}
Check out the PHP cURL functions. They should do what you want.
Or if you just want a simple URL GET then:
$lines = file('http://www.example.com/');
If you need this once write:
NSString *stringToSearchThrough = @"-rangeOfString method finds and returns the range of the first occurrence of a given string within the receiver.";
BOOL contains = [stringToSearchThrough rangeOfString:@"occurence of a given string"].location != NSNotFound;
To extend Sean's great and concise answer with some sugar and modern syntax:
// date.js
const getMonthName = (num) => {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Oct', 'Nov', 'Dec'];
return months[num];
};
const formatDate = (d) => {
const date = new Date(d);
const year = date.getFullYear();
const month = getMonthName(date.getMonth());
const day = ('0' + date.getDate()).slice(-2);
const hour = ('0' + date.getHours()).slice(-2);
const minutes = ('0' + date.getMinutes()).slice(-2);
return `${year} ${month} ${day}, ${hour}:${minutes}`;
};
module.exports = formatDate;
Then eg.
import formatDate = require('./date');
const myDate = "2018-07-24T13:44:46.493Z"; // Actual value from wherever, eg. MongoDB date
console.log(formatDate(myDate)); // 2018 Jul 24, 13:44
img
in the center of its parent.img
is an inline element, text-center
aligns inline elements in the center of its container should the container be a block
element. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col text-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
mx-auto
centers block
elements. In order to so, change display
of the img from inline
to block
with d-block
class. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid d-block mx-auto">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
d-flex
and justify-content-center
on its parent. <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.1/css/bootstrap.css" rel="stylesheet"/>_x000D_
<div class="container mt-5">_x000D_
<div class="row">_x000D_
<div class="col d-flex justify-content-center">_x000D_
<img src="https://upload.wikimedia.org/wikipedia/en/8/80/Wikipedia-logo-v2.svg" alt="" class="img-fluid">_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
You could use a ParametrizedThreadStart delegate:
string parameter = "Hello world!";
Thread t = new Thread(new ParameterizedThreadStart(MyMethod));
t.Start(parameter);
I worked around this by using UriBuilder instead.
UriBuilder builder = new UriBuilder(slct.Text);
if (DeleteFileOnServer(builder.Uri))
{
...
}
'sender' is called object which has some action perform on some control
'event' its having some information about control which has some behavoiur and identity perform by some user.when action will generate by occuring for event add it keep within array is called event agrs
private static final String hostExtractorRegexString = "(?:https?://)?(?:www\\.)?(.+\\.)(com|au\\.uk|co\\.in|be|in|uk|org\\.in|org|net|edu|gov|mil)";
private static final Pattern hostExtractorRegexPattern = Pattern.compile(hostExtractorRegexString);
public static String getDomainName(String url){
if (url == null) return null;
url = url.trim();
Matcher m = hostExtractorRegexPattern.matcher(url);
if(m.find() && m.groupCount() == 2) {
return m.group(1) + m.group(2);
}
return null;
}
Explanation : The regex has 4 groups. The first two are non-matching groups and the next two are matching groups.
The first non-matching group is "http" or "https" or ""
The second non-matching group is "www." or ""
The second matching group is the top level domain
The first matching group is anything after the non-matching groups and anything before the top level domain
The concatenation of the two matching groups will give us the domain/host name.
PS : Note that you can add any number of supported domains to the regex.
I think that's another case of git error messages being misleading. Usually when I've seen that error it's due to ssh problems. Did you add your public ssh key to your github account?
Edit: Also, the xinet.d forum post is referring to running the git-daemon as a service so that people could pull from your system. It's not necessary to run git-daemon to push to github.
Since sockstat wasn't natively installed on my machine I hacked up stanwise's answer to use netstat instead..
netstat -nlp | grep -E "[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\:2000" | awk '{print $7}' | sed -e "s/\/.*//g""
This is a well-known nuisance when posting multiline commands in R. (You can get different behavior when you source()
a script to when you copy-and-paste the lines, both with multiline and comments)
ggplot(...) + geom_whatever1(...) +
geom_whatever2(...) +
stat_whatever3(...) +
geom_title(...) + scale_y_log10(...)
Error in "+ geom_whatever2(...) invalid argument to unary operator"
cf. answer to "Split code over multiple lines in an R script"
Just leave banner as being undefined and it does not get included.
Screen Size Class
-
Hidden on all .d-none
Hidden only on xs .d-none .d-sm-block
Hidden only on sm .d-sm-none .d-md-block
Hidden only on md .d-md-none .d-lg-block
Hidden only on lg .d-lg-none .d-xl-block
Hidden only on xl .d-xl-none
Visible on all .d-block
Visible only on xs .d-block .d-sm-none
Visible only on sm .d-none .d-sm-block .d-md-none
Visible only on md .d-none .d-md-block .d-lg-none
Visible only on lg .d-none .d-lg-block .d-xl-none
Visible only on xl .d-none .d-xl-block
Refer this link http://getbootstrap.com/docs/4.0/utilities/display/#hiding-elements
4.5 link: https://getbootstrap.com/docs/4.5/utilities/display/#hiding-elements
You'll need to serialize the image to a binary format that can be stored in a SQL BLOB column. Assuming you're using SQL Server, here is a good article on the subject:
this works too, ...if you have multiple column joins
from p in context.Periods
join f in context.Facts
on new {
id = p.periodid,
p.otherid
} equals new {
f.id,
f.otherid
} into fg
from fgi in fg.DefaultIfEmpty()
where p.companyid == 100
select f.value
In your NGINX vhost file, in location block which processes your PHP files (usually location ~ \.php$ {
) through FastCGI, make sure you have next lines:
proxy_buffer_size 128k;
proxy_buffers 4 256k;
proxy_busy_buffers_size 256k;
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
After that don't forget to restart fpm and nginx.
Additional:
NGINX vhost paths
/etc/nginx/sites-enabled/
- LinuxRestart NGINX:
sudo service nginx restart
- Linuxbrew service restart nginx
- MacRestart FPM:
Determine fpm process name:
- systemctl list-unit-files | grep fpm
- Linux
- brew services list | grep php
- Mac
and then restart it with:
sudo service <service-name> restart
- Linuxbrew services restart <service-name>
- MacA little more compact than the other answers if you want to use c as a TForm:
if(c is TForm form){
form.DoStuff();
}
this is what i did
first execute create database x
. x is the name of your old database eg the name of the mdf.
Then open sql sever configration and stop the sql sever.
There after browse to the location of your new created database it should be under program file, in my case is
C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQL\MSSQL\DATA
and repleace the new created mdf and Idf with the old files/database.
then simply restart the sql server and walla :)
The easiest way to do this is to just fake it. A List Apart has covered this extensively over the years, like in this article from Dan Cederholm from 2004.
Here's how I usually do it:
<div id="container" class="clearfix" style="margin:0 auto;width:950px;background:white url(SOME_REPEATING_PATTERN.png) scroll repeat-y center top;">
<div id="navigation" style="float:left;width:190px;padding-right:10px;">
<!-- Navigation -->
</div>
<div id="content" style="float:left;width:750px;">
<!-- Content -->
</div>
</div>
You can easily add a header onto this design by wrapping #container in another div, embedding the header div as #container's sibling, and moving the margin and width styles to the parent container. Also, the CSS should be moved into a separate file and not kept inline, etc. etc. Finally, the clearfix class can be found on positioniseverything.
Just make use of JavaScript promises. Put the then
method after swal
function. We do not need to use timer features.
For example:
swal({
title: "Wow!",
text: "Message!",
type: "success"
}).then(function() {
window.location = "redirectURL";
});
The promise method .then
is used to wait until the user reads the information of modal window and decide which decision to make by clicking in one button. For example, Yes
or No
.
After the click, the Sweet Alert could redirect the user to another screen, call another Sweet Alert modal window with contains new and subsequent question, go to a external link, etc.
Again, we do not have to use timer because it is much better to control user action. The user could wait for the eternity or take action as a Thanos' or Iron Man's finger snap.
With the use of promises, the code becomes shorter, clean and elegant.
Using your code with some random data, this would work:
fig, axs = plt.subplots(2,5, figsize=(15, 6), facecolor='w', edgecolor='k')
fig.subplots_adjust(hspace = .5, wspace=.001)
axs = axs.ravel()
for i in range(10):
axs[i].contourf(np.random.rand(10,10),5,cmap=plt.cm.Oranges)
axs[i].set_title(str(250+i))
The layout is off course a bit messy, but that's because of your current settings (the figsize, wspace etc).
Just to update this answer for the sake of others who happen to end up on this page.
In Rails 3, you just need to create a file at views/users/show.json.erb
. The @user
object will be available to the view (just like it would be for html.) You don't even need to_json
anymore.
To summarize, it's just
# users contoller
def show
@user = User.find( params[:id] )
respond_to do |format|
format.html
format.json
end
end
and
/* views/users/show.json.erb */
{
"name" : "<%= @user.name %>"
}
Because it's the same component. You can either listen to route change by injecting the ActivatedRoute
and reacting to changes of params and query params, or you can change the default RouteReuseStrategy
, so that a component will be destroyed and re-rendered when the URL changes instead of re-used.
Heres a quick solution.
You find styles.xml and you change the base application theme to "Theme.AppCompat.NoActionBar" as shown below.
<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
<!-- Customize your theme here. -->
</style>
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
For Windows, S3 Browser is the easiest way I have found. It is excellent software, and it is free for non-commercial use.
To "remove" the 1st character point to the second character:
char mystr[] = "Nmy stringP";
char *p = mystr;
p++; /* 'N' is not in `p` */
To remove the last character replace it with a '\0'
.
p[strlen(p)-1] = 0; /* 'P' is not in `p` (and it isn't in `mystr` either) */
This is how it worked for me:
I ran the below command
sudo install_name_tool -change libmysqlclient.18.dylib /usr/local/mysql/lib/libmysqlclient.18.dylib ~/.rvm/gems/ruby-1.9.2-p180/gems/mysql2-0.2.7/lib/mysql2/mysql2.bundle
My environments:
$ rails -v
Rails 3.0.6
$ mysql --version
mysql Ver 14.14 Distrib 5.5.11, for osx10.6 (i386) using readline 5.1
$ ruby -v
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.7.0]
Hope this helps someone.
While hash(frozenset(x.items())
and hash(tuple(sorted(x.items()))
work, that's doing a lot of work allocating and copying all the key-value pairs. A hash function really should avoid a lot of memory allocation.
A little bit of math can help here. The problem with most hash functions is that they assume that order matters. To hash an unordered structure, you need a commutative operation. Multiplication doesn't work well as any element hashing to 0 means the whole product is 0. Bitwise &
and |
tend towards all 0's or 1's. There are two good candidates: addition and xor.
from functools import reduce
from operator import xor
class hashable(dict):
def __hash__(self):
return reduce(xor, map(hash, self.items()), 0)
# Alternative
def __hash__(self):
return sum(map(hash, self.items()))
One point: xor works, in part, because dict
guarantees keys are unique. And sum works because Python will bitwise truncate the results.
If you want to hash a multiset, sum is preferable. With xor, {a}
would hash to the same value as {a, a, a}
because x ^ x ^ x = x
.
If you really need the guarantees that SHA makes, this won't work for you. But to use a dictionary in a set, this will work fine; Python containers are resiliant to some collisions, and the underlying hash functions are pretty good.
If you want the year from a (unknown) datetime-object:
tijd = datetime.datetime(9999, 12, 31, 23, 59, 59)
>>> tijd.timetuple()
time.struct_time(tm_year=9999, tm_mon=12, tm_mday=31, tm_hour=23, tm_min=59, tm_sec=59, tm_wday=4, tm_yday=365, tm_isdst=-1)
>>> tijd.timetuple().tm_year
9999
I encountered a similar problem when I was using the below to obtain connection factory
ConnectionFactory factory = new
ActiveMQConnectionFactory("admin","admin","tcp://:61616");
Its resolved when I changed it to the below
ConnectionFactory factory = new ActiveMQConnectionFactory("tcp://:61616");
The below then showed that my Q size was increasing..
http://:8161/admin/queues.jsp
Try calling label.Invalidate()
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invalidate(VS.80).aspx
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
R only automatically prints the output of unassigned expressions, so just assign the result of the apply
to a variable, and it won't get printed.
git show
is also a great command.
It's kind of like svn diff
, but you can pass it a commit guid and see that diff.
PDO offers an alternative designed to replace mysql_escape_string() with the PDO::quote() method.
Here is an excerpt from the PHP website:
<?php
$conn = new PDO('sqlite:/home/lynn/music.sql3');
/* Simple string */
$string = 'Nice';
print "Unquoted string: $string\n";
print "Quoted string: " . $conn->quote($string) . "\n";
?>
The above code will output:
Unquoted string: Nice
Quoted string: 'Nice'
you can try this code to capture a div When the div is very wide or offset relative to the screen
var div = $("#div")[0];
var rect = div.getBoundingClientRect();
var canvas = document.createElement("canvas");
canvas.width = rect.width;
canvas.height = rect.height;
var ctx = canvas.getContext("2d");
ctx.translate(-rect.left,-rect.top);
html2canvas(div, {
canvas:canvas,
height:rect.height,
width:rect.width,
onrendered: function(canvas) {
var image = canvas.toDataURL("image/png");
var pHtml = "<img src="+image+" />";
$("#parent").append(pHtml);
}
});
It's simpler than I initially thought.. Basically you have a page that does nothing, until the data you want to send is available (say, a new message arrives).
Here is a really basic example, which sends a simple string after 2-10 seconds. 1 in 3 chance of returning an error 404 (to show error handling in the coming Javascript example)
msgsrv.php
<?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
Note: With a real site, running this on a regular web-server like Apache will quickly tie up all the "worker threads" and leave it unable to respond to other requests.. There are ways around this, but it is recommended to write a "long-poll server" in something like Python's twisted, which does not rely on one thread per request. cometD is an popular one (which is available in several languages), and Tornado is a new framework made specifically for such tasks (it was built for FriendFeed's long-polling code)... but as a simple example, Apache is more than adequate! This script could easily be written in any language (I chose Apache/PHP as they are very common, and I happened to be running them locally)
Then, in Javascript, you request the above file (msg_srv.php
), and wait for a response. When you get one, you act upon the data. Then you request the file and wait again, act upon the data (and repeat)
What follows is an example of such a page.. When the page is loaded, it sends the initial request for the msgsrv.php
file.. If it succeeds, we append the message to the #messages
div, then after 1 second we call the waitForMsg function again, which triggers the wait.
The 1 second setTimeout()
is a really basic rate-limiter, it works fine without this, but if msgsrv.php
always returns instantly (with a syntax error, for example) - you flood the browser and it can quickly freeze up. This would better be done checking if the file contains a valid JSON response, and/or keeping a running total of requests-per-minute/second, and pausing appropriately.
If the page errors, it appends the error to the #messages
div, waits 15 seconds and then tries again (identical to how we wait 1 second after each message)
The nice thing about this approach is it is very resilient. If the clients internet connection dies, it will timeout, then try and reconnect - this is inherent in how long polling works, no complicated error-handling is required
Anyway, the long_poller.htm
code, using the jQuery framework:
<html>
<head>
<title>BargePoller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type="text/css" media="screen">
body{ background:#000;color:#fff;font-size:.9em; }
.msg{ background:#aaa;padding:.2em; border-bottom:1px #000 solid}
.old{ background-color:#246499;}
.new{ background-color:#3B9957;}
.error{ background-color:#992E36;}
</style>
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
/* Simple helper to add a div.
type is the name of a CSS class (old/new/error).
msg is the contents of the div */
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
/* This requests the url "msgsrv.php"
When it complete (or errors)*/
$.ajax({
type: "GET",
url: "msgsrv.php",
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data){ /* called when request to barge.php completes */
addmsg("new", data); /* Add response to a .msg div (with the "new" class)*/
setTimeout(
waitForMsg, /* Request next message */
1000 /* ..after 1 seconds */
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg, /* Try again after.. */
15000); /* milliseconds (15seconds) */
}
});
};
$(document).ready(function(){
waitForMsg(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="messages">
<div class="msg old">
BargePoll message requester!
</div>
</div>
</body>
</html>
SOLVED
.table-wrapper {
overflow-x:scroll;
overflow-y:visible;
width:250px;
margin-left: 120px;
}
td, th {
padding: 5px 20px;
width: 100px;
}
th:first-child {
position: fixed;
left: 5px
}
UPDATE
$(function () { _x000D_
$('.table-wrapper tr').each(function () {_x000D_
var tr = $(this),_x000D_
h = 0;_x000D_
tr.children().each(function () {_x000D_
var td = $(this),_x000D_
tdh = td.height();_x000D_
if (tdh > h) h = tdh;_x000D_
});_x000D_
tr.css({height: h + 'px'});_x000D_
});_x000D_
});
_x000D_
body {_x000D_
position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
overflow-x:scroll;_x000D_
overflow-y:visible;_x000D_
width:200px;_x000D_
margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
padding: 5px 20px;_x000D_
width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
_x000D_
}_x000D_
th:first-child {_x000D_
position: absolute;_x000D_
left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
<meta charset="utf-8">_x000D_
<title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
<h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
<table id="consumption-data" class="data">_x000D_
<thead class="header">_x000D_
<tr>_x000D_
<th>Month</th>_x000D_
<th>Item 1</th>_x000D_
<th>Item 2</th>_x000D_
<th>Item 3</th>_x000D_
<th>Item 4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tbody class="results">_x000D_
<tr>_x000D_
<th>Jan is an awesome month</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Feb</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Mar</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Apr</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td> _x000D_
</tr>_x000D_
<tr> _x000D_
<th>May</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<th>Jun</th>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
<td>3163</td>_x000D_
</tr>_x000D_
_x000D_
<tr>_x000D_
<th>...</th>_x000D_
<td>...</td>_x000D_
<td>...</td>_x000D_
<td>...</td>_x000D_
<td>...</td>_x000D_
</tr>_x000D_
</tbody>_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
DELETE FROM blob
WHERE NOT EXISTS (
SELECT *
FROM files
WHERE id=blob.id
)
May be this is useful to you.
//Method writes a string to a text file
-(void) writeToTextFile{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
//create content - four lines of text
NSString *content = @"One\nTwo\nThree\nFour\nFive";
//save content to the documents directory
[content writeToFile:fileName
atomically:NO
encoding:NSUTF8StringEncoding
error:nil];
}
//Method retrieves content from documents directory and
//displays it in an alert
-(void) displayContent{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *fileName = [NSString stringWithFormat:@"%@/textfile.txt",
documentsDirectory];
NSString *content = [[NSString alloc] initWithContentsOfFile:fileName
usedEncoding:nil
error:nil];
//use simple alert from my library (see previous post for details)
[ASFunctions alert:content];
[content release];
}
So for people who want semantics similar to:
$ chmod 755 somefile
Use:
$ python -c "import os; os.chmod('somefile', 0o755)"
If your Python is older than 2.6:
$ python -c "import os; os.chmod('somefile', 0755)"
Normally when you don't use __block, the block will copy(retain) the variable, so even if you modify the variable, the block has access to the old object.
NSString* str = @"hello";
void (^theBlock)() = ^void() {
NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints @"hello"
In these 2 cases you need __block:
1.If you want to modify the variable inside the block and expect it to be visible outside:
__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
str = @"how are you";
};
theBlock();
NSLog(@"%@", str); //prints "how are you"
2.If you want to modify the variable after you have declared the block and you expect the block to see the change:
__block NSString* str = @"hello";
void (^theBlock)() = ^void() {
NSLog(@"%@", str);
};
str = @"how are you";
theBlock(); //prints "how are you"
Add System.IO.Compression.ZipFile as nuget reference it is working
If you are using web api then you should make a http POST
call to URL : https://www.googleapis.com/oauth2/v4/token
with following request body
client_id: <YOUR_CLIENT_ID>
client_secret: <YOUR_CLIENT_SECRET>
refresh_token: <REFRESH_TOKEN_FOR_THE_USER>
grant_type: refresh_token
refresh token never expires so you can use it any number of times. The response will be a JSON like this:
{
"access_token": "your refreshed access token",
"expires_in": 3599,
"scope": "Set of scope which you have given",
"token_type": "Bearer"
}
To generate in the range: {0,..,9}
r=$(( $RANDOM % 10 )); echo $r
To generate in the range: {40,..,49}
r=$(( $RANDOM % 10 + 40 )); echo $r
In SQL Server 2016 Management Studio, the process for getting an azure database to your local machine has been streamlined.
Right click on the database you want to import, click Tasks > Export data-tier application, and export your database to a local .dacpac file.
In your local target SQL server instance, you can right click Databases > Import data-tier application, and once it's local, you can do things like backup and restore the database.
I was able to overcome this by using the "vh" metric with max-height on the .modal-body element. 70vh looked about right for my uses.
.modal-body {
overflow-y: auto;
max-height: 70vh;
}
One big difference with python 3.4 + pycharm is that the dict() constructor produces a "syntax error" message if the number of keys exceeds 256.
I prefer using the dict literal now.
You can refer to socket.io rooms. When you handshaked socket - you can join him to named room, for instance "user.#{userid}".
After that, you can send private message to any client by convenient name, for instance:
io.sockets.in('user.125').emit('new_message', {text: "Hello world"})
In operation above we send "new_message" to user "125".
thanks.
Quick List: There are a number of common types of
setup.exe
files. Here are some of them in a "short-list". More fleshed-out details here (towards bottom).
Setup.exe Extract: (various flavors to try)
setup.exe /a setup.exe /s /extract_all setup.exe /s /extract_all:[path] setup.exe /stage_only setup.exe /extract "C:\My work" setup.exe /x setup.exe /x [path] setup.exe /s /x /b"C:\FolderInWhichMSIWillBeExtracted" /v"/qn" dark.exe -x outputfolder setup.exe
dark.exe
is a WiX binary - install WiX to extract a WiX setup.exe (as of now). More (section 4).
There is always:
setup.exe /?
MSI Extract: msiexec.exe
/ File.msi
extraction:
msiexec /a File.msi msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn
Many Setup Tools: It is impossible to cover all the different kinds of possible setup.exe
files. They might feature all kinds of different command line switches. There are so many possible tools that can be used. (non-MSI
,MSI
, admin-tools
, multi-platform
, etc...).
NSIS / Inno: Commmon, free tools such as Inno Setup
seem to make extraction hard (unofficial unpacker, not tried by me, run by virustotal.com). Whereas NSIS
seems to use regular archives that standard archive software (7-zip et al) can open and extract.
General Tricks: One trick is to launch the
setup.exe
and look in the1)
system's temp folder for extracted files
. Another trick is to use2)
7-Zip, WinRAR, WinZip
or similar archive tools to see if they can read the format. Some claim success by3)
opening the setup.exe in Visual Studio
. Not a technique I use.4)
And there is obviously application repackaging
- capturing the changes done to a computer after a setup has run and clean it up - requires a special tool (most of the free ones come and go, Advanced Installer Architect and AdminStudio are big players).
UPDATE: A quick presentation of various deployment tools used to create installers: How to create windows installer (comprehensive links).
And a simpler list view of the most used development tools as of now (2018), for quicker reading and overview.
And for safekeeping:
- Create MSI from extracted setup files (towards bottom)
- Regarding silent installation using Setup.exe generated using Installshield 2013 (.issuite) project file (different kinds of Installshield setup.exe files)
- What is the purpose of administrative installation initiated using msiexec /a?.
Just a disclaimer: A setup.exe
file can contain an embedded MSI, it can be a legacy style (non-MSI) installer or it can be just a regular executable with no means of extraction whatsoever. The "discussion" below first presents the use of admin images for MSI files and how to extract MSI files from setup.exe files. Then it provides some links to handle other types of setup.exe files. Also see the comments section.
UPDATE: a few sections have now been added directly below, before the description of MSI file extract using administrative installation. Most significantly a blurb about extracting WiX setup.exe bundles (new kid on the block). Remember that a "last resort" to find extracted setup files, is to launch the installer and then look for extracted files in the temp folder (Hold down Windows Key, tap R, type %temp%
or %tmp%
and hit Enter) - try the other options first though - for reliability reasons.
Apologies for the "generalized mess" with all this heavy inter-linking. I do believe that you will find what you need if you dig enough in the links, but the content should really be cleaned up and organized better.
General links:
Extract content:
Vendor links:
Tech Note: The WiX toolkit now delivers setup.exe
files built with the bootstrapper tool Burn
that you need the toolkit's own dark.exe
decompiler to extract. Burn is used to build setup.exe files that can install several embedded MSI or executables in a specified sequence. Here is a sample extraction command:
dark.exe -x outputfolder MySetup.exe
Before you can run such an extraction, some prerequisite steps are required:
command prompt
, CD
to the folder where the setup.exe
resides. Then specify the above command and press EnterMSI or Windows Installer has built-in support for this - the extraction of files from an MSI file. This is called an administrative installation. It is basically intended as a way to create a network installation point from which the install can be run on many target computers. This ensures that the source files are always available for any repair operations.
Note that running an admin install versus using a zip tool to extract the files is very different! The latter will not adjust the media layout of the media table so that the package is set to use external source files - which is the correct way. Always prefer to run the actual admin install over any hacky zip extractions. As to compression, there are actually three different compression algorithms used for the cab files inside the MSI file format: MSZip, LZX, and Storing (uncompressed). All of these are handled correctly by doing an admin install.
Important: Windows Installer caches installed MSI files on the system for repair, modify and uninstall scenarios. Starting with Windows 7 (MSI version 5) the MSI files are now cached full size to avoid breaking the file signature that prevents the UAC prompt on setup launch (a known Vista problem). This may cause a tremendous increase in disk space consumption (several gigabytes for some systems). To prevent caching a huge MSI file, you should run an admin-install of the package before installing. This is how a company with proper deployment in a managed network would do things, and it will strip out the cab files and make a network install point with a small MSI file and files besides it.
It is recommended to read more about admin-installs since it is a useful concept, and I have written a post on stackoverflow: What is the purpose of administrative installation initiated using msiexec /a?.
In essence the admin install is important for:
Please read the stackoverflow post linked above for more details. It is quite an important concept for system administrators, application packagers, setup developers, release managers, and even the average user to see what they are installing etc...
You can perform an admin-install in a few different ways depending on how the installer is delivered. Essentially it is either delivered as an MSI file or wrapped in an setup.exe file.
Run these commands from an elevated command prompt, and follow the instructions in the GUI for the interactive command lines:
MSI files:
msiexec /a File.msi
that's to run with GUI, you can do it silently too:
msiexec /a File.msi TARGETDIR=C:\MyInstallPoint /qn
setup.exe files:
setup.exe /a
A setup.exe file can also be a legacy style setup (non-MSI) or the dreaded Installscript MSI file type - a well known buggy Installshield project type with hybrid non-standards-compliant MSI format. It is essentially an MSI with a custom, more advanced GUI, but it is also full of bugs.
For legacy setup.exe files the /a will do nothing, but you can try the /extract_all:[path] switch as explained in this pdf. It is a good reference for silent installation and other things as well. Another resource is this list of Installshield setup.exe command line parameters.
MSI patch files (*.MSP) can be applied to an admin image to properly extract its files. 7Zip will also be able to extract the files, but they will not be properly formatted.
Finally - the last resort - if no other way works, you can get hold of extracted setup files by cleaning out the temp folder on your system, launch the setup.exe interactively and then wait for the first dialog to show up. In most cases the installer will have extracted a bunch of files to a temp folder. Sometimes the files are plain, other times in CAB format, but Winzip, 7Zip or even Universal Extractor (haven't tested this product) - may be able to open these.
i think cgywin might not work for you as you can only compile your code in Win7 if you fire up the command prompt; you need to use MinGW compiler toolset instead. After you have install your compiler, go to Properties->C/C++ Build->Tool Chain Editor -> Change your current toolchain to MinGW GCC.
I've tried to find a "fit to screen" property but there is no such.
But setting widget's "maximumSize" to a "some big number" ( like 2000 x 2000 ) will automatically fit the widget to the parent widget space.
For me it was a permission problem.
enter:
mysqld --verbose --help | grep -A 1 "Default options"
[Warning] World-writable config file '/etc/mysql/my.cnf' is ignored.
So try to execute the following, and then restart the server
chmod 644 '/etc/mysql/my.cnf'
It will give mysql access to read and write to the file.
This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.
I don't think that other example is what you're looking for. If you're just updating one column from another column in the same table you should be able to use something like this.
update some_table set null_column = not_null_column where null_column is null
Try this for a friendly representation of time differences (in milliseconds):
String friendlyTimeDiff(long timeDifferenceMilliseconds) {
long diffSeconds = timeDifferenceMilliseconds / 1000;
long diffMinutes = timeDifferenceMilliseconds / (60 * 1000);
long diffHours = timeDifferenceMilliseconds / (60 * 60 * 1000);
long diffDays = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24);
long diffWeeks = timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 7);
long diffMonths = (long) (timeDifferenceMilliseconds / (60 * 60 * 1000 * 24 * 30.41666666));
long diffYears = timeDifferenceMilliseconds / ((long)60 * 60 * 1000 * 24 * 365);
if (diffSeconds < 1) {
return "less than a second";
} else if (diffMinutes < 1) {
return diffSeconds + " seconds";
} else if (diffHours < 1) {
return diffMinutes + " minutes";
} else if (diffDays < 1) {
return diffHours + " hours";
} else if (diffWeeks < 1) {
return diffDays + " days";
} else if (diffMonths < 1) {
return diffWeeks + " weeks";
} else if (diffYears < 1) {
return diffMonths + " months";
} else {
return diffYears + " years";
}
}
Here's another method if you can safely use CSS3's transform
property:
.fixed-horizontal-center
{
position: fixed;
top: 100px; /* or whatever top you need */
left: 50%;
width: auto;
-webkit-transform: translateX(-50%);
-moz-transform: translateX(-50%);
-ms-transform: translateX(-50%);
-o-transform: translateX(-50%);
transform: translateX(-50%);
}
...or if you want both horizontal AND vertical centering:
.fixed-center
{
position: fixed;
top: 50%;
left: 50%;
width: auto;
height: auto;
-webkit-transform: translate(-50%,-50%);
-moz-transform: translate(-50%,-50%);
-ms-transform: translate(-50%,-50%);
-o-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);
}
Use the below snippet it will be helpfull.
string POCpath = @"G:\Althaf\abc.xlsx";
string POCConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + POCpath + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";
OleDbConnection POCcon = new OleDbConnection(POCConnection);
OleDbCommand POCcommand = new OleDbCommand();
DataTable dt = new DataTable();
OleDbDataAdapter POCCommand = new OleDbDataAdapter("select * from [Sheet1$] ", POCcon);
POCCommand.Fill(dt);
Console.WriteLine(dt.Rows.Count);
Change:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\\Wow6432Node\\MySQL AB\\MySQL Connector\\Net"))
To:
using (RegistryKey key = Registry.LocalMachine.OpenSubKey("Software\Wow6432Node\MySQL AB\MySQL Connector\Net"))
DateTime dateTime = DateTime.Parse(dateTimeStr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = explode("\r\n\r\nHTTP/", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = explode("\r\n\r\n", $parts, 2);
Works with HTTP/1.1 100 Continue
before other headers.
If you need work with buggy servers which sends only LF instead of CRLF as line breaks you can use preg_split
as follows:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$parts = preg_split("@\r?\n\r?\nHTTP/@u", $response);
$parts = (count($parts) > 1 ? 'HTTP/' : '').array_pop($parts);
list($headers, $body) = preg_split("@\r?\n\r?\n@u", $parts, 2);
I suspect there are many answers like this on SO but here you go:
if ( typeof pagetype !== 'undefined' && pagetype == 'textpage' ) {
...
}
Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
Set rFND = Nothing
With SHT.UsedRange
Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
sFirstAddress = rFND.Address
Do
If strResults = vbNullString Then
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
End If
Set rFND = .FindNext(rFND)
Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
End If
End With
Next
If strResults = vbNullString Then
GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
GetSearchArray = Array(strResults)
Else
GetSearchArray = Split(strResults, "|")
End If
End Function
Sub test2()
For Each X In GetSearchArray("1")
Debug.Print X
Next
End Sub
Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.
You may want to build a virtualenv
of python3, then install packages of python3 after activating the virtualenv. So your system won't be messed up :)
This could be something like:
virtualenv -p /usr/bin/python3 py3env
source py3env/bin/activate
pip install package-name
I just found the same issue with Aliases on a Windows install of Xampp.
To solve the 403 error:
<Directory "C:/Your/Directory/With/No/Trailing/Slash">
Require all granted
</Directory>
Alias /dev "C:/Your/Directory/With/No/Trailing/Slash"
The default Xampp set up should be fine with just this. Some people have experienced issues with a deny placed on the root directory so flipping out the directory tag to:
<Directory "C:/Your/Directory/With/No/Trailing/Slash">
Allow from all
Require all granted
</Directory>
Would help with this but the current version of Xampp (v1.8.1 at the time of writing) doesn't require it.
As for op's issue with port 80 Xampp includes a handy Netstat button to discover what's using your ports. Fire that off and fix the conflict, I imagine it could have been IIS but can't be sure.
You can use the Session object
import requests
headers = {'User-Agent': 'Mozilla/5.0'}
payload = {'username':'niceusername','password':'123456'}
session = requests.Session()
session.post('https://admin.example.com/login.php',headers=headers,data=payload)
# the session instance holds the cookie. So use it to get/post later.
# e.g. session.get('https://example.com/profile')
<roleManager
enabled="true"
cacheRolesInCookie="false"
cookieName=".ASPXROLES"
cookieTimeout="30"
cookiePath="/"
cookieRequireSSL="false"
cookieSlidingExpiration="true"
cookieProtection="All"
defaultProvider="AspNetSqlRoleProvider"
createPersistentCookie="false"
maxCachedResults="25">
<providers>
<clear />
<add
connectionStringName="MembershipConnection"
applicationName="Mvc3"
name="AspNetSqlRoleProvider"
type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
<add
applicationName="Mvc3"
name="AspNetWindowsTokenRoleProvider"
type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
Insert:
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
at the end of AssemblyInfo.cs file
I also like to define my own functions that take and return arguments in degrees rather than radians. I am sure there some capitalization purest who don't like my names, but I just use a capital first letter for my custom functions. The definitions and testing code are below.
#Definitions for trig functions using degrees.
def Cos(a):
return cos(radians(a))
def Sin(a):
return sin(radians(a))
def Tan(a):
return tan(radians(a))
def ArcTan(a):
return degrees(arctan(a))
def ArcSin(a):
return degrees(arcsin(a))
def ArcCos(a):
return degrees(arccos(a))
#Testing Code
print(Cos(90))
print(Sin(90))
print(Tan(45))
print(ArcTan(1))
print(ArcSin(1))
print(ArcCos(0))
Note that I have imported math (or numpy) into the namespace with
from math import *
Also note, that my functions are in the namespace in which they were defined. For instance,
math.Cos(45)
does not exist.
Using Eclipse Mars.1 CTRL + / on Linux in Java will comment out multiple lines of code. When trying to un-comment those multiple lines, Eclipse was commenting the comments. I found that if there is a blank line in the comments it will do this. If you have 10 lines of code, a blank line, and 10 more lines of code, CTRL + / will comment it all. You'll have to remove the line or un-comment them in blocks of 10.
Try using float: left
(or right
) instead of display: inline
. Inline display replaces list-item display, which is what adds the bullet points.
implementation 'com.treebo:internetavailabilitychecker:1.0.1'
public class MyApp extends Application {
@Override
public void onCreate() {
super.onCreate();
InternetAvailabilityChecker.init(this);
}
@Override
public void onLowMemory() {
super.onLowMemory();
InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
}
}
@Barry Kelly and @Andrew Hare, actually, I don't think multiplying is the most clear way to do this (alltough correct).
An Int32 "formatted" IP address can be seen as the following structure
[StructLayout(LayoutKind.Sequential, Pack = 1)]
struct IPv4Address
{
public Byte A;
public Byte B;
public Byte C;
public Byte D;
}
// to actually cast it from or to an int32 I think you
// need to reverse the fields due to little endian
So to convert the ip address 64.233.187.99 you could do:
(64 = 0x40) << 24 == 0x40000000
(233 = 0xE9) << 16 == 0x00E90000
(187 = 0xBB) << 8 == 0x0000BB00
(99 = 0x63) == 0x00000063
---------- =|
0x40E9BB63
so you could add them up using + or you could binairy or them together. Resulting in 0x40E9BB63 which is 1089059683. (In my opinion looking in hex it's much easier to see the bytes)
So you could write the function as:
int ipToInt(int first, int second,
int third, int fourth)
{
return (first << 24) | (second << 16) | (third << 8) | (fourth);
}
The correct way to 'solve' it is to close the connection and forget about the client. The client has closed the connection while you where still writing to it, so he doesn't want to know you, so that's it, isn't it?
It is really easy to achieve since the Support Library v24.2.0.
What you need to do is just:
Add the design library to your dependecies
dependencies {
compile "com.android.support:design:24.2.0"
}
Use TextInputEditText
in conjunction with TextInputLayout
<android.support.design.widget.TextInputLayout
android:id="@+id/etPasswordLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:passwordToggleEnabled="true"
android:layout_marginBottom="@dimen/login_spacing_bottom">
<android.support.design.widget.TextInputEditText
android:id="@+id/etPassword"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/fragment_login_password_hint"
android:inputType="textPassword"/>
</android.support.design.widget.TextInputLayout>
The passwordToggleEnabled
attribute will do the job!
In your root layout don't forget to add xmlns:app="http://schemas.android.com/apk/res-auto"
You can customize your password toggle by using:
app:passwordToggleDrawable
- Drawable to use as the password input visibility toggle icon.
app:passwordToggleTint
- Icon to use for the password input visibility toggle.
app:passwordToggleTintMode
- Blending mode used to apply the background tint.
More details in TextInputLayout documentation.
For AndroidX
Replace android.support.design.widget.TextInputLayout
with com.google.android.material.textfield.TextInputLayout
Replace android.support.design.widget.TextInputEditText
with com.google.android.material.textfield.TextInputEditText
This is best practice
$("input[name='radioGroup']:checked").val()
.table-striped>tbody>tr:nth-child(odd)>td,
.table-striped>tbody>tr:nth-child(odd)>th {
background-color: #e08283;
color: white;
}
.table-striped>tbody>tr:nth-child(even)>td,
.table-striped>tbody>tr:nth-child(even)>th {
background-color: #ECEFF1;
color: white;
}
Use 'even' for change colour of even rows and use 'odd' for change colour of odd rows.
There are 4 dimensions of the tensor you want to convert.
[:, ::-1, :, :]
:
means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.
::-1
means that for the second axes it reverses the the axes
Source : http://git-scm.com/book/en/Git-Basics-Undoing-Things
git checkout -- modifiedfile.java
1)$ git status
you will see the modified file
2)$git checkout -- modifiedfile.java
3)$git status
We can use package Guzzle in Laravel, it is a PHP HTTP client to send HTTP requests.
You can install Guzzle through composer
composer require guzzlehttp/guzzle:~6.0
Or you can specify Guzzle as a dependency in your project's existing composer.json
{
"require": {
"guzzlehttp/guzzle": "~6.0"
}
}
Example code in laravel 5 using Guzzle as shown below,
use GuzzleHttp\Client;
class yourController extends Controller {
public function saveApiData()
{
$client = new Client();
$res = $client->request('POST', 'https://url_to_the_api', [
'form_params' => [
'client_id' => 'test_id',
'secret' => 'test_secret',
]
]);
echo $res->getStatusCode();
// 200
echo $res->getHeader('content-type');
// 'application/json; charset=utf8'
echo $res->getBody();
// {"type":"User"...'
}
Take a peek at the ng-click
directive source:
...
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
It shows how the event
object is being passed on to the ng-click
expression, using $event
as a name of the parameter. This is done by the $parse service, which doesn't allow for the parameters to bleed into the target scope, which means the answer is no, you can't access the $event
object any other way but through the callback parameter.
For reCaptcha v2, use:
grecaptcha.reset();
If you're using reCaptcha v1 (probably not):
Recaptcha.reload();
This will do if there is an already loaded Recaptcha on the window
.
(Updated based on @SebiH's comment below.)
var key = "Name_radio";
var val = "value_radio";
var rdo = $('*[name="' + key + '"]');
if (rdo.attr('type') == "radio") {
$.each(rdo, function (keyT, valT){
if ((valT.value == $.trim(val)) && ($.trim(val) != '') && ($.trim(val) != null))
{
$('*[name="' + key + '"][value="' + (val) + '"]').prop('checked', true);
}
})
}
For iOS7 create launch images in the following sizes:
For iPhone 5 and iPod touch (5th generation):
For other iPhone and iPod touch devices:
For iPad portrait:
For iPad landscape:
See iOS 7 Design Resources > iOS Human Interface Guidelines > Launch Images
UPDATE 1
For iPhone 6:
For iPhone 6 Plus:
UPDATE 2
For iPhone X:
One line answer:
if val, ok := dict["foo"]; ok {
//do something here
}
if
statements in Go can include both a condition and an initialization statement. The example above uses both:
initializes two variables - val
will receive either the value of "foo" from the map or a "zero value" (in this case the empty string) and ok
will receive a bool that will be set to true
if "foo" was actually present in the map
evaluates ok
, which will be true
if "foo" was in the map
If "foo" is indeed present in the map, the body of the if
statement will be executed and val
will be local to that scope.
I personaly prefer to use plural names to represent a set, it just "sounds" better to my relational mind.
At this exact moment i am using singular names to define a data model for my company, because most of the people at work feel more confortable with it. Sometimes you just have to make life easier to everyone instead of imposing your personal preferences. (that's how i ended up in this thread, to get a confirmation on what should be the "best practice" for naming tables)
After reading all the arguing in this thread, i reached one conclusion:
I like my pancakes with honey, no matter what everybody's favorite flavour is. But if i am cooking for other people, i will try to serve them something they like.
Bryan Denny's post above is not working for me since not all extensions have a "Content Type" sub-key in the registry. I had to tweak the code as follows:
private string GetMimeType(string sFileName)
{
// Get file extension and if it is empty, return unknown
string sExt = Path.GetExtension(sFileName);
if (string.IsNullOrEmpty(sExt)) return "Unknown file type";
// Default type is "EXT File"
string mimeType = string.Format("{0} File", sExt.ToUpper().Replace(".", ""));
// Open the registry key for the extension under HKEY_CLASSES_ROOT and return default if it doesn't exist
Microsoft.Win32.RegistryKey regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sExt);
if (regKey == null) return mimeType;
// Get the "(Default)" value and re-open the key for that value
string sSubType = regKey.GetValue("").ToString();
regKey = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(sSubType);
// If it exists, get the "(Default)" value of the new key
if (regKey?.GetValue("") != null) mimeType = regKey.GetValue("").ToString();
// Return the value
return mimeType;
}
Now it works fine for me for all registered file types and un-registered or generic file types (like JPG, etc).
In addition to @user26409021 's answer, If you have added a ItemFragment, The message in the ItemFragment is;
Activities containing this fragment MUST implement the {@link OnListFragmentInteractionListener} interface.
And You should add in your activity;
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, ItemFragment.OnListFragmentInteractionListener {
//the code is omitted
public void onListFragmentInteraction(DummyContent.DummyItem uri){
//you can leave it empty
}
Here the dummy item is what you have on the bottom of your ItemFragment
A Fragment is a piece of an application's user interface or behavior that can be placed in an Activity which enable a more modular activity design. It will not be wrong if we say a fragment is a kind of subactivity.
Following are important points about a fragment:
A fragment has its own layout and its own behavior with its own lifecycle callbacks.
You can add or remove fragments in an activity while the activity is running.
You can combine multiple fragments in a single activity to build a multi-pane UI.
A fragment can be used in multiple activities.
The fragment life cycle is closely related to the lifecycle of its host activity.
When the activity is paused, all the fragments available in the acivity will also be stopped.
A fragment can implement a behavior that has no user interface component.
Fragments were added to the Android API in Android 3 (Honeycomb) with API version 11.
For more details, please visit the official site, Fragments.
It's worth mentioning that if you have a systemd set up, then things are a little bit different. The set up typically would have the core files be piped, by means of core_pattern
sysctl value, through systemd-coredump(8)
. The core file size rlimit would typically be configured as "unlimited" already.
It is then possible to retrieve the core dumps using coredumpctl(1)
.
The storage of core dumps, etc. is configured by coredump.conf(5)
. There are examples of how to get the core files in the coredumpctl man page, but in short, it would look like this:
Find the core file:
[vps@phoenix]~$ coredumpctl list test_me | tail -1
Sun 2019-01-20 11:17:33 CET 16163 1224 1224 11 present /home/vps/test_me
Get the core file:
[vps@phoenix]~$ coredumpctl -o test_me.core dump 16163
change in php.in file from wampicon/php/php
session.gc_maxlifetime = 1440
to
session.gc_maxlifetime = 43200
Using CSS you cannot, CSS will only change the appearance of the span. However you can do it without changing the structure of the div by adding an onclick handler to the span:
<html>
<head>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
You can then style it so that it looks un-clickable too:
<html>
<head>
<style type='text/css'>
a span.unclickable { text-decoration: none; }
a span.unclickable:hover { cursor: default; }
</style>
</head>
<body>
<div>
<a href="http://www.google.com">
<span>title<br></span>
<span class='unclickable' onclick='return false;'>description<br></span>
<span>some url</span>
</a>
</div>
</body>
</html>
You could use the LINQ select
clause and reference the property that relates to your Name column.
Thanks to all the posts on this topic, there are some really helpful ways to adjust the rowHeight of a UITableViewCell.
Here is a compilation of some of the concepts from everyone else that really helps when building for the iPhone and iPad. You can also access different sections and adjust them according to the varying sizes of views.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
{
int cellHeight = 0;
if ([indexPath section] == 0)
{
cellHeight = 16;
settingsTable.rowHeight = cellHeight;
}
else if ([indexPath section] == 1)
{
cellHeight = 20;
settingsTable.rowHeight = cellHeight;
}
return cellHeight;
}
else
{
int cellHeight = 0;
if ([indexPath section] == 0)
{
cellHeight = 24;
settingsTable.rowHeight = cellHeight;
}
else if ([indexPath section] == 1)
{
cellHeight = 40;
settingsTable.rowHeight = cellHeight;
}
return cellHeight;
}
return 0;
}
For those trying to create a Google Cloud instance using the "Deploy a container image to this VM instance." option then the correct url format would be
docker.io/<dockerimagename>:version
The suggestion above of registry.hub.docker.com/library/<dockerimagename>
did not work for me.
I finally found the solution here (in my case, i was trying to run docker.io/tensorflow/serving:latest)
With the release of iOS 7 (September 18th, 2013) apple increased the over-the-air cellular download limit to 100MBs.
Maximum app size remains 2GBs.
Steps I did:
Init cookies as being NOT http-only in server-side app.'s:
app.configure(function(){
//a bunch of stuff
app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
Then in client-side services.jss I put ['ngCookies'] in like this:
angular.module('swrp', ['ngCookies']).//etc
Then in controller.js
, in my function UserLoginCtrl
, I have $cookies
in there with $scope
at the top like so:
function UserLoginCtrl($scope, $cookies, socket) {
Lastly, to get the value of a cookie inside the controller function I did:
var mySession = $cookies['connect.sess'];
Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.
Yes, case insensitivity can be enabled and disabled at will in Java regex.
It looks like you want something like this:
System.out.println(
"Have a meRry MErrY Christmas ho Ho hO"
.replaceAll("(?i)\\b(\\w+)(\\s+\\1)+\\b", "$1")
);
// Have a meRry Christmas ho
Note that the embedded Pattern.CASE_INSENSITIVE
flag is (?i)
not \?i
. Note also that one superfluous \b
has been removed from the pattern.
The (?i)
is placed at the beginning of the pattern to enable case-insensitivity. In this particular case, it is not overridden later in the pattern, so in effect the whole pattern is case-insensitive.
It is worth noting that in fact you can limit case-insensitivity to only parts of the whole pattern. Thus, the question of where to put it really depends on the specification (although for this particular problem it doesn't matter since \w
is case-insensitive.
To demonstrate, here's a similar example of collapsing runs of letters like "AaAaaA"
to just "A"
.
System.out.println(
"AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
.replaceAll("(?i)\\b([A-Z])\\1+\\b", "$1")
); // A e I O u
Now suppose that we specify that the run should only be collapsed only if it starts with an uppercase letter. Then we must put the (?i)
in the appropriate place:
System.out.println(
"AaAaaA eeEeeE IiiIi OoooOo uuUuUuu"
.replaceAll("\\b([A-Z])(?i)\\1+\\b", "$1")
); // A eeEeeE I O uuUuUuu
More generally, you can enable and disable any flag within the pattern as you wish.
java.util.regex.Pattern
/regex/i
(Pattern.CASE_INSENSITIVE
in Java), you can do /(?i)regex/
/first(?i)second(?-i)third/
/first(?i:second)third/
\b
between a \w
and a \s
)In my case I forgot to enable
app.use(express.json());
in my NodeJs server.
No need to apologize for asking a question! Try using the RIGHT
function. It returns the last n characters of a string.
=RIGHT(A1, 1)
According to official documentation: Creating REST Controllers with the @RestController annotation
@RestController is a stereotype annotation that combines @ResponseBody and @Controller. More than that, it gives more meaning to your Controller and also may carry additional semantics in future releases of the framework.
It seems that it's best to use @RestController
for clarity, but you can also combine it with ResponseEntity
for flexibility when needed (According to official tutorial and the code here and my question to confirm that).
For example:
@RestController
public class MyController {
@GetMapping(path = "/test")
@ResponseStatus(HttpStatus.OK)
public User test() {
User user = new User();
user.setName("Name 1");
return user;
}
}
is the same as:
@RestController
public class MyController {
@GetMapping(path = "/test")
public ResponseEntity<User> test() {
User user = new User();
user.setName("Name 1");
HttpHeaders responseHeaders = new HttpHeaders();
// ...
return new ResponseEntity<>(user, responseHeaders, HttpStatus.OK);
}
}
This way, you can define ResponseEntity
only when needed.
Update
You can use this:
return ResponseEntity.ok().headers(responseHeaders).body(user);
Following line in above code is not working
DB_PASSWORD=$(eval echo ${DB_PASSWORD} | base64 --decode)
Correct line is:
DB_PASSWORD=`echo $PASSWORD|base64 -d`
And save the password in other file as PASSWORD.
import json
row = [1L,[0.1,0.2],[[1234L,1],[134L,2]]]
row_json = json.dumps(row)
This is like many other optimizations - you sacrifice some readability for speed. As John mentioned, if you've done your profiling homework and found this to be a significantly useful enough change and you need the extra speed, then go for it. It'd probably be good to put a note up with all the other imports:
from foo import bar
from baz import qux
# Note: datetime is imported in SomeClass below
(PC-Name)\
.aws s3api list-objects --bucket bucket-name
For more details see here - http://docs.aws.amazon.com/cli/latest/reference/s3api/list-objects.html
As far as I know, by using only Docker this is not possible. You need some DNS to map container ip:s to hostnames.
If you want out of the box solution. One solution is to use for example Kontena. It comes with network overlay technology from Weave and this technology is used to create virtual private LAN networks for each service and every service can be reached by service_name.kontena.local-address
.
Here is simple example of Wordpress application's YAML file where Wordpress service connects to MySQL server with wordpress-mysql.kontena.local address:
wordpress:
image: wordpress:4.1
stateful: true
ports:
- 80:80
links:
- mysql:wordpress-mysql
environment:
- WORDPRESS_DB_HOST=wordpress-mysql.kontena.local
- WORDPRESS_DB_PASSWORD=secret
mysql:
image: mariadb:5.5
stateful: true
environment:
- MYSQL_ROOT_PASSWORD=secret
Just make sure put single space before and after "and" Keyword..
The onkeypress event works for all the keys except ALT, CTRL, SHIFT, ESC in all browsers where as onkeydown event works for all keys. Means onkeydown event captures all the keys.
Here's the simple example.
diff --git a/file b/file
index 10ff2df..84d4fa2 100644
--- a/file
+++ b/file
@@ -1,5 +1,5 @@
line1
line2
-this line will be deleted
line4
line5
+this line is added
Here's an explanation (see details here).
--git
is not a command, this means it's a git version of diff (not unix)a/ b/
are directories, they are not real. it's just a convenience when we deal with the same file (in my case a/ is in index and b/ is in working directory)10ff2df..84d4fa2
are blob IDs of these 2 files100644
is the “mode bits,” indicating that this is a regular file (not executable and not a symbolic link)--- a/file +++ b/file
minus signs shows lines in the a/ version but missing from the b/ version; and plus signs shows lines missing in a/ but present in b/ (in my case --- means deleted lines and +++ means added lines in b/ and this the file in the working directory)@@ -1,5 +1,5 @@
in order to understand this it's better to work with a big file; if you have two changes in different places you'll get two entries like @@ -1,5 +1,5 @@
; suppose you have file line1 ... line100 and deleted line10 and add new line100 - you'll get:@@ -7,7 +7,6 @@ line6 line7 line8 line9 -this line10 to be deleted line11 line12 line13 @@ -98,3 +97,4 @@ line97 line98 line99 line100 +this is new line100
Install Entity Framework in each project (Ex: In Web, In Class Libraries) from NuGet Package Manager orelse Open Tools - Nuget Package Manager - Package Manager Console and use Install-Package EntityFramework to install the Entity Framework.
Don't need to add the below code in every config file. By default it will be added in the project where the database is called through Entity Framework.
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
For those coming from Ionic or Cordova, you can try the following:
Open the file yourproject/platforms/ios/cordova/build-release.xcconfig
and change from this:
CODE_SIGN_IDENTITY = iPhone Distribution
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Distribution
into this:
CODE_SIGN_IDENTITY = iPhone Developer
CODE_SIGN_IDENTITY[sdk=iphoneos*] = iPhone Developer
and try to run the ios cordova build ios --release
again to compile a release build.
There is no need to invoke PHP for this. Just put it directly into the HTML:
<a href="http://www.example.com/">...
You'll need to scrape the resulting page, but you can view the most recent cache page using this URL:
http://webcache.googleusercontent.com/search?q=cache:www.something.com/path
Google information is put in the first div in the body tag.
How about:
def ExtractAlphanumeric(InputString):
from string import ascii_letters, digits
return "".join([ch for ch in InputString if ch in (ascii_letters + digits)])
This works by using list comprehension to produce a list of the characters in InputString
if they are present in the combined ascii_letters
and digits
strings. It then joins the list together into a string.
DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";
// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");
Ref: http://www.csharp-examples.net/dataview-rowfilter/
http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx
The answer from dbarnard has the formula to calculate the correct radius, but since you were looking for the templates, all the masks and overlays can be found in this directory:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator5.1.sdk/System/Library/PrivateFrameworks/MobileIcons.framework
(path is for recent versions of XCode. For older version it will probably be inside /Developer/).
As others have noted, you should NOT mask them yourself, but you can use these to check how your icons will look once masked.
(credits for this finding goes to Neven Mrgan IIRC)
this does not refresh your component I solved the problem by using Vux create a module for vuex "page"
export const state = {
currentScrollY: 0,
};
export const getters = {
currentScrollY: s => s.currentScrollY
};
export const actions = {
setCurrentScrollY ({ commit }, y) {
commit('setCurrentScrollY', {y});
},
};
export const mutations = {
setCurrentScrollY (s, {y}) {
s.currentScrollY = y;
},
};
export default {
state,
getters,
actions,
mutations,
};
in App.vue :
created() {
window.addEventListener("scroll", this.handleScroll);
},
destroyed() {
window.removeEventListener("scroll", this.handleScroll);
},
methods: {
handleScroll () {
this.$store.dispatch("page/setCurrentScrollY", window.scrollY);
}
},
in your component :
computed: {
currentScrollY() {
return this.$store.getters["page/currentScrollY"];
}
},
watch: {
currentScrollY(val) {
if (val > 100) {
this.isVisibleStickyMenu = true;
} else {
this.isVisibleStickyMenu = false;
}
}
},
and it works great.
Use Linq-XML,
XDocument doc = XDocument.Load(file);
var result = from ele in doc.Descendants("sog")
select new
{
field1 = (string)ele.Element("field1")
};
foreach (var t in result)
{
HttpContext.Current.Response.Write(t.field1);
}
OR : Get the node list of <sog>
tag.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(myXML);
XmlNodeList parentNode = xmlDoc.GetElementsByTagName("sog");
foreach (XmlNode childrenNode in parentNode)
{
HttpContext.Current.Response.Write(childrenNode.SelectSingleNode("field1").InnerText);
}
wrap button inside <div class="text-xs-center">
<div class="text-xs-center">
<v-btn primary>
Signup
</v-btn>
</div>
Dev uses it in his examples.
For centering buttons in v-card-actions
we can add class="justify-center"
(note in v2 class is text-center
(so without xs
):
<v-card-actions class="justify-center">
<v-btn>
Signup
</v-btn>
</v-card-actions>
For more examples with regards to centering see here
You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.
//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()//Your tableView here
})
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
}
The second quote is correct, the size of a word varies from computer to computer. The ARM NEON architecture is an example of an architecture with 32-bit words, where 64-bit quantities are referred to as "doublewords" and 128-bit quantities are referred to as "quadwords":
A NEON operand can be a vector or a scalar. A NEON vector can be a 64-bit doubleword vector or a 128-bit quadword vector.
Normally speaking, 16-bit words are only found on 16-bit systems, like the Amiga 500.
Full Document height calculation:
To be more generic and find the height of any document you could just find the highest DOM Node on current page with a simple recursion:
;(function() {
var pageHeight = 0;
function findHighestNode(nodesList) {
for (var i = nodesList.length - 1; i >= 0; i--) {
if (nodesList[i].scrollHeight && nodesList[i].clientHeight) {
var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight);
pageHeight = Math.max(elHeight, pageHeight);
}
if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes);
}
}
findHighestNode(document.documentElement.childNodes);
// The entire page height is found
console.log('Page height is', pageHeight);
})();
You can Test it on your sample sites (http://fandango.com/ or http://paperbackswap.com/) with pasting this script to a DevTools Console.
NOTE: it is working with Iframes
.
Enjoy!
You should use the pickaxe (-S
) option of git log
.
To search for Foo
:
git log -SFoo -- path_containing_change
git log -SFoo --since=2009.1.1 --until=2010.1.1 -- path_containing_change
See Git history - find lost line by keyword for more.
As Jakub Narebski commented:
this looks for differences that introduce or remove an instance of <string>
.
It usually means "revisions where you added or removed line with 'Foo'".
the --pickaxe-regex
option allows you to use extended POSIX regex instead of searching for a string.
Example (from git log
): git log -S"frotz\(nitfol" --pickaxe-regex
As Rob commented, this search is case-sensitive - he opened a follow-up question on how to search case-insensitive.
If you have jQuery loaded already, you should use $.getScript.
This has an advantage over the other answers here in that you have a built in callback function (to guarantee the script is loaded before the dependant code runs) and you can control caching.
awk 'NF' filename
awk 'NF > 0' filename
sed -i '/^$/d' filename
awk '!/^$/' filename
awk '/./' filename
The NF also removes lines containing only blanks or tabs, the regex /^$/
does not.
My business aim was removing classes form previous input and add it to a new one.
In this case there was simple solution: remove classes from all inputs before add
<div>
<input type="radio" checked><b class="darkred">Value1</b>
<input type="radio"><b>Value2</b>
<input type="radio"><b>Value3</b>
</div>
and
$('input[type="radio"]').on('change', function () {
var current = $(this);
current.closest('div').find('input').each(function () {
(this).next().removeClass('darkred')
});
current.next().addClass('darkred');
});
JsFiddle: http://jsfiddle.net/gkislin13/tybp8skL
Code Formatting Shortcut:
VSCode on Windows - Shift + Alt + F
VSCode on MacOS - Shift + Option + F
VSCode on Ubuntu - Ctrl + Shift + I
You can also customize this shortcut using preference setting if needed.
column selection with keyboard Ctrl + Shift + Alt + Arrow
Go to your project in the navigator, right click on properties.
Go to the Java Build Path tab on the left.
Go to the libraries tab on top.
Click add external jars.
Go to your ADT Bundle folder, go to sdk/extras/android/support/v7/appcompat/libs.
Select the file android-support-v7-appcompat.jar
Go to order and export and check the box next to your new jar.
Click ok.
For the sake of an alternative answer for those searching for a lightweight way to just find a user's home dir...
Rather than messing with su
hacks, or bothering with the overhead of launching another bash
shell just to find the $HOME
environment variable...
There is a command specifically for this: getent
getent passwd someuser | cut -f6 -d:
getent
can do a lot more... just see the man page. The passwd
nsswitch database will return the user's entry in /etc/passwd
format. Just split it on the colon :
to parse out the fields.
It should be installed on most Linux systems (or any system that uses GNU Lib C (RHEL: glibc-common
, Deb: libc-bin
)
If you write only equal condition just: Select Case columns1 When 0 then 'Value1' when 1 then 'Value2' else 'Unknown' End
If you want to write greater , Less then or equal you must do like this: Select Case When [ColumnsName] >0 then 'value1' When [ColumnsName]=0 Or [ColumnsName]<0 then 'value2' Else 'Unkownvalue' End
From tablename
Thanks Mr.Buntha Khin
Prepare for Segue in Swift 4.2 and Swift 5.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "OrderVC") {
// pass data to next view
let viewController = segue.destination as? MyOrderDetailsVC
viewController!.OrderData = self.MyorderArray[selectedIndex]
}
}
How to Call segue On specific Event(Like Button Click etc):
performSegue(withIdentifier: "OrderVC", sender: self)
Use the keys
method: {"apple" => "fruit", "carrot" => "vegetable"}.keys == ["apple", "carrot"]
Here's a creative idea using box-shadow
:
#header {
background-image: url("apple.jpg");
box-shadow: inset 0 0 99999px rgba(0, 120, 255, 0.5);
}
The background
sets the background for your element.
The box-shadow
is the important bit. It basically sets a really big shadow on the inside of the element, on top of the background, that is semi-transparent
torch.Tensor.view()
Simply put, torch.Tensor.view()
which is inspired by numpy.ndarray.reshape()
or numpy.reshape()
, creates a new view of the tensor, as long as the new shape is compatible with the shape of the original tensor.
Let's understand this in detail using a concrete example.
In [43]: t = torch.arange(18)
In [44]: t
Out[44]:
tensor([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17])
With this tensor t
of shape (18,)
, new views can only be created for the following shapes:
(1, 18)
or equivalently (1, -1)
or (-1, 18)
(2, 9)
or equivalently (2, -1)
or (-1, 9)
(3, 6)
or equivalently (3, -1)
or (-1, 6)
(6, 3)
or equivalently (6, -1)
or (-1, 3)
(9, 2)
or equivalently (9, -1)
or (-1, 2)
(18, 1)
or equivalently (18, -1)
or (-1, 1)
As we can already observe from the above shape tuples, the multiplication of the elements of the shape tuple (e.g. 2*9
, 3*6
etc.) must always be equal to the total number of elements in the original tensor (18
in our example).
Another thing to observe is that we used a -1
in one of the places in each of the shape tuples. By using a -1
, we are being lazy in doing the computation ourselves and rather delegate the task to PyTorch to do calculation of that value for the shape when it creates the new view. One important thing to note is that we can only use a single -1
in the shape tuple. The remaining values should be explicitly supplied by us. Else PyTorch will complain by throwing a RuntimeError
:
RuntimeError: only one dimension can be inferred
So, with all of the above mentioned shapes, PyTorch will always return a new view of the original tensor t
. This basically means that it just changes the stride information of the tensor for each of the new views that are requested.
Below are some examples illustrating how the strides of the tensors are changed with each new view.
# stride of our original tensor `t`
In [53]: t.stride()
Out[53]: (1,)
Now, we will see the strides for the new views:
# shape (1, 18)
In [54]: t1 = t.view(1, -1)
# stride tensor `t1` with shape (1, 18)
In [55]: t1.stride()
Out[55]: (18, 1)
# shape (2, 9)
In [56]: t2 = t.view(2, -1)
# stride of tensor `t2` with shape (2, 9)
In [57]: t2.stride()
Out[57]: (9, 1)
# shape (3, 6)
In [59]: t3 = t.view(3, -1)
# stride of tensor `t3` with shape (3, 6)
In [60]: t3.stride()
Out[60]: (6, 1)
# shape (6, 3)
In [62]: t4 = t.view(6,-1)
# stride of tensor `t4` with shape (6, 3)
In [63]: t4.stride()
Out[63]: (3, 1)
# shape (9, 2)
In [65]: t5 = t.view(9, -1)
# stride of tensor `t5` with shape (9, 2)
In [66]: t5.stride()
Out[66]: (2, 1)
# shape (18, 1)
In [68]: t6 = t.view(18, -1)
# stride of tensor `t6` with shape (18, 1)
In [69]: t6.stride()
Out[69]: (1, 1)
So that's the magic of the view()
function. It just changes the strides of the (original) tensor for each of the new views, as long as the shape of the new view is compatible with the original shape.
Another interesting thing one might observe from the strides tuples is that the value of the element in the 0th position is equal to the value of the element in the 1st position of the shape tuple.
In [74]: t3.shape
Out[74]: torch.Size([3, 6])
|
In [75]: t3.stride() |
Out[75]: (6, 1) |
|_____________|
This is because:
In [76]: t3
Out[76]:
tensor([[ 0, 1, 2, 3, 4, 5],
[ 6, 7, 8, 9, 10, 11],
[12, 13, 14, 15, 16, 17]])
the stride (6, 1)
says that to go from one element to the next element along the 0th dimension, we have to jump or take 6 steps. (i.e. to go from 0
to 6
, one has to take 6 steps.) But to go from one element to the next element in the 1st dimension, we just need only one step (for e.g. to go from 2
to 3
).
Thus, the strides information is at the heart of how the elements are accessed from memory for performing the computation.
This function would return a view and is exactly the same as using torch.Tensor.view()
as long as the new shape is compatible with the shape of the original tensor. Otherwise, it will return a copy.
However, the notes of torch.reshape()
warns that:
contiguous inputs and inputs with compatible strides can be reshaped without copying, but one should not depend on the copying vs. viewing behavior.
If you are assigning default value for boolean fact then ensure that no quotes is used inside default().
- name: create bool default
set_fact:
name: "{{ my_bool | default(true) }}"
For other variables used the same method given in verified answer.
- name: Create user
user:
name: "{{ my_variable | default('default_value') }}"
I would recommend adding headers for the same. Moving metadata to headers helps in getting rid of envelops like result
, data
or records
and response body only contains the data we need. You can use Link header if you generate pagination links too.
HTTP/1.1 200
Pagination-Count: 100
Pagination-Page: 5
Pagination-Limit: 20
Content-Type: application/json
[
{
"id": 10,
"name": "shirt",
"color": "red",
"price": "$23"
},
{
"id": 11,
"name": "shirt",
"color": "blue",
"price": "$25"
}
]
For details refer to:
https://github.com/adnan-kamili/rest-api-response-format
For swagger file:
There are multiple ways to do this in particular with Python 3.0 and above
Approach 1
This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:
def bad_method():
try:
sqrt = 0**-1
except Exception as e:
print(e)
bad_method()
Approach 2
This approach is recommended because it provides more detail about each exception. It includes:
The only drawback is tracback needs to be imported.
import traceback
def bad_method():
try:
sqrt = 0**-1
except Exception:
print(traceback.print_exc())
bad_method()
I got the same error and the cause was the directory:
U:.....WEB\WebRoot\WEB-INF\classes\com\yourcompany\cc\dao
was corrupted(directory or file not readable or damaged).. solved with
if the problem still exists try to force changing the pass
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start mysqld_safe daemon with --skip-grant-tables
mysqld_safe --skip-grant-tables &
mysql -u root
Setup new MySQL root user password
use mysql;
update user set password=PASSWORD("NEW-ROOT-PASSWORD") where User='root';
flush privileges;
quit;
Stop MySQL Server (on Linux):
/etc/init.d/mysql stop
Stop MySQL Server (on Mac OS X):
mysql.server stop
Start MySQL server service and test to login by root:
mysql -u root -p
For Wamp Server users there is easier way: You may enable that setting simply (left) click once on the WampServer icon, choose PHP -> PHP settings -> short open tag. Wait for a second, then WampServer will automatically restart your PHP and also its web service.
originally from: http://osticket.com/forums/showthread.php?t=3149
Here's my one liner to determine the windows version:
for /f "tokens=1-9" %%a in ('"systeminfo | find /i "OS Name""') do (set ver=%%e & echo %ver%)
This returns the windows version, i.e., XP, Vista, 7, and sets the value of "ver" to equal the same...
Apparently, the SSH server on Raspbian is now disabled by default. If there is no server listening for connections, it will not accept them. You can manually enable the SSH server according to this raspberrypi.org tutorial :
As of the November 2016 release, Raspbian has the SSH server disabled by default.
There are now multiple ways to enable it. Choose one:
- Launch
Raspberry Pi Configuration
from thePreferences
menu- Navigate to the
Interfaces
tab- Select
Enabled
next toSSH
- Click
OK
raspi-config
- Enter
sudo raspi-config
in a terminal window- Select
Interfacing Options
- Navigate to and select
SSH
- Choose
Yes
- Select
Ok
- Choose
Finish
systemctl
sudo systemctl enable ssh sudo systemctl start ssh
For headless setup, SSH can be enabled by placing a file named
ssh
, without any extension, onto the boot partition of the SD card. When the Pi boots, it looks for thessh
file. If it is found, SSH is enabled, and the file is deleted. The content of the file does not matter: it could contain text, or nothing at all.
give the LI float: left (or right)
They will all be in the same line until there will be no more room in the container (your case, a ul). (forgot): If you have a block element after the floating elements, he will also stick to them, unless you give him a clear:both, OR put an empty div before it with clear:both
Install firebug: http://getfirebug.com/logging . You can use its console to test Javascript code. Google Chrome comes with Web Inspector in which you can do the same. IE and Safari also have Web Developer tools in which you can test Javascript.
py2exe is a Python Distutils extension which converts Python scripts into executable Windows programs, able to run without requiring a Python installation.
[StringLength(16, ErrorMessageResourceName= "PasswordMustBeBetweenMinAndMaxCharacters", ErrorMessageResourceType = typeof(Resources.Resource), MinimumLength = 6)]
[Display(Name = "Password", ResourceType = typeof(Resources.Resource))]
public string Password { get; set; }
Save resource like this
"ThePasswordMustBeAtLeastCharactersLong" | "The password must be {1} at least {2} characters long"
What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.
You could also write the first query like this:
SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
FROM Supplies su, Projects pr
WHERE su.sid = s.sid
AND pr.jid = su.jid) >= 2
It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.
I found a solution that is similar to the one with psexec but works without additional tools and survives a reboot.
Just add a sheduled task, insert "system" in the "run as" field and point the task to a batch file with the simple command
net use z: \servername\sharedfolder /persistent:yes
Then select "run at system startup" (or similar, I do not have an English version) and you are done.
Most of the time you can just npm update (or yarn upgrade) a module to get the latest non breaking changes (respecting the semver specified in your package.json) (<-- read that last part again).
npm update browser-sync
-------
yarn upgrade browser-sync
- Use
npm|yarn outdated
to see which modules have newer versions- Use
npm update|yarn upgrade
(without a package name) to update all modules- Include
--save-dev|--dev
if you want to save the newer version numbers to your package.json. (NOTE: as of npm v5.0 this is only necessary fordevDependencies
).
Major version upgrades:
In your case, it looks like you want the next major version (v2.x.x), which is likely to have breaking changes and you will need to update your app to accommodate those changes. You can install/save the latest 2.x.x
by doing:
npm install browser-sync@2 --save-dev
-------
yarn add browser-sync@2 --dev
...or the latest 2.1.x
by doing:
npm install [email protected] --save-dev
-------
yarn add [email protected] --dev
...or the latest and greatest by doing:
npm install browser-sync@latest --save-dev
-------
yarn add browser-sync@latest --dev
Note: the last one is no different than doing this:
npm uninstall browser-sync --save-dev npm install browser-sync --save-dev ------- yarn remove browser-sync --dev yarn add browser-sync --dev
The
--save-dev
part is important. This will uninstall it, remove the value from your package.json, and then reinstall the latest version and save the new value to your package.json.
Edit / Paste from the title bar's context menu (until they fix the control key shortcuts)
You only have to add the millisecond field in your date format string:
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
The API doc of SimpleDateFormat describes the format string in detail.
You can use the clear method
List<string> test = new List<string>();
test.Clear();
Pretty easy to overlook like I did, but don't forget to use UITapGestureRecognizer
rather than UIGestureRecognizer
.
Initializer block is just like any bits of code; it's not "attached" to any field/method preceding it. To assign values to fields, you have to explicitly use the field as the lhs of an assignment statement.
private int lineCount; {
try{
lineCount = LineCounter.countLines(sFileName);
/*^^^^^^^*/
}
catch(IOException ex){
System.out.println (ex.toString());
System.out.println("Could not find file " + sFileName);
}
}
Also, your countLines
can be made simpler:
public static int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
while (reader.readLine() != null) {}
reader.close();
return reader.getLineNumber();
}
Based on my test, it looks like you can getLineNumber()
after close()
.
While Shannon's answer is technically correct, it looks like overkill.
The simple solution is that you need to put your summation outside of the case
statement.
This should do the trick:
sum(CASE WHEN col1 > col2 THEN col3*col4 ELSE 0 END) AS some_product
Basically, your old code tells SQL to execute the sum(X*Y)
for each line individually (leaving each line with its own answer that can't be grouped).
The code line I have written takes the sum product, which is what you want.
If you sort the outer array, you can use _.isEqual()
since the inner array is already sorted.
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
_.isEqual(array1.sort(), array2.sort()); //true
Note that .sort()
will mutate the arrays. If that's a problem for you, make a copy first using (for example) .slice()
or the spread operator (...
).
Or, do as Daniel Budick recommends in a comment below:
_.isEqual(_.sortBy(array1), _.sortBy(array2))
Lodash's sortBy()
will not mutate the array.
The core problem seems to be you are opening a window to show a page whose content is already cached in the browser. Therefore no loading happens and therefore no load-event happens.
One possibility could be to use the 'pageshow' -event instead, as described in:
If you have successfully deleted from workspace tab but still it is showing in drop down menu. Then also you can successfully remove that by following these steps:
user_name will be your username of your computer
There will be two tag
varName = "RecentlyUsedWorkspaces" remove the deleted workspace tag
A propertyList tag will be there with varName=deleted_workspace_name delete that tag.
from drop down menu workspace name will be deleted
To answer your question about downloading files by hand, you can extract the relevant URLs from the SDK Manager's repository manifest:
Assume if all the input elements are inside a form u can refer the below code.
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
place after input
<script type="text/javascript">document.formname.inputname.focus();</script>
You could delete all the rows from all tables using an approach like Rubens suggested, or you could just drop and recreate all the tables. Always a good idea to have the full db creation scripts anyway so that may be the easiest/quickest method.
With Javascript you can get full size profile images like this
pass your accessToken
to the getface()
function from your FB.init
call
function getface(accessToken){
FB.api('/me/friends', function (response) {
for (id in response.data) {
var homie=response.data[id].id
FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
for (album in aresponse.data) {
if (aresponse.data[album].name == "Profile Pictures") {
FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
console.log(aresponse.data[0].images[0].source);
});
}
}
});
}
});
}
If you get this when using DevDesktop - just restart DevDesktop!
This isn't an answer, sadly. After running into the intermittent error for some time and finally being annoyed enough to try to fix it, I have yet to find a fix. I have, however, determined a recipe for reproducing my problem, which might help others.
In my case it is SOLELY a localhost problem, on my dev machine that also has the app's DB. It's a .NET 2.0 app I'm editing with VS2005. The Win7 64 bit machine also has VS2008 and .NET 3.5 installed.
Here's what will generate the error, from a variety of forms:
A minute or two delay "waiting for localhost" and then "Connection was reset" by the browser, and global.asax
's application error trap logs:
Application_Error event: Invalid length for a Base-64 char array.
Stack Trace:
at System.Convert.FromBase64String(String s)
at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString)
at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState)
at System.Web.UI.HiddenFieldPageStatePersister.Load()
In this case, it is not the SIZE of the viewstate, but something to do with page and/or viewstate caching that seems to be biting me. Setting <pages>
parameters enableEventValidation="false"
, and viewStateEncryption="Never"
in the Web.config
did not change the behavior. Neither did setting the maxPageStateFieldLength
to something modest.
I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.
The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.