I have a UITableViewCell which has a text wrap label. I worked text wrapping as follows.
1) Set UILabel constraints as follows.
2) Set no. of lines to 0.
3) Added UILabel height constraint to UITableViewCell.
@IBOutlet weak var priorityLabelWidth: NSLayoutConstraint!
4) On UITableViewCell:
priorityLabel.sizeToFit()
priorityLabelWidth.constant = priorityLabel.intrinsicContentSize().width+5
There are two ways to go about this. You can either use the IDE to generate a WSDL, or you can do it via the command line.
1. To create it via the IDE:
In the solution explorer pane, right click on the project that you would like to add the Service to:
Then, you can enter the path to your service WSDL and hit go:
2. To create it via the command line:
Open a VS 2010 Command Prompt (Programs -> Visual Studio 2010 -> Visual Studio Tools)
Then execute:
WSDL /verbose C:\path\to\wsdl
WSDL.exe will then output a .cs file for your consumption.
If you have other dependencies that you received with the file, such as xsd's, add those to the argument list:
WSDL /verbose C:\path\to\wsdl C:\path\to\some\xsd C:\path\to\some\xsd
If you need VB output, use /language:VB
in addition to the /verbose
.
Pass an argument to round containing the number of decimal places to round to
>> 2.3465.round
=> 2
>> 2.3465.round(2)
=> 2.35
>> 2.3465.round(3)
=> 2.347
Yes, for scalar values, a combination of implode and array_slice will do:
$bar = implode(array_slice($array, 0, 1));
$bin = implode(array_slice($array, 1, 1));
$ipsum = implode(array_slice($array, 2, 1));
Or mix it up with array_values
and list
(thanks @nikic) so that it works with all types of values:
list($bar) = array_values(array_slice($array, 0, 1));
for Mac users, install the Intel HAXM kernel extension to allow the emulator to make use of CPU virtualization extensions.
The steps to configure VM acceleration are as follows:
sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_version.dmg.
kextstat | grep intel
You should see a status message containing the following extension name, indicating that the kernel extension is loaded:com.intel.kext.intelhaxm
Reference:
https://developer.android.com/studio/run/emulator-acceleration.html#vm-mac
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:
class Engine
def start
#code goes here
end
alias run start
end
If you need to extend your code, use the ruby meta alternative.
class Engine
def start
puts "start me"
end
end
Engine.new.start() # => start me
Engine.class_eval do
unless method_defined?(:run)
alias_method :run, :start
define_method(:start) do
puts "'before' extension"
run()
puts "'after' extension"
end
end
end
Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension
Engine.new.run # => start me
It is possible to make a link fill the entire div which gives the appearance of making the div clickable.
CSS:
#my-div {
background-color: #f00;
width: 200px;
height: 200px;
}
a.fill-div {
display: block;
height: 100%;
width: 100%;
text-decoration: none;
}
HTML:
<div id="my-div">
<a href="#" class="fill-div"></a>
</div>
You can do it by using simple one line JavaScript code and also be careful that if JavaScript is turned off it will not work. The below code will do it's job if JavaScript is turned off.
Turn off JavaScript and run the code on you own file to know it's full function.(If you turn off JavaScript here, the below Code Snippet will not work)
.noscript-error {_x000D_
color: red;_x000D_
}
_x000D_
<body onload="document.getElementById('payment-form').submit();">_x000D_
_x000D_
<div align="center">_x000D_
<h1>_x000D_
Please Waite... You Will be Redirected Shortly<br/>_x000D_
Don't Refresh or Press Back _x000D_
</h1>_x000D_
</div>_x000D_
_x000D_
<form method='post' action='acction.php' id='payment-form'>_x000D_
<input type='hidden' name='field-name' value='field-value'>_x000D_
<input type='hidden' name='field-name2' value='field-value2'>_x000D_
<noscript>_x000D_
<div align="center" class="noscript-error">Sorry, your browser does not support JavaScript!._x000D_
<br>Kindly submit it manually_x000D_
<input type='submit' value='Submit Now' />_x000D_
</div>_x000D_
</noscript>_x000D_
</form>_x000D_
_x000D_
</body>
_x000D_
The right way is:
db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})
$elemMatch
allows you to match more than one component within the same array element.
Without $elemMatch
mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.
See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.
For latest Windows 10 (HP & Intel motherboard/processor),
Follow the below steps, starting with :
Settings ->
Update & Security ->
Recovery ->
Advanced startUp -> Restart now
F10 (System Recovery) -> System Configuration tab -> Virtualization Technology
Enable
F10 to save and exit
Your working tree is what is actually in the files that you are currently working on.
HEAD
is a pointer to the branch or commit that you last checked out, and which will be the parent of a new commit if you make it. For instance, if you're on the master
branch, then HEAD
will point to master
, and when you commit, that new commit will be a descendent of the revision that master
pointed to, and master
will be updated to point to the new commit.
The index is a staging area where the new commit is prepared. Essentially, the contents of the index are what will go into the new commit (though if you do git commit -a
, this will automatically add all changes to files that Git knows about to the index before committing, so it will commit the current contents of your working tree). git add
will add or update files from the working tree into your index.
If you need to convert a string float to an int you can use this method.
Example: '38.0'
to 38
In order to convert this to an int you can cast it as a float then an int. This will also work for float strings or integer strings.
>>> int(float('38.0'))
38
>>> int(float('38'))
38
Note: This will strip any numbers after the decimal.
>>> int(float('38.2'))
38
Probably the best way is this one here.
fileprivate func NSLocalizedString(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
and
import Foundation
extension String {
static let Hello = NSLocalizedString("Hello")
static let ThisApplicationIsCreated = NSLocalizedString("This application is created by the swifting.io team")
static let OpsNoFeature = NSLocalizedString("Ops! It looks like this feature haven't been implemented yet :(!")
}
you can then use it like this
let message: String = .ThisApplicationIsCreated
print(message)
to me this is the best because
Yes, this can be done with the UIWebView.
If you are trying to display a PDF file residing on a server somewhere, you can simply load it in your web view directly:
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [NSURL URLWithString:@"https://www.example.com/document.pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSURL(string: "https://www.example.com/document.pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
Or if you have a PDF file bundled with your application (in this example named "document.pdf"):
Objective-C
UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(10, 10, 200, 200)];
NSURL *targetURL = [[NSBundle mainBundle] URLForResource:@"document" withExtension:@"pdf"];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[webView loadRequest:request];
[self.view addSubview:webView];
Swift
let webView = UIWebView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
let targetURL = NSBundle.mainBundle().URLForResource("document", withExtension: "pdf")! // This value is force-unwrapped for the sake of a compact example, do not do this in your code
let request = NSURLRequest(URL: targetURL)
webView.loadRequest(request)
view.addSubview(webView)
You can find more information here: Technical QA1630: Using UIWebView to display select document types.
I too had this problem. My solution was:
sc.setSoLinger(true, 10);
COPY FROM A WEBSITE -->By using the setSoLinger()
method, you can explicitly set a delay before a reset is sent, giving more time for data to be read or send.
Maybe it is not the answer to everybody but to some people.
You can use 'th:if' together with 'th:text'
<span th:if="${someObject.someProperty != null}" th:text="${someObject.someProperty}">someValue</span>
>>> A = {'a':1, 'b':2, 'c':3}
>>> B = {'b':3, 'c':4, 'd':5}
>>> c = {x: A.get(x, 0) + B.get(x, 0) for x in set(A).union(B)}
>>> print(c)
{'a': 1, 'c': 7, 'b': 5, 'd': 5}
Even better!
long tStart = System.nanoTime();
long tEnd = System.nanoTime();
long tRes = tEnd - tStart; // time in nanoseconds
Read the documentation about nanoTime()!
Use TcpView to see ports listening and connections. This will not give you the requests though.
In order to see requests, you need reverse of a proxy which I do not know of any such tools.
Use tracing to give you parts of the requests (first 1KB of the request).
For Linux: Simple you can run below commands:
1) git config -l
2) git config --global http.postBuffer 524288000
Or set double value 1048576000
3) git config --global https.postBuffer
4) git config --global core.compression -1
5) service apache2 restart
Then again check the config of git
git config -l
now you can run clone command
git clone yourrepo
I hope this will be solved the issue.
Just wrap all that inside a ScrollView
:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- Here you put the rest of your current view-->
</ScrollView>
As David Hedlund said, ScrollView
can contain just one item... so if you had something like this:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- bla bla bla-->
</LinearLayout>
You must change it to:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<!-- bla bla bla-->
</LinearLayout>
</ScrollView>
A covering index is one which can satisfy all requested columns in a query without performing a further lookup into the clustered index.
There is no such thing as a covering query.
Have a look at this Simple-Talk article: Using Covering Indexes to Improve Query Performance.
A transient
variable is a variable that may not be serialized.
One example of when this might be useful that comes to mind is, variables that make only sense in the context of a specific object instance and which become invalid once you have serialized and deserialized the object. In that case it is useful to have those variables become null
instead so that you can re-initialize them with useful data when needed.
To be clear there are 4 types of caches you can clear depending upon your case.
php artisan cache:clear
You can run the above statement in your console when you wish to clear the application cache. What it does is that this statement clears all caches inside storage\framework\cache.
php artisan route:cache
This clears your route cache. So if you have added a new route or have changed a route controller or action you can use this one to reload the same.
php artisan config:cache
This will clear the caching of the env file and reload it
php artisan view:clear
This will clear the compiled view files of your application.
Most of the shared hosting providers don't provide SSH access to the systems. In such a case you will need to create a route and call the following line as below:
Route::get('/clear-cache', function() {
Artisan::call('cache:clear');
return "All cache cleared";
});
In your own (base) class, willSet
and didSet
are quite reduntant , as you could instead define a calculated property (i.e get- and set- methods) that access a _propertyVariable
and does the desired pre- and post- prosessing.
If, however, you override a class where the property is already defined, then the willSet
and didSet
are useful and not redundant!
VAR=$VAR"$VARTOADD(STRING)"
echo $VAR
Use FROM_UNIXTIME()
:
SELECT
FROM_UNIXTIME(timestamp)
FROM
your_table;
See also: MySQL documentation on FROM_UNIXTIME()
.
I was struggling with the same problem and found one solution. I guess it can help you. when you run python manage.py runserver, it will take 127.0.0.1 as default ip address and 8000. 127.0.0.0 is the same as localhost which can be accessed locally. to access it from cross origin you need to run it on your system ip or 0.0.0.0. 0.0.0.0 can be accessed from any origin in the network. for port number, you need to set inbound and outbound policy of your system if you want to use your own port number not the default one.
To do this you need to run server with command python manage.py runserver 0.0.0.0:<your port>
as mentioned above
or, set a default ip and port in your python environment. For this see my answer on django change default runserver port
Enjoy coding .....
This is taken from Romain Guy's presentation at Devoxx, pdf found here.
Paint mShadow = new Paint();
// radius=10, y-offset=2, color=black
mShadow.setShadowLayer(10.0f, 0.0f, 2.0f, 0xFF000000);
// in onDraw(Canvas)
canvas.drawBitmap(bitmap, 0.0f, 0.0f, mShadow);
Hope this helps.
NOTES
In views with {{}}
and/or ng-model, Angular is setting up $watch()
es for you behind the scenes.
By default $watch
compares by reference. If you set the third parameter to $watch
to true
, Angular will instead "shallow" watch the object for changes. For arrays this means comparing the array items, for object maps this means watching the properties. So this should do what you want:
$scope.$watch('myModel', function() { ... }, true);
Update: Angular v1.2 added a new method for this, `$watchCollection():
$scope.$watchCollection('myModel', function() { ... });
Note that the word "shallow" is used to describe the comparison rather than "deep" because references are not followed -- e.g., if the watched object contains a property value that is a reference to another object, that reference is not followed to compare the other object.
Look you can do it using StringTokenizer
String str = "as:"+123+"as:"+234+"as:"+345;
StringTokenizer st = new StringTokenizer(str,"as:");
while(st.hasMoreTokens())
{
String k = st.nextToken(); // you will get first numeric data i.e 123
int kk = Integer.parseInt(k);
System.out.println("k string token in integer " + kk);
String k1 = st.nextToken(); // you will get second numeric data i.e 234
int kk1 = Integer.parseInt(k1);
System.out.println("new string k1 token in integer :" + kk1);
String k2 = st.nextToken(); // you will get third numeric data i.e 345
int kk2 = Integer.parseInt(k2);
System.out.println("k2 string token is in integer : " + kk2);
}
Since we are taking these numeric data into three different variables we can use this data anywhere in the code (for further use)
You only need to parse String values using Double
String someValue= "52.23";
Double doubleVal = Double.parseDouble(someValue);
System.out.println(doubleVal);
Object.create()
is a Javascript function which takes 2 arguments and returns a new object. const proto = {_x000D_
talk : () => console.log('hi')_x000D_
}_x000D_
_x000D_
const props = {_x000D_
age: {_x000D_
writable: true,_x000D_
configurable: true,_x000D_
value: 26_x000D_
}_x000D_
}_x000D_
_x000D_
_x000D_
let Person = Object.create(proto, props)_x000D_
_x000D_
console.log(Person.age);_x000D_
Person.talk();
_x000D_
new
keyword you have no control over this (however, you can overwrite them of course).new
keyword invokes a constructor function. With Object.create()
there is no need for invoking or even declaring a constructor function.You could use something like the following
scp -r username_Linuxmachine@LinuxMachineAddress:Path/To/File Path/To/Local/System/Directory
This will copy the File
to the specified local directory on the system you are currently working on.
The -r
flag tells scp
to recursively copy if the remote path is indeed a directory.
Well, I didn't like any of those answers, my solution of the same problem was to add this:<div> </div>
. So in your scheme it would look like this (more or less), no style changes were necessary in my case:
-row-fluid-------------------------------------
+-span6----------+ +----span6----------+
| | | +---div---+ |
| content | | | & nbsp; | |
| that | | +---------+ |
| is tall | | +-----div--------+|
| | | |short content ||
| | | +----------------+|
+----------------+ +-------------------+
-----------------------------------------------
The selected answer is correct for iOS 6 and below.
In iOS 7, sizeWithFont:constrainedToSize:lineBreakMode:
has been deprecated. It is now recommended you use boundingRectWithSize:options:attributes:context:
.
CGRect expectedLabelSize = [yourString boundingRectWithSize:sizeOfRect
options:<NSStringDrawingOptions>
attributes:@{
NSFontAttributeName: yourString.font
AnyOtherAttributes: valuesForAttributes
}
context:(NSStringDrawingContext *)];
Note that the return value is a CGRect
not a CGSize
. Hopefully that'll be of some assistance to people using it in iOS 7.
You don't need to create a binding datasource. If you want to apply sorting for all of your columns, here is a more generic solution of mine;
private int _previousIndex;
private bool _sortDirection;
private void gridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
if (e.ColumnIndex == _previousIndex)
_sortDirection ^= true; // toggle direction
gridView.DataSource = SortData(
(List<MainGridViewModel>)gridReview.DataSource, gridReview.Columns[e.ColumnIndex].Name, _sortDirection);
_previousIndex = e.ColumnIndex;
}
public List<MainGridViewModel> SortData(List<MainGridViewModel> list, string column, bool ascending)
{
return ascending ?
list.OrderBy(_ => _.GetType().GetProperty(column).GetValue(_)).ToList() :
list.OrderByDescending(_ => _.GetType().GetProperty(column).GetValue(_)).ToList();
}
Make sure you subscribe your data grid to the event ColumnHeaderMouseClick
. When the user clicks on the column it will sort by descending. If the same column header is clicked again, sorting will be applied by ascending.
Given the specific title of this post, here's my suggestion:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'
The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:
ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo
The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.
Here are three ways to parse strings into integers, from fastest runtime to slowest:
strconv.ParseInt(...)
fasteststrconv.Atoi(...)
still very fastfmt.Sscanf(...)
not terribly fast but most flexibleHere's a benchmark that shows usage and example timing for each function:
package main
import "fmt"
import "strconv"
import "testing"
var num = 123456
var numstr = "123456"
func BenchmarkStrconvParseInt(b *testing.B) {
num64 := int64(num)
for i := 0; i < b.N; i++ {
x, err := strconv.ParseInt(numstr, 10, 64)
if x != num64 || err != nil {
b.Error(err)
}
}
}
func BenchmarkAtoi(b *testing.B) {
for i := 0; i < b.N; i++ {
x, err := strconv.Atoi(numstr)
if x != num || err != nil {
b.Error(err)
}
}
}
func BenchmarkFmtSscan(b *testing.B) {
for i := 0; i < b.N; i++ {
var x int
n, err := fmt.Sscanf(numstr, "%d", &x)
if n != 1 || x != num || err != nil {
b.Error(err)
}
}
}
You can run it by saving as atoi_test.go
and running go test -bench=. atoi_test.go
.
goos: darwin
goarch: amd64
BenchmarkStrconvParseInt-8 100000000 17.1 ns/op
BenchmarkAtoi-8 100000000 19.4 ns/op
BenchmarkFmtSscan-8 2000000 693 ns/op
PASS
ok command-line-arguments 5.797s
The answer seems to be just no.
Although there are many good other answers, they either just hide the uglyness (which I did not ask for) or introduce new problems (edge cases).
That is because is does not exist, since it is bounded to Windows.
Use the standard functions from <stdio.h>
instead, such as getc
The suggested ncurses library is good if you want to write console-based GUIs, but I don't think it is what you want.
There would be two ways to define constants - const
and static final
, with the exact same semantics. Furthermore static final
describes the behaviour better than const
If you don't need typesafe, just bring block to a new separated file and change the extension to .js,.jsx
python 3.2
>>>> from itertools import chain
>>>> eg=sorted(list(set(list(chain(*eg)))), reverse=True)
[7, 6, 5, 4, 3, 2, 1]
##### eg contain 2 list within a list. so if you want to use set() function
you should flatten the list like [1, 2, 3, 4, 4, 5, 6, 7]
>>> res= list(chain(*eg)) # [1, 2, 3, 4, 4, 5, 6, 7]
>>> res1= set(res) # [1, 2, 3, 4, 5, 6, 7]
>>> res1= sorted(res1,reverse=True)
Use jFeed - a jQuery RSS/Atom plugin. According to the docs, it's as simple as:
jQuery.getFeed({
url: 'rss.xml',
success: function(feed) {
alert(feed.title);
}
});
Python actually makes this quite easy.
Something like
for i in range(10):
print '%-12i%-12i' % (10 ** i, 20 ** i)
will have the output
1 1
10 20
100 400
1000 8000
10000 160000
100000 3200000
1000000 64000000
10000000 1280000000
100000000 25600000000
1000000000 512000000000
The % within the string is essentially an escape character and the characters following it tell python what kind of format the data should have. The % outside and after the string is telling python that you intend to use the previous string as the format string and that the following data should be put into the format specified.
In this case I used "%-12i" twice. To break down each part:
'-' (left align)
'12' (how much space to be given to this part of the output)
'i' (we are printing an integer)
From the docs: https://docs.python.org/2/library/stdtypes.html#string-formatting
Sitepoint: Disable back for Javascript
event.stopPropagation()
and event.preventDefault()
do nothing in IE. I had to send return event.keyCode == 11
(I just picked something) instead of just saying "if not = 8, run the event"
to make it work, though. event.returnValue = false
also works.
C99 does, if you have
#include <stdbool.h>
If the compiler does not support C99, you can define it yourself:
// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H
#define false 0
#define true 1
typedef int bool; // or #define bool int
#endif
(but note that this definition changes ABI for bool
type so linking against external libraries which were compiled with properly defined bool
may cause hard-to-diagnose runtime errors).
Your student.h file only forward declares a struct named "Student", it does not define one. This is sufficient if you only refer to it through reference or pointer. However, as soon as you try to use it (including creating one) you will need the full definition of the structure.
In short, move your struct Student { ... }; into the .h file and use the .cpp file for implementation of member functions (which it has none so you don't need a .cpp file).
A referral is sent by an AD server when it doesn't have the information requested itself, but know that another server have the info. It usually appears in trust environment where a DC can refer to a DC in trusted domain.
In your case you are only specifying a domain, relying on automatic lookup of what domain controller to use. I think that you should try to find out what domain controller is used for the query and look if that one really holds the requested information.
If you provide more information on your AD setup, including any trusts/subdomains, global catalogues and the DNS resource records for the domain controllers it will be easier to help you.
If you're running Windows 8/Windows Server 2012 or newer, you can use the Test-NetConnection command in PowerShell.
Ex:
Test-NetConnection -Port 53 -ComputerName LON-DC1
SWIFT 5
if let settingsUrl = URL(string: UIApplication.openSettingsURLString) {
UIApplication.shared.open(settingsUrl)
}
In iOS 8+ you can do the following:
func buttonClicked(sender:UIButton)
{
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString))
}
Swift 4
let settingsUrl = URL(string: UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(settingsUrl)
You forgot braces around the if block, and a semicolon between the statements in the block.
awk '{if($3 != 0) {a = ($3/$4); print $0, a;} else if($3==0) print $0, "-" }' file > out
And in Bash
line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef| grep wowzaDataSync | grep -v grep | awk '{print $2}'`
echo "-------->"${line1}
if [ -z $line1 ] && [ ! -z $vpid ]
then
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Process Is Working Fine"
else
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Prcess Hanging Due To Exception With PID :"${pid}
fi
OR in Bash
line1=`tail -3 /opt/Scripts/wowzaDataSync.log | grep "AmazonHttpClient" | head -1`
vpid=`ps -ef| grep wowzaDataSync | grep -v grep | awk '{print $2}'`
echo "-------->"${line1}
if [ -z $line1 ] || [ ! -z $vpid ]
then
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Process Is Working Fine"
else
echo `date --date "NOW" +%Y-%m-%d` `date --date "NOW" +%H:%M:%S` ::
"Prcess Hanging Due To Exception With PID :"${pid}
fi
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
s3_sync:
bucket: ansible-harshika
file_root: "{{ pathoftsfiles }}"
validate_certs: false
mode: push
key_prefix: "{{ folder }}"
here the variables are being used named as 'pathoftsfiles' and 'folder'. Now the value to this variable can be given by the below command
sudo ansible-playbook multiadd.yml --extra-vars "pathoftsfiles=/opt/lampp/htdocs/video/uploads/tsfiles/$2 folder=nitesh"
Note: Don't use the inverted commas while passing the values to the variable in the shell command
Use:
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
Just to add to Alex Poole's answer, here is how you do the date and time:
TO_DATE('31/DEC/2017 12:59:59', 'dd/mm/yyyy hh24:mi:ss')
Old topic, but never clearly answered. I've been working on similar as well, and found the solution:
The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:
Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
$Name += $_.Name
$Phone += $_."Phone Number"
}
Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)
That's how I achieved it, which is not visible (HORRIBLE SOUND....)
<!-- horrible is your mp3 file name any other supported format.-->
<audio controls autoplay hidden="" src="horrible.mp3" type ="audio/mp3"">your browser does not support Html5</audio>
appendChild
is a pure javascript method where as append
is a jQuery method.
Or with Prototype:
Event.observe(this, 'load', function() { new Ajax.Request(... ) );
Or better, define the function elsewhere rather than inline, then:
Event.observe(this, 'load', functionName );
You don't have to use jQuery or Prototype specifically, but I hope you're using some kind of library. Either library is going to handle the event handling in a more consistent manner than onload, and of course is going to make it much easier to process the Ajax call. If you must use the body onload attribute, then you should just be able to call the same function as referenced in these examples (onload="javascript:functionName();"
).
However, if your database update doesn't depend on the rendering on the page, why wait until it's fully loaded? You could just include a call to the Ajax-calling function at the end of the JavaScript on the page, which should give nearly the same effect.
This one works for me
CREATE Function [dbo].[RemoveNumericCharacters](@Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare @NumRange as varchar(50) = '%[0-9]%'
While PatIndex(@NumRange, @Temp) > 0
Set @Temp = Stuff(@Temp, PatIndex(@NumRange, @Temp), 1, '')
Return @Temp
End
and you can use it like so
SELECT dbo.[RemoveNumericCharacters](Name) FROM TARGET_TABLE
When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.
One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.
Use FirstOrDefault or a foreach loop as already mentioned. Manually fetching an enumerator and calling Current should be avoided. foreach will dispose your enumerator for you if it implements IDisposable. When calling MoveNext and Current you have to dispose it manually (if aplicable).
This article might be helpful with changing fonts.
From the article:
The commands to change font attributes are illustrated by the following example:
\fontencoding{T1}
\fontfamily{garamond}
\fontseries{m}
\fontshape{it}
\fontsize{12}{15}
\selectfont
This series of commands set the current font to medium weight italic garamond 12pt type with 15pt leading in the T1 encoding scheme, and the \selectfont command causes LaTeX to look in its mapping scheme for a metric corresponding to these attributes.
Actually i am getting return value from a another sp into @temp and then it @temp =1 then i want to inc the count of @SelectoneCount by 1 and so on. Please let me know what is the correct syntax.
What's wrong with:
IF @Temp = 1 --Or @Temp = 2 also?
BEGIN
SET @SelectoneCount = @SelectoneCount + 1
END
(Although this does reek of being procedural code - not usually the best way to use SQL)
The curl installed by default in Debian supports HTTPS since a great while back. (a long time ago there were two separate packages, one with and one without SSL but that's not the case anymore)
You can send an OPTIONS request with curl like this:
curl -i -X OPTIONS http://example.org/path
You may also use -v
instead of -i
to see more output.
To send a plain * (instead of the path, see RFC 7231) with the OPTIONS method, you need curl 7.55.0 or later as then you can run a command line like:
curl -i --request-target "*" -X OPTIONS http://example.org
My favorite no-conflict-friendly construct:
jQuery(function($) {
// ...
});
Calling jQuery with a function pointer is a shortcut for $(document).ready(...)
Or as we say in coffeescript:
jQuery ($) ->
# code here
In case someone else stumbles upon this question and wants it here is the SASS mixin I use.
@mixin rotate($deg: 90){
$sDeg: #{$deg}deg;
-webkit-transform: rotate($sDeg);
-moz-transform: rotate($sDeg);
-ms-transform: rotate($sDeg);
-o-transform: rotate($sDeg);
transform: rotate($sDeg);
}
For a correct implementation, you need to change a series of things.
Database (immediately after the connection):
mysql_query("SET NAMES utf8");
// Meta tag HTML (probably it's already set):
meta charset="utf-8"
header php (before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset (for each row):
utf8_unicode_ci
try this:
key=key.replace(/ /g,"_");
that'll do a global find/replace
The psql \o
command was already described by jhwist.
An alternative approach is using the COPY TO
command to write directly to a file on the server. This has the advantage that it's dumped in an easy-to-parse format of your choice -- rather than psql's tabulated format. It's also very easy to import to another table/database using COPY FROM
.
NB! This requires superuser privileges and will write to a file on the server.
Example: COPY (SELECT foo, bar FROM baz) TO '/tmp/query.csv' (format csv, delimiter ';')
Creates a CSV file with ';' as the field separator.
As always, see the documentation for details
You'd want to bind a change()
handler so that the event will fire when the state of a checkbox changes. Then, just deselect all checkboxes apart from the one which triggered the handler:
$('input[type="checkbox"]').on('change', function() {
$('input[type="checkbox"]').not(this).prop('checked', false);
});
As for grouping, if your checkbox "groups" were all siblings:
<div>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<div>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
<div>
<input type="checkbox" />
<input type="checkbox" />
<input type="checkbox" />
</div>
You could do this:
$('input[type="checkbox"]').on('change', function() {
$(this).siblings('input[type="checkbox"]').prop('checked', false);
});
If your checkboxes are grouped by another attribute, such as name
:
<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group1[]" />
<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group2[]" />
<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />
<input type="checkbox" name="group3[]" />
You could do this:
$('input[type="checkbox"]').on('change', function() {
$('input[name="' + this.name + '"]').not(this).prop('checked', false);
});
UFT causing issues with RDz (Eclipse based) after install These suggestions will allow to work around this situation even with the environment variables in place and with corresponding values.
Note: Conflicting application will not be recognized in a java context because it is being excluded from the java support mechanism.
Instructions:
a. Locate the executable filename of the application conflicting with add-in(s) support. Either use the Task Manager or the Microsoft Process Explorer.
b. Open Windows Registry Editor.
c. Navigate to: HKEY_LOCAL_MACHINE\SOFTWARE\Mercury Interactive\JavaAgent\Modules For 32bits applications on Windows x64: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mercury Interactive\JavaAgent\Modules
d. Create a DWORD value with the name of the conflicting software executable filenmae and set the value to 0.
Thats just the directories showing you where PHP was looking for your file. Make sure that cron1.php
exists where you think it does. And make sure you know where dirname(__FILE__)
and $_SERVER['DOCUMENT_ROOT']
are pointing where you'd expect.
This value can be adjusted in your php.ini file.
If you have Oracle 10g, REGEXP_REPLACE is pretty flexible.
Using the following string as a test:
chr(9) || 'Q qwer' || chr(9) || chr(10) ||
chr(13) || 'qwerqwer qwerty' || chr(9) ||
chr(10) || chr(13)
The [[:space:]]
will remove all whitespace, and the ([[:cntrl:]])|(^\t)
regexp will remove non-printing characters and tabs.
select
tester,
regexp_replace(tester, '(^[[:space:]]+)|([[:space:]]+$)',null)
regexp_tester_1,
regexp_replace(tester, '(^[[:cntrl:]^\t]+)|([[:cntrl:]^\t]+$)',null)
regexp_tester_2
from
(
select
chr(9) || 'Q qwer' || chr(9) || chr(10) ||
chr(13) || 'qwerqwer qwerty' || chr(9) ||
chr(10) || chr(13) tester
from
dual
)
Returning:
Qqwerqwerqwerqwerty
"Q qwerqwerqwer qwerty
"Hope this is of some use.
I would include all functions of one case in an include
file, and the others in another include
.
For instance simple.inc
would contain function boofoo() { simple }
and really.inc
would contain function boofoo() { really }
It helps the readability / maintenance of your program, having all functions of the same kind in the same inc
.
Then at the top of your main module
if ($_GET['foolevel'] == 10) {
include "really.inc";
}
else {
include "simple.inc";
}
The docs now have a whole section about this.
Basically, use npm
to install yo
, and run the command yo code
and you'll get a little text-based wizard -- one of whose options will be to create and edit a copy of the default dark scheme.
This Python-script[*] does exactly that:
"""
Show/Modify/Append registry env-vars (ie `PATH`) and notify Windows-applications to pickup changes.
First attempts to show/modify HKEY_LOCAL_MACHINE (all users), and
if not accessible due to admin-rights missing, fails-back
to HKEY_CURRENT_USER.
Write and Delete operations do not proceed to user-tree if all-users succeed.
Syntax:
{prog} : Print all env-vars.
{prog} VARNAME : Print value for VARNAME.
{prog} VARNAME VALUE : Set VALUE for VARNAME.
{prog} +VARNAME VALUE : Append VALUE in VARNAME delimeted with ';' (i.e. used for `PATH`).
{prog} -VARNAME : Delete env-var value.
Note that the current command-window will not be affected,
changes would apply only for new command-windows.
"""
import winreg
import os, sys, win32gui, win32con
def reg_key(tree, path, varname):
return '%s\%s:%s' % (tree, path, varname)
def reg_entry(tree, path, varname, value):
return '%s=%s' % (reg_key(tree, path, varname), value)
def query_value(key, varname):
value, type_id = winreg.QueryValueEx(key, varname)
return value
def yield_all_entries(tree, path, key):
i = 0
while True:
try:
n,v,t = winreg.EnumValue(key, i)
yield reg_entry(tree, path, n, v)
i += 1
except OSError:
break ## Expected, this is how iteration ends.
def notify_windows(action, tree, path, varname, value):
win32gui.SendMessage(win32con.HWND_BROADCAST, win32con.WM_SETTINGCHANGE, 0, 'Environment')
print("---%s %s" % (action, reg_entry(tree, path, varname, value)), file=sys.stderr)
def manage_registry_env_vars(varname=None, value=None):
reg_keys = [
('HKEY_LOCAL_MACHINE', r'SYSTEM\CurrentControlSet\Control\Session Manager\Environment'),
('HKEY_CURRENT_USER', r'Environment'),
]
for (tree_name, path) in reg_keys:
tree = eval('winreg.%s'%tree_name)
try:
with winreg.ConnectRegistry(None, tree) as reg:
with winreg.OpenKey(reg, path, 0, winreg.KEY_ALL_ACCESS) as key:
if not varname:
for regent in yield_all_entries(tree_name, path, key):
print(regent)
else:
if not value:
if varname.startswith('-'):
varname = varname[1:]
value = query_value(key, varname)
winreg.DeleteValue(key, varname)
notify_windows("Deleted", tree_name, path, varname, value)
break ## Don't propagate into user-tree.
else:
value = query_value(key, varname)
print(reg_entry(tree_name, path, varname, value))
else:
if varname.startswith('+'):
varname = varname[1:]
value = query_value(key, varname) + ';' + value
winreg.SetValueEx(key, varname, 0, winreg.REG_EXPAND_SZ, value)
notify_windows("Updated", tree_name, path, varname, value)
break ## Don't propagate into user-tree.
except PermissionError as ex:
print("!!!Cannot access %s due to: %s" %
(reg_key(tree_name, path, varname), ex), file=sys.stderr)
except FileNotFoundError as ex:
print("!!!Cannot find %s due to: %s" %
(reg_key(tree_name, path, varname), ex), file=sys.stderr)
if __name__=='__main__':
args = sys.argv
argc = len(args)
if argc > 3:
print(__doc__.format(prog=args[0]), file=sys.stderr)
sys.exit()
manage_registry_env_vars(*args[1:])
Below are some usage examples, assuming it has been saved in a file called setenv.py
somewhere in your current path.
Note that in these examples i didn't have admin-rights, so the changes affected only my local user's registry tree:
> REM ## Print all env-vars
> setenv.py
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
HKEY_CURRENT_USER\Environment:PATH=...
...
> REM ## Query env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
!!!Cannot find HKEY_CURRENT_USER\Environment:PATH due to: [WinError 2] The system cannot find the file specified
> REM ## Set env-var:
> setenv.py PATH C:\foo
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo
> REM ## Append env-var:
> setenv.py +PATH D:\Bar
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Set HKEY_CURRENT_USER\Environment:PATH=C:\foo;D:\Bar
> REM ## Delete env-var:
> setenv.py -PATH
!!!Cannot access HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment:PATH due to: [WinError 5] Access is denied
---Deleted HKEY_CURRENT_USER\Environment:PATH
[*] Adapted from: http://code.activestate.com/recipes/416087-persistent-environment-variables-on-windows/
The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document
) and will be executed when an event reaches that element having originated on an element matching the selector.
This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id
element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.
The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.
By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id
element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.
Defining useful repr() methods for your classes (so you can see what an object is) and using repr() or "%r" % (...) or "...{0!r}..".format(...) in your debug messages/logs is IMHO a key to efficient debugging.
Also, the debuggers mentioned in other answers will make use of the repr() methods.
Note: This example uses the draft version of the Flexible Box Layout Module. It has been superseded by the incompatible modern specification.
Center the child elements of a div box by using the box-align and box-pack properties together.
Example:
div
{
width:350px;
height:100px;
border:1px solid black;
/* Internet Explorer 10 */
display:-ms-flexbox;
-ms-flex-pack:center;
-ms-flex-align:center;
/* Firefox */
display:-moz-box;
-moz-box-pack:center;
-moz-box-align:center;
/* Safari, Opera, and Chrome */
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
/* W3C */
display:box;
box-pack:center;
box-align:center;
}
It looks like you're writing PHP, in which case you want:
<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>
Notice that the ('us'=>'United', 'ca'=>'canada')
needs to be a parameter to the array function in PHP.
Most programming languages that support associative arrays or dictionaries use arr['key']
to retrieve the item specified by 'key'
For instance:
ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
=> {"us"=>"USA", "ca"=>"Canada"}
ruby-1.9.1-p378 > h['ca']
=> "Canada"
>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'
#
class P
{
static void Main()
{
var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
System.Console.WriteLine(d["ca"]);
}
}
t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables
Best answer is great, short and on point, but I would like to put my pennyworth.
Basically npm start and ng serve can be used interchangeably in Angular projects as long as you do not want the command to do additional stuff. Let me elaborate on this one.
For example you may want to configure your proxy in package.json start script like this: "start": "ng serve --proxy-config proxy.config.json",
Obviously sole use of ng serve will not be enough.
Another instance is when instead of using the defaults you need to use some additional options ad hoc like define the temporary port: ng serve --port 4444
Some parameters are only available to ng serve, others to npm start. Notice that port option works for both, so in that case it is up to your taste, again. :)
If you want to reuse in multiple places:
var maxHeight = function(elems){
return Math.max.apply(null, elems.map(function ()
{
return $(this).height();
}).get());
}
Then you can use:
maxHeight($("some selector"));
const img = '../../img/splash/splash_bg.png';
<ImageBackground source={{ uri: img }} style={styles.backgroundImage} >
</ImageBackground>
This worked for me. Reference to RN docs can be found here.I wrote mine by reading this- https://facebook.github.io/react-native/docs/images.html#background-image-via-nesting
It seems that the most common method of achieving this is to draw a GPolygon with enough points to simulate a circle. The example you referenced uses this method. This page has a good example - look for the function drawCircle in the source code.
I thought I had the same problem but actually I have a slight difference that makes the problem easier to solve. For others looking at this question it's worth checking the format of your input list. In my case the numbers are initially floats not strings as in the question:
a = [['a', 1.2, 4.2], ['b', 70, 0.03], ['x', 5, 0]]
but by processing the list too much before creating the dataframe I lose the types and everything becomes a string.
Creating the data frame via a numpy array
df = pd.DataFrame(np.array(a))
df
Out[5]:
0 1 2
0 a 1.2 4.2
1 b 70 0.03
2 x 5 0
df[1].dtype
Out[7]: dtype('O')
gives the same data frame as in the question, where the entries in columns 1 and 2 are considered as strings. However doing
df = pd.DataFrame(a)
df
Out[10]:
0 1 2
0 a 1.2 4.20
1 b 70.0 0.03
2 x 5.0 0.00
df[1].dtype
Out[11]: dtype('float64')
does actually give a data frame with the columns in the correct format
Math.Round(0.5) returns zero due to floating point rounding errors, so you'll need to add a rounding error amount to the original value to ensure it doesn't round down, eg.
Console.WriteLine(Math.Round(0.5, 0).ToString()); // outputs 0 (!!)
Console.WriteLine(Math.Round(1.5, 0).ToString()); // outputs 2
Console.WriteLine(Math.Round(0.5 + 0.00000001, 0).ToString()); // outputs 1
Console.WriteLine(Math.Round(1.5 + 0.00000001, 0).ToString()); // outputs 2
Console.ReadKey();
You can copy into vim by gnome-terminal's shortcut for paste. Make the file in insert mode and use
Ctrl+Shift+v.
Remember beforehand to
:set paste
to avoid messing with the indentation.
Naive Bayes: Naive Bayes comes under supervising machine learning which used to make classifications of data sets. It is used to predict things based on its prior knowledge and independence assumptions.
They call it naive because it’s assumptions (it assumes that all of the features in the dataset are equally important and independent) are really optimistic and rarely true in most real-world applications.
It is classification algorithm which makes the decision for the unknown data set. It is based on Bayes Theorem which describe the probability of an event based on its prior knowledge.
Below diagram shows how naive Bayes works
Formula to predict NB:
How to use Naive Bayes Algorithm ?
Let's take an example of how N.B woks
Step 1: First we find out Likelihood of table which shows the probability of yes or no in below diagram. Step 2: Find the posterior probability of each class.
Problem: Find out the possibility of whether the player plays in Rainy condition?
P(Yes|Rainy) = P(Rainy|Yes) * P(Yes) / P(Rainy)
P(Rainy|Yes) = 2/9 = 0.222
P(Yes) = 9/14 = 0.64
P(Rainy) = 5/14 = 0.36
Now, P(Yes|Rainy) = 0.222*0.64/0.36 = 0.39 which is lower probability which means chances of the match played is low.
For more reference refer these blog.
Refer GitHub Repository Naive-Bayes-Examples
I've got a handy extension method that uses TryParse, as IsDefined is case-sensitive.
public static bool IsParsable<T>(this string value) where T : struct
{
return Enum.TryParse<T>(value, true, out _);
}
If someone is looking for the simplest way without collections
module. I guess this will be helpful:
>>> s = "asldaksldkalskdla"
>>> {i:s.count(i) for i in set(s)}
{'a': 4, 'd': 3, 'k': 3, 's': 3, 'l': 4}
or
>>> [(i,s.count(i)) for i in set(s)]
[('a', 4), ('k', 3), ('s', 3), ('l', 4), ('d', 3)]
Solution by sub query fiddle Link
select * from messages where id in
(select max(id) from messages group by Name)
Solution By join condition fiddle link
select m1.* from messages m1
left outer join messages m2
on ( m1.id<m2.id and m1.name=m2.name )
where m2.id is null
Reason for this post is to give fiddle link only. Same SQL is already provided in other answers.
For Eclipse, modify project.properties
like this: (your path please)
android.library.reference.1=../../../../workspace/appcompat_v7_22
And remove android-support-v4.jar
file in your project's libs
folder.
If you can't just use filter join but need to perform some operations on the array's entry:
{% for entry in array %}
User {{ entry.attribute1 }} has id {{ entry.attribute2 }}
{% if not loop.last %}, {% endif %}
{% endfor %}
Unless you try to extend the Android CardView
class, you cannot customize that attribute from XML
.
Nonetheless, there is a way of obtaining that effect.
Place a CardView
inside another CardView
and apply a transparent background to your outer CardView
and remove its corner radius ("cornerRadios = 0dp"
). Your inner CardView
will have a cornerRadius value of 3dp, for example. Then apply a marginTop to your inner CardView
, so its bottom bounds will be cut by the outer CardView
. This way, the bottom corner radius of your inner CardView
will be hidden.
The XML code is the following:
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_outer"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
card_view:cardBackgroundColor="@android:color/transparent"
card_view:cardCornerRadius="0dp"
card_view:cardElevation="3dp" >
<android.support.v7.widget.CardView
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="@+id/card_view_inner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center"
android:layout_marginTop="3dp"
card_view:cardBackgroundColor="@color/green"
card_view:cardCornerRadius="4dp"
card_view:cardElevation="0dp" >
</android.support.v7.widget.CardView>
</android.support.v7.widget.CardView>
And the visual effect is the following:
Always put your content in your Inner CardView
. Your outer CardView serves only the purpose of "hiding" the bottom Rounded Corners of the inner CardView
.
I met this problem when doing sudo apt-get update
. My env is debian8, with python2.7 + 3.4(default) + 3.5.
The following code will only re-create a apt_pkg....so
file for python 3.5
sudo apt-get install python3-apt --reinstall
The following code solved my problem,
cd /usr/lib/python3/dist-packages
sudo ln -s apt_pkg.cpython-{35m,34m}-x86_64-linux-gnu.so
So, obviously, python3-apt checks the highest python version, instead of the current python version in use.
This tool: jscompressor.com is pretty good.
Try this:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
try
{
cn.Open();
SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
cmd.ExecuteNonQuery();
lblAlert.Text = "SucessFully Connected";
cn.Close();
}
catch (Exception eq)
{
lblAlert.Text = eq.ToString();
}
}
Impossible. A file descriptor may have multiple names in the filesystem, or it may have no name at all.
Edit: Assuming you are talking about a plain old POSIX system, without any OS-specific APIs, since you didn't specify an OS.
I was getting this problem due to pack200 mangling a class file. A bit of searching turned this java bug up. Basically, setting --effort=4
caused the problem to go away.
Using java 1.5.0_17 (though it cropped up in every single variant of java 1.5 I tried it in).
You should use
import Dan.Vik;
This makes the class visible and the its public methods available.
You can simply get the text size for a Paint object using getTextSize() method. For example:
Paint mTextPaint = new Paint (Paint.ANTI_ALIAS_FLAG);
//use densityMultiplier to take into account different pixel densities
final float densityMultiplier = getContext().getResources()
.getDisplayMetrics().density;
mTextPaint.setTextSize(24.0f*densityMultiplier);
//...
float size = mTextPaint.getTextSize();
Long expireTime = 69l;
Long tempParam = 0l;
Long seconds = math.mod(expireTime, 60);
tempParam = expireTime - seconds;
expireTime = tempParam/60;
Long minutes = math.mod(expireTime, 60);
tempParam = expireTime - minutes;
expireTime = expireTime/60;
Long hours = math.mod(expireTime, 24);
tempParam = expireTime - hours;
expireTime = expireTime/24;
Long days = math.mod(expireTime, 30);
system.debug(days + '.' + hours + ':' + minutes + ':' + seconds);
This should print: 0.0:1:9
I believe using * invalidate the entire cache in the distribution. I am trying at the moment, I would update it further
Update:
It worked as expected. Please note that you can invalidate the object you would like by specifying the object path.
just Step 1 > get the String value from JSON or dataSource
Step 2 > create a local variable and assign it.
let startDate = CurrentDashBoard.startdate
Step 3> create an instance of DateFormatter.
let dateFormatter = DateFormatter()
step 4> call the dateFormat from dateFormatter and provide saved date dataType.
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss"("may be String formate")
step 5> Assign the Local variable to this variable to convert.
let dateFromStringstartDate : NSDate = dateFormatter.date(from: startDate)! as NSDate
Step 6> provide your required date Formate by the following code.
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
Step 6> Assign it to label/text
cell.lblStartDate.text = String(format: "%@", strstartDate)
Code:
let startDate = CurrentDashBoard.startdate let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy HH:mm:ss" let dateFromStringstartDate :
NSDate = dateFormatter.date(from: startDate)! as NSDate
dateFormatter.dateFormat = "MM/dd/yyyy HH:mm:ss"
let strstartDate = dateFormatter.string(from: dateFromStringstartDate as Date)
it turns out that with python 2.5.2, del l[:]
is slightly slower than l[:] = []
by 1.1 usec.
$ python -mtimeit "l=list(range(1000))" "b=l[:];del b[:]"
10000 loops, best of 3: 29.8 usec per loop
$ python -mtimeit "l=list(range(1000))" "b=l[:];b[:] = []"
10000 loops, best of 3: 28.7 usec per loop
$ python -V
Python 2.5.2
As Pekka stated above
foreach ($array as $key => $value)
Also you might want to try a recursive function
displayRecursiveResults($site);
function displayRecursiveResults($arrayObject) {
foreach($arrayObject as $key=>$data) {
if(is_array($data)) {
displayRecursiveResults($data);
} elseif(is_object($data)) {
displayRecursiveResults($data);
} else {
echo "Key: ".$key." Data: ".$data."<br />";
}
}
}
Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application.....
with filename = GetFileName(Range("A1"))
Function GetFileName(rngNamedCell As Range) As String
Dim strSaveDirectory As String: strSaveDirectory = ""
Dim strFileName As String: strFileName = ""
Dim strTestPath As String: strTestPath = ""
Dim strFileBaseName As String: strFileBaseName = ""
Dim strFilePath As String: strFilePath = ""
Dim intFileCounterIndex As Integer: intFileCounterIndex = 1
' Get the users desktop directory.
strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
Debug.Print "Saving to: " & strSaveDirectory
' Base file name
strFileBaseName = Trim(rngNamedCell.Value)
Debug.Print "File Name will contain: " & strFileBaseName
' Loop until we find a free file number
Do
If intFileCounterIndex > 1 Then
' Build test path base on current counter exists.
strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
Else
' Build test path base just on base name to see if it exists.
strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
End If
If (Dir(strTestPath) = "") Then
' This file path does not currently exist. Use that.
strFileName = strTestPath
Else
' Increase the counter as we have not found a free file yet.
intFileCounterIndex = intFileCounterIndex + 1
End If
Loop Until strFileName <> ""
' Found useable filename
Debug.Print "Free file name: " & strFileName
GetFileName = strFileName
End Function
The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.
In Action
My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.
Sub Testing()
Dim filename As String: filename = GetFileName(Range("o1"))
ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
filename:=filename, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
End Sub
Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.
If the command that you are trying to execute fails, it would write the output onto the error stream and would then be printed out to the console.
To avoid it, you must redirect the error stream:
result=$(ls -l something_that_does_not_exist 2>&1)
The [0]
needs to be inside the )
.
To override already included executables;
set PATH=C:\xampp\php;%PATH%;
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long
is at least 32 bits, so %lu
together with (unsigned long)k
is always correct:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_t
is trickier, which is why %zu
was added in C99. If you can't use that, then treat it just like k
(long
is the biggest type in C89, size_t
is very unlikely to be larger).
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printf
will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
<script type="text/javascript" >
function aa()
{
var YourArray = ['United States', 'Canada', 'Argentina', 'Armenia'];
var ObjUl = $('<ul></ul>');
for (i = 0; i < YourArray.length; i++)
{
var Objli = $('<li></li>');
var Obja = $('<a></a>');
ObjUl.addClass("ui-menu-item");
ObjUl.attr("role", "menuitem");
Obja.addClass("ui-all");
Obja.attr("tabindex", "-1");
Obja.text(YourArray[i]);
Objli.append(Obja);
ObjUl.append(Objli);
}
$('.DivSai').append(ObjUl);
}
</script>
</head>
<body onload="aa()">
<form id="form1" runat="server">
<div class="DivSai" >
</div>
</form>
</body>
Any of these methods will work:
name = 'Smith'
puts name.[0..0] # => S
puts name.[0] # => S
puts name.[0,1] # => S
puts name.[0].chr # => S
I think that you are looking for something like this:
function rightclick() {
var rightclick;
var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert(rightclick); // true or false, you can trap right click here by if comparison
}
(http://www.quirksmode.org/js/events_properties.html)
And then use the onmousedown even with the function rightclick() (if you want to use it globally on whole page you can do this <body onmousedown=rightclick(); >
/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
/// <summary>
/// Returns list of items that are in initial but not in final list.
/// </summary>
/// <param name="listA"></param>
/// <param name="listB"></param>
/// <returns></returns>
public static IEnumerable<string> NonIntersect(
List<string> initial, List<string> final)
{
//subtracts the content of initial from final
//assumes that final.length < initial.length
return initial.Except(final);
}
/// <summary>
/// Returns the symmetric difference between the two list.
/// http://en.wikipedia.org/wiki/Symmetric_difference
/// </summary>
/// <param name="initial"></param>
/// <param name="final"></param>
/// <returns></returns>
public static IEnumerable<string> SymmetricDifference(
List<string> initial, List<string> final)
{
IEnumerable<string> setA = NonIntersect(final, initial);
IEnumerable<string> setB = NonIntersect(initial, final);
// sum and return the two set.
return setA.Concat(setB);
}
}
String path = Server.MapPath("~/MP_Upload/");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
This is worked for me
$('<div>We failed</div>')
.dialog(
{
title: 'Error',
close: function(event, ui)
{
$(this).dialog("close");
$(this).remove();
}
});
Cheers!
PS: I had a somewhat similar problem and the above approach solved it.
Use an Gradient Generator - and everything will be perfect ;) http://www.colorzilla.com/gradient-editor/
This button post to the current page while at the same time opens OtherPage.aspx
in a new browser window. I think this is what you mean with ...the original page and the newly launched page should both be launched.
<asp:Button ID="myBtn" runat="server" Text="Click me"
onclick="myBtn_Click" OnClientClick="window.open('OtherPage.aspx', 'OtherPage');" />
The answer is simple, you should break the direct prop mutation by assigning the value to some local component variables(could be data property, computed with getters, setters, or watchers).
Here's a simple solution using the watcher.
<template>
<input
v-model="input"
@input="updateInput"
@change="updateInput"
/>
</template>
<script>
export default {
props: {
value: {
type: String,
default: '',
},
},
data() {
return {
input: '',
};
},
watch: {
value: {
handler(after) {
this.input = after;
},
immediate: true,
},
},
methods: {
updateInput() {
this.$emit('input', this.input);
},
},
};
</script>
It's what I use to create any data input components and it works just fine. Any new data sent(v-model(ed)) from parent will be watched by the value watcher and is assigned to the input variable and once the input is received, we can catch that action and emit input to parent suggesting that data is input from the form element.
tools:ignore="ProtectedPermissions"
Try adding this attribute to that permission.
You should try sqlldr's SKIP_INDEX_MAINTENANCE parameter.
For the 3.4 version, please use the following syntax:
mongoimport -u "username" -p "password" -d "test" -c "collections" --type csv --file myCsv.csv --headerline
After 3 days, I finally made it on my own. Thanks to all the users who supported me.
var inp=readLine();//reading the input as one line string
var nums=inp.split(" ").map(Number);//making an array of numbers
console.log(nums);`
input : 1 9 0 65 5 7 output:[ 1, 9, 0, 65, 5, 7 ]
what if we dont use .map(Number)
code
var inp=readLine();//reading the input as one line string
var nums=inp.split(" ");//making an array of strings
console.log(nums);
input : 1 9 0 65 5 7 output:[ '1', '9', '0', '65', '5', '7']
shape
is a tuple that gives you an indication of the number of dimensions in the array. So in your case, since the index value of Y.shape[0]
is 0, your are working along the first dimension of your array.
From http://www.scipy.org/Tentative_NumPy_Tutorial#head-62ef2d3c0a5b4b7d6fdc48e4a60fe48b1ffe5006
An array has a shape given by the number of elements along each axis:
>>> a = floor(10*random.random((3,4)))
>>> a
array([[ 7., 5., 9., 3.],
[ 7., 2., 7., 8.],
[ 6., 8., 3., 2.]])
>>> a.shape
(3, 4)
and http://www.scipy.org/Numpy_Example_List#shape has some more examples.
// Pear Mail Library
require_once "Mail.php";
$from = '<[email protected]>';
$to = '<[email protected]>';
$subject = 'Hi!';
$body = "Hi,\n\nHow are you?";
$headers = array(
'From' => $from,
'To' => $to,
'Subject' => $subject
);
$smtp = Mail::factory('smtp', array(
'host' => 'ssl://smtp.gmail.com',
'port' => '465',
'auth' => true,
'username' => '[email protected]',
'password' => 'passwordxxx'
));
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail)) {
echo('<p>' . $mail->getMessage() . '</p>');
} else {
echo('<p>Message successfully sent!</p>');
}
I use that and it works :
<!--[if !IE]><!--> if it is not IE <!--<![endif]-->
If you are often programming dynamic stored procedures, you will fall in love with your second example (using where). If you have various input parameters and lots of morph mess, then that is the only way. Otherwise, they both will run the same query plan so there is definitely no obvious difference in classic queries.
Is this possible using HttpWebRequest and HttpWebResponse?
You could have your web server simply catch and write the exception text into the body of the response, then set status code to 500. Now the client would throw an exception when it encounters a 500 error but you could read the response stream and fetch the message of the exception.
So you could catch a WebException which is what will be thrown if a non 200 status code is returned from the server and read its body:
catch (WebException ex)
{
using (var stream = ex.Response.GetResponseStream())
using (var reader = new StreamReader(stream))
{
Console.WriteLine(reader.ReadToEnd());
}
}
catch (Exception ex)
{
// Something more serious happened
// like for example you don't have network access
// we cannot talk about a server exception here as
// the server probably was never reached
}
Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so
let markdown = `
1. Apple
2. Mango
this is juicy
3. Orange
`
Try:
With DependencedIncidents AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
),
lalala AS
(
SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
(
SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A
CROSS JOIN [Incident] AS X
WHERE
patindex('%' + A.[Col] + '%', X.[SQL]) > 0
) AS INC
)
And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.
That's not how ASP.NET MVC is supposed to be used. You do not redirect from views. You redirect from the corresponding controller action:
public ActionResult SomeAction()
{
...
return RedirectToAction("SomeAction", "SomeController");
}
Now since I see that in your example you are attempting to redirect to the LogOn
action, you don't really need to do this redirect manually, but simply decorate the controller action that requires authentication with the [Authorize]
attribute:
[Authorize]
public ActionResult SomeProtectedAction()
{
...
}
Now when some anonymous user attempts to access this controller action, the Forms Authentication module will automatically intercept the request much before it hits the action and redirect the user to the LogOn action that you have specified in your web.config (loginUrl
).
private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
if (DgvRoomInformation.CurrentCell.ColumnIndex == 4) //example-'Column index=4'
{
DgvRoomInformation.BeginEdit(true);
}
}
Simply you can use:
on server side:
Registry <objectName1> =LocateRegisty.createRegistry(1099);
Registry <objectName2> =LocateRegisty.getRegistry();
on Client Side:
Registry <object name you want> =LocateRegisty.getRegistry();
update TABLENAME
set COLUMNNAME = COLUMNNAME + 1
where id = 'YOURID'
For the sake of completeness, now we also have ImmutableArrays at our disposal. This should be truly immutable:
public readonly static ImmutableArray<string> Tiles = ImmutableArray.Create(new[] { "German", "Spanish", "Corrects", "Wrongs" });
Requires System.Collections.Immutable NuGet reference
https://msdn.microsoft.com/en-us/library/mt452182(v=vs.111).aspx
You might want colored output with this.
I use this one-liner for listing the tracked files and directories in the current directory of the current branch:
ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)
You might want to add it as an alias:
alias gl='ls --group-directories-first --color=auto -d $(git ls-tree $(git branch | grep \* | cut -d " " -f2) --name-only)'
If you want to recursively list files:
'ls' --color=auto -d $(git ls-tree -rt $(git branch | grep \* | cut -d " " -f2) --name-only)
And an alias:
alias glr="'ls' --color=auto -d \$(git ls-tree -rt \$(git branch | grep \\* | cut -d \" \" -f2) --name-only)"
To rotate by 45 degrees in IE, you need the following code in your stylesheet:
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */
You’ll note from the above that IE8 has different syntax to IE6/7. You need to supply both lines of code if you want to support all versions of IE.
The horrible numbers there are in Radians; you’ll need to work out the figures for yourself if you want to use an angle other than 45 degrees (there are tutorials on the internet if you look for them).
Also note that the IE6/7 syntax causes problems for other browsers due to the unescaped colon symbol in the filter string, meaning that it is invalid CSS. In my tests, this causes Firefox to ignore all CSS code after the filter. This is something you need to be aware of as it can cause hours of confusion if you get caught out by it. I solved this by having the IE-specific stuff in a separate stylesheet which other browsers didn’t load.
All other current browsers (including IE9 and IE10 — yay!) support the CSS3 transform
style (albeit often with vendor prefixes), so you can use the following code to achieve the same effect in all other browsers:
-moz-transform: rotate(45deg); /* FF3.5/3.6 */
-o-transform: rotate(45deg); /* Opera 10.5 */
-webkit-transform: rotate(45deg); /* Saf3.1+ */
transform: rotate(45deg); /* Newer browsers (incl IE9) */
Hope that helps.
Since this answer is still getting up-votes, I feel I should update it with information about a JavaScript library called CSS Sandpaper that allows you to use (near) standard CSS code for rotations even in older IE versions.
Once you’ve added CSS Sandpaper to your site, you should then be able to write the following CSS code for IE6–8:
-sand-transform: rotate(40deg);
Much easier than the traditional filter
style you'd normally need to use in IE.
Also note an additional quirk specifically with IE9 (and only IE9), which supports both the standard transform
and the old style IE -ms-filter
. If you have both of them specified, this can result in IE9 getting completely confused and rendering just a solid black box where the element would have been. The best solution to this is to avoid the filter
style by using the Sandpaper polyfill mentioned above.
By default, the JDBCTemplate
does its own PreparedStatement
internally, if you just use the .update(String sql, Object ... args)
form. Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. One of the saving graces of Spring. A link to Spring 2.5's documentation on this. Hope it makes things clearer. Also, statement caching can be done at the JDBC level, as in the case of at least some of Oracle's JDBC drivers.
That will go into a lot more detail than I can competently.
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
Just assign row to a particular index, using loc
:
df.loc[-1] = [2, 3, 4] # adding a row
df.index = df.index + 1 # shifting index
df = df.sort_index() # sorting by index
And you get, as desired:
A B C
0 2 3 4
1 5 6 7
2 7 8 9
See in Pandas documentation Indexing: Setting with enlargement.
This line add in TableView
cell:
static var nib : UINib{
return UINib(nibName: identifier, bundle: nil)
}
static var identifier : String{
return String(describing: self)
}
And register in viewcontroller like
//This line use in viewdid load
tableview.register(TopDealLikedTableViewCell.nib, forCellReuseIdentifier: TopDealLikedTableViewCell.identifier)
// cell for row at indexpath
if let cell = tableView.dequeueReusableCell(withIdentifier:
TopDealLikedTableViewCell.identifier) as? TopDealLikedTableViewCell{
return cell
}
return UITableViewCell()
alert()
doesn't support HTML, but you have some alternatives to format your message.
You can use Unicode characters as others stated, or you can make use of the ES6 Template literals. For example:
...
.catch(function (error) {
const alertMessage = `Error retrieving resource. Please make sure:
• the resource server is accessible
• you're logged in
Error: ${error}`;
window.alert(alertMessage);
}
As you can see, it maintains the line breaks and spaces that we included in the variable, with no extra characters.
Use CopyOnWriteArrayList
and if you want to remove it, do the following:
for (Iterator<String> it = userList.iterator(); it.hasNext() ;)
{
if (wordsToRemove.contains(word))
{
it.remove();
}
}
You can hold onto the percentage as decimal (value \ total)
and then when you want to render to a human you can make use of Habeeb's answer or using string interpolation you could have something even cleaner:
var displayPercentage = $"{(decimal)value / total:P}";
or
//Calculate percentage earlier in code
decimal percentage = (decimal)value / total;
...
//Now render percentage
var displayPercentage = $"{percentage:P}";
The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.
Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...
I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.
Creating /etc/docker/daemon.json file and adding the below content and then doing a docker restart on CentOS 7 resolved the issue.
{
"insecure-registries" : [ "hostname.cloudapp.net:5000" ]
}
I imagine this forum posting, which I quote fully below, should answer the question.
Inside a procedure, function, or trigger definition, or in a dynamic SQL statement (embedded in a host program):
BEGIN ATOMIC
DECLARE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
END
or (in any environment):
WITH t(example) AS (VALUES('welcome'))
SELECT *
FROM tablename, t
WHERE column1 = example
or (although this is probably not what you want, since the variable needs to be created just once, but can be used thereafter by everybody although its content will be private on a per-user basis):
CREATE VARIABLE example VARCHAR(15) ;
SET example = 'welcome' ;
SELECT *
FROM tablename
WHERE column1 = example ;
Use a bytecode editor, like:
Be careful because you need a very good knowledge of the Java bytecode.
You can also change the class at runtime with bytecode weaving (like AspectJ).
Success!
After checking the log files and making sure the permissions on php_openssl.dll were correct, I googled the warning and found more things to try.
So I:
I'm not sure which of these fixed my problem, but it's definately fixed now! :)
I found these things to try on this page: http://php.net/manual/en/install.windows.extensions.php
Thanks for your help!
The problem with these answers is that, with every Xcode update, menus and locations will change.
Just go to /Applications/Xcode.app/Contents/Developer/Platforms
and delete what you don't need. Xcode will start fine. If you're at all concerned then you can simply restore from Trash.
You could either use a lookahead assertion like others have suggested. Or, if you just want to use basic regular expression syntax:
^(.?$|[^m].+|m[^y].*)
This matches strings that are either zero or one characters long (^.?$
) and thus can not be my
. Or strings with two or more characters where when the first character is not an m
any more characters may follow (^[^m].+
); or if the first character is a m
it must not be followed by a y
(^m[^y]
).
add Microsoft.AspNet.Mvc nuget package.
Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
P = New Uri(P).LocalPath
Check out http://mywiki.wooledge.org/DotFiles for an excellent resource on the topic aside from man bash
.
Summary:
~/.bash_profile
or ~/.profile
is read and executed. Since everything you run from your login shell inherits the login shell's environment, you should put all your environment variables in there. Like LESS
, PATH
, MANPATH
, LC_*
, ... For an example, see: My .profile
~/.bashrc
, not /.profile
or ~/.bash_profile
, for this exact reason, so in there define everything that only applies to bash. That's functions, aliases, bash-only variables like HISTSIZE (this is not an environment variable, don't export it!), shell options with set
and shopt
, etc. For an example, see: My .bashrc
~/.bashrc
but only ~/.profile
or ~/.bash_profile
, so you should source that one manually from the latter. You'll see me do that in my ~/.profile
too: source ~/.bashrc
.in gradle.properties, you can even delete
org.gradle.jvmargs=-Xmx1536m
such lines or comment them out. Let android studio decide for it. When I ran into this same problem, none of above solutions worked for me. Commenting out this line in gradle.properties helped in solving that error.
Use NSBatchDeleteRequest
to delete all objects in the entity without having to load them into memory or iterate through them.
// create the delete request for the specified entity
let fetchRequest: NSFetchRequest<NSFetchRequestResult> = MyEntity.fetchRequest()
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
// get reference to the persistent container
let persistentContainer = (UIApplication.shared.delegate as! AppDelegate).persistentContainer
// perform the delete
do {
try persistentContainer.viewContext.execute(deleteRequest)
} catch let error as NSError {
print(error)
}
This code has been updated for iOS 10 and Swift 3. If you need to support iOS 9, see this question.
Sources:
One simplistic approach to measuring the "elapsed time" between events is to just grab the current date and time.
In SQL Server Management Studio
SELECT GETDATE();
SELECT /* query one */ 1 ;
SELECT GETDATE();
SELECT /* query two */ 2 ;
SELECT GETDATE();
To calculate elapsed times, you could grab those date values into variables, and use the DATEDIFF function:
DECLARE @t1 DATETIME;
DECLARE @t2 DATETIME;
SET @t1 = GETDATE();
SELECT /* query one */ 1 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;
SET @t1 = GETDATE();
SELECT /* query two */ 2 ;
SET @t2 = GETDATE();
SELECT DATEDIFF(millisecond,@t1,@t2) AS elapsed_ms;
That's just one approach. You can also get elapsed times for queries using SQL Profiler.
I implemented a function similar to the momentjs method subtract.
function addDate(dt, amount, dateType) {
switch (dateType) {
case 'days':
return dt.setDate(dt.getDate() + amount) && dt;
case 'weeks':
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case 'months':
return dt.setMonth(dt.getMonth() + amount) && dt;
case 'years':
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months');// use -1 to subtract
export enum dateAmountType {
DAYS,
WEEKS,
MONTHS,
YEARS,
}
export function addDate(dt: Date, amount: number, dateType: dateAmountType): Date {
switch (dateType) {
case dateAmountType.DAYS:
return dt.setDate(dt.getDate() + amount) && dt;
case dateAmountType.WEEKS:
return dt.setDate(dt.getDate() + (7 * amount)) && dt;
case dateAmountType.MONTHS:
return dt.setMonth(dt.getMonth() + amount) && dt;
case dateAmountType.YEARS:
return dt.setFullYear( dt.getFullYear() + amount) && dt;
}
}
example:
let dt = new Date();
dt = addDate(dt, -1, 'months'); // use -1 to subtract
I also made some unit-tests for this function using Jasmine:
it('addDate() should works properly', () => {
for (const test of [
{ amount: 1, dateType: dateAmountType.DAYS, expect: '2020-04-13'},
{ amount: -1, dateType: dateAmountType.DAYS, expect: '2020-04-11'},
{ amount: 1, dateType: dateAmountType.WEEKS, expect: '2020-04-19'},
{ amount: -1, dateType: dateAmountType.WEEKS, expect: '2020-04-05'},
{ amount: 1, dateType: dateAmountType.MONTHS, expect: '2020-05-12'},
{ amount: -1, dateType: dateAmountType.MONTHS, expect: '2020-03-12'},
{ amount: 1, dateType: dateAmountType.YEARS, expect: '2021-04-12'},
{ amount: -1, dateType: dateAmountType.YEARS, expect: '2019-04-12'},
]) {
expect(formatDate(addDate(new Date('2020-04-12'), test.amount, test.dateType))).toBe(test.expect);
}
});
To use this test you need this function:
// get format date as 'YYYY-MM-DD'
export function formatDate(date: Date): string {
const d = new Date(date);
let month = '' + (d.getMonth() + 1);
let day = '' + d.getDate();
const year = d.getFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (day.length < 2) {
day = '0' + day;
}
return [year, month, day].join('-');
}
A UHF RFID reader option for both Android and iOS is available from a company called U Grok It.
It is just UHF, which is "non-NFC enabled Android", if that's what you meant. My apologies if you meant an NFC reader for Android devices that don't have an NFC reader built-in.
Their reader has a range up to 7 meters (~21 feet). It connects via the audio port, not bluetooth, which has the advantage of pairing instantly, securely, and with way less of a power draw.
They have a free native SDK for Android, iOS, Cordova, and Xamarin, as well as an Android keyboard wedge.
using System;
using System.IO;
class Test
{
public static void Main()
{
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
Console.WriteLine("Drive {0}", d.Name);
Console.WriteLine(" Drive type: {0}", d.DriveType);
if (d.IsReady == true)
{
Console.WriteLine(" Volume label: {0}", d.VolumeLabel);
Console.WriteLine(" File system: {0}", d.DriveFormat);
Console.WriteLine(
" Available space to current user:{0, 15} bytes",
d.AvailableFreeSpace);
Console.WriteLine(
" Total available space: {0, 15} bytes",
d.TotalFreeSpace);
Console.WriteLine(
" Total size of drive: {0, 15} bytes ",
d.TotalSize);
}
}
}
}
/*
This code produces output similar to the following:
Drive A:\
Drive type: Removable
Drive C:\
Drive type: Fixed
Volume label:
File system: FAT32
Available space to current user: 4770430976 bytes
Total available space: 4770430976 bytes
Total size of drive: 10731683840 bytes
Drive D:\
Drive type: Fixed
Volume label:
File system: NTFS
Available space to current user: 15114977280 bytes
Total available space: 15114977280 bytes
Total size of drive: 25958948864 bytes
Drive E:\
Drive type: CDRom
The actual output of this code will vary based on machine and the permissions
granted to the user executing it.
*/
Your site's root directory:
ini_set('memory_limit', '1024M');
Example to show last 3 digits of account number.
x = '1234567890'
x.replace(x[:7], '')
o/p: '890'
<style name="MineCustomTabText" parent="TextAppearance.Design.Tab">
<item name="android:textSize">16sp</item>
</style>
Use is in TabLayout
like this
<android.support.design.widget.TabLayout
app:tabTextAppearance="@style/MineCustomTabText"
...
/>
Useful tool for debugging java programs, it gives the number of threads and other relevant info on them:
jconsole <process-id>
Since PostgreSQL 9.1 there is the convenient FOREACH
:
DO
$do$
DECLARE
m varchar[];
arr varchar[] := array[['key1','val1'],['key2','val2']];
BEGIN
FOREACH m SLICE 1 IN ARRAY arr
LOOP
RAISE NOTICE 'another_func(%,%)',m[1], m[2];
END LOOP;
END
$do$
Solution for older versions:
DO
$do$
DECLARE
arr varchar[] := '{{key1,val1},{key2,val2}}';
BEGIN
FOR i IN array_lower(arr, 1) .. array_upper(arr, 1)
LOOP
RAISE NOTICE 'another_func(%,%)',arr[i][1], arr[i][2];
END LOOP;
END
$do$
Also, there is no difference between varchar[]
and varchar[][]
for the PostgreSQL type system. I explain in more detail here.
The DO
statement requires at least PostgreSQL 9.0, and LANGUAGE plpgsql
is the default (so you can omit the declaration).
Use the Find method if item_manuf_id
is a primary key:
var result = dtPs.Rows.Find("some value");
If you only want to know if the value is in there then use the Contains method.
if (dtPs.Rows.Contains("some value"))
{
...
}
Primary key restriction applies to Contains
aswell.
Yes, there is: https://github.com/robinrowe/libunistd
Clone the repository and add path\to\libunistd\unistd
to the INCLUDE
environment variable.
Use the jQuery hashchange event plugin instead. Regarding your full ajax navigation, try to have SEO friendly ajax. Otherwise your pages shown nothing in browsers with JavaScript limitations.
<ul id="category-tabs">
<li><a href="javascript:void"><i class="fa fa-plus-circle"></i>Category 1</a>
<ul>
<li><a href="javascript:void">item 1</a></li>
<li><a href="javascript:void">item 2</a></li>
<li><a href="javascript:void">item 3</a></li>
</ul>
</li> </ul>
//Jquery
$(document).ready(function() {
$('li').click(function() {
$('i').toggleClass('fa-plus-square fa-minus-square');
});
});
If, as I just encountered, you happen to have a jar file listed in the Project Structures->Libraries that is not in your classpath, the correct answer can be found by following the link given by @CrazyCoder above: Look here http://www.jetbrains.com/idea/webhelp/configuring-module-dependencies-and-libraries.html
This says that to add the jar file as a module dependency within the Project Structure dialog:
I'm surprised noone mentioned the git reflog (http://git-scm.com/docs/git-reflog):
# git reflog
<find the place before your staged anything>
# git reset HEAD@{1}
The reflog is a git history that not only tracks the changes to the repo, but also tracks the user actions (Eg. pull, checkout to different branch, etc) and allows to undo those actions. So instead of unstaging the file that was mistakingly staged, where you can revert to the point where you didn't stage the files.
This is similar to git reset HEAD <file>
but in certain cases may be more granular.
Sorry - not really answering your question, but just pointing yet another way to unstage files that I use quite often (I for one like answers by Ryan Stewart and waldyrious very much.) ;) I hope it helps.
Use setState
in your view to change employed
property of state. This is example of React render engine.
someFunctionWhichChangeParamEmployed(isEmployed) {
this.setState({
employed: isEmployed
});
}
getInitialState() {
return {
employed: true
}
},
render(){
if (this.state.employed) {
return (
<div>
<MyInput ref="job-title" name="job-title" />
</div>
);
} else {
return (
<div>
<span>Diff me!</span>
<MyInput ref="unemployment-reason" name="unemployment-reason" />
<MyInput ref="unemployment-duration" name="unemployment-duration" />
</div>
);
}
}
User order by with desc
order:
select * from t
order by id desc
limit 1
Use the random
module: http://docs.python.org/library/random.html
import random
random.sample(set([1, 2, 3, 4, 5, 6]), 2)
This samples the two values without replacement (so the two values are different).
$.ajax(
{
type: 'post',
url: 'mail.php',
data: form.serialize(),
beforeSend: function()
{
$('.content').html('loading...');
},
success: function(data)
{
$('.content').html(data);
},
error: function()
{
$('.content').html('error');
}
});
have fun playing arround!
if you should have quick loading times which prevent te loading showing, you can add a timeout of some sort.
I solved it by updating listener.ora file inside oracle directory oraclexe\app\oracle\product\11.2.0\server\network\ADMIN.
Why did it happen to me was because I changed my system name but inside listener.ora there was old name for HOST.
This might be one of the reasons... for those who still face such issue might think of this possibility as well.
If there were just one header line in the first record, then the most efficient way to filter it out would be:
rdd.mapPartitionsWithIndex {
(idx, iter) => if (idx == 0) iter.drop(1) else iter
}
This doesn't help if of course there are many files with many header lines inside. You can union three RDDs you make this way, indeed.
You could also just write a filter
that matches only a line that could be a header. This is quite simple, but less efficient.
Python equivalent:
from itertools import islice
rdd.mapPartitionsWithIndex(
lambda idx, it: islice(it, 1, None) if idx == 0 else it
)
Try this on your position:fixed element.
overflow-y: scroll;
max-height: 100%;
this will do the trick for you
if (!!val) {
alert("this is not null")
} else {
alert("this is null")
}
Try deleting Bolts.framework
from linked framework and re-add it. Also, in your Framework Search Path
keep path until Bolts.framework
like $(PROJECT_DIR)/Bolts
if it is inside Bolts folder at your project directory path.
When running ant from the shell, you don't need to export JAVA_HOME
first, which would set that variable for your current shell and all future commands, instead use
user@host:~# JAVA_HOME=/path/to/jdk ant targets
Please check: http://man7.org/linux/man-pages/man5/proc.5.html
address perms offset dev inode pathname
00400000-00452000 r-xp 00000000 08:02 173521 /usr/bin/dbus-daemon
The address field is the address space in the process that the mapping occupies.
The perms field is a set of permissions:
r = read
w = write
x = execute
s = shared
p = private (copy on write)
The offset field is the offset into the file/whatever;
dev is the device (major:minor);
inode is the inode on that device.0 indicates that no inode is associated with the memoryregion, as would be the case with BSS (uninitialized data).
The pathname field will usually be the file that is backing the mapping. For ELF files, you can easily coordinate with the offset field by looking at the Offset field in the ELF program headers (readelf -l).
Under Linux 2.0, there is no field giving pathname.
The highly regarded Joda Time library is also worth a look. This is basis for the new date and time api that is pencilled in for Java 7. The design is neat, intuitive, well documented and avoids a lot of the clumsiness of the original java.util.Date
/ java.util.Calendar
classes.
Joda's DateFormatter
can parse a String to a Joda DateTime
.
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
As of now (06/07/2018), an easy approach would be running az account show in the Azure Cloud Shell (requires a Storage Account) in the Azure Portal.
--- Command ---
az account show
--- Command Output ---
{
"environmentName": "AzureCloud",
"id": "{Subscription Id (GUID)}",
"isDefault": true,
"name": "{Subscription Name}",
"state": "Enabled",
"tenantId": "{Tenant Id (GUID)}",
"user": {
"cloudShellID": true,
"name": "{User email}",
"type": "user"
}
}
Find more details on Azure Cloud Shell at https://docs.microsoft.com/en-us/azure/cloud-shell/overview.
element: HTMLElement;
constructor() {}
fakeClick(){
this.element = document.getElementById('ButtonX') as HTMLElement;
this.element.click();
}
An alternative to coord_flip()
is to use the ggstance
package.
The advantage is that it makes it easier to combine the graphs with other graph types and you can, maybe more importantly, set fixed scale ratios for your coordinate system.
library(ggplot2)
library(ggstance)
diamonds$cut <- paste("Super Dee-Duper", as.character(diamonds$cut))
ggplot(data=diamonds, aes(carat, cut)) + geom_boxploth()
Created on 2020-03-11 by the reprex package (v0.3.0)
Use Number
from the numbers
module to test isinstance(n, Number)
(available since 2.6).
isinstance(n, numbers.Number)
Here it is in action with various kinds of numbers and one non-number:
>>> from numbers import Number
... from decimal import Decimal
... from fractions import Fraction
... for n in [2, 2.0, Decimal('2.0'), complex(2,0), Fraction(2,1), '2']:
... print '%15s %s' % (n.__repr__(), isinstance(n, Number))
2 True
2.0 True
Decimal('2.0') True
(2+0j) True
Fraction(2, 1) True
'2' False
This is, of course, contrary to duck typing. If you are more concerned about how an object acts rather than what it is, perform your operations as if you have a number and use exceptions to tell you otherwise.
This is the most native and scalable approach I could find:
>>> myindex = pd.Series(myseries.index, index=myseries)
>>> myindex[7]
3
>>> myindex[[7, 5, 7]]
7 3
5 4
7 3
dtype: int64