All has been pointed out. Just use either DELETE ON CASCADE
on the parent table
or delete from the child-table
and then parent
.
here my solution
function isEmpty(value) {
if(Object.prototype.toString.call(value) === '[object Array]') {
return value.length == 0;
} else if(value != null && typeof value === 'object') {
return Object.getOwnPropertyNames(value).length == 0;
} else {
return !(value || (value === 0));
}
}
Chears
The solution you are really looking for is web sockets. However, the chromium project has developed some new technologies that are direct TCP connections TCP chromium
SIGABRT means in general that there is an uncaught exception. There should be more information on the console.
for same height you should chage your css "display" Properties. For more detail see given example.
.list{_x000D_
display: table;_x000D_
flex-wrap: wrap;_x000D_
max-width: 500px;_x000D_
}_x000D_
_x000D_
.list-item{_x000D_
background-color: #ccc;_x000D_
display: table-cell;_x000D_
padding: 0.5em;_x000D_
width: 25%;_x000D_
margin-right: 1%;_x000D_
margin-bottom: 20px;_x000D_
}_x000D_
.list-content{_x000D_
width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h2>box 1</h2>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h1>h1</h1>_x000D_
</div>_x000D_
</li>
_x000D_
Via SQL as per MSDN
SET IDENTITY_INSERT sometableWithIdentity ON
INSERT INTO sometableWithIdentity
(IdentityColumn, col2, col3, ...)
VALUES
(AnIdentityValue, col2value, col3value, ...)
SET IDENTITY_INSERT sometableWithIdentity OFF
The complete error message tells you exactly what is wrong...
Cannot insert explicit value for identity column in table 'sometableWithIdentity' when IDENTITY_INSERT is set to OFF.
$arraysAreEqual = ($a == $b); // TRUE if $a and $b have the same key/value pairs.
$arraysAreEqual = ($a === $b); // TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
See Array Operators.
EDIT
The inequality operator is !=
while the non-identity operator is !==
to match the equality
operator ==
and the identity operator ===
.
SELECT (cast(timestamp_1 as bigint) - cast(timestamp_2 as bigint)) FROM table;
In case if someone is having an issue using extract.
You can navigate to your parent root like this
this.router.navigate(['.'], { relativeTo: this.activeRoute.parent });
You will need to inject the current active Route in the constructor
constructor(
private router: Router,
private activeRoute: ActivatedRoute) {
}
The programmatically trigger to call the autocomplete.change event is via a namespaced trigger on the source select element.
$("#CompanyList").trigger("blur.autocomplete");
Within version 1.8 of jquery UI..
.bind( "blur.autocomplete", function( event ) {
if ( self.options.disabled ) {
return;
}
clearTimeout( self.searching );
// clicks on the menu (or a button to trigger a search) will cause a blur event
self.closing = setTimeout(function() {
self.close( event );
self._change( event );
}, 150 );
});
Easy codes that work successfully:
protected void Page_Load(object sender, EventArgs e)
{
.
.
using (MemoryStream ms = new MemoryStream())
{
.
.
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54);
iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
writer.PageEvent = new HeaderFooter();
doc.Open();
.
.
// make your document content..
.
.
doc.Close();
writer.Close();
// output
Response.ContentType = "application/pdf;";
Response.AddHeader("Content-Disposition", "attachment; filename=clientfilename.pdf");
byte[] pdf = ms.ToArray();
Response.OutputStream.Write(pdf, 0, pdf.Length);
}
.
.
.
}
class HeaderFooter : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{
// Make your table header using PdfPTable and name that tblHeader
.
.
tblHeader.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, page.Top, writer.DirectContent);
.
.
// Make your table footer using PdfPTable and name that tblFooter
.
.
tblFooter.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
}
}
Here is my solution with a few assumptions:
Feel free to adjust to meet your needs.
Centered layout with variable cell width:
protocol HACenteredLayoutDelegate: UICollectionViewDataSource {
func getCollectionView() -> UICollectionView
func sizeOfCell(at index: IndexPath) -> CGSize
func contentInsets() -> UIEdgeInsets
}
class HACenteredLayout: UICollectionViewFlowLayout {
weak var delegate: HACenteredLayoutDelegate?
private var cache = [UICollectionViewLayoutAttributes]()
private var contentSize = CGSize.zero
override var collectionViewContentSize: CGSize { return self.contentSize }
required init(delegate: HACenteredLayoutDelegate) {
self.delegate = delegate
super.init()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func invalidateLayout() {
cache.removeAll()
super.invalidateLayout()
}
override func prepare() {
if cache.isEmpty && self.delegate != nil && self.delegate!.collectionView(self.delegate!.getCollectionView(), numberOfItemsInSection: 0) > 0 {
let insets = self.delegate?.contentInsets() ?? UIEdgeInsets.zero
var rows: [(width: CGFloat, count: Int)] = [(0, 0)]
let viewWidth: CGFloat = UIScreen.main.bounds.width
var y = insets.top
var unmodifiedIndexes = [IndexPath]()
for itemNumber in 0 ..< self.delegate!.collectionView(self.delegate!.getCollectionView(), numberOfItemsInSection: 0) {
let indexPath = IndexPath(item: itemNumber, section: 0)
let cellSize = self.delegate!.sizeOfCell(at: indexPath)
let potentialRowWidth = rows.last!.width + (rows.last!.count > 0 ? self.minimumInteritemSpacing : 0) + cellSize.width + insets.right + insets.left
if potentialRowWidth > viewWidth {
let leftOverSpace = max((viewWidth - rows[rows.count - 1].width)/2, insets.left)
for i in unmodifiedIndexes {
self.cache[i.item].frame.origin.x += leftOverSpace
}
unmodifiedIndexes = []
rows.append((0, 0))
y += cellSize.height + self.minimumLineSpacing
}
unmodifiedIndexes.append(indexPath)
let attribute = UICollectionViewLayoutAttributes(forCellWith: indexPath)
rows[rows.count - 1].count += 1
rows[rows.count - 1].width += rows[rows.count - 1].count > 1 ? self.minimumInteritemSpacing : 0
attribute.frame = CGRect(x: rows[rows.count - 1].width, y: y, width: cellSize.width, height: cellSize.height)
rows[rows.count - 1].width += cellSize.width
cache.append(attribute)
}
let leftOverSpace = max((viewWidth - rows[rows.count - 1].width)/2, insets.left)
for i in unmodifiedIndexes {
self.cache[i.item].frame.origin.x += leftOverSpace
}
self.contentSize = CGSize(width: viewWidth, height: y + self.delegate!.sizeOfCell(at: IndexPath(item: 0, section: 0)).height + insets.bottom)
}
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache {
if attributes.frame.intersects(rect) {
layoutAttributes.append(attributes)
}
}
return layoutAttributes
}
override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if indexPath.item < self.cache.count {
return self.cache[indexPath.item]
}
return nil
}
}
Result:
I faced this issue once, and I solved this by wrapping the LayoutManager
and disabling predictive animations.
Here an example:
public class LinearLayoutManagerWrapper extends LinearLayoutManager {
public LinearLayoutManagerWrapper(Context context) {
super(context);
}
public LinearLayoutManagerWrapper(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public LinearLayoutManagerWrapper(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public boolean supportsPredictiveItemAnimations() {
return false;
}
}
And set it to RecyclerView
:
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManagerWrapper(context, LinearLayoutManager.VERTICAL, false);
All the previous answers only provide a hard-coded location of where the first column ends and the second column starts. I would have expected that this is not required or even not wanted.
Recent CSS versions know about an attribute called columns
which makes column based layouts super easy. For older browsers you need to include -moz-columns
and -webkit-columns
, too.
Here's a very simple example which creates up to three columns if each of them has at least 200 pixes width, otherwise less columns are used:
<html>
<head>
<title>CSS based columns</title>
</head>
<body>
<h1>CSS based columns</h1>
<ul style="columns: 3 200px; -moz-columns: 3 200px; -webkit-columns: 3 200px;">
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
<li>Item four</li>
<li>Item five</li>
<li>Item six</li>
<li>Item eight</li>
<li>Item nine</li>
<li>Item ten</li>
<li>Item eleven</li>
<li>Item twelve</li>
<li>Item thirteen</li>
</ul>
</body>
</html>
Instead of
return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);
try
return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);
In Python 2.7.3:
import urllib2
import socket
class MyException(Exception):
pass
try:
urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
print type(e) #not catch
except socket.timeout as e:
print type(e) #catched
raise MyException("There was an error: %r" % e)
Thanks for the research FIRESTICK is a solution for non Android based but there's another one Im using if you guys want to try it let me know...
LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP, PHILCO and TOSHIBA.
Sometimes you get a case where some of the requests made with axios are pointed to endpoints that do not accept authorization headers. Thus, alternative way to set authorization header only on allowed domain is as in the example below. Place the following function in any file that gets executed each time React application runs such as in routes file.
export default () => {
axios.interceptors.request.use(function (requestConfig) {
if (requestConfig.url.indexOf(<ALLOWED_DOMAIN>) > -1) {
const token = localStorage.token;
requestConfig.headers['Authorization'] = `Bearer ${token}`;
}
return requestConfig;
}, function (error) {
return Promise.reject(error);
});
}
Simple method to get the records count:
df.count()[0]
If you would like to redirect requests for "domain1.com" to "domain2.com", you could create a server block that looks like this:
server {
listen 80;
server_name domain1.com;
return 301 $scheme://domain2.com$request_uri;
}
I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :
https://gist.github.com/smalot/6183152
Hope it helps everone
When using Visual Studio 2012 with IIS Express, changing an existing binding does not work permanently. (It may work until you close VS, but after that, things get really messed up.)
The key is keeping the existing localhost binding and adding a new binding after it.
Unless you're running as administrator, you'll also need to run netsh add urlacl
(to give yourself permissions to run a non-localhost site as a standard user).
If you want to allow any host name, the full process is as follows:
From an administrator prompt, run the following commands (replacing portnumber with the port number you figured out in #1):
netsh http add urlacl url="http://*:portnumber/" user=everyone
netsh http add urlacl url="http://localhost:portnumber/" user=everyone
You can also use your user name (DOMAIN\USER) instead of everyone for better security.
Add one more binding with the host name you want (in this case, *). For example:
<site name="MvcApplication1" id="2">
<application path="/" applicationPool="Clr4IntegratedAppPool">
<virtualDirectory path="/" physicalPath="C:\sites\MvcApplication1" />
</application>
<bindings>
<binding protocol="http" bindingInformation="*:12853:localhost" />
<binding protocol="http" bindingInformation="*:12853:*" />
</bindings>
</site>
Note that, if want to open up all host names (*), you'll need two netsh commands (one for * and one for localhost). If you only want to open up a specific host name, you don't strictly need the second netsh command (localhost); just the one with your specific host name is sufficient.
https://stackoverflow.com/a/32448434/159695 does not work in Python3.
https://stackoverflow.com/a/35993/159695 works in Python3.
And I extends it to add default values.
class myStruct:
def __init__(self, **kwds):
self.x=0
self.__dict__.update(kwds) # Must be last to accept assigned member variable.
def __repr__(self):
args = ['%s=%s' % (k, repr(v)) for (k,v) in vars(self).items()]
return '%s(%s)' % ( self.__class__.__qualname__, ', '.join(args) )
a=myStruct()
b=myStruct(x=3,y='test')
c=myStruct(x='str')
>>> a
myStruct(x=0)
>>> b
myStruct(x=3, y='test')
>>> c
myStruct(x='str')
There must be more to a Python dictionary than a table lookup on hash(). By brute experimentation I found this hash collision:
>>> hash(1.1)
2040142438
>>> hash(4504.1)
2040142438
Yet it doesn't break the dictionary:
>>> d = { 1.1: 'a', 4504.1: 'b' }
>>> d[1.1]
'a'
>>> d[4504.1]
'b'
Sanity check:
>>> for k,v in d.items(): print(hash(k))
2040142438
2040142438
Possibly there's another lookup level beyond hash() that avoids collisions between dictionary keys. Or maybe dict() uses a different hash.
(By the way, this in Python 2.7.10. Same story in Python 3.4.3 and 3.5.0 with a collision at hash(1.1) == hash(214748749.8)
.)
Use the built-in timestamps
option for your Schema.
var ItemSchema = new Schema({
name: { type: String, required: true, trim: true }
},
{
timestamps: true
});
This will automatically add createdAt
and updatedAt
fields to your schema.
Adding to Greg Hewgill answer (of using core.fileMode
config variable):
You can use --chmod=(-|+)x
option of git update-index (low-level version of "git add") to change execute permissions in the index, from where it would be picked up if you use "git commit" (and not "git commit -a").
On Mac OS X El Capitan I had to run these two commands to fix this error:
xcode-select --install
pip install lxml
Which ended up installing lxml-3.5.0
When you run the xcode-select command you may have to sign a EULA (so have an X-Term handy for the UI if you're doing this on a headless machine).
An ioctl
, which means "input-output control" is a kind of device-specific system call. There are only a few system calls in Linux (300-400), which are not enough to express all the unique functions devices may have. So a driver can define an ioctl which allows a userspace application to send it orders. However, ioctls are not very flexible and tend to get a bit cluttered (dozens of "magic numbers" which just work... or not), and can also be insecure, as you pass a buffer into the kernel - bad handling can break things easily.
An alternative is the sysfs
interface, where you set up a file under /sys/
and read/write that to get information from and to the driver. An example of how to set this up:
static ssize_t mydrvr_version_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", DRIVER_RELEASE);
}
static DEVICE_ATTR(version, S_IRUGO, mydrvr_version_show, NULL);
And during driver setup:
device_create_file(dev, &dev_attr_version);
You would then have a file for your device in /sys/
, for example, /sys/block/myblk/version
for a block driver.
Another method for heavier use is netlink, which is an IPC (inter-process communication) method to talk to your driver over a BSD socket interface. This is used, for example, by the WiFi drivers. You then communicate with it from userspace using the libnl
or libnl3
libraries.
Try this:
mynewlist = [s for s in mylist if s.isdigit()]
From the docs:
str.isdigit()
Return true if all characters in the string are digits and there is at least one character, false otherwise.
For 8-bit strings, this method is locale-dependent.
As noted in the comments, isdigit()
returning True
does not necessarily indicate that the string can be parsed as an int via the int()
function, and it returning False
does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.
$(function(){
var navMain = $("#your id");
navMain.on("click", "a", null, function () {
navMain.collapse('hide');
});
});
I'm on 64-bit Windows 7 and went to:
Then downloaded the exe for my system, installed it, and it worked for me.
Here's a non-jQuery version that is considerably faster than both the jQuery .html()
version and the .replace()
version. This preserves all whitespace, but like the jQuery version, doesn't handle quotes.
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
Speed: http://jsperf.com/htmlencoderegex/17
function htmlEncode( html ) {
return document.createElement( 'a' ).appendChild(
document.createTextNode( html ) ).parentNode.innerHTML;
};
function htmlDecode( html ) {
var a = document.createElement( 'a' ); a.innerHTML = html;
return a.textContent;
};
document.getElementById( 'text' ).value = htmlEncode( document.getElementById( 'hidden' ).value );
//sanity check
var html = '<div> & hello</div>';
document.getElementById( 'same' ).textContent =
'html === htmlDecode( htmlEncode( html ) ): '
+ ( html === htmlDecode( htmlEncode( html ) ) );
<input id="hidden" type="hidden" value="chalk & cheese" />
<input id="text" value="" />
<div id="same"></div>
if you have xcopy
, you can use the /E
param, which will copy directories and subdirectories and the files within them, including maintaining the directory structure for empty directories
xcopy [source] [destination] /E
This will get ALL parameters from the request. For Debugging purposes only:
@RequestMapping (value = "/promote", method = {RequestMethod.POST, RequestMethod.GET})
public ModelAndView renderPromotePage (HttpServletRequest request) {
Map<String, String[]> parameters = request.getParameterMap();
for(String key : parameters.keySet()) {
System.out.println(key);
String[] vals = parameters.get(key);
for(String val : vals)
System.out.println(" -> " + val);
}
ModelAndView mv = new ModelAndView();
mv.setViewName("test");
return mv;
}
I know that I'm not answering the xargs
question directly but it's worth mentioning find
's -exec
option.
Given the following file system:
[root@localhost bokeh]# tree --charset assci bands
bands
|-- Dream\ Theater
|-- King's\ X
|-- Megadeth
`-- Rush
0 directories, 4 files
The find command can be made to handle the space in Dream Theater and King's X. So, to find the drummers of each band using grep:
[root@localhost]# find bands/ -type f -exec grep Drums {} +
bands/Dream Theater:Drums:Mike Mangini
bands/Rush:Drums: Neil Peart
bands/King's X:Drums:Jerry Gaskill
bands/Megadeth:Drums:Dirk Verbeuren
In the -exec
option {}
stands for the filename including path. Note that you don't have to escape it or put it in quotes.
The difference between -exec
's terminators (+
and \;
) is that +
groups as many file names that it can onto one command line. Whereas \;
will execute the command for each file name.
So, find bands/ -type f -exec grep Drums {} +
will result in:
grep Drums "bands/Dream Theater" "bands/Rush" "bands/King's X" "bands/Megadeth"
and find bands/ -type f -exec grep Drums {} \;
will result in:
grep Drums "bands/Dream Theater"
grep Drums "bands/Rush"
grep Drums "bands/King's X"
grep Drums "bands/Megadeth"
In the case of grep
this has the side effect of either printing the filename or not.
[root@localhost bokeh]# find bands/ -type f -exec grep Drums {} \;
Drums:Mike Mangini
Drums: Neil Peart
Drums:Jerry Gaskill
Drums:Dirk Verbeuren
[root@localhost bokeh]# find bands/ -type f -exec grep Drums {} +
bands/Dream Theater:Drums:Mike Mangini
bands/Rush:Drums: Neil Peart
bands/King's X:Drums:Jerry Gaskill
bands/Megadeth:Drums:Dirk Verbeuren
Of course, grep
's options -h
and -H
will control whether or not the filename is printed regardless of how grep
is called.
xargs
xargs
can also control how man files are on the command line.
xargs
by default groups all the arguments onto one line. In order to do the same thing that -exec \;
does use xargs -l
. Note that the -t
option tells xargs
to print the command before executing it.
[root@localhost bokeh]# find ./bands -type f | xargs -d '\n' -l -t grep Drums
grep Drums ./bands/Dream Theater
Drums:Mike Mangini
grep Drums ./bands/Rush
Drums: Neil Peart
grep Drums ./bands/King's X
Drums:Jerry Gaskill
grep Drums ./bands/Megadeth
Drums:Dirk Verbeuren
See that the -l
option tells xargs to execute grep for every filename.
Versus the default (i.e. no -l
option):
[root@localhost bokeh]# find ./bands -type f | xargs -d '\n' -t grep Drums
grep Drums ./bands/Dream Theater ./bands/Rush ./bands/King's X ./bands/Megadeth
./bands/Dream Theater:Drums:Mike Mangini
./bands/Rush:Drums: Neil Peart
./bands/King's X:Drums:Jerry Gaskill
./bands/Megadeth:Drums:Dirk Verbeuren
xargs
has better control on how many files can be on the command line. Give the -l
option the max number of files per command.
[root@localhost bokeh]# find ./bands -type f | xargs -d '\n' -l2 -t grep Drums
grep Drums ./bands/Dream Theater ./bands/Rush
./bands/Dream Theater:Drums:Mike Mangini
./bands/Rush:Drums: Neil Peart
grep Drums ./bands/King's X ./bands/Megadeth
./bands/King's X:Drums:Jerry Gaskill
./bands/Megadeth:Drums:Dirk Verbeuren
[root@localhost bokeh]#
See that grep
was executed with two filenames because of -l2
.
When you use angle brackets, the compiler searches for the file in the include path list. When you use double quotes, it first searches the current directory (i.e. the directory where the module being compiled is) and only then it'll search the include path list.
So, by convention, you use the angle brackets for standard includes and the double quotes for everything else. This ensures that in the (not recommended) case in which you have a local header with the same name as a standard header, the right one will be chosen in each case.
curl -X PUT -d 'new_value' URL_PATH/key
where,
X - option to be used for request command
d - option to be used in order to put data on remote url
URL_PATH - remote url
new_value - value which we want to put to the server's key
How about std::cin.get();
?
Also, if you're using Visual Studio, you can run without debugging (CTRL-F5 by default) and it won't close the console at the end. If you run it with debugging, you could always put a breakpoint at the closing brace of main()
.
Here is a simple query containing coalesce -
select * from person where coalesce(addressId, ContactId) is null.
It will return the persons where both addressId and contactId are null.
coalesce function
e.g.
Update: Angular 1.1.5 added a ternary operator, so now we can simply write
<li ng-class="$first ? 'firstRow' : 'nonFirstRow'">
If you are using an earlier version of Angular, your two choices are:
(condition && result_if_true || !condition && result_if_false)
{true: 'result_if_true', false: 'result_if_false'}[condition]
item 2. above creates an object with two properties. The array syntax is used to select either the property with name true or the property with name false, and return the associated value.
E.g.,
<li class="{{{true: 'myClass1 myClass2', false: ''}[$first]}}">...</li>
or
<li ng-class="{true: 'myClass1 myClass2', false: ''}[$first]">...</li>
$first is set to true inside an ng-repeat for the first element, so the above would apply class 'myClass1' and 'myClass2' only the first time through the loop.
With ng-class there is an easier way though: ng-class takes an expression that must evaluate to one of the following:
An example of 1) was given above. Here is an example of 3, which I think reads much better:
<li ng-class="{myClass: $first, anotherClass: $index == 2}">...</li>
The first time through an ng-repeat loop, class myClass is added. The 3rd time through ($index starts at 0), class anotherClass is added.
ng-style takes an expression that must evaluate to a map/object of CSS style names to CSS values. E.g.,
<li ng-style="{true: {color: 'red'}, false: {}}[$first]">...</li>
memset
is generally designed to be very very fast general-purpose setting/zeroing code. It handles all cases with different sizes and alignments, which affect the kinds of instructions you can use to do your work. Depending on what system you're on (and what vendor your stdlib comes from), the underlying implementation might be in assembler specific to that architecture to take advantage of whatever its native properties are. It might also have internal special cases to handle the case of zeroing (versus setting some other value).
That said, if you have very specific, very performance critical memory zeroing to do, it's certainly possible that you could beat a specific memset
implementation by doing it yourself. memset
and its friends in the standard library are always fun targets for one-upmanship programming. :)
This should also work (even in SQL-Server 2005):
SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
AND Created < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))
This is also an alternate use of case-when...
UPDATE [dbo].[JobTemplates]
SET [CycleId] =
CASE [Id]
WHEN 1376 THEN 44 --ACE1 FX1
WHEN 1385 THEN 44 --ACE1 FX2
WHEN 1574 THEN 43 --ACE1 ELEM1
WHEN 1576 THEN 43 --ACE1 ELEM2
WHEN 1581 THEN 41 --ACE1 FS1
WHEN 1585 THEN 42 --ACE1 HS1
WHEN 1588 THEN 43 --ACE1 RS1
WHEN 1589 THEN 44 --ACE1 RM1
WHEN 1590 THEN 43 --ACE1 ELEM3
WHEN 1591 THEN 43 --ACE1 ELEM4
WHEN 1595 THEN 44 --ACE1 SSTn
ELSE 0
END
WHERE
[Id] IN (1376,1385,1574,1576,1581,1585,1588,1589,1590,1591,1595)
I like the use of the temporary tables in cases where duplicate values are not permitted and your update may create them. For example:
SELECT
[Id]
,[QueueId]
,[BaseDimensionId]
,[ElastomerTypeId]
,CASE [CycleId]
WHEN 29 THEN 44
WHEN 30 THEN 43
WHEN 31 THEN 43
WHEN 101 THEN 41
WHEN 102 THEN 43
WHEN 116 THEN 42
WHEN 120 THEN 44
WHEN 127 THEN 44
WHEN 129 THEN 44
ELSE 0
END AS [CycleId]
INTO
##ACE1_PQPANominals_1
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
WHERE
[QueueId] = 3
ORDER BY
[BaseDimensionId], [ElastomerTypeId], [Id];
---- (403 row(s) affected)
UPDATE [dbo].[ProductionQueueProcessAutoclaveNominals]
SET
[CycleId] = X.[CycleId]
FROM
[dbo].[ProductionQueueProcessAutoclaveNominals]
INNER JOIN
(
SELECT
MIN([Id]) AS [Id],[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
FROM
##ACE1_PQPANominals_1
GROUP BY
[QueueId],[BaseDimensionId],[ElastomerTypeId],[CycleId]
) AS X
ON
[dbo].[ProductionQueueProcessAutoclaveNominals].[Id] = X.[Id];
----(375 row(s) affected)
This is what worked for me. Very simple jQuery and CSS to make responsive carousel works independently of carousels on the same page. Highly customizable but basically a div with white-space nowrap containing a bunch of inline-block elements and put the last one at the beginning to move back or the first one to the end to move forward. Thank you insertAfter
!
$('.carosel-control-right').click(function() {_x000D_
$(this).blur();_x000D_
$(this).parent().find('.carosel-item').first().insertAfter($(this).parent().find('.carosel-item').last());_x000D_
});_x000D_
$('.carosel-control-left').click(function() {_x000D_
$(this).blur();_x000D_
$(this).parent().find('.carosel-item').last().insertBefore($(this).parent().find('.carosel-item').first());_x000D_
});
_x000D_
@media (max-width: 300px) {_x000D_
.carosel-item {_x000D_
width: 100%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 300px) {_x000D_
.carosel-item {_x000D_
width: 50%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 500px) {_x000D_
.carosel-item {_x000D_
width: 33.333%;_x000D_
}_x000D_
}_x000D_
@media (min-width: 768px) {_x000D_
.carosel-item {_x000D_
width: 25%;_x000D_
}_x000D_
}_x000D_
.carosel {_x000D_
position: relative;_x000D_
background-color: #000;_x000D_
}_x000D_
.carosel-inner {_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
font-size: 0;_x000D_
}_x000D_
.carosel-item {_x000D_
display: inline-block;_x000D_
}_x000D_
.carosel-control {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
padding: 15px;_x000D_
box-shadow: 0 0 10px 0px rgba(0, 0, 0, 0.5);_x000D_
transform: translateY(-50%);_x000D_
border-radius: 50%;_x000D_
color: rgba(0, 0, 0, 0.5);_x000D_
font-size: 30px;_x000D_
display: inline-block;_x000D_
}_x000D_
.carosel-control-left {_x000D_
left: 15px;_x000D_
}_x000D_
.carosel-control-right {_x000D_
right: 15px;_x000D_
}_x000D_
.carosel-control:active,_x000D_
.carosel-control:hover {_x000D_
text-decoration: none;_x000D_
color: rgba(0, 0, 0, 0.8);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="carosel" id="carosel1">_x000D_
<a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
<div class="carosel-inner">_x000D_
<img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&text=1" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/CCCCCC&text=2" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/eeeeee&text=3" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/f4f4f4&text=4" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&text=5" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/f477f4/fff&text=6" />_x000D_
</div>_x000D_
<a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>_x000D_
<div class="carosel" id="carosel2">_x000D_
<a class="carosel-control carosel-control-left glyphicon glyphicon-chevron-left" href="#"></a>_x000D_
<div class="carosel-inner">_x000D_
<img class="carosel-item" src="http://placehold.it/500/bbbbbb/fff&text=1" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/CCCCCC&text=2" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/eeeeee&text=3" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/f4f4f4&text=4" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/fcfcfc/333&text=5" />_x000D_
<img class="carosel-item" src="http://placehold.it/500/f477f4/fff&text=6" />_x000D_
</div>_x000D_
<a class="carosel-control carosel-control-right glyphicon glyphicon-chevron-right" href="#"></a>_x000D_
</div>
_x000D_
You can directly convert to an int using the str::parse::<T>()
method.
let my_string = "27".to_string(); // `parse()` works with `&str` and `String`!
let my_int = my_string.parse::<i32>().unwrap();
You can either specify the type to parse to with the turbofish operator (::<>
) as shown above or via explicit type annotation:
let my_int: i32 = my_string.parse().unwrap();
As mentioned in the comments, parse()
returns a Result
. This result will be an Err
if the string couldn't be parsed as the type specified (for example, the string "peter"
can't be parsed as i32
).
using recursion
let myArr = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
let size = 4; //Math.sqrt(myArr.length); --> For a n x n matrix
let tempArr = [];
function createMatrix(arr, i) {
if (arr.length !== 0) {
if(i % size == 0) {
tempArr.push(arr.splice(0,size))
}
createMatrix(arr, i - 1)
}
}
createMatrix(myArr, myArr.length);
console.log(tempArr);
Note: The existing array i.e. myArr will be modified.
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
Call the parent method with the parent scope resolution operator.
Parent::method()
class Primate {
public:
void whatAmI(){
cout << "I am of Primate order";
}
};
class Human : public Primate{
public:
void whatAmI(){
cout << "I am of Human species";
}
void whatIsMyOrder(){
Primate::whatAmI(); // <-- SCOPE RESOLUTION OPERATOR
}
};
Snagit...lots of tech folks use that.
Let's say I have an array arr. When would the following not give the number of elements of the array:
sizeof(arr) / sizeof(arr[0])
?
In contexts where arr
is not actually the array (but instead a pointer to the initial element). Other answers explain how this happens.
I can thing of only one case: the array contains elements that are of different derived types of the type of the array.
This cannot happen (for, fundamentally, the same reason that Java arrays don't play nicely with generics). The array is statically typed; it reserves "slots" of memory that are sized for a specific type (the base type).
Sorry for the trivial question, I am a Java dev and I am rather new to C++.
C++ arrays are not first-class objects. You can use boost::array to make them behave more like Java arrays, but keep in mind that you will still have value semantics rather than reference semantics, just like with everything else. (In particular, this means that you cannot really declare a variable of type analogous to Foo[]
in Java, nor replace an array with another one of a different size; the array size is a part of the type.) Use .size()
with this class where you would use .length
in Java. (It also supplies iterators that provide the usual interface for C++ iterators.)
if you want to copy folder from currant directory to binary (build folder) folder
file(COPY ${CMAKE_CURRENT_SOURCE_DIR}/yourFolder/ DESTINATION ${CMAKE_CURRENT_BINARY_DIR}/yourFolder/)
then the syntexe is :
file(COPY pathSource DESTINATION pathDistination)
http://constc.blogspot.com/2008/07/undeclared-undefined-null-in-javascript.html
Depends on how specific you want the test to be. You could maybe get away with
if(page_name){ string += "&page_name=" + page_name; }
jQuery.post(post_url,{ content: "John" } )_x000D_
.done(function( data ) {_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check
ob_start();_x000D_
_x000D_
include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
$content = ob_get_clean();_x000D_
_x000D_
_x000D_
_x000D_
$test = $_SESSION['content'] ;_x000D_
_x000D_
require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
$html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 ); _x000D_
$html2pdf->setDefaultFont('Arial');_x000D_
$html2pdf->WriteHTML($test);
_x000D_
This is how I did it. I don't know why MapRoute() doesn't allow you to set the area, but it does return the route object so you can continue to make any additional changes you would like. I use this because I have a modular MVC site that is sold to enterprise customers and they need to be able to drop dlls into the bin folder to add new modules. I allow them to change the "HomeArea" in the AppSettings config.
var route = routes.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
route.DataTokens["area"] = area;
Edit: You can try this as well in your AreaRegistration.RegisterArea for the area you want the user going to by default. I haven't tested it but AreaRegistrationContext.MapRoute does sets route.DataTokens["area"] = this.AreaName;
for you.
context.MapRoute(
"Home_Default",
"",
new {controller = "Home", action = "index" },
new[] { "IPC.Web.Core.Controllers" }
);
The MySQL function LAST_INSERT_ID()
does just what you need: it retrieves the id that was inserted during this session. So it is safe to use, even if there are other processes (other people calling the exact same script, for example) inserting values into the same table.
The PHP function mysql_insert_id()
does the same as calling SELECT LAST_INSERT_ID()
with mysql_query()
.
setInterval(function() {
$('#board').append('.');
}, 1000);
You can use clearInterval if you wanted to stop it at one point.
Here's how I would do this:
class ClassPropertyDescriptor(object):
def __init__(self, fget, fset=None):
self.fget = fget
self.fset = fset
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
return self.fget.__get__(obj, klass)()
def __set__(self, obj, value):
if not self.fset:
raise AttributeError("can't set attribute")
type_ = type(obj)
return self.fset.__get__(obj, type_)(value)
def setter(self, func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
self.fset = func
return self
def classproperty(func):
if not isinstance(func, (classmethod, staticmethod)):
func = classmethod(func)
return ClassPropertyDescriptor(func)
class Bar(object):
_bar = 1
@classproperty
def bar(cls):
return cls._bar
@bar.setter
def bar(cls, value):
cls._bar = value
# test instance instantiation
foo = Bar()
assert foo.bar == 1
baz = Bar()
assert baz.bar == 1
# test static variable
baz.bar = 5
assert foo.bar == 5
# test setting variable on the class
Bar.bar = 50
assert baz.bar == 50
assert foo.bar == 50
The setter didn't work at the time we call Bar.bar
, because we are calling
TypeOfBar.bar.__set__
, which is not Bar.bar.__set__
.
Adding a metaclass definition solves this:
class ClassPropertyMetaClass(type):
def __setattr__(self, key, value):
if key in self.__dict__:
obj = self.__dict__.get(key)
if obj and type(obj) is ClassPropertyDescriptor:
return obj.__set__(self, value)
return super(ClassPropertyMetaClass, self).__setattr__(key, value)
# and update class define:
# class Bar(object):
# __metaclass__ = ClassPropertyMetaClass
# _bar = 1
# and update ClassPropertyDescriptor.__set__
# def __set__(self, obj, value):
# if not self.fset:
# raise AttributeError("can't set attribute")
# if inspect.isclass(obj):
# type_ = obj
# obj = None
# else:
# type_ = type(obj)
# return self.fset.__get__(obj, type_)(value)
Now all will be fine.
This is the error line:
if (called_from.equalsIgnoreCase("add")) { --->38th error line
This means that called_from
is null. Simple check if it is null above:
String called_from = getIntent().getStringExtra("called");
if(called_from == null) {
called_from = "empty string";
}
if (called_from.equalsIgnoreCase("add")) {
// do whatever
} else {
// do whatever
}
That way, if called_from
is null, it'll execute the else
part of your if statement.
Converting an int to a byte in Python 3:
n = 5
bytes( [n] )
>>> b'\x05'
;) guess that'll be better than messing around with strings
source: http://docs.python.org/3/library/stdtypes.html#binaryseq
Already mentioned. Just a LINQ answer:
var columns = reader.GetSchemaTable().Rows
.Cast<DataRow>()
.Select(r => (string)r["ColumnName"])
.ToList();
//Or
var columns = Enumerable.Range(0, reader.FieldCount)
.Select(reader.GetName)
.ToList();
The second one is cleaner and much faster. Even if you cache GetSchemaTable
in the first approach, the querying is going to be very slow.
When you want to have cross component interaction, then you need to know what are @Input , @Output , EventEmitter and Subjects.
If the relation between components is parent- child or vice versa we use @input & @output with event emitter..
@output emits an event and you need to emit using event emitter.
If it's not parent child relationship.. then you have to use subjects or through a common service.
Example: index = False
import pandas as pd
writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save()
I was also wondering how to store it cleanly in a variable. As using
char c = '•';
is not very good practice (I guess). I found out the following way of storing it in a variable
char c = (char)0x2022;// or 0x25cf depending on the one you choose
or even cleaner
char c = '\u2022';// or "\u25cf"
https://msdn.microsoft.com/en-us/library/aa664669%28v=vs.71%29.aspx
same for strings
string s = "\u2022";
mysqldump
utility can help you, basically with --tab
option it's a wrapped for SELECT INTO OUTFILE
statement.
Example:
mysqldump -u root -p --tab=/tmp world Country --fields-enclosed-by='"' --fields-terminated-by="," --lines-terminated-by="\n" --no-create-info
This will create csv formatted file /tmp/Country.txt
Use it this way:
<div [ngClass]="{cssClass A: condition 1, cssClass B: condition 2, cssClass C: condition 3}">...</div>
If you want the types of convenience methods mentioned in other answers but need portability (or even if you don't), you might want to check out Flurl [disclosure: I'm the author]. It (thinly) wraps HttpClient
and Json.NET and adds some fluent sugar and other goodies, including some baked-in testing helpers.
Post as JSON:
var resp = await "http://localhost:44268/api/test".PostJsonAsync(widget);
or URL-encoded:
var resp = await "http://localhost:44268/api/test".PostUrlEncodedAsync(widget);
Both examples above return an HttpResponseMessage
, but Flurl includes extension methods for returning other things if you just want to cut to the chase:
T poco = await url.PostJsonAsync(data).ReceiveJson<T>();
dynamic d = await url.PostUrlEncodedAsync(data).ReceiveJson();
string s = await url.PostUrlEncodedAsync(data).ReceiveString();
Flurl is available on NuGet:
PM> Install-Package Flurl.Http
After you've run the Inspect by Name, select all the locations, and make use of the Apply quick fixes to all the problems drop-down, and use either (or both) of Delete unused parameter(s) and Safe Delete.
Don't forget to hit Do Refactor afterwards.
Then you'll need to run another analysis, as the refactored code will no doubt reveal more unused declarations.
Use for...in
loop:
for (var key in obj) {
console.log(' name=' + key + ' value=' + obj[key]);
// do some more stuff with obj[key]
}
In agreement with aleho's response here's a complete example. It works like a charm and is super simple.
Controller code
[HttpGet]
public async Task<ActionResult> ChildItems()
{
var client = TranslationDataHttpClient.GetClient();
HttpResponseMessage response = await client.GetAsync("childItems);
if (response.IsSuccessStatusCode)
{
string content = response.Content.ReadAsStringAsync().Result;
List<WorkflowItem> parameters = JsonConvert.DeserializeObject<List<WorkflowItem>>(content);
return Json(content, JsonRequestBehavior.AllowGet);
}
else
{
return new HttpStatusCodeResult(response.StatusCode, response.ReasonPhrase);
}
}
}
Javascript code in the view
var url = '@Html.Raw(@Url.Action("ChildItems", "WorkflowItemModal")';
$.ajax({
type: "GET",
dataType: "json",
url: url,
contentType: "application/json; charset=utf-8",
success: function (data) {
// Do something with the returned data
},
error: function (xhr, status, error) {
// Handle the error.
}
});
Hope this helps someone else!
You are trying to access the struct statically with a .
instead of ::
, nor are its members static
. Either instantiate ReducedForm
:
ReducedForm rf;
rf.iSimplifiedNumerator = 5;
or change the members to static
like this:
struct ReducedForm
{
static int iSimplifiedNumerator;
static int iSimplifiedDenominator;
};
In the latter case, you must access the members with ::
instead of .
I highly doubt however that the latter is what you are going for ;)
This is not perfect, but it works.
<asp:LinkButton id="lbnkVidTtile1" runat="Server"
CssClass="bodytext" Text='<%# Eval("newvideotitle") %>'
OnClientClick="return PostToNewWindow();" />
<script type="text/javascript">
function PostToNewWindow()
{
originalTarget = document.forms[0].target;
document.forms[0].target='_blank';
window.setTimeout("document.forms[0].target=originalTarget;",300);
return true;
}
</script>
Use negative lookaround: (?!
pattern
)
Positive lookarounds can be used to assert that a pattern matches. Negative lookarounds is the opposite: it's used to assert that a pattern DOES NOT match. Some flavor supports assertions; some puts limitations on lookbehind, etc.
These are attempts to come up with regex solutions to toy problems as exercises; they should be educational if you're trying to learn the various ways you can use lookarounds (nesting them, using them to capture, etc):
came out of this issue by changing the version in package.json file and also changing the name of the package and finally deleted the package-lock.json file
Learn More Using this link https://developer.android.com/training/improving-layouts/reusing-layouts.html
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Game_logic">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:id="@+id/text1"
android:textStyle="bold"
tools:text="Player " />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:layout_marginLeft="20dp"
android:id="@+id/text2"
tools:text="Player 2" />
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
Blockquote
Above layout you can used in other activity using
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SinglePlayer">
<include layout="@layout/activity_game_logic"/>
</androidx.constraintlayout.widget.ConstraintLayout>
You can have it on github using the command
git clone https://github.com/coreutils/coreutils.git
You can find all the source codes in the src folder.
You need to have git installed.
Things have changed since 2012, ls
source code has now 5309 lines
I was all in favour of throwing IllegalArgumentException
for null parameters, until today, when I noticed the java.util.Objects.requireNonNull
method in Java 7. With that method, instead of doing:
if (param == null) {
throw new IllegalArgumentException("param cannot be null.");
}
you can do:
Objects.requireNonNull(param);
and it will throw a NullPointerException
if the parameter you pass it is null
.
Given that that method is right bang in the middle of java.util
I take its existence to be a pretty strong indication that throwing NullPointerException
is "the Java way of doing things".
I think I'm decided at any rate.
Note that the arguments about hard debugging are bogus because you can of course provide a message to NullPointerException
saying what was null and why it shouldn't be null. Just like with IllegalArgumentException
.
One added advantage of NullPointerException
is that, in highly performance critical code, you could dispense with an explicit check for null (and a NullPointerException
with a friendly error message), and just rely on the NullPointerException
you'll get automatically when you call a method on the null parameter. Provided you call a method quickly (i.e. fail fast), then you have essentially the same effect, just not quite as user friendly for the developer. Most times it's probably better to check explicitly and throw with a useful message to indicate which parameter was null, but it's nice to have the option of changing that if performance dictates without breaking the published contract of the method/constructor.
You can use:
NOW() + INTERVAL 1 DAY
If you are only interested in the date, not the date and time then you can use CURDATE instead of NOW:
CURDATE() + INTERVAL 1 DAY
try this:
first write this in your .h file of viewcontroller
UIButton *btn;
Now write this in your .m file of viewcontrollers viewDidLoad.
btn=[[UIButton alloc]initWithFrame:CGRectMake(50, 20, 30, 30)];
[btn setBackgroundColor:[UIColor orangeColor]];
//adding action programatically
[btn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
write this outside viewDidLoad method in .m file of your view controller
- (IBAction)btnClicked:(id)sender
{
//Write a code you want to execute on buttons click event
}
Double check your data types. The dotnet model binder will not convert a float to an integer (and I'm assuming other related concepts). This will cause the entire model to be rejected.
If you have json like this:
{
"shoeSize": 10.5
}
but your c# model looks like this:
class Shoe{
public int shoeSize;
}
the model binder will reject the model and you will get null.
Using com.ibm.etools.marshall.util.BigDecimalRange util class of IBM one can compare if BigDecimal in range.
boolean isCalculatedSumInRange = BigDecimalRange.isInRange(low, high, calculatedSum);
First check - is the working directory the directory that the application is running in:
If this isn't the problem, then ask if Autodesk.Navisworks.Timeliner.dll is requiring another DLL which is not there.
If Timeliner.dll is not a .NET assembly, you can determine the required imports using the command utility DUMPBIN
.
dumpbin /imports Autodesk.Navisworks.Timeliner.dll
If it is a .NET assembly, there are a number of tools that can check dependencies.
Reflector
has already been mentioned, and I use JustDecompile
from Telerik.
Since image is deprecated, you should use varbinary.
per Microsoft (thanks for the link @Christopher)
ntext , text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead.
Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.
I have developed an answer inspired by Jamie Hutber's.
It's a promise based function where you can set:
10
;100 ms
.Therefore, by default, it will wait 1 second until the element appears on the DOM.
If it does not show up it will return a promise.reject
with null
so you can handle the error as per your wish.
Code
function waitForElement(selector, delay = 1000, tries = 10) {
const element = document.querySelector(selector);
// creates a local variable w/ the name of the selector to keep track of all tries
if (!window[`__${selector}`]) {
window[`__${selector}`] = 0;
}
function _search() {
return new Promise((resolve) => {
window[`__${selector}`]++;
console.log(window[`__${selector}`]);
setTimeout(resolve, delay);
});
}
//element not found, retry
if (element === null) {
if (window[`__${selector}`] >= tries) {
window[`__${selector}`] = 0;
return Promise.reject(null);
}
return _search().then(() => waitForElement(selector));
} else {
return Promise.resolve(element);
}
}
Usage:
async function wait(){
try{
const $el = await waitForElement(".llama");
console.log($el);
} catch(err){
console.error("Timeout - couldn't find element.")
}
}
wait();
In the example above it will wait for the selector .llama
. You can add a greater delay and test it here on the console of StackoverFlow.
Just add the class llama
to any element on the DOM.
The way I typically handle this is with a second piece of software. For Windows I use Notepad++, for OS X I use Sublime Text 2.
Bit late response to this question, however I do have something to add that might be useful for others.
If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH
if ($('input.checkbox_check').is(':checked')) {
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u
means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u
in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.
You can create a Unicode string multiple ways:
>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'
But the real reason is to represent something like this (translation here):
>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????
For the most part, Unicode and non-Unicode strings are interoperable on Python 2.
There are other symbols you will see, such as the "raw" symbol r
for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.
>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'
Unicode and non-Unicode strings can be equal on Python 2:
>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True
but not on Python 3:
>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False
<!--
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])
CREATE TABLE `images` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`image` longblob NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB ;
-->
<!-- this form is user to store images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />
<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post" enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>
<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
mysql_connect("", "", "") OR DIE (mysql_error());
mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
header("location:search.php");
}
//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
$name=$_POST['image_name'];
$email=$_POST['mail'];
$fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
}
// our sql query
$sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
mysql_query($sql) or die("Error in Query insert: " . mysql_error());
}
?>
<?php
//SEARCH.PHP PAGE
//connect to database.db name = images
mysql_connect("localhost", "root", "") OR DIE (mysql_error());
mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database
$msg="";
$sql="select * from images";
if(mysql_query($sql))
{
$res=mysql_query($sql);
while($row=mysql_fetch_array($res))
{
$id=$row['id'];
$name=$row['name'];
$image=$row['image'];
$msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " /> </a>';
}
}
else
$msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>
Interesting observation using Java 11 and switching off loop unrolling with the following VM option:
-XX:LoopUnrollLimit=0
The loop with the 2 * (i * i)
expression results in more compact native code1:
L0001: add eax,r11d
inc r8d
mov r11d,r8d
imul r11d,r8d
shl r11d,1h
cmp r8d,r10d
jl L0001
in comparison with the 2 * i * i
version:
L0001: add eax,r11d
mov r11d,r8d
shl r11d,1h
add r11d,2h
inc r8d
imul r11d,r8d
cmp r8d,r10d
jl L0001
Java version:
java version "11" 2018-09-25
Java(TM) SE Runtime Environment 18.9 (build 11+28)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11+28, mixed mode)
Benchmark results:
Benchmark (size) Mode Cnt Score Error Units
LoopTest.fast 1000000000 avgt 5 694,868 ± 36,470 ms/op
LoopTest.slow 1000000000 avgt 5 769,840 ± 135,006 ms/op
Benchmark source code:
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@Warmup(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 5, time = 5, timeUnit = TimeUnit.SECONDS)
@State(Scope.Thread)
@Fork(1)
public class LoopTest {
@Param("1000000000") private int size;
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder()
.include(LoopTest.class.getSimpleName())
.jvmArgs("-XX:LoopUnrollLimit=0")
.build();
new Runner(opt).run();
}
@Benchmark
public int slow() {
int n = 0;
for (int i = 0; i < size; i++)
n += 2 * i * i;
return n;
}
@Benchmark
public int fast() {
int n = 0;
for (int i = 0; i < size; i++)
n += 2 * (i * i);
return n;
}
}
1 - VM options used: -XX:+UnlockDiagnosticVMOptions -XX:+PrintAssembly -XX:LoopUnrollLimit=0
The state of the checkbox will be reflected on whatever model you have it bound to, in this case, $scope.answers[item.questID]
Using python 3 and opencv-python version 4.4.0, the following code should work:
img_src = cv2.imread('image.png')
img_clone = img_src.copy()
All you need is to make an ajax request to your pythoncode. You can do this with jquery http://api.jquery.com/jQuery.ajax/, or use just javascript
$.ajax({
type: "POST",
url: "~/pythoncode.py",
data: { param: text}
}).done(function( o ) {
// do something
});
If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.
using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;
public class Miclass
{
private void AllViews()
{
List<PortClass> ports = new List<PortClass>();
List<Printersclass> Printersfor = new List<Printersclass>();
string[] portnames = SerialPort.GetPortNames();
/*PORTS*/
for (int i = 0; i < portnames.Count(); i++)
{
ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
}
/*PRINTER*/
for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
{
Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
}
}
}
public class PortClass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
public class Printersclass
{
public string Name { get; set; }
public string Desc { get; set; }
public override string ToString()
{
return string.Format("{0} ({1})", Name, Desc);
}
}
This is an old question, but no one seems to have mentioned this.
You were getting lucky that the thing was linking at all.
You needed to change
g++ -g -Wall -o my_binary -L/my/dir -lfoo bar.cpp
to this:
g++ -g -Wall -o my_binary -L/my/dir bar.cpp -lfoo
Your linker keeps track of symbols it needs to resolve. If it reads the library first, it doesn't have any needed symbols, so it ignores the symbols in it. Specify the libraries after the things that need to link to them so that your linker has symbols to find in them.
Also, -lfoo
makes it search specifically for a file named libfoo.a
or libfoo.so
as needed. Not libfoo.so.0
. So either ln
the name or rename the library as appopriate.
To quote the gcc man page:
-l library
...
It makes a difference where in the command you
write this option; the linker searches and processes
libraries and object files in the order they are
specified. Thus, foo.o -lz bar.o searches library z
after file foo.o but before bar.o. If bar.o refers
to functions in z, those functions may not be loaded.
Adding the file directly to g++
's command line should have worked,
unless of course, you put it prior to bar.cpp
, causing the linker
to ignore it for lacking any needed symbols, because no symbols were needed yet.
Set your PRIMARY KEY as AUTO_INCREMENT.
Increase the memory limit for composer
php -d memory_limit=4G /usr/local/bin/composer update
If you are using the latest version of Android studio. then you don't need to install additional software for Git other than GIT itself - https://git-scm.com/downloads
Steps
That's it. You can find your project on your github now
public class EmployeeApiController : ApiController
{
private readonly IEmployee _employeeRepositary;
public EmployeeApiController()
{
_employeeRepositary = new EmployeeRepositary();
}
public async Task<HttpResponseMessage> Create(EmployeeModel Employee)
{
var returnStatus = await _employeeRepositary.Create(Employee);
return Request.CreateResponse(HttpStatusCode.OK, returnStatus);
}
}
Persistance
public async Task<ResponseStatusViewModel> Create(EmployeeModel Employee)
{
var responseStatusViewModel = new ResponseStatusViewModel();
var connection = new SqlConnection(EmployeeConfig.EmployeeConnectionString);
var command = new SqlCommand("usp_CreateEmployee", connection);
command.CommandType = CommandType.StoredProcedure;
var pEmployeeName = new SqlParameter("@EmployeeName", SqlDbType.VarChar, 50);
pEmployeeName.Value = Employee.EmployeeName;
command.Parameters.Add(pEmployeeName);
try
{
await connection.OpenAsync();
await command.ExecuteNonQueryAsync();
command.Dispose();
connection.Dispose();
}
catch (Exception ex)
{
throw ex;
}
return responseStatusViewModel;
}
Repository
Task<ResponseStatusViewModel> Create(EmployeeModel Employee);
public class EmployeeConfig
{
public static string EmployeeConnectionString;
private const string EmployeeConnectionStringKey = "EmployeeConnectionString";
public static void InitializeConfig()
{
EmployeeConnectionString = GetConnectionStringValue(EmployeeConnectionStringKey);
}
private static string GetConnectionStringValue(string connectionStringName)
{
return Convert.ToString(ConfigurationManager.ConnectionStrings[connectionStringName]);
}
}
'profiles'
from the table 'django_migrations'
.python manage.py makemigrations
and python manage.py migrate
command.Here is another relatively simple solution that:
dirname()
(which does not work as expected on one level arguments like "file.txt" or relative parents like "..")abspath()
(avoiding any assumptions about the current working directory) but instead preserves the relative character of pathsit just uses normpath
and join
:
def parent(p):
return os.path.normpath(os.path.join(p, os.path.pardir))
# Example:
for p in ['foo', 'foo/bar/baz', 'with/trailing/slash/',
'dir/file.txt', '../up/', '/abs/path']:
print parent(p)
Result:
.
foo/bar
with/trailing
dir
..
/abs
This is not possible.
Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.
Why don't you use an image with an onclick
attribute?
For example:
<script>
function myfunction() {
}
</script>
<img src='Myimg.jpg' onclick='myfunction()'>
You can specify how to initialize members in the member initializer list:
BigMommaClass {
BigMommaClass(int, int);
private:
ThingOne thingOne;
ThingTwo thingTwo;
};
BigMommaClass::BigMommaClass(int numba1, int numba2)
: thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}
Check the latest version of Has on Intel website and install it. Let the ram in recommended size "preset 2048", then try to run the app. Things should work fine.
<button>
's are in fact submit buttons, they have no other main functionality. You will have to set the type to button.
But if you bind your event handler like below, you target all buttons and do not have to do it manually for each button!
$('form button').on("click",function(e){
e.preventDefault();
});
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
If you find yourself unable to catch errors with any of the solutions provided here, it may be that the server isn't handling CORS requests.
In that event, Javascript, much less Angular, can access the error information.
Look for warnings in your console that include CORB
or Cross-Origin Read Blocking
.
Also, the syntax has changed for handling errors (as described in every other answer). You now use pipe-able operators, like so:
this.service.requestsMyInfo(payload).pipe(
catcheError(err => {
// handle the error here.
})
);
Seems the SMTP as internet standard uses only reliable Transport protocol. RFC821 has TCP, NCP, NITS as examples!
<?php
$j=1;
array_reverse($skills_nav);
foreach ( $skills_nav as $skill ) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
?>
For windows, @shoaly parameters didn't completely work for me. I was getting this error:
NCAT DEBUG: Proxy returned status code 501.
Ncat: Proxy returned status code 501.
ssh_exchange_identification: Connection closed by remote host
I wanted to ssh to a REMOTESERVER and the SSH port had been closed in my network. I found two solutions but the second is better.
To solve the problem using Ncat:
ncat.exe
into the current directory.SSH using Ncat as ProxyCommand in Git Bash with addition --proxy-type socks4
parameter:
ssh -o "ProxyCommand=./ncat --proxy-type socks4 --proxy 127.0.0.1:9150 %h %p" USERNAME@REMOTESERVER
Note that this implementation of Ncat does not support socks5.
THE BETTER SOLUTION:
SSH using connect.c as ProxyCommand in Git Bash:
ssh -o "ProxyCommand=connect -a none -S 127.0.0.1:9150 %h %p"
Note that connect.c supports socks version 4/4a/5.
To use the proxy in git
commands using ssh (for example while using GitHub) -- assuming you installed Git Bash in C:\Program Files\Git\
-- open ~/.ssh/config
and add this entry:
host github.com
user git
hostname github.com
port 22
proxycommand "/c/Program Files/Git/mingw64/bin/connect.exe" -a none -S 127.0.0.1:9150 %h %p
Is this what you are looking for?
https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant
types is optional
You can use the command wget
to download from command line. Specifically, you could use
wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz
However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).
Intellij imports the project after resolving all the dependencies. In my case, it was unable to resolve dependencies for some of the modules and was stuck there. I had to copy my Maven settings.xml
from local repo to the default .m2
folder in order to point it to the correct local repo.
SELECT Convert(varchar(10),CONVERT(date,'columnname',105),105) as "end";
OR
SELECT CONVERT(VARCHAR(10), CAST(event_enddate AS DATE), 105) AS [end];
will return the particular date in the format of 'dd-mm-yyyy'
The result would be like this..
04-07-2016
Here is my working solution (SCSS):
.item{
display: flex;
justify-content: space-between;
align-items: center;
min-height: 120px;
&:after{
content:'';
min-height:inherit;
font-size:0;
}
}
This could be because of proxy or firewall. If it's proxy, then you need to specify proxy setting at entry point of your code or project.
import os #for proxy
proxy = 'http://10.XX.XX.XX:8X8X' #your own proxy 'http://<user>:<pass>@<proxy>:<port>'
os.environ['http_proxy'] = proxy
os.environ['HTTP_PROXY'] = proxy
os.environ['https_proxy'] = proxy
os.environ['HTTPS_PROXY'] = proxy
#rest of code .....
I have managed to get pycrypto
to compile by using MinGW32
and MSYS
. This presumes that you have pip
or easy_install
installed.
Here's how I did it:
1) Install MinGW32. For the sake of this explanation, let's assume it's installed in C:\MinGW
. When using the installer, which I recommend, select the C++ compiler.
MSYS should install with MinGW
2) Add c:\mingw\bin,c:\mingw\mingw32\bin,C:\MinGW\msys\1.0, c:\mingw\msys\1.0\bin and c:\mingw\msys\1.0\sbin
to your %PATH%
. If you aren't familiar, this article is very helpful.
3) From the search bar, run msys
and the MSYS terminal will open. For those familiar with Cygwin
, it works in a similar fashion.
4) From within the MSYS terminal pip install pycrypto
should run without error after this.
In XML Serializing, you can use the [XmlIgnore] attribute (System.Xml.Serialization.XmlIgnoreAttribute) to ignore a property when serializing a class.
This may be of use to you (Or it just may be of use to anyone who found this question when attempting to find out how to ignore a property when Serializing in XML, as I was).
Your sort logic is wrong. This is the pseudo-code for bubble sort:
for i = 1:n,
swapped = false
for j = n:i+1,
if a[j] < a[j-1],
swap a[j,j-1]
swapped = true
? invariant: a[1..i] in final position
break if not swapped
end
See this sorting web site for good tutorial on all the various sorting methods.
There's
Arrays.fill(myArray, null);
Not that it does anything different than you'd do on your own (it just loops through every element and sets it to null). It's not native in that it's pure Java code that performs this, but it is a library function if maybe that's what you meant.
This of course doesn't allow you to resize the array (to zero), if that's what you meant by
"empty". Array sizes are fixed, so if you want the "new" array to have different dimensions you're best to just reassign the reference to a new array as the other answers demonstrate. Better yet, use a List
type like an ArrayList
which can have variable size.
This situation isn't in any way different from the standard Java. You can use the standard way to stop a thread:
class WorkerThread extends Thread {
volatile boolean running = true;
public void run() {
// Do work...
if (!running) return;
//Continue doing the work
}
}
The main idea is to check the value of the field from time to time. When you need to stop your thread, you set running
to false. Also, as Chris has pointed out, you can use the interruption mechanism.
By the way, when you use AsyncTask, your apporach won't differ much. The only difference is that you will have to call isCancel()
method from your task instead of having a special field. If you call cancel(true)
, but don't implement this mechanism, the thread still won't stop by itself, it will run to the end.
i use return statement instead of throw as throw gives error in console. the best way to do it is to check the condition
if(condition){
return //whatever you want to return
}
this simply stops the execution of the program from that line, instead of giving any errors in the console.
In Swift use this,
If you wants to have pull to refresh in WebView,
So try this code:
override func viewDidLoad() {
super.viewDidLoad()
addPullToRefreshToWebView()
}
func addPullToRefreshToWebView(){
var refreshController:UIRefreshControl = UIRefreshControl()
refreshController.bounds = CGRectMake(0, 50, refreshController.bounds.size.width, refreshController.bounds.size.height) // Change position of refresh view
refreshController.addTarget(self, action: Selector("refreshWebView:"), forControlEvents: UIControlEvents.ValueChanged)
refreshController.attributedTitle = NSAttributedString(string: "Pull down to refresh...")
YourWebView.scrollView.addSubview(refreshController)
}
func refreshWebView(refresh:UIRefreshControl){
YourWebView.reload()
refresh.endRefreshing()
}
Thanks to everyone's contributions to this question, I've come up with the following script. Change the values for $SvcName
and $SvrName
to suit your needs. This script will start the remote service if it is stopped, or stop it if it is started. And it uses the cool .WaitForStatus
method to wait while the service responds.
#Change this values to suit your needs:
$SvcName = 'Spooler'
$SvrName = 'remotePC'
#Initialize variables:
[string]$WaitForIt = ""
[string]$Verb = ""
[string]$Result = "FAILED"
$svc = (get-service -computername $SvrName -name $SvcName)
Write-host "$SvcName on $SvrName is $($svc.status)"
Switch ($svc.status) {
'Stopped' {
Write-host "Starting $SvcName..."
$Verb = "start"
$WaitForIt = 'Running'
$svc.Start()}
'Running' {
Write-host "Stopping $SvcName..."
$Verb = "stop"
$WaitForIt = 'Stopped'
$svc.Stop()}
Default {
Write-host "$SvcName is $($svc.status). Taking no action."}
}
if ($WaitForIt -ne "") {
Try { # For some reason, we cannot use -ErrorAction after the next statement:
$svc.WaitForStatus($WaitForIt,'00:02:00')
} Catch {
Write-host "After waiting for 2 minutes, $SvcName failed to $Verb."
}
$svc = (get-service -computername $SvrName -name $SvcName)
if ($svc.status -eq $WaitForIt) {$Result = 'SUCCESS'}
Write-host "$Result`: $SvcName on $SvrName is $($svc.status)"
}
Of course, the account you run this under will need the proper privileges to access the remote computer and start and stop services. And when executing this against older remote machines, you might first have to install WinRM 3.0 on the older machine.
You can use the from
and size
parameters to page through all your data. This could be very slow depending on your data and how much is in the index.
http://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-from-size.html
You can use jQuery's getJSON() or Load(); with the latter, you can reference an existing html file. For more details, see http://www.codeproject.com/Articles/661782/Three-Ways-to-Dynamically-Load-HTML-Content-into-a
Try it with sudo
apachectl -V
-bash: apachectl: command not found
sudo apachectl -V
Server version: Apache/2.4.6 (Debian)
Server built: Aug 12 2013 18:20:23
Server's Module Magic Number: 20120211:24
Server loaded: APR 1.4.8, APR-UTIL 1.5.3
Compiled using: APR 1.4.8, APR-UTIL 1.5.2
Architecture: 32-bit
Server MPM: prefork
threaded: no
forked: yes (variable process count)
Server compiled with....
bla bla....
This is an old thread but apparently the C++ Faq
has a section (Archived 2013 version) on this. This apparently will be updated if the author is contacted so this will probably be more up to date in the long run, but here is the current version:
Depends on what you mean. If you mean, Is it possible to convert C++ to readable and maintainable C-code? then sorry, the answer is No — C++ features don't directly map to C, plus the generated C code is not intended for humans to follow. If instead you mean, Are there compilers which convert C++ to C for the purpose of compiling onto a platform that yet doesn't have a C++ compiler? then you're in luck — keep reading.
A compiler which compiles C++ to C does full syntax and semantic checking on the program, and just happens to use C code as a way of generating object code. Such a compiler is not merely some kind of fancy macro processor. (And please don't email me claiming these are preprocessors — they are not — they are full compilers.) It is possible to implement all of the features of ISO Standard C++ by translation to C, and except for exception handling, it typically results in object code with efficiency comparable to that of the code generated by a conventional C++ compiler.
Here are some products that perform compilation to C:
- Comeau Computing offers a compiler based on Edison Design Group's front end that outputs C code.
- LLVM is a downloadable compiler that emits C code. See also here and here. Here is an example of C++ to C conversion via LLVM.
Cfront, the original implementation of C++, done by Bjarne Stroustrup and others at AT&T, generates C code. However it has two problems: it's been difficult to obtain a license since the mid 90s when it started going through a maze of ownership changes, and development ceased at that same time and so it doesn't get bug fixes and doesn't support any of the newer language features (e.g., exceptions, namespaces, RTTI, member templates).
Contrary to popular myth, as of this writing there is no version of g++ that translates C++ to C. Such a thing seems to be doable, but I am not aware that anyone has actually done it (yet).
Note that you typically need to specify the target platform's CPU, OS and C compiler so that the generated C code will be specifically targeted for this platform. This means: (a) you probably can't take the C code generated for platform X and compile it on platform Y; and (b) it'll be difficult to do the translation yourself — it'll probably be a lot cheaper/safer with one of these tools.
One more time: do not email me saying these are just preprocessors — they are not — they are compilers.
For Intellij Idea set everything appropriately (similarly to this):
JAVA_HOME = C:\Program Files\Java\jdk1.8.0_60
JRE_HOME = JAVA_HOME\jre
and dont forget to restart Idea. This program picks up variables at start so any changes to environtment variables while the program is running will not have any effect.
Transition is more like an animation.
div.sicon a {
background:-moz-radial-gradient(left, #ffffff 24%, #cba334 88%);
transition: background 0.5s linear;
-moz-transition: background 0.5s linear; /* Firefox 4 */
-webkit-transition: background 0.5s linear; /* Safari and Chrome */
-o-transition: background 0.5s linear; /* Opera */
-ms-transition: background 0.5s linear; /* Explorer 10 */
}
So you need to invoke that animation with an action.
div.sicon a:hover {
background:-moz-radial-gradient(left, #cba334 24%, #ffffff 88%);
}
Also check for browser support and if you still have some problem with whatever you're trying to do! Check css-overrides in your stylesheet and also check out for behavior: ***.htc
css hacks.. there may be something overriding your transition!
You should check this out: http://www.w3schools.com/css/css3_transitions.asp
From the documentation:
Return date object with same year, month and day.
Normally yes, .gitignore
is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG
or something. In those cases you probably don't want to force that on anyone else.
Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.
In the non-Express version of VS, the import libray name is specfied in the project settings here:
Configuration Properties/Linker/Advanced/Import Library
I assume it's the same in Express (if it even provides the ability to configure the name).
Here's an example: http://duncan99.wordpress.com/2011/10/08/google-maps-api-infowindows/
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
// assuming you also want to hide the infowindow when user mouses-out
marker.addListener('mouseout', function() {
infowindow.close();
});
If using Java-JSP, What worked for me is to paste below in JSP page
<%@ page contentType="text/html; charset=UTF-8" %>
See question: How to find an item in a std::vector?
You'll also need to ensure you've implemented a suitable operator==()
for your object, if the default one isn't sufficient for a "deep" equality test.
for Swift 3 it is very simple
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
if you want to hide keyboard on pressing RETURN key
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
but in second case you will also need to pass delegate from all textFields to the ViewController in the Main.Storyboard
You can use JPGraph and Graphpite
The options for popen
can be used in call
args,
bufsize=0,
executable=None,
stdin=None,
stdout=None,
stderr=None,
preexec_fn=None,
close_fds=False,
shell=False,
cwd=None,
env=None,
universal_newlines=False,
startupinfo=None,
creationflags=0
So...
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=myoutput)
Then you can do what you want with myoutput
(which would need to be a file btw).
Also, you can do something closer to a piped output like this.
dmesg | grep hda
would be:
p1 = Popen(["dmesg"], stdout=PIPE)
p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
There's plenty of lovely, useful info on the python manual page.
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
You could opt for a pure CSS solution:
#hfont1 {
transition: color 1s ease-in-out;
-moz-transition: color 1s ease-in-out; /* FF 4 */
-webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
-o-transition: color 1s ease-in-out; /* Opera */
}
CSS3 introduced flexible boxes (aka. flex box) which can also achieve this behavior.
Simply define the width of the first div, and then give the second a flex-grow
value of 1
which will allow it to fill the remaining width of the parent.
.container{
display: flex;
}
.fixed{
width: 200px;
}
.flex-item{
flex-grow: 1;
}
<div class="container">
<div class="fixed"></div>
<div class="flex-item"></div>
</div>
Demo:
div {
color: #fff;
font-family: Tahoma, Verdana, Segoe, sans-serif;
padding: 10px;
}
.container {
background-color:#2E4272;
display:flex;
}
.fixed {
background-color:#4F628E;
width: 200px;
}
.flex-item {
background-color:#7887AB;
flex-grow: 1;
}
_x000D_
<div class="container">
<div class="fixed">Fixed width</div>
<div class="flex-item">Dynamically sized content</div>
</div>
_x000D_
Note that flex boxes are not backwards compatible with old browsers, but is a great option for targeting modern browsers (see also Caniuse and MDN). A great comprehensive guide on how to use flex boxes is available on CSS Tricks.
As variant, use simple lib > http://codeproject.com/Articles/42035/Enum-to-String-and-Vice-Versa-in-C
In the code
#include <EnumString.h>
enum FORM {
F_NONE = 0,
F_BOX,
F_CUBE,
F_SPHERE,
};
add lines
Begin_Enum_String( FORM )
{
Enum_String( F_NONE );
Enum_String( F_BOX );
Enum_String( F_CUBE );
Enum_String( F_SPHERE );
}
End_Enum_String;
Work fine, if values in enum are not dublicate.
Example usage
enum FORM f = ...
const std::string& str = EnumString< FORM >::From( f );
and vice versa
assert( EnumString< FORM >::To( f, str ) );
Using JSON.decode
for this comes with significant drawbacks that you must be aware of:
JSON.decode
(after wrapping them in double quotes) will error even though these are all valid: \\n
, \n
, \\0
, a"a
\\x45
\\u{045}
There are other caveats as well. Essentially, using JSON.decode
for this purpose is a hack and doesn't work the way you might always expect. You should stick with using the JSON
library to handle JSON, not for string operations.
I recently ran into this issue myself and wanted a robust decoder, so I ended up writing one myself. It's complete and thoroughly tested and is available here: https://github.com/iansan5653/unraw. It mimics the JavaScript standard as closely as possible.
The source is about 250 lines so I won't include it all here, but essentially it uses the following Regex to find all escape sequences and then parses them using parseInt(string, 16)
to decode the base-16 numbers and then String.fromCodePoint(number)
to get the corresponding character:
/\\(?:(\\)|x([\s\S]{0,2})|u(\{[^}]*\}?)|u([\s\S]{4})\\u([^{][\s\S]{0,3})|u([\s\S]{0,4})|([0-3]?[0-7]{1,2})|([\s\S])|$)/g
Commented (NOTE: This regex matches all escape sequences, including invalid ones. If the string would throw an error in JS, it throws an error in my library [ie, '\x!!'
will error]):
/
\\ # All escape sequences start with a backslash
(?: # Starts a group of 'or' statements
(\\) # If a second backslash is encountered, stop there (it's an escaped slash)
| # or
x([\s\S]{0,2}) # Match valid hexadecimal sequences
| # or
u(\{[^}]*\}?) # Match valid code point sequences
| # or
u([\s\S]{4})\\u([^{][\s\S]{0,3}) # Match surrogate code points which get parsed together
| # or
u([\s\S]{0,4}) # Match non-surrogate Unicode sequences
| # or
([0-3]?[0-7]{1,2}) # Match deprecated octal sequences
| # or
([\s\S]) # Match anything else ('.' doesn't match newlines)
| # or
$ # Match the end of the string
) # End the group of 'or' statements
/g # Match as many instances as there are
Using that library:
import unraw from "unraw";
let step1 = unraw('http\\u00253A\\u00252F\\u00252Fexample.com');
// yields "http%3A%2F%2Fexample.com"
// Then you can use decodeURIComponent to further decode it:
let step2 = decodeURIComponent(step1);
// yields http://example.com
This is the complete way to omit unneeded redirects, too ;)
These rules are intended to be used in .htaccess files, as a RewriteRule in a *:80 VirtualHost entry needs no Conditions.
RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
Eplanations:
RewriteEngine on
==> enable the engine at all
RewriteCond %{HTTPS} off [OR]
==> match on non-https connections, or (not setting [OR] would cause an implicit AND !)
RewriteCond %{HTTP:X-Forwarded-Proto} !https
==> match on forwarded connections (proxy, loadbalancer, etc.) without https
RewriteRule ^/(.*) https://%{HTTP_HOST}/$1 [NC,R=301,L]
==> if one of both Conditions match, do the rewrite of the whole URL, sending a 301 to have this 'learned' by the client (some do, some don't) and the L for the last rule.
I think you should make a subquery to do grouping. In this case inner subquery returns few rows and you don't need a CASE statement. So I think this is going to be faster:
select Detail.ReceiptDate AS 'DATE',
SUM(TotalMailed),
SUM(TotalReturnMail),
SUM(TraceReturnedMail)
from
(
select SentDate AS 'ReceiptDate',
count('TotalMailed') AS TotalMailed,
0 as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract
where sentdate is not null
GROUP BY SentDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
count(TotalReturnMail) as TotalReturnMail,
0 as TraceReturnedMail
from MailDataExtract MDE
where MDE.ReturnMailDate is not null
GROUP BY MDE.ReturnMailDate
UNION ALL
select MDE.ReturnMailDate AS 'ReceiptDate',
0 AS TotalMailed,
0 as TotalReturnMail,
count(TraceReturnedMail) as TraceReturnedMail
from MailDataExtract MDE
inner join DTSharedData.dbo.ScanData SD
ON SD.ScanDataID = MDE.ReturnScanDataID
where MDE.ReturnMailDate is not null AND SD.ReturnMailTypeID = 1
GROUP BY MDE.ReturnMailDate
) as Detail
GROUP BY Detail.ReceiptDate
ORDER BY 1
You can use trim function from php to trim both sides (left and right)
trim($yourinputdata," ");
Or
trim($yourinputdata);
You can also use
ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string
System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php
I had similar problem. My header file which included the definition of the class wasn't working. I wasn't able to use the member functions of that class. So i simply copied my class to another header file. Now its working all ok.
Trivial (but working) solution:
echo -e "---------------------------- [UP]\r$PROC_NAME "
Credit should go here: how to detect if a link was clicked when window.onbeforeunload is triggered?
Basically, the solution adds a listener to detect if a link or window caused the unload event to fire.
var link_was_clicked = false;
document.addEventListener("click", function(e) {
if (e.target.nodeName.toLowerCase() === 'a') {
link_was_clicked = true;
}
}, true);
window.onbeforeunload = function(e) {
if(link_was_clicked) {
return;
}
return confirm('Are you sure?');
}
I can't find a way to do this with code, but in stock Firefox 64, events are listed next to each HTML entity in the Developer Tools Inspector as noted on MDN's Examine Event Listeners page and as demonstrated in this image:
Swift 4.1 and 5. We use queues in many places in our code. So, I created Threads class with all queues. If you don't want to use Threads class you can copy the desired queue code from class methods.
class Threads {
static let concurrentQueue = DispatchQueue(label: "AppNameConcurrentQueue", attributes: .concurrent)
static let serialQueue = DispatchQueue(label: "AppNameSerialQueue")
// Main Queue
class func performTaskInMainQueue(task: @escaping ()->()) {
DispatchQueue.main.async {
task()
}
}
// Background Queue
class func performTaskInBackground(task:@escaping () throws -> ()) {
DispatchQueue.global(qos: .background).async {
do {
try task()
} catch let error as NSError {
print("error in background thread:\(error.localizedDescription)")
}
}
}
// Concurrent Queue
class func perfromTaskInConcurrentQueue(task:@escaping () throws -> ()) {
concurrentQueue.async {
do {
try task()
} catch let error as NSError {
print("error in Concurrent Queue:\(error.localizedDescription)")
}
}
}
// Serial Queue
class func perfromTaskInSerialQueue(task:@escaping () throws -> ()) {
serialQueue.async {
do {
try task()
} catch let error as NSError {
print("error in Serial Queue:\(error.localizedDescription)")
}
}
}
// Perform task afterDelay
class func performTaskAfterDealy(_ timeInteval: TimeInterval, _ task:@escaping () -> ()) {
DispatchQueue.main.asyncAfter(deadline: (.now() + timeInteval)) {
task()
}
}
}
Example showing the use of main queue.
override func viewDidLoad() {
super.viewDidLoad()
Threads.performTaskInMainQueue {
//Update UI
}
}
Use inputstream once don't use it multiple times and Do inputstream.close()
You can use VBA to export an Access database table as a Worksheet in an Excel Workbook.
To obtain the path of the Access database, use the CurrentProject.Path
property.
To name the Excel Workbook file with the current date, use the Format(Date, "yyyyMMdd")
method.
Finally, to export the table as a Worksheet, use the DoCmd.TransferSpreadsheet
method.
Example:
Dim outputFileName As String
outputFileName = CurrentProject.Path & "\Export_" & Format(Date, "yyyyMMdd") & ".xls"
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table1", outputFileName , True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, "Table2", outputFileName , True
This will output both Table1 and Table2 into the same Workbook.
HTH
set the value first. then set the focus. when it focuses, it will use the value that exists at the time of focus, so your value must be set first.
this logic works for me with an application that populates an <input>
with the value of a clicked <button>
. val()
is set first. then focus()
$('button').on('click','',function(){
var value = $(this).attr('value');
$('input[name=item1]').val(value);
$('input[name=item1]').focus();
});
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
From your question I guess you are using Ubuntu (or a derivate). If you use:
apt-file search opencv.pc
then you see that you have to install libopencv-dev
.
After you do so, pkg-config --cflags opencv
and pkg-config --libs opencv
should work as expected.
Yes, the result is always truncated towards zero. It will round towards the smallest absolute value.
-5 / 2 = -2
5 / 2 = 2
For unsigned and non-negative signed values, this is the same as floor (rounding towards -Infinity).
As per dart 2.6
The optional onError
parameter of int.parse
is deprecated. Therefore, you should use int.tryParse
instead.
Note:
The same applies to double.parse
. Therefore, use double.tryParse
instead.
/**
* ...
*
* The [onError] parameter is deprecated and will be removed.
* Instead of `int.parse(string, onError: (string) => ...)`,
* you should use `int.tryParse(string) ?? (...)`.
*
* ...
*/
external static int parse(String source, {int radix, @deprecated int onError(String source)});
The difference is that int.tryParse
returns null
if the source string is invalid.
/**
* Parse [source] as a, possibly signed, integer literal and return its value.
*
* Like [parse] except that this function returns `null` where a
* similar call to [parse] would throw a [FormatException],
* and the [source] must still not be `null`.
*/
external static int tryParse(String source, {int radix});
So, in your case it should look like:
// Valid source value
int parsedValue1 = int.tryParse('12345');
print(parsedValue1); // 12345
// Error handling
int parsedValue2 = int.tryParse('');
if (parsedValue2 == null) {
print(parsedValue2); // null
//
// handle the error here ...
//
}
Difference in output of map and flatMap:
1.flatMap
val a = sc.parallelize(1 to 10, 5)
a.flatMap(1 to _).collect()
Output:
1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2.map
:
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length).collect()
Output:
3 6 6 3 8
git checkout -b <branch-name> <sha1-of-commit>
According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO
option or a certificate directory can be specified with the CURLOPT_CAPATH
option.
Also look at CURLOPT_SSL_VERIFYHOST:
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
You could read line by line so you don't have to read the entire all at once (probably at all)
int i=0
while(!stream.eof() && i!=lineNum)
stream.readLine()
i++
line = stream.readLine()
If your compiler doesn't support strongly typed enums yet, you can give a look to the following article from the c++ source:
From the abstract:
This article presents a solution to the problem of constraining bit operations to
allow only safe and legitimate ones, and turn all invalid bit manipulations into compile-time errors. Best of all, the syntax of bit operations remains unchanged, and the code working with bits does not need to be modified, except possibly to fix errors that had as yet remained undetected.
This code works for me perfectly:
String numbers = text.substring(Math.max(0, text.length() - 7));
VAL1 and VAL2 need to be dimmed as integer, not as string, to be used as an argument for Cells, which takes integers, not strings, as arguments.
Dim val1 As Integer, val2 As Integer, i As Integer
For i = 1 To 333
Sheets("Feuil2").Activate
ActiveSheet.Cells(i, 1).Select
val1 = Cells(i, 1).Value
val2 = Cells(i, 2).Value
Sheets("Classeur2.csv").Select
Cells(val1, val2).Select
ActiveCell.FormulaR1C1 = "1"
Next i
I think the correct access method is using the index:
df_2.loc[:,'D'] = df_2['B']
here is a quick implement, i used it to get a 'Matrix'(sruct) from a string. you can have a bigger array and change its values on the run also:
typedef struct { int** lines; int isDefined; }mat;
mat matA, matB, matC, matD, matE, matF;
/* an auxilary struct to be used in a dictionary */
typedef struct { char* str; mat *matrix; }stringToMat;
/* creating a 'dictionary' for a mat name to its mat. lower case only! */
stringToMat matCases [] =
{
{ "mat_a", &matA },
{ "mat_b", &matB },
{ "mat_c", &matC },
{ "mat_d", &matD },
{ "mat_e", &matE },
{ "mat_f", &matF },
};
mat* getMat(char * str)
{
stringToMat* pCase;
mat * selected = NULL;
if (str != NULL)
{
/* runing on the dictionary to get the mat selected */
for(pCase = matCases; pCase != matCases + sizeof(matCases) / sizeof(matCases[0]); pCase++ )
{
if(!strcmp( pCase->str, str))
selected = (pCase->matrix);
}
if (selected == NULL)
printf("%s is not a valid matrix name\n", str);
}
else
printf("expected matrix name, got NULL\n");
return selected;
}
You can execute any shell command using the shelljs module
const shell = require('shelljs')
shell.exec('./path_to_your_file')
vi /usr/local/etc/redis.conf
Look for dir, logfile
# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/
# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null
logfile "redis_log"
So the log file is created at /usr/local/var/db/redis/redis_log
with the name redis_log
You can also try MONITOR
command from redis-cli
to review the number of commands executed.
Manually:
libs
folder in your project(Where build.gradle
is located). E.g. applibs
implementation files('libs/<name>.jar')
into build.gradle
. It is the same as UI Add as library
doI believe you are looking for setInterval()
For those like @sha1 wondering why the OP's code doesn't work -
OP's logic for deleting player at server side is in the handler for DelPlayer
event,
and the code that emits this event (DelPlayer
) is in inside disconnected
event callback of client.
The server side code that emits this disconnected
event is inside the disconnect
event callback which is fired when the socket loses connection. Since the socket already lost connection, disconnected
event doesn't reach the client.
Accepted solution executes the logic on disconnect
event at server side, which is fired when the socket disconnects, hence works.
If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue
: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)
ObjectMapper mapper = new ObjectMapper();
JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
JsonNode tree = jsonParser.readValueAsTree();
// Do stuff to the tree
mapper.readValue(tree, Foo.class);
I don't believe there's any way to get a cell's color from a formula. The closest you can get is the CELL
formula, but (at least as of Excel 2003), it doesn't return the cell's color.
It would be pretty easy to implement with VBA:
Public Function myColor(r As Range) As Integer
myColor = r.Interior.ColorIndex
End Function
Then in the worksheet:
=mycolor(A1)
Assuming a Windows installation, do please refer to this:
http://www.oracle-base.com/articles/misc/ManualOracleUninstall.php
- Uninstall all Oracle components using the Oracle Universal Installer (OUI).
- Run regedit.exe and delete the HKEY_LOCAL_MACHINE\SOFTWARE\ORACLE key. This contains registry entires for all Oracle products.
- Delete any references to Oracle services left behind in the following part of the registry:
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Ora*
It should be pretty obvious which ones relate to Oracle.- Reboot your machine.
- Delete the "C:\Oracle" directory, or whatever directory is your ORACLE_BASE.
- Delete the "C:\Program Files\Oracle" directory.
- Empty the contents of your "C:\temp" directory.
- Empty your recycle bin.
Calling additional attention to some great comments that were left here:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\ORACLE
key from the registry.%ORACLE_HOME%
.%PATH%
.This set of instructions happens to match an almost identical process that I had reverse-engineered myself over the years after a few messed-up Oracle installs, and has almost always met the need.
Note that even if the OUI is no longer available or doesn't work, simply following the remaining steps should still be sufficient.
(Revision #7 reverted as to not misquote the original source, and to not remove credit to the other comments that contributed to the answer. Further edits are appreciated (and then please remove this comment), if a way can be found to maintain these considerations.)
The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).
Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:
When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:
Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)
(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)
#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT
From the n3242.pdf file (I expect the final standard text to be similar):
17.6.3.3.2 Global names [global.names]
Certain sets of names and function signatures are always reserved to the implementation:
— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.
— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.
But also:
17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]
Literal suffix identifiers that do not start with an underscore are reserved for future standardization.
This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...
Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar
If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.
There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.
text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
^^^^^^^^^^^^^^^^^
def depositCallBack(self,event):
text.set('change the value')
Technically, you can't return more than one value. However, there are multiple ways to work around that limitation. The way that acts most like returning multiple values, is with the list
keyword:
function getXYZ()
{
return array(4,5,6);
}
list($x,$y,$z) = getXYZ();
// Afterwards: $x == 4 && $y == 5 && $z == 6
// (This will hold for all samples unless otherwise noted)
Technically, you're returning an array and using list
to store the elements of that array in different values instead of storing the actual array. Using this technique will make it feel most like returning multiple values.
The list
solution is a rather php-specific one. There are a few languages with similar structures, but more languages that don't. There's another way that's commonly used to "return" multiple values and it's available in just about every language (in one way or another). However, this method will look quite different so may need some getting used to.
// note that I named the arguments $a, $b and $c to show that
// they don't need to be named $x, $y and $z
function getXYZ(&$a, &$b, &$c)
{
$a = 4;
$b = 5;
$c = 6;
}
getXYZ($x, $y, $z);
This technique is also used in some functions defined by php itself (e.g. $count
in str_replace, $matches
in preg_match). This might feel quite different from returning multiple values, but it is worth at least knowing about.
A third method is to use an object to hold the different values you need. This is more typing, so it's not used quite as often as the two methods above. It may make sense to use this, though, when using the same set of variables in a number of places (or of course, working in a language that doesn't support the above methods or allows you to do this without extra typing).
class MyXYZ
{
public $x;
public $y;
public $z;
}
function getXYZ()
{
$out = new MyXYZ();
$out->x = 4;
$out->y = 5;
$out->z = 6;
return $out;
}
$xyz = getXYZ();
$x = $xyz->x;
$y = $xyz->y;
$z = $xyz->z;
The above methods sum up the main ways of returning multiple values from a function. However, there are variations on these methods. The most interesting variations to look at, are those in which you are actually returning an array, simply because there's so much you can do with arrays in PHP.
First, we can simply return an array and not treat it as anything but an array:
function getXYZ()
{
return array(1,2,3);
}
$array = getXYZ();
$x = $array[0];
$y = $array[1];
$z = $array[2];
The most interesting part about the code above is that the code inside the function is the same as in the very first example I provided; only the code calling the function changed. This means that it's up to the one calling the function how to treat the result the function returns.
Alternatively, one could use an associative array:
function getXYZ()
{
return array('x' => 4,
'y' => 5,
'z' => 6);
}
$array = getXYZ();
$x = $array['x'];
$y = $array['y'];
$z = $array['z'];
Php does have the compact
function that allows you to do same as above but while writing less code. (Well, the sample won't have less code, but a real world application probably would.) However, I think the amount of typing saving is minimal and it makes the code harder to read, so I wouldn't do it myself. Nevertheless, here's a sample:
function getXYZ()
{
$x = 4;
$y = 5;
$z = 6;
return compact('x', 'y', 'z');
}
$array = getXYZ();
$x = $array['x'];
$y = $array['y'];
$z = $array['z'];
It should be noted that while compact
does have a counterpart in extract
that could be used in the calling code here, but since it's a bad idea to use it (especially for something as simple as this) I won't even give a sample for it. The problem is that it will do "magic" and create variables for you, while you can't see which variables are created without going to other parts of the code.
Finally, I would like to mention that list
doesn't really play well with associative array. The following will do what you expect:
function getXYZ()
{
return array('x' => 4,
'y' => 5,
'z' => 6);
}
$array = getXYZ();
list($x, $y, $z) = getXYZ();
However, the following will do something different:
function getXYZ()
{
return array('x' => 4,
'z' => 6,
'y' => 5);
}
$array = getXYZ();
list($x, $y, $z) = getXYZ();
// Pay attention: $y == 6 && $z == 5
If you used list
with an associative array, and someone else has to change the code in the called function in the future (which may happen just about any situation) it may suddenly break, so I would recommend against combining list
with associative arrays.
C++17 (N4659
) includes a proposal Refining Expression Evaluation Order for Idiomatic C++
which defines a stricter order of expression evaluation.
In particular, the following sentence
8.18 Assignment and compound assignment operators:
....In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.
together with the following clarification
An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.
make several cases of previously undefined behavior valid, including the one in question:
a[++i] = i;
However several other similar cases still lead to undefined behavior.
In N4140
:
i = i++ + 1; // the behavior is undefined
But in N4659
i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined
Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.
This worked for me.
I created a folder then changed into the folder using CD option from command prompt.
Then executed the jar from there.
d:\LS\afterchange>jar xvf ..\mywar.war
profile name is not valid [SQLSTATE 42000] (Error 14607)
This happened to me after I copied job script from old SQL server to new SQL server. In SSMS, under Management, the Database Mail profile name was different in the new SQL Server. All I had to do was update the name in job script.
According to http://khason.net/blog/how-to-use-systemdrawingbitmap-hbitmap-in-wpf/
[DllImport("gdi32")]
static extern int DeleteObject(IntPtr o);
public static BitmapSource loadBitmap(System.Drawing.Bitmap source)
{
IntPtr ip = source.GetHbitmap();
BitmapSource bs = null;
try
{
bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip,
IntPtr.Zero, Int32Rect.Empty,
System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
}
finally
{
DeleteObject(ip);
}
return bs;
}
It gets System.Drawing.Bitmap (from WindowsBased) and converts it into BitmapSource, which can be actually used as image source for your Image control in WPF.
image1.Source = YourUtilClass.loadBitmap(SomeBitmap);
Follow it...
<form action="index.php" method="POST">
<input type="number" name="array[]" value="1">
<input type="number" name="array[]" value="2">
<input type="number" name="array[]" value="3"> <!--taking array input by input name array[]-->
<input type="number" name="array[]" value="4">
<input type="submit" name="submit">
</form>
<?php
$a=$_POST['array'];
echo "Input :" .$a[3]; // Displaying Selected array Value
foreach ($a as $v) {
print_r($v); //print all array element.
}
?>
The problem with taking IEnumerable
as a parameter is that it tells callers "I wish to enumerate this". It doesn't tell them how many times you wish to enumerate.
I can change the objects parameter to be List and then avoid the possible multiple enumeration but then I don't get the highest object that I can handle.
The goal of taking the highest object is noble, but it leaves room for too many assumptions. Do you really want someone to pass a LINQ to SQL query to this method, only for you to enumerate it twice (getting potentially different results each time?)
The semantic missing here is that a caller, who perhaps doesn't take time to read the details of the method, may assume you only iterate once - so they pass you an expensive object. Your method signature doesn't indicate either way.
By changing the method signature to IList
/ICollection
, you will at least make it clearer to the caller what your expectations are, and they can avoid costly mistakes.
Otherwise, most developers looking at the method might assume you only iterate once. If taking an IEnumerable
is so important, you should consider doing the .ToList()
at the start of the method.
It's a shame .NET doesn't have an interface that is IEnumerable + Count + Indexer, without Add/Remove etc. methods, which is what I suspect would solve this problem.
You can use the ImageLocation
property of pictureBox1
:
pictureBox1.ImageLocation = @"C:\Users\MSI\Desktop\MYAPP\Slider\Slider\bt1.jpg";
An alternate way of accomplishing this could be to make use of chars()
introduced with Java 9, this can be used to iterate over the characters making sure any char which maps to a surrogate code point is passed through uninterpreted. This can be used as:-
String myString = "\u0048\u0065\u006C\u006C\u006F World";
myString.chars().forEach(a -> System.out.print((char)a));
// would print "Hello World"
If the component name is explained in the file name MyComponent.js
, just don't name the component, keeps code slim.
import React from 'react'
export default (props) =>
<div id='static-page-template'>
{props.children}
</div>
Update: Since this labels it as unknown in stack tracing, it isn't recommended
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[@name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
You cannot delete a variable if you declared it (with var x;
) at the time of first use.
However, if your variable x
first appeared in the script without a declaration, then you can use the delete
operator (delete x;
) and your variable will be deleted, very similar to deleting an element of an array or deleting a property of an object.
You'll have to find the index of the person
in your persons
array, then use the array's splice
method:
$scope.persons.splice( $scope.persons.indexOf(person), 1 );
I suggest checking if the substring is a digit:
In [1]: [int(i) for i in '1 2 3a'.split() if i.isdigit()]
Out[1]: [1, 2]
Maybe decorator based? You can pass as decorator arguments list of exceptions on which we want to retry and/or number of tries.
def retry(exceptions=None, tries=None):
if exceptions:
exceptions = tuple(exceptions)
def wrapper(fun):
def retry_calls(*args, **kwargs):
if tries:
for _ in xrange(tries):
try:
fun(*args, **kwargs)
except exceptions:
pass
else:
break
else:
while True:
try:
fun(*args, **kwargs)
except exceptions:
pass
else:
break
return retry_calls
return wrapper
from random import randint
@retry([NameError, ValueError])
def foo():
if randint(0, 1):
raise NameError('FAIL!')
print 'Success'
@retry([ValueError], 2)
def bar():
if randint(0, 1):
raise ValueError('FAIL!')
print 'Success'
@retry([ValueError], 2)
def baz():
while True:
raise ValueError('FAIL!')
foo()
bar()
baz()
of course the 'try' part should be moved to another funcion becouse we using it in both loops but it's just example;)
I believe that the assumption that the graph is connected can be handful. thus, you can use the proof shown above, that the running time is O(|V|). if not, then |E|>|V|. reminder: the running time of DFS is O(|V|+|E|).
Setting the following git setting fixed this for me
git config --global --add http.sslVersion tlsv1.0
I'm guessing the corporate proxy server did not like the default encryption protocol.
You can simply use the method change
of JQuery to get the value of the current radio checked with the following code:
$(document).on('change', '[type="radio"]', function() {
var currentlyValue = $(this).val(); // Get the radio checked value
alert('Currently value: '+currentlyValue); // Show a alert with the current value
});
You can change the selector '[type="radio"]'
for a class or id that you want.
I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)
For example:
$('.btnName').click(function() {
top.$('#panel').toggle(function() {
$(this).animate({
// style change
}, 500);
},
function() {
$(this).animate({
// style change back
}, 500);
});