Solution using 1 variable (Only p):
typedef unsigned long AddressType;
#define A (*( AddressType* )&p )
#define B (*( AddressType* )&first->link->link )
#define C (*( AddressType* )&first->link )
/* Reversing linked list */
p = first;
while( first->link )
{
A = A + B + C;
B = A - B - C;
A = A - B;
C = A - C;
A = A - C;
}
first = p;
Look ma, no recursion!
struct llist * llist_merge(struct llist *one, struct llist *two, int (*cmp)(struct llist *l, struct llist *r) )
{
struct llist *result, **tail;
for (result=NULL, tail = &result; one && two; tail = &(*tail)->next ) {
if (cmp(one,two) <=0) { *tail = one; one=one->next; }
else { *tail = two; two=two->next; }
}
*tail = one ? one: two;
return result;
}
package LinkedList;
import java.util.LinkedList;
public class LinkedListNode {
private int value;
private LinkedListNode next = null;
public LinkedListNode(int i) {
this.value = i;
}
public LinkedListNode addNode(int i) {
this.next = new LinkedListNode(i);
return next;
}
public LinkedListNode getNext() {
return next;
}
@Override
public String toString() {
String restElement = value+"->";
LinkedListNode newNext = getNext();
while(newNext != null)
{restElement = restElement + newNext.value + "->";
newNext = newNext.getNext();}
restElement = restElement +newNext;
return restElement;
}
public static void main(String[] args) {
LinkedListNode headnode = new LinkedListNode(1);
headnode.addNode(2).addNode(3).addNode(4).addNode(5).addNode(6);
System.out.println(headnode);
headnode = reverse(null,headnode,headnode.getNext());
System.out.println(headnode);
}
private static LinkedListNode reverse(LinkedListNode prev, LinkedListNode current, LinkedListNode next) {
current.setNext(prev);
if(next == null)
return current;
return reverse(current,next,next.getNext());
}
private void setNext(LinkedListNode prev) {
this.next = prev;
}
}
os.path.split(os.path.realpath(__file__))[0]
os.path.realpath(__file__)
return the abspath of the current script; os.path.split(abspath)[0] return the current dir
Visual Studio Code: Version 1.14.2 (1.14.2)
At default setting, you can see this:
// Columns at which to show vertical rulers
"editor.rulers": [],
This means the empty array won't show the vertical rulers.
At right window "user setting", add the following:
"editor.rulers": [140]
Save the file, and you will see the rulers.
Yes, it is 128, except for temp tables, whose names can only be up to 116 character long. It is perfectly explained here.
And the verification can be easily made with the following script contained in the blog post before:
DECLARE @i NVARCHAR(800)
SELECT @i = REPLICATE('A', 116)
SELECT @i = 'CREATE TABLE #'+@i+'(i int)'
PRINT @i
EXEC(@i)
Another good trick is to go into UTF8 mode in your editor so that you can actually see these funny characters and delete them yourself.
If I need navigate to method in currently opened class, I use this combination: ALT+7 (CMD+7 on Mac) to open structure view, and press two times (first time open, second time focus on view), type name of methods, select on of needed.
I am using a ListView instead of a GridView in 3.5. When the user wants to edit I have set the selected item of the dropdown to the exising value of that column for the record. I am able to access the dropdown in the ItemDataBound event. Here's the code:
protected void listViewABC_ItemDataBound(object sender, ListViewItemEventArgs e)
{
// This stmt is used to execute the code only in case of edit
if (((ListView)(sender)).EditIndex != -1 && ((ListViewDataItem)(e.Item)).DisplayIndex == ((ListView)(sender)).EditIndex)
{
((DropDownList)(e.Item.FindControl("ddlXType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).XTypeId.ToString();
((DropDownList)(e.Item.FindControl("ddlIType"))).SelectedValue = ((MyClass)((ListViewDataItem)e.Item).DataItem).ITypeId.ToString();
}
}
:set runtimepath?
This lists the path of all plugins loaded when a file is opened with Vim.
Take care about the UITableView
properties in the storyboard, what happened in my case was that I had the combox in the storyboard selected as "Selection: Single Selection", that does not allow the method didSelectRowAtIndexPath
run.
According to wikipedia, the most browser-compatible incantation is:
<link rel="shortcut icon" href="favicon.ico" />
After that, you just need to worry about whether your browser is actually downloading the icon. What do the server logs say? Have you checked your browsers network debugging console?
@Paul answer links to a great solution, but the code doesn't allow to use onClickListeners on items children (the callback functions are never called). I've been struggling for a while to find a solution and I've decided to post here what you need to modify in that code (in case somebody need it).
Instead of overriding dispatchTouchEvent
override onTouchEvent
. Use the same code of dispatchTouchEvent
and delete the method (you can read the difference between the two here http://developer.android.com/guide/topics/ui/ui-events.html#EventHandlers )
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean handled = mGesture.onTouchEvent(event);
return handled;
}
Then, add the following code which will decide to steal the event from the item children and give it to our onTouchEvent
, or let it be handled by them.
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch( ev.getActionMasked() ){
case MotionEvent.ACTION_DOWN:
mInitialX = ev.getX();
mInitialY = ev.getY();
return false;
case MotionEvent.ACTION_MOVE:
float deltaX = Math.abs(ev.getX() - mInitialX);
float deltaY = Math.abs(ev.getY() - mInitialY);
return ( deltaX > 5 || deltaY > 5 );
default:
return super.onInterceptTouchEvent(ev);
}
}
Finally, don't forget to declare the variables in your class:
private float mInitialX;
private float mInitialY;
You can use the MSXML Base64 encoding functionality as described at www.nonhostile.com/howto-encode-decode-base64-vb6.asp:
Function EncodeBase64(text As String) As String
Dim arrData() As Byte
arrData = StrConv(text, vbFromUnicode)
Dim objXML As MSXML2.DOMDocument
Dim objNode As MSXML2.IXMLDOMElement
Set objXML = New MSXML2.DOMDocument
Set objNode = objXML.createElement("b64")
objNode.dataType = "bin.base64"
objNode.nodeTypedValue = arrData
EncodeBase64 = objNode.Text
Set objNode = Nothing
Set objXML = Nothing
End Function
Another way to do something similar is with flexbox on a wrapper element, i.e.,
.row {_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
}
_x000D_
<div class="row">_x000D_
<div>Left</div>_x000D_
<div>Right</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
It should be :
public async Task<ActionResult> GetSomeJsonData()
{
var model = // ... get data or build model etc.
return Json(new { Data = model }, JsonRequestBehavior.AllowGet);
}
or more simply:
return Json(model, JsonRequestBehavior.AllowGet);
I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...
You can use this :
'mobile_number' => ['required', 'digits:10'],
for varname=$prefix_suffix
format, just use:
varname=${prefix}_suffix
Check if there's a .dockerignore
file, if so, add:
!mydir/test.json
!mydir/test.py
By default there will be no branches listed and pops up only after some file is placed. You don't have to worry much about it. Just run all your commands like creating folder structures, adding/deleting files, commiting files, pushing it to server or creating branches. It works seamlessly without any issue.
This regex works for C#, PCRE and Go to name a few.
It doesn't work for JavaScript on Chrome from what RegexBuddy says. But there's already an example for that here.
This main part of this is:
\p{L}
which represents \p{L}
or \p{Letter}
any kind of letter from any language.`
The full regex itself: [^\w\d\s:\p{L}]
Example: https://regex101.com/r/K59PrA/2
On the Web API side, simply use Request object instead of creating new HttpRequestMessage
var re = Request;
var headers = re.Headers;
if (headers.Contains("Custom"))
{
string token = headers.GetValues("Custom").First();
}
return null;
Output -
Try the Magnific Popup, it's responsive and weights just around 3KB.
You will have to use the fluent API to do this.
Try adding the following to your DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<User>()
.HasOptional(a => a.UserDetail)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
}
comdlg32.dll is not really a COM dll (you can't register it).
What you need is comdlg32.ocx which contains the MSComDlg.CommonDialog COM class (and indeed relies on comdlg32.dll to work). Once you get ahold on a comdlg32.ocx, then you will be able to do regsvr32 comdlg32.ocx
.
//Here pdate is the string date time
var date1=GetDate(pdate);
function GetDate(a){
var dateString = a.substr(6);
var currentTime = new Date(parseInt(dateString ));
var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
var day =("0"+ currentTime.getDate()).slice(-2);
var year = currentTime.getFullYear();
var date = day + "/" + month + "/" + year;
return date;
}
use the xclip
which is command line interface to X selections
apt-get install xclip
echo "test xclip " > /tmp/test.xclip
xclip -i < /tmp/test.xclip
xclip -o > /tmp/test.xclip.out
cat /tmp/test.xclip.out # "test xclip"
enjoy.
Try This:
int positionOfJPG=url.IndexOf(".jpg");
string newString = url.Substring(18, url.Length - positionOfJPG);
TLDR; MySql does not have an equivalent concept of varchar(max)
, this is a MS SQL Server feature.
varchar(max)
is a feature of Microsoft SQL Server.
The amount of data that a column could store in Microsoft SQL server versions prior to version 2005 was limited to 8KB. In order to store more than 8KB you would have to use TEXT
, NTEXT
, or BLOB
columns types, these column types stored their data as a collection of 8K pages separate from the table data pages; they supported storing up to 2GB per row.
The big caveat to these column types was that they usually required special functions and statements to access and modify the data (e.g. READTEXT
, WRITETEXT
, and UPDATETEXT
)
In SQL Server 2005, varchar(max)
was introduced to unify the data and queries used to retrieve and modify data in large columns. The data for varchar(max)
columns is stored inline with the table data pages.
As the data in the MAX column fills an 8KB data page an overflow page is allocated and the previous page points to it forming a linked list. Unlike TEXT
, NTEXT
, and BLOB
the varchar(max)
column type supports all the same query semantics as other column types.
So varchar(MAX)
really means varchar(AS_MUCH_AS_I_WANT_TO_STUFF_IN_HERE_JUST_KEEP_GROWING)
and not varchar(MAX_SIZE_OF_A_COLUMN)
.
In order to get the same amount of storage as a varchar(max)
in MySql you would still need to resort to a BLOB
column type. This article discusses a very effective method of storing large amounts of data in MySql efficiently.
As of Swift 4 (Xcode 9), the Swift standard
library provides methods to convert between Swift string ranges
(Range<String.Index>
) and NSString
ranges (NSRange
).
Example:
let str = "abc"
let r1 = str.range(of: "")!
// String range to NSRange:
let n1 = NSRange(r1, in: str)
print((str as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) //
Therefore the text replacement in the text field delegate method can now be done as
func textField(_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
if let oldString = textField.text {
let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
with: string)
// ...
}
// ...
}
(Older answers for Swift 3 and earlier:)
As of Swift 1.2, String.Index
has an initializer
init?(_ utf16Index: UTF16Index, within characters: String)
which can be used to convert NSRange
to Range<String.Index>
correctly
(including all cases of Emojis, Regional Indicators or other extended
grapheme clusters) without intermediate conversion to an NSString
:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
let to16 = advance(from16, nsRange.length, utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
This method returns an optional string range because not all NSRange
s
are valid for a given Swift string.
The UITextFieldDelegate
delegate method can then be written as
func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let swRange = textField.text.rangeFromNSRange(range) {
let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
// ...
}
return true
}
The inverse conversion is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(from - utf16view.startIndex, to - from)
}
}
A simple test:
let str = "abc"
let r1 = str.rangeOfString("")!
// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) //
// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) //
Update for Swift 2:
The Swift 2 version of rangeFromNSRange()
was already given
by Serhii Yakovenko in this answer, I am including it
here for completeness:
extension String {
func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
if let from = String.Index(from16, within: self),
let to = String.Index(to16, within: self) {
return from ..< to
}
return nil
}
}
The Swift 2 version of NSRangeFromRange()
is
extension String {
func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
let utf16view = self.utf16
let from = String.UTF16View.Index(range.startIndex, within: utf16view)
let to = String.UTF16View.Index(range.endIndex, within: utf16view)
return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
}
}
Update for Swift 3 (Xcode 8):
extension String {
func nsRange(from range: Range<String.Index>) -> NSRange {
let from = range.lowerBound.samePosition(in: utf16)
let to = range.upperBound.samePosition(in: utf16)
return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
length: utf16.distance(from: from, to: to))
}
}
extension String {
func range(from nsRange: NSRange) -> Range<String.Index>? {
guard
let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
let from = from16.samePosition(in: self),
let to = to16.samePosition(in: self)
else { return nil }
return from ..< to
}
}
Example:
let str = "abc"
let r1 = str.range(of: "")!
// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) //
// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) //
I use this Function I modified (the Days part) From @Dane answer: https://stackoverflow.com/a/57720/2097023
CREATE FUNCTION dbo.EdadAMD
(
@FECHA DATETIME
)
RETURNS NVARCHAR(10)
AS
BEGIN
DECLARE
@tmpdate DATETIME
, @years INT
, @months INT
, @days INT
, @EdadAMD NVARCHAR(10);
SELECT @tmpdate = @FECHA;
SELECT @years = DATEDIFF(yy, @tmpdate, GETDATE()) - CASE
WHEN (MONTH(@FECHA) > MONTH(GETDATE()))
OR (
MONTH(@FECHA) = MONTH(GETDATE())
AND DAY(@FECHA) > DAY(GETDATE())
) THEN
1
ELSE
0
END;
SELECT @tmpdate = DATEADD(yy, @years, @tmpdate);
SELECT @months = DATEDIFF(m, @tmpdate, GETDATE()) - CASE
WHEN DAY(@FECHA) > DAY(GETDATE()) THEN
1
ELSE
0
END;
SELECT @tmpdate = DATEADD(m, @months, @tmpdate);
IF MONTH(@FECHA) = MONTH(GETDATE())
AND DAY(@FECHA) > DAY(GETDATE())
SELECT @days =
DAY(EOMONTH(GETDATE(), -1)) - (DAY(@FECHA) - DAY(GETDATE()));
ELSE
SELECT @days = DATEDIFF(d, @tmpdate, GETDATE());
SELECT @EdadAMD = CONCAT(@years, 'a', @months, 'm', @days, 'd');
RETURN @EdadAMD;
END;
GO
It works pretty well.
A char in C is already a number (the character's ASCII code), no conversion required.
If you want to convert a digit to the corresponding character, you can simply add '0':
c = i +'0';
The '0' is a character in the ASCll table.
static void InsertSettings(IEnumerable<Entry> settings) {
using (SqlConnection oConnection = new SqlConnection("Data Source=(local);Initial Catalog=Wip;Integrated Security=True")) {
oConnection.Open();
using (SqlTransaction oTransaction = oConnection.BeginTransaction()) {
using (SqlCommand oCommand = oConnection.CreateCommand()) {
oCommand.Transaction = oTransaction;
oCommand.CommandType = CommandType.Text;
oCommand.CommandText = "INSERT INTO [Setting] ([Key], [Value]) VALUES (@key, @value);";
oCommand.Parameters.Add(new SqlParameter("@key", SqlDbType.NChar));
oCommand.Parameters.Add(new SqlParameter("@value", SqlDbType.NChar));
try {
foreach (var oSetting in settings) {
oCommand.Parameters[0].Value = oSetting.Key;
oCommand.Parameters[1].Value = oSetting.Value;
if (oCommand.ExecuteNonQuery() != 1) {
//'handled as needed,
//' but this snippet will throw an exception to force a rollback
throw new InvalidProgramException();
}
}
oTransaction.Commit();
} catch (Exception) {
oTransaction.Rollback();
throw;
}
}
}
}
}
If you are reading that text from a file or from the network.
You can achieve it by adding HTML tags to your text like mentioned
This text is <i>italic</i> and <b>bold</b>
and <u>underlined</u> <b><i><u>bolditalicunderlined</u></b></i>
and then you can use the HTML class that processes HTML strings into displayable styled text.
// textString is the String after you retrieve it from the file
textView.setText(Html.fromHtml(textString));
Folding has been rolled out and is now implemented since Visual Studio Code version 0.10.11. There are these keyboard shortcuts available:
Fold folds the innermost uncollapsed region at the cursor:
Unfold unfolds the collapsed region at the cursor:
Fold All folds all regions in the editor:
Unfold All unfolds all regions in the editor:
References: https://code.visualstudio.com/docs/getstarted/keybindings
Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :
@Mock
private SomeService serviceMock;
private Demo demo;
/* ... */
@BeforeEach
public void beforeEach(){
demo = new Demo(serviceMock);
}
Using Mockito spy
for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks
and @Spy
also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy()
javadoc before using that blindly (emphasis is not mine) :
Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.
As usual you are going to read the
partial mock warning
: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.
it depends on your php settings...
use phpinfo()
and take a look at the session chapter. There are values like session.gc_maxlifetime
and session.cache_expire
and session.cookie_lifetime
which affects the sessions lifetime
EDIT: it's like Martin write before
In this line:
const char* cstr2 = ss.str().c_str();
ss.str()
will make a copy of the contents of the stringstream. When you call c_str()
on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char*
to point to unowned memory.
Not sure if your teacher allows you to use filters but...
filter(lambda x: x.isalpha(), "a1a2a3s3d4f5fg6h")
returns-
'aaasdffgh'
Much more efficient than looping...
Example:
for i in range(10):
a.replace(str(i),'')
sed -i s/$/:80/ file.txt
sed
stream editor
-i
in-place (edit file in place)s
substitution command/replacement_from_reg_exp/replacement_to_text/
statement$
matches the end of line (replacement_from_reg_exp):80
text you want to add at the end of every line (replacement_to_text)file.txt
the file nameUnfortunately, this is not currently possible in the latest version of DataContractJsonSerializer. See: http://connect.microsoft.com/VisualStudio/feedback/details/558686/datacontractjsonserializer-should-serialize-dictionary-k-v-as-a-json-associative-array
The current suggested workaround is to use the JavaScriptSerializer as Mark suggested above.
Good luck!
That's an old question, I know. But, according to me, it is missing proper answer.
The actual / optimal workflow here would be to incorporate SVN's post-commit hook so it triggers Jenkins job after the actual commit is issued only, not in any other case. This way you avoid unneeded polls on your SCM system.
You may find the following links interesting:
In case of my setup in the corp's SVN server, I utilize the following (censored) script as a post-commit hook on the subversion server side:
#!/bin/sh
# POST-COMMIT HOOK
REPOS="$1"
REV="$2"
#TXN_NAME="$3"
LOGFILE=/var/log/xxx/svn/xxx.post-commit.log
MSG=$(svnlook pg --revprop $REPOS svn:log -r$REV)
JENK="http://jenkins.xxx.com:8080/job/xxx/job/xxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
JENKtest="http://jenkins.xxx.com:8080/view/all/job/xxx/job/xxxx/buildWithParameters?token=xxx&username=xxx&cause=xxx+r$REV"
echo post-commit $* >> $LOGFILE 2>&1
# trigger Jenkins job - xxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx/xxx/Source"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx/xxx/Source" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENK >> $LOGFILE 2>&1
curl -qs $JENK >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
# trigger Jenkins job - xxxx
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -qP "branches/xxx_TEST"
if test 0 -eq $? ; then
echo $(date) - $REPOS - $REV: >> $LOGFILE
svnlook changed $REPOS -r $REV | cut -d' ' -f4 | grep -P "branches/xxx_TEST" >> $LOGFILE 2>&1
echo logmsg: $MSG >> $LOGFILE 2>&1
echo curl -qs $JENKtest >> $LOGFILE 2>&1
curl -qs $JENKtest >> $LOGFILE 2>&1
echo -------- >> $LOGFILE
fi
exit 0
For symfony 2.6 and above we can use
{{ app.user.getFirstname() }}
as app.security global variable for Twig template has been deprecated and will be removed from 3.0
more info:
http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements
and see the global variables in
http://symfony.com/doc/current/reference/twig_reference.html
Just use the below formation###
rules_id = ["9","10"]
sql2 = "SELECT * FROM attendance_rules_staff WHERE id in"+str(tuple(rules_id))
note the str(tuple(rules_id))
.
#!/bin/sh
wc -m $1 | awk '{print $1}'
wc -m
counts the number of characters; the awk
command prints the number of characters only, omitting the filename.
wc -c
would give you the number of bytes (which can be different to the number of characters, as depending on the encoding you may have a character encoded on several bytes).
The "ARM EABI v7a System Image" must be available. Install it via the Android SDK manager:
Another hint (see here) - with
you are able to turn on GPU emulation to get a faster emulator:
Note : As per you786 comment if you have previously created emulator then you need to recreate it, otherwise this will not work.
Alternative 1
Intel provides the "Intel hardware accelerated execution manager", which is a VM based emulator for executing X86 images and which is also served by the Android SDK Manager. See a tutorial for the Intel emulator here: HAXM Speeds Up the Android Emulator. Roman Nurik posts here that the Intel emulator with Android 4.3 is "blazing fast".
Alternative 2
In the comments of the post above you can find a reference to Genymotion which claims to be the "fastest Android emulator for app testing and presentation". Genymotion runs on VirtualBox. See also their site on Google+, this post from Cyril Mottier and this guide on reddit.
Alternative 3
In XDA-Forums I read about MEmu - Most Powerful Android Emulator for PC, Better Than Bluestacks. You can find the emulator here. This brings me to ...
Alternative 4
... this XDA-Forum entry: How to use THE FAST! BlueStack as your alternate Android development emulator. You can find the emulator here.
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe"
.Paste the value into Location of the item, and append --kiosk <your url>
:
"C:\Users\zero\AppData\Local\Google\Chrome\Application\chrome.exe" --kiosk http://www.google.com
Press Apply, then OK.
long
can only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float
the value before calling the long
. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int
to provide the key as well.
So, the answer is long(float('234.89'))
or it could just be int(float('234.89'))
if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int
You can escape (this is how this principle is called) the double quotes by prefixing them with another double quote. You can put them in a string as follows:
Dim MyVar as string = "some text ""hello"" "
This will give the MyVar
variable a value of some text "hello"
.
I had this issue with a specific application and not the entire IIS site. In my case, access to the application directory was not the problem. Instead, I needed to give the application pool a recycle.
I think this was related to how the application was deployed and the IIS settings were set (done via scripts and a deployment agent).
your jump link looks like this
<a href="#div_id">jump link</a>
Then make
<div id="div_id"></div>
the jump link will take you to that div
I've written a complement to the accepted answer. In case someone, like myself need a prefixed version of the keys, this can be helpful.
Array
(
[root] => Array
(
[url] => http://localhost/misc/markia
)
)
Array
(
[root.url] => http://localhost/misc/markia
)
<?php
function flattenOptions($array, $old = '') {
if (!is_array($array)) {
return FALSE;
}
$result = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$result = array_merge($result, flattenOptions($value, $key));
}
else {
$result[$old . '.' . $key] = $value;
}
}
return $result;
}
Remy Sharp has a good description of the process in his article "Doing it right: skipping the iPhone url bar":
Making the iPhone hide the url bar is fairly simple, you need run the following JavaScript:
window.scrollTo(0, 1);
However there's the question of when? You have to do this once the height is correct so that the iPhone can scroll to the first pixel of the document, otherwise it will try, then the height will load forcing the url bar back in to view.
You could wait until the images have loaded and the window.onload event fires, but this doesn't always work, if everything is cached, the event fires too early and the scrollTo never has a chance to jump. Here's an example using window.onload: http://jsbin.com/edifu4/4/
I personally use a timer for 1 second - which is enough time on a mobile device while you wait to render, but long enough that it doesn't fire too early:
setTimeout(function () { window.scrollTo(0, 1); }, 1000);
However, you only want this to setup if it's an iPhone (or just mobile) browser, so a sneaky sniff (I don't generally encourage this, but I'm comfortable with this to prevent "normal" desktop browsers from jumping one pixel):
/mobile/i.test(navigator.userAgent) && setTimeout(function () { window.scrollTo(0, 1); }, 1000);
The very last part of this, and this is the part that seems to be missing from some examples I've seen around the web is this: if the user specifically linked to a url fragment, i.e. the url has a hash on it, you don't want to jump. So if I navigate to http://full-frontal.org/tickets#dayconf - I want the browser to scroll naturally to the element whose id is dayconf, and not jump to the top using scrollTo(0, 1):
/mobile/i.test(navigator.userAgent) && !location.hash && setTimeout(function () { window.scrollTo(0, 1); }, 1000);?
Try this out on an iPhone (or simulator) http://jsbin.com/edifu4/10 and you'll see it will only scroll when you've landed on the page without a url fragment.
System.setProperty("javax.net.ssl.trustStore", path_to_your_jks_file);
validate
: It validates the schema and makes no changes to the DB.
Assume you have added a new column in the mapping file and perform the insert operation, it will throw an Exception "missing the XYZ column" because the existing schema is different than the object you are going to insert. If you alter the table by adding that new column manually then perform the Insert operation then it will definitely insert all columns along with the new column to the Table.
Means it doesn't make any changes/alters the existing schema/table.
update
: it alters the existing table in the database when you perform operation.
You can add or remove columns with this option of hbm2ddl.
But if you are going to add a new column that is 'NOT NULL' then it will ignore adding that particular column to the DB. Because the Table must be empty if you want to add a 'NOT NULL' column to the existing table.
As Sotirios Delimanolis already pointed out in the comments, there are two options:
ResponseEntity
with error messageChange your method like this:
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity getUser(@RequestHeader(value="Access-key") String accessKey,
@RequestHeader(value="Secret-key") String secretKey) {
try {
// see note 1
return ResponseEntity
.status(HttpStatus.CREATED)
.body(this.userService.chkCredentials(accessKey, secretKey, timestamp));
}
catch(ChekingCredentialsFailedException e) {
e.printStackTrace(); // see note 2
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note 1: You don't have to use the ResponseEntity
builder but I find it helps with keeping the code readable. It also helps remembering, which data a response for a specific HTTP status code should include. For example, a response with the status code 201 should contain a link to the newly created resource in the Location
header (see Status Code Definitions). This is why Spring offers the convenient build method ResponseEntity.created(URI)
.
Note 2: Don't use printStackTrace()
, use a logger instead.
@ExceptionHandler
Remove the try-catch block from your method and let it throw the exception. Then create another method in a class annotated with @ControllerAdvice
like this:
@ControllerAdvice
public class ExceptionHandlerAdvice {
@ExceptionHandler(ChekingCredentialsFailedException.class)
public ResponseEntity handleException(ChekingCredentialsFailedException e) {
// log exception
return ResponseEntity
.status(HttpStatus.FORBIDDEN)
.body("Error Message");
}
}
Note that methods which are annotated with @ExceptionHandler
are allowed to have very flexible signatures. See the Javadoc for details.
You should use the *ngIf Directive
<div *ngIf="edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
(...)
public edited = false;
(...)
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
Update: you are missing the reference to the outer scope when you are inside the Timeout callback.
so add the .bind(this) like I added Above
Q : edited is a global variable. What would be your approach within a *ngFor-loop? – Blauhirn
A : I would add edit as a property to the object I am iterating over.
<div *ngFor="let obj of listOfObjects" *ngIf="obj.edited" class="alert alert-success box-msg" role="alert">
<strong>List Saved!</strong> Your changes has been saved.
</div>
export class AppComponent implements OnInit{
public listOfObjects = [
{
name : 'obj - 1',
edit : false
},
{
name : 'obj - 2',
edit : false
},
{
name : 'obj - 2',
edit : false
}
];
saveTodos(): void {
//show box msg
this.edited = true;
//wait 3 Seconds and hide
setTimeout(function() {
this.edited = false;
console.log(this.edited);
}.bind(this), 3000);
}
}
AFAIK all you can do is omit the returns to make things more compact in C++:
switch(Answer)
{
case 1: case 2: case 3: case 4:
cout << "You need more cars.";
break;
...
}
(You could remove the other returns as well, of course.)
You can simply create a controller funciton and pass your parameters with the $scope object.
$scope.Edit = function (modalParam) {
var modalInstance = $modal.open({
templateUrl: '/app/views/admin/addeditphone.html',
controller: function($scope) {
$scope.modalParam = modalParam;
}
});
}
Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.
const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class array_test {
public static void main(String args[]) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = br.readLine();
String[] s_array = line.split(" ");
/* Splitting the array of number separated by space into string array.*/
Integer [] a = new Integer[s_array.length];
/Creating the int array of size equals to string array./
for(int i =0; i<a.length;i++)
{
a[i]= Integer.parseInt(s_array[i]);// Parsing from string to int
System.out.println(a[i]);
}
// your integer array is ready to use.
}
}
Here is an easy to understand solution
import numpy as np
import pandas as pd
# Creating a 2 dimensional numpy array
>>> data = np.array([[5.8, 2.8], [6.0, 2.2]])
>>> print(data)
>>> data
array([[5.8, 2.8],
[6. , 2.2]])
# Creating pandas dataframe from numpy array
>>> dataset = pd.DataFrame({'Column1': data[:, 0], 'Column2': data[:, 1]})
>>> print(dataset)
Column1 Column2
0 5.8 2.8
1 6.0 2.2
sudo apt-get install php-pear php7.x-dev
x is your php version like 7.2 the php7.2-dev
apt-get install libmcrypt-dev libreadline-dev
pecl install mcrypt-1.0.1
then add "extension=mcrypt.so" in "/etc/php/7.2/apache2/php.ini"
here php.ini is depends on your php installatio and apache used php version.
For other users getting this problem.
You may get this error if you are running a newer ElasticSearch (5.5 or later) while running Spring Boot <2 version.
Recommendation is to use the REST Client since the Java Client will be deprecated.
Other workaround would be to upgrade to Spring Boot 2, since that should be compatible.
See https://discuss.elastic.co/t/spring-data-elasticsearch-cant-connect-with-elasticsearch-5-5-0/94235 for more information.
Do it the vi way.
To delete 5 lines press: 5dd
( 5 delete )
To select ( actually copy them to the clipboard ) you type: 10yy
It is a bit hard to grasp, but very handy to learn when using those remote terminals
Be aware of the learning curves for some editors:
(source: calver at unix.rulez.org)
You have to copy the bits over a new image with the target resolution, like this:
using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
{
using (Bitmap newBitmap = new Bitmap(bitmap))
{
newBitmap.SetResolution(300, 300);
newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
}
}
You could average the RGB values of random colors with those of a constant color:
(example in Java)
public Color generateRandomColor(Color mix) {
Random random = new Random();
int red = random.nextInt(256);
int green = random.nextInt(256);
int blue = random.nextInt(256);
// mix the color
if (mix != null) {
red = (red + mix.getRed()) / 2;
green = (green + mix.getGreen()) / 2;
blue = (blue + mix.getBlue()) / 2;
}
Color color = new Color(red, green, blue);
return color;
}
Mixing random colors with white (255, 255, 255) creates neutral pastels by increasing the lightness while keeping the hue of the original color. These randomly generated pastels usually go well together, especially in large numbers.
Here are some pastel colors generated using the above method:
You could also mix the random color with a constant pastel, which results in a tinted set of neutral colors. For example, using a light blue creates colors like these:
Going further, you could add heuristics to your generator that take into account complementary colors or levels of shading, but it all depends on the impression you want to achieve with your random colors.
Some additional resources:
arrayList.set(location,newValue); location= where u wnna insert, newValue= new element you are inserting.
notify is optional, depends on conditions.
I was having a similar problem trying to install a package called AED. I tried using the install.packages() command:
install.packages('FILE_PATH', repos=NULL, type = "source")
but kept getting the following warning message:
Warning message:
In install.packages("/Users/blahblah/R-2.14.0/AED", :
installation of package ‘/Users/blahblah/R-2.14.0/AED’ had
non-zero exit status
It turned out the folder 'AED' had another folder inside of it that hadn't been uncompressed. I just uncompressed it and tried installing the package again and it worked.
According to https://git-scm.com/docs/git-log, for more pretty output in console you can use --decorate argument of git-log command:
git log --pretty=oneline --decorate
will print:
2a5ccd714972552064746e0fb9a7aed747e483c7 (HEAD -> master) New commit
fe00287269b07e2e44f25095748b86c5fc50a3ef (tag: v1.1-01) Commit 3
08ed8cceb27f4f5e5a168831d20a9d2fa5c91d8b (tag: v1.1, tag: v1.0-0.1) commit 1
116340f24354497af488fd63f4f5ad6286e176fc (tag: v1.0) second
52c1cdcb1988d638ec9e05a291e137912b56b3af test
For windows
Install anaconda-clean module using
conda install anaconda-clean
then, run the following command to delete files step by step:
anaconda-clean
Or, just run following command to delete them all-
anaconda-clean --yes
After this Open Control Panel> Programs> Uninstall Program, here uninstall that python for which publisher is Anaconda.
Now, you can remove anaconda/scripts and /anaconda/ from PATH variable.
Hope, it helps.
I have several library projects with the same package name specified in the AndroidManifest (so no duplicate field names are generated by R.java). I had to remove any permissions and activities from the AndroidManifest.xml for all library projects to remove the error so Manifest.java wasn't created multiple times. Hopefully this can help someone.
you can also use
$result = curl_exec($ch);
return response()->json(json_decode($result));
If your dates
column does not contain time information, you could get away with:
WHERE dates BETWEEN '20121211' and '20121213'
However, given your dates
column is actually datetime, you want this
WHERE dates >= '20121211'
AND dates < '20121214' -- i.e. 00:00 of the next day
Another option for SQL Server 2008 onwards that retains SARGability (ability to use index for good performance) is:
WHERE CAST(dates as date) BETWEEN '20121211' and '20121213'
Note: always use ISO-8601 format YYYYMMDD with SQL Server for unambiguous date literals.
You may use the class java.util.Random with method
char c = (char)(rnd.nextInt(128-32))+32
20x to get Bytes, which you interpret as ASCII. If you're fine with ASCII.
32 is the offset, from where the characters are printable in general.
As per Link: http://bavotasan.com/2011/style-select-box-using-only-css/ there are lot of extra rework that needs to be done(Put extra div and position the image there. Also the design will break as the option drilldown will be mis alligned to the the select.
Here is an easy and simple way which will allow you to put your own dropdown image and remove the browser default dropdown.(Without using any extra div). Its cross browser as well.
HTML
<select class="dropdown" name="drop-down">
<option value="select-option">Please select...</option>
<option value="Local-Community-Enquiry">Option 1</option>
<option value="Bag-Packing-in-Store">Option 2</option>
</select>
CSS
select.dropdown {
margin: 0px;
margin-top: 12px;
height: 48px;
width: 100%;
border-width: 1px;
border-style: solid;
border-color: #666666;
padding: 9px;
font-family: tescoregular;
font-size: 16px;
color: #666666;
-webkit-appearance: none;
-webkit-border-radius: 0px;
-moz-appearance: none;
appearance: none;
background: url('yoururl/dropdown.png') no-repeat 97% 50% #ffffff;
background-size: 11px 7px;
}
Suppose you have TextBox with Id txtName
$("[id*=txtName]").on('keydown', function(e) {
var keyCode = e.keyCode || e.which;
if (keyCode == 9) {
e.preventDefault();
alert('Tab Pressed');
}
});
for you objects override clone() method
class You_class {
int a;
@Override
public You_class clone() {
You_class you_class = new You_class();
you_class.a = this.a;
return you_class;
}
}
and call .clone() for Vector obj or ArraiList obj....
Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
Adam explain well in his answer But I used this way. I think this is easiest way to understand time comparison in java
First create 3 calender object with set your time only , Hour and min.
then get GMT milliseconds of that time and simply compare.
Ex.
Calendar chechDateTime = Calendar.getInstance();
chechDateTime.set(Calendar.MILLISECOND, 0);
chechDateTime.set(Calendar.SECOND, 0);
chechDateTime.set(Calendar.HOUR, 11);
chechDateTime.set(Calendar.MINUTE, 22);
Calendar startDateTime = Calendar.getInstance();
startDateTime.set(Calendar.MILLISECOND, 0);
startDateTime.set(Calendar.SECOND, 0);
startDateTime.set(Calendar.HOUR, 10);
startDateTime.set(Calendar.MINUTE, 0);
Calendar endDateTime = Calendar.getInstance();
endDateTime.set(Calendar.MILLISECOND, 0);
endDateTime.set(Calendar.SECOND, 0);
endDateTime.set(Calendar.HOUR, 18);
endDateTime.set(Calendar.MINUTE, 22);
long chechDateTimeMilliseconds=chechDateTime.getTime().getTime();
long startDateTimeMilliseconds=startDateTime.getTime().getTime();
long endDateTimeMilliseconds=endDateTime.getTime().getTime();
System.out.println("chechDateTime : "+chechDateTimeMilliseconds);
System.out.println("startDateTime "+startDateTimeMilliseconds);
System.out.println("endDateTime "+endDateTimeMilliseconds);
if(chechDateTimeMilliseconds>=startDateTimeMilliseconds && chechDateTimeMilliseconds <= endDateTimeMilliseconds ){
System.out.println("In between ");
}else{
System.out.println("Not In between ");
}
Output will look like this :
chechDateTime : 1397238720000
startDateTime 1397233800000
endDateTime 1397263920000
In between
This issue can be solved using MediaQuery.of(context)
To get Screen width: MediaQuery.of(context).size.width
To get Screen height: MediaQuery.of(context).size.height
For more information about MediaQuery Widget watch, https://www.youtube.com/watch?v=A3WrA4zAaPw
function extractSummary(iCalContent) {
var rx = /\nSUMMARY:(.*)\n/g;
var arr = rx.exec(iCalContent);
return arr[1];
}
You need these changes:
Put the *
inside the parenthesis as
suggested above. Otherwise your matching
group will contain only one
character.
Get rid of the ^
and $
. With the global option they match on start and end of the full string, rather than on start and end of lines. Match on explicit newlines instead.
I suppose you want the matching group (what's
inside the parenthesis) rather than
the full array? arr[0]
is
the full match ("\nSUMMARY:..."
) and
the next indexes contain the group
matches.
String.match(regexp) is supposed to return an array with the matches. In my browser it doesn't (Safari on Mac returns only the full match, not the groups), but Regexp.exec(string) works.
trick that works for me when target device not found:
click the "attach debugger to android process" button. (that will enable adb integration for you)
click the run button
As noted in another answer, the official word from Microsoft is to open an Access 97 file in Access 2003 and upgrade it to a newer file format. Unfortunately, from now on many people will have difficulty getting their hands on a legitimate copy of Access 2003 (or any other version prior to Access 2013, or whatever the latest version happens to be).
In that case, a possible workaround would be to
I just tried that with a 32-bit version of SQL Server 2008 R2 Express Edition and it worked for me. Access 2013 adamantly refused to have anything to do with the Access 97 file, but SQL Server imported the tables without complaint.
At that point you could import the tables from SQL Server into an Access 2013 database. Or, if your goal was simply to get the data out of the Access 97 file then you could continue to work with it in SQL Server, or move it to some other platform, or whatever.
*Important: The import needs to be done using the older Jet ODBC driver ...
Microsoft Access Driver (*.mdb)
... which ships with Windows but is only available to 32-bit applications. The Access 2013 version of the newer Access Database Engine ("ACE") ODBC driver ...
Microsoft Access Driver (*.mdb, *.accdb)
also refuses to read Access 97 files (with the same error message cited in the question).
So I follow first answer, but my vnc viewer gives me grey screen when I connect to it. And I found this Ask Ubuntu link to solve that.
The only difference with previous answer is you need to install these extra packages:
apt-get install gnome-panel gnome-settings-daemon metacity nautilus gnome-terminal
And use this ~/.vnc/xstartup file:
#!/bin/sh
export XKL_XMODMAP_DISABLE=1
unset SESSION_MANAGER
unset DBUS_SESSION_BUS_ADDRESS
[ -x /etc/vnc/xstartup ] && exec /etc/vnc/xstartup
[ -r $HOME/.Xresources ] && xrdb $HOME/.Xresources
xsetroot -solid grey
vncconfig -iconic &
gnome-panel &
gnome-settings-daemon &
metacity &
nautilus &
gnome-terminal &
Everything else is the same.
Tested on EC2 Ubuntu 14.04 LTS.
If you can make an image on Photoshop where the main layer has an opacity of 1 or so and is basically transparent, put that img in the div and then make the real picture the background image. THEN set the opacity of the img to 1 and add the size dimensions you want.
That picture is done that way, and you can't even drag the invisible image off the page which is cool.
I think you can do this:
var client = new HttpClient();
HttpContent content = new Widget();
client.PostAsync<Widget>("http://localhost:44268/api/test", content, new FormUrlEncodedMediaTypeFormatter())
.ContinueWith((postTask) => { postTask.Result.EnsureSuccessStatusCode(); });
I had the same problem with a file that I've created on my mac. If I try to run it in a shell with ./filename I got the file not found error message. I think that something was wrong with the file.
what I've done:
open a ssh session to the server
cat filename
copy the output to the clipboard
rm filename
touch filename
vi filename
i for insert mode
paste the content from the clipboard
ESC to end insert mode
:wq!
This worked for me.
I think, that in this case using PYTHONPATH is a better thing, mostly because it doesn't introduce (questionable) unneccessary code.
After all, if you think of it, your user doesn't need that sys.path
thing, because your package will get installed into site-packages, because you will be using a packaging system.
If the user chooses to run from a "local copy", as you call it, then I've observed, that the usual practice is to state, that the package needs to be added to PYTHONPATH manually, if used outside the site-packages.
Mid(strYourString, 4)
(i.e. without the optional length argument) will return the substring starting from the 4th character and going to the end of the string.
Because you can only deactivate the active environment, so conda deactivate does not need nor accept arguments. The error message is very explicit here.
Just call conda deactivate https://github.com/conda/conda/issues/7296#issuecomment-389504269
If you need a CakePHP Docker Container with MySQL, I have created a Docker image for that purpose! No need to worry about setting it up. It just works!
Here's how I installed in Ubuntu-based image:
https://github.com/marcellodesales/php-apache-mysql-4-cakephp-docker/blob/master/Dockerfile#L8
RUN docker-php-ext-install mysql mysqli pdo pdo_mysql
Building and running your application is just a 2 step process (considering you are in the current directory of the app):
$ docker build -t myCakePhpApp .
$ docker run -ti myCakePhpApp
The problem is: adb
is not in your PATH
. This is where the shell looks for executables. You can check your current PATH
with echo $PATH
.
Bash will first try to look for a binary called adb
in your Path, and not in the current directory. Therefore, if you are currently in the platform-tools
directory, just call
./adb --help
The dot is your current directory, and this tells Bash to use adb
from there.
But actually, you should add platform-tools
to your PATH
, as well as some other tools that the Android SDK comes with. This is how you do it:
Find out where you installed the Android SDK. This might be (where $HOME
is your user's home directory) one of the following (or verify via Configure > SDK Manager in the Android Studio startup screen):
$HOME/Android/Sdk
$HOME/Library/Android/sdk
Find out which shell profile to edit, depending on which file is used:
$HOME/.bashrc
$HOME/.bash_profile
$HOME/.zshrc
Open the shell profile from step two, and at the bottom of the file, add the following lines. Make sure to replace the path with the one where you installed platform-tools
if it differs:
export ANDROID_HOME="$HOME/Android/Sdk"
export PATH="$ANDROID_HOME/tools:$ANDROID_HOME/tools/bin:$ANDROID_HOME/platform-tools:$PATH"
Save the profile file, then, re-start the terminal or run source ~/.bashrc
(or whatever you just modified).
Note that setting ANDROID_HOME
is required for some third party frameworks, so it does not hurt to add it.
The main reason you use the default queue over the main queue is to run tasks in the background.
For instance, if I am downloading a file from the internet and I want to update the user on the progress of the download, I will run the download in the priority default queue and update the UI in the main queue asynchronously.
dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void){
//Background Thread
dispatch_async(dispatch_get_main_queue(), ^(void){
//Run UI Updates
});
});
super()
lets you avoid referring to the base class explicitly, which can be nice. But the main advantage comes with multiple inheritance, where all sorts of fun stuff can happen. See the standard docs on super if you haven't already.
Note that the syntax changed in Python 3.0: you can just say super().__init__()
instead of super(ChildB, self).__init__()
which IMO is quite a bit nicer. The standard docs also refer to a guide to using super()
which is quite explanatory.
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()
You can also use:
fig, ax = plt.subplots(figsize=(20, 10))
The best source of information is the official Python tutorial on list comprehensions. List comprehensions are nearly the same as for loops (certainly any list comprehension can be written as a for-loop) but they are often faster than using a for loop.
Look at this longer list comprehension from the tutorial (the if
part filters the comprehension, only parts that pass the if statement are passed into the final part of the list comprehension (here (x,y)
):
>>> [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
It's exactly the same as this nested for loop (and, as the tutorial says, note how the order of for and if are the same).
>>> combs = []
>>> for x in [1,2,3]:
... for y in [3,1,4]:
... if x != y:
... combs.append((x, y))
...
>>> combs
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
The major difference between a list comprehension and a for loop is that the final part of the for loop (where you do something) comes at the beginning rather than at the end.
On to your questions:
What type must object be in order to use this for loop structure?
An iterable. Any object that can generate a (finite) set of elements. These include any container, lists, sets, generators, etc.
What is the order in which i and j are assigned to elements in object?
They are assigned in exactly the same order as they are generated from each list, as if they were in a nested for loop (for your first comprehension you'd get 1 element for i, then every value from j, 2nd element into i, then every value from j, etc.)
Can it be simulated by a different for loop structure?
Yes, already shown above.
Can this for loop be nested with a similar or different structure for loop? And how would it look?
Sure, but it's not a great idea. Here, for example, gives you a list of lists of characters:
[[ch for ch in word] for word in ("apple", "banana", "pear", "the", "hello")]
After struggling a lot while creating a low level utility to handle the post and get requests for my project, I decided to post my effort here. Much on the lines of accepted answer, here is a snippet for making http and https POST requests for sending JSON data.
const http = require("http")
const https = require("https")
// Request handler function
let postJSON = (options, postData, callback) => {
// Serializing JSON
post_data = JSON.stringify(postData)
let port = options.port == 443 ? https : http
// Callback function for the request
let req = port.request(options, (res) => {
let output = ''
res.setEncoding('utf8')
// Listener to receive data
res.on('data', (chunk) => {
output += chunk
});
// Listener for intializing callback after receiving complete response
res.on('end', () => {
let obj = JSON.parse(output)
callback(res.statusCode, obj)
});
});
// Handle any errors occurred while making request
req.on('error', (err) => {
//res.send('error: ' + err.message)
});
// Request is made here, with data as string or buffer
req.write(post_data)
// Ending the request
req.end()
};
let callPost = () => {
let data = {
'name': 'Jon',
'message': 'hello, world'
}
let options = {
host: 'domain.name', // Your domain name
port: 443, // 443 for https and 80 for http
path: '/path/to/resource', // Path for the request
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data)
}
}
postJSON(options, data, (statusCode, result) => {
// Handle response
// Process the received data
});
}
None of the above changes worked for me. Please see my worked configuration below:
Dependencies:
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxrs</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-rs-extension-providers</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-jaxrs</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jettison</groupId>
<artifactId>jettison</artifactId>
<version>1.4.0</version>
</dependency>
web.xml:
<servlet>
<servlet-name>cfxServlet</servlet-name>
<servlet-class>org.apache.cxf.jaxrs.servlet.CXFNonSpringJaxrsServlet</servlet-class>
<init-param>
<param-name>javax.ws.rs.Application</param-name>
<param-value>com.MyApplication</param-value>
</init-param>
<init-param>
<param-name>jaxrs.providers</param-name>
<param-value>org.codehaus.jackson.jaxrs.JacksonJsonProvider</param-value>
</init-param>
<init-param>
<param-name>jaxrs.extensions</param-name>
<param-value>
json=application/json
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>cfxServlet</servlet-name>
<url-pattern>/v1/*</url-pattern>
</servlet-mapping>
Enjoy coding .. :)
Check - JS Fiddle
HTML
<div id="myDiv">
<button class="btn btn-large btn-danger" data-toggle="tooltip" data-placement="top" title="" data-original-title="Tooltip on top">Tooltip on top</button>
</div>
Javascript
$(function () {
$("[data-toggle='tooltip']").tooltip();
});
You can do it by
git archive --format=tar --remote=origin HEAD | tar xf -
git archive --format=tar --remote=origin HEAD <file> | tar xf -
Sample code to change an image into a byte array
public byte[] ImageToByteArray(System.Drawing.Image imageIn)
{
using (var ms = new MemoryStream())
{
imageIn.Save(ms,imageIn.RawFormat);
return ms.ToArray();
}
}
C# Image to Byte Array and Byte Array to Image Converter Class
SIGINT can be send to program using windows-kill, by syntax windows-kill -SIGINT PID
, where PID
can be obtained by Microsoft's pslist.
Regarding catching SIGINTs, if your program is in Python then you can implement SIGINT processing/catching like in this solution.
Copy problematic folder into some backup directory and remove it from your SVN working directory. Remember to delete all .svn
hidden directories from the copied folder.
Now update your project, clean-up and commit what has left. Now move your folder back to working directory, add it and commit. Most of the time this workaround works, it seems that basically SVN got confused...
Update: quoting comment by @Mark:
Didn't need to move the folder around, just deleting the
.svn
folder and then svn-adding it worked.
I haven't tried it yet, but pyiso8601 promises to support this.
Two maps. One Map<K1, V>
and one Map<K2, V>
. If you must have a single interface, write a wrapper class that implements said methods.
Here's another case where raw types will bite you:
public class StrangeClass<T> {
@SuppressWarnings("unchecked")
public <X> X getSomethingElse() {
return (X)"Testing something else!";
}
public static void main(String[] args) {
final StrangeClass<String> withGeneric = new StrangeClass<>();
final StrangeClass withoutGeneric = new StrangeClass();
final String value1,
value2;
// Compiles
value1 = withGeneric.getSomethingElse();
// Produces compile error:
// incompatible types: java.lang.Object cannot be converted to java.lang.String
value2 = withoutGeneric.getSomethingElse();
}
}
This is counter-intuitive because you'd expect the raw type to only affect methods bound to the class type parameter, but it actually also affects generic methods with their own type parameters.
As was mentioned in the accepted answer, you lose all support for generics within the code of the raw type. Every type parameter is converted to its erasure (which in the above example is just Object
).
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}
I was also looking for the relative path version, this works OK. Note when run (Spyder 3.6) you will see (unicode error) 'unicodeescape' codec can't decode bytes at the closing triple quote. Remove the offending comment lines 14 and 15 and adjust the file names and location for your environment and check for indentation.
""" Created on Fri Jan 24 12:12:40 2020
Source: Read a .csv into pandas from F: drive on Windows 7
Demonstrates: Load a csv not in the CWD by specifying relative path - windows version
@author: Doug
From CWD C:\Users\Doug\.spyder-py3\Data Camp\pandas
we will load file
C:/Users/Doug/.spyder-py3/Data Camp/Cleaning/g1803.csv
"""
import csv
trainData2 = []
with open(r'../Cleaning/g1803.csv', 'r') as train2Csv:
trainReader2 = csv.reader(train2Csv, delimiter=',', quotechar='"')
for row in trainReader2:
trainData2.append(row)
print(trainData2)
Well, we have few good answers here for resizing image, but I just modify as per my need. hope this help someone like me.
My Requirement was
if (originalImage.size.width > 1920)
{
CGSize newSize;
newSize.width = 1920;
newSize.height = (1920 * originalImage.size.height) / originalImage.size.width;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
if (originalImage.size.height > 1080)
{
CGSize newSize;
newSize.width = (1080 * originalImage.size.width) / originalImage.size.height;
newSize.height = 1080;
originalImage = [ProfileEditExperienceViewController imageWithImage:originalImage scaledToSize:newSize];
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
Thanks to @Srikar Appal , for resizing I have used his method.
You may like to check this as well for resize calculation.
I'm using PhoneGap Build (v3.4.0), with focus on iOS, and I needed to have this entry in my config.xml for PhoneGap to recognize the InAppBrowser plug-in.
<gap:plugin name="org.apache.cordova.inappbrowser" />
After that, using window.open(url, target) should work as expected, as documented here.
I'm trying to learn closures and I think the example that I have created is a practical use case. You can run a snippet and see the result in the console.
We have two separate users who have separate data. Each of them can see the actual state and update it.
function createUserWarningData(user) {
const data = {
name: user,
numberOfWarnings: 0,
};
function addWarning() {
data.numberOfWarnings = data.numberOfWarnings + 1;
}
function getUserData() {
console.log(data);
return data;
}
return {
getUserData: getUserData,
addWarning: addWarning,
};
}
const user1 = createUserWarningData("Thomas");
const user2 = createUserWarningData("Alex");
//USER 1
user1.getUserData(); // Returning data user object
user1.addWarning(); // Add one warning to specific user
user1.getUserData(); // Returning data user object
//USER2
user2.getUserData(); // Returning data user object
user2.addWarning(); // Add one warning to specific user
user2.addWarning(); // Add one warning to specific user
user2.getUserData(); // Returning data user object
_x000D_
You can also use this syntax: (in column D to concatenate A, B, and C)
=A2 & " """ & B2 & """ " & C2
This post already has a checked answer, but the answer doesn't filter for null values. The correct answer should prevent null values by using the Object::nonNull function as a predicate.
BigDecimal result = invoiceList.stream()
.map(Invoice::total)
.filter(Objects::nonNull)
.filter(i -> (i.getUnit_price() != null) && (i.getQuantity != null))
.reduce(BigDecimal.ZERO, BigDecimal::add);
This prevents null values from attempting to be summed as we reduce.
My fix is more simple, create a factory, and implement as one variable. For example
angular.module('myApp', [])_x000D_
_x000D_
// This a searchCustom factory. Copy the factory and implement in the controller_x000D_
.factory("searchCustom", function($http,$log){ _x000D_
return {_x000D_
valuesParams : function(params){_x000D_
paramsResult = [];_x000D_
params = params.replace('(', '').replace(')','').split("&");_x000D_
_x000D_
for(x in params){_x000D_
paramsKeyTmp = params[x].split("=");_x000D_
_x000D_
// Si el parametro esta disponible anexamos al vector paramResult_x000D_
if (paramsKeyTmp[1] !== '' && paramsKeyTmp[1] !== ' ' && _x000D_
paramsKeyTmp[1] !== null){ _x000D_
_x000D_
paramsResult.push(params[x]);_x000D_
}_x000D_
}_x000D_
_x000D_
return paramsResult;_x000D_
}_x000D_
}_x000D_
})_x000D_
_x000D_
.controller("SearchController", function($scope, $http,$routeParams,$log,searchCustom){_x000D_
$ctrl = this;_x000D_
_x000D_
var valueParams = searchCustom.valuesParams($routeParams.value);_x000D_
valueParams = valueParams.join('&');_x000D_
_x000D_
$http({_x000D_
method : "GET",_x000D_
url: webservice+"q?"+valueParams_x000D_
}).then( function successCallback(response){_x000D_
data = response.data;_x000D_
$scope.cantEncontrados = data.length; _x000D_
$scope.dataSearch = data;_x000D_
_x000D_
} , function errorCallback(response){_x000D_
console.log(response.statusText);_x000D_
})_x000D_
_x000D_
})
_x000D_
<html>_x000D_
<head>_x000D_
</head>_x000D_
<body ng-app="myApp">_x000D_
<div ng-controller="SearchController">_x000D_
<form action="#" >_x000D_
_x000D_
_x000D_
<input ng-model="param1" _x000D_
placeholder="param1" />_x000D_
_x000D_
<input ng-model="param2" _x000D_
placeholder="param2"/>_x000D_
_x000D_
<!-- Implement in the html code _x000D_
(param1={{param1}}¶m2={{param2}}) -> this is a one variable, the factory searchCustom split and restructure in the array params_x000D_
--> _x000D_
<a href="#seach/(param1={{param1}}¶m2={{param2}})">_x000D_
<buttom ng-click="searchData()" >Busqueda</buttom>_x000D_
</a>_x000D_
</form> _x000D_
</div>_x000D_
</body>
_x000D_
I'm not sure how far it will get you, but you can execute JavaScript one line at a time from the Developer Tool Console.
According to mzabriskie on GitHub:
Overall they are very similar. Some benefits of axios:
Transformers: allow performing transforms on data before a request is made or after a response is received
Interceptors: allow you to alter the request or response entirely (headers as well). also, perform async operations before a request is made or before Promise settles
Built-in XSRF protection
please check Browser Support Axios
I think you should use axios.
If you're talking about bitwise operators, then you're after:
~ Not
^ XOR
| Or
& And
Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.
Here are more than 30 answers and a lot of answers are helpful. But I want to share a generalized form for the System.Windows.Forms.TextBox and System.Windows.Controls.TextBox.
There is not available KeyPress event in System.Windows.Controls.TextBox. This answer is for those people who want to implement with the same logic for System.Windows.Forms.TextBox and System.Windows.Controls.TextBox.
This is NumberTextBox code. Use commented line instead of the previous line for System.Windows.Controls.TextBox.
public class NumberTextBox : System.Windows.Forms.TextBox
//public class NumberTextBox : System.Windows.Controls.TextBox
{
private double _maxValue;
private double _minValue;
private bool _flag;
private string _previousValue;
public NumberTextBox()
{
this.TextAlign = HorizontalAlignment.Right;
//TextAlignment = TextAlignment.Right;
KeyDown += TextBox_KeyDown;
TextChanged += TextBox_TextChanged;
_minValue = double.MinValue;
_maxValue = double.MaxValue;
}
private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
_previousValue = this.Text;
_flag = this.SelectedText.Length > 0;
}
private void TextBox_TextChanged(object sender, EventArgs e)
//private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var text = this.Text;
if (text.Length < 1) return;
var cursorPosition = SelectionStart == 0 ? SelectionStart : SelectionStart - 1;
var insertedChar = text[cursorPosition];
if (IsInvalidInput(insertedChar, cursorPosition, text))
{
HandleText(text, cursorPosition);
}
ValidateRange(text, cursorPosition);
}
private bool IsInvalidInput(char insertedChar, int cursorPosition, string text)
{
return !char.IsDigit(insertedChar) && insertedChar != '.' && insertedChar != '-' ||
insertedChar == '-' && cursorPosition != 0 ||
text.Count(x => x == '.') > 1 ||
text.Count(x => x == '-') > 1;
}
private void HandleText(string text, int cursorPosition)
{
this.Text = _flag ? _previousValue : text.Remove(cursorPosition, 1);
this.SelectionStart = cursorPosition;
this.SelectionLength = 0;
}
private void ValidateRange(string text, int cursorPosition)
{
try
{
if (text == "." || _minValue < 0 && text == "-") return;
var doubleValue = Convert.ToDouble(text);
if (doubleValue > _maxValue || doubleValue < _minValue)
{
HandleText(text, cursorPosition);
}
}
catch (Exception)
{
HandleText(text, cursorPosition);
}
}
protected void SetProperties(double minValue = double.MinValue, double maxValue = double.MaxValue)
{
_minValue = minValue;
_maxValue = maxValue;
}
}
PositiveNumberTextBox code:
public class PositiveNumberTextBox : NumberTextBox
{
public PositiveNumberTextBox()
{
SetProperties(0);
}
}
FractionNumberTextBox code:
public class FractionNumberTextBox : NumberTextBox
{
public FractionNumberTextBox()
{
SetProperties(0, 0.999999);
}
}
You can use eval() for this purpose
>>> url = "'http address'"
>>> eval(url)
'http address'
while eval() poses risk , i think in this context it is safe.
Well, here is my "answer". It uses the fact that String.Split can be told hold many items it should split to (which I found lacking in the other answers):
string theString = "Some Very Large String Here";
var array = theString.Split(new [] { ' ' }, 2); // return at most 2 parts
// note: be sure to check it's not an empty array
string firstElem = array[0];
// note: be sure to check length first
string restOfArray = array[1];
This is very similar to the Substring
method, just by a different means.
Set JAVA_HOME
in environment variable.
set JAVA_HOME
to only JDK1.6.0_23
or whatever jdk folder
you have. dont include bin
folder in path.
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
Could you post the exact query? The ExecuteNonQuery
method returns the @@ROWCOUNT
Sql Server variable what ever it is after the last query has executed is what the ExecuteNonQuery
method returns.
Laravel 5 now supports changing a column; here's an example from the offical documentation:
Schema::table('users', function($table)
{
$table->string('name', 50)->nullable()->change();
});
Source: http://laravel.com/docs/5.0/schema#changing-columns
Laravel 4 does not support modifying columns, so you'll need use another technique such as writing a raw SQL command. For example:
// getting Laravel App Instance
$app = app();
// getting laravel main version
$laravelVer = explode('.',$app::VERSION);
switch ($laravelVer[0]) {
// Laravel 4
case('4'):
DB::statement('ALTER TABLE `pro_categories_langs` MODIFY `name` VARCHAR(100) NULL;');
break;
// Laravel 5, or Laravel 6
default:
Schema::table('pro_categories_langs', function(Blueprint $t) {
$t->string('name', 100)->nullable()->change();
});
}
Try this one,
Create rounded_edittext.xml
file in your Drawable
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" android:padding="15dp">
<solid android:color="#FFFFFF" />
<corners
android:bottomRightRadius="0dp"
android:bottomLeftRadius="0dp"
android:topLeftRadius="0dp"
android:topRightRadius="0dp" />
<stroke android:width="1dip" android:color="#f06060" />
</shape>
Apply background for your EditText
in xml file
<EditText
android:id="@+id/edit_expiry_date"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:background="@drawable/rounded_edittext"
android:hint="@string/shop_name"
android:inputType="text" />
You will get output like this
You can do it with Linq, as mamoo showed, but the oldies are good too:
var filteredDataTable = dt.Select(@"EmpId > 2
AND (EmpName <> 'abc' OR EmpName <> 'xyz')
AND EmpName like '%il%'" );
Check your servers error log, typically /var/log/apache2/error.log
.
Here is another solution
Set a hidden scope variable in your html then you can use it from your controller:
<span style="display:none" >{{ formValid = myForm.$valid}}</span>
Here is the full working example:
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
$scope.userType = 'guest';_x000D_
$scope.formValid = false;_x000D_
console.info('Ctrl init, no form.');_x000D_
_x000D_
$scope.$watch('myForm', function() {_x000D_
console.info('myForm watch');_x000D_
console.log($scope.formValid);_x000D_
});_x000D_
_x000D_
$scope.isFormValid = function() {_x000D_
//test the new scope variable_x000D_
console.log('form valid?: ', $scope.formValid);_x000D_
};_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
userType: <input name="input" ng-model="userType" required>_x000D_
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
<tt>userType = {{userType}}</tt><br>_x000D_
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
_x000D_
_x000D_
/*-- Hidden Variable formValid to use in your controller --*/_x000D_
<span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
_x000D_
_x000D_
<br/>_x000D_
<button ng-click="isFormValid()">Check Valid</button>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
You can use:
from io import StringIO # python3; python2: BytesIO
import boto3
bucket = 'my_bucket_name' # already created on S3
csv_buffer = StringIO()
df.to_csv(csv_buffer)
s3_resource = boto3.resource('s3')
s3_resource.Object(bucket, 'df.csv').put(Body=csv_buffer.getvalue())
PopupWindow
can only be attached to an Activity
. In your case you are trying to add PopupWindow
to service
which is not right.
To solve this problem you can use a blank and transparent Activity
. On click of floating icon, launch the Activity
and on onCreate
of Activity
show the PopupWindow
.
On dismiss of PopupWindow
, you can finish
the transparent Activity
.
Hope this helps you.
This is how it worked for me (from above answers it was showing both default title and my custom view also).
ActionBar.LayoutParams layout = new ActionBar.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
// actionBar.setCustomView(view); //last view item must set to android:layout_alignParentRight="true" if few views are there
actionBar.setCustomView(view, layout); // layout param width=fill/match parent
actionBar.setDisplayShowCustomEnabled(true);//must other wise its not showing custom view.
What I noticed is that both setCustomView(view)
and setCustomView(view,params)
the view width=match/fill parent. setDisplayShowCustomEnabled (boolean showCustom)
Simple code
// Events
$(document).on('mousewheel DOMMouseScroll', "element", function(e) {
let delta = e.originalEvent.wheelDelta;
if (delta > 0 || e.originalEvent.detail < 0) upScrollFunction();
if (delta < 0 || e.originalEvent.detail > 0) donwScrollFunction();
}
In jquery you could try this $("#select_id>option:selected").text()
static void Main()
{
for (int i=0; i<GetNames().Length; i++)
{
Console.WriteLine (GetNames()[i]);
}
}
static string[] GetNames()
{
string[] ret = {"Answer", "by", "Anonymous", "Pakistani"};
return ret;
}
Select Into functionality only works for PL/SQL Block, when you use Execute immediate , oracle interprets v_query_str as a SQL Query string so you can not use into .will get keyword missing Exception. in example 2 ,we are using begin end; so it became pl/sql block and its legal.
A concise version using the "rename"
command:
find my_root_dir -depth -exec rename 's/(.*)\/([^\/]*)/$1\/\L$2/' {} \;
This avoids problems with directories being renamed before files and trying to move files into non-existing directories (e.g. "A/A"
into "a/a"
).
Or, a more verbose version without using "rename"
.
for SRC in `find my_root_dir -depth`
do
DST=`dirname "${SRC}"`/`basename "${SRC}" | tr '[A-Z]' '[a-z]'`
if [ "${SRC}" != "${DST}" ]
then
[ ! -e "${DST}" ] && mv -T "${SRC}" "${DST}" || echo "${SRC} was not renamed"
fi
done
The latter allows more flexibility with the move command (for example, "svn mv"
).
The standard equivalent of find -iname ... -exec mv -t dest {} +
for find
implementations that don't support -iname
or mv
implementations that don't support -t
is to use a shell to re-order the arguments:
find . -name '*.[cC][pP][pP]' -type f -exec sh -c '
exec mv "$@" /dest/dir/' sh {} +
By using -name '*.[cC][pP][pP]'
, we also avoid the reliance on the current locale to decide what's the uppercase version of c
or p
.
Note that +
, contrary to ;
is not special in any shell so doesn't need to be quoted (though quoting won't harm, except of course with shells like rc
that don't support \
as a quoting operator).
The trailing /
in /dest/dir/
is so that mv
fails with an error instead of renaming foo.cpp
to /dest/dir
in the case where only one cpp
file was found and /dest/dir
didn't exist or wasn't a directory (or symlink to directory).
Assuming here you're referring to the javax.inject.Inject
annotation. @Inject
is part of the Java CDI (Contexts and Dependency Injection) standard introduced in Java EE 6 (JSR-299), read more. Spring has chosen to support using the @Inject
annotation synonymously with their own @Autowired
annotation.
So, to answer your question, @Autowired
is Spring's own annotation. @Inject
is part of a Java technology called CDI that defines a standard for dependency injection similar to Spring. In a Spring application, the two annotations works the same way as Spring has decided to support some JSR-299 annotations in addition to their own.
Create some nice new 10 year certificates and install them. The procedure is fairly easy.
Start at (1B) Generate your own CA (Certificate Authority) on this web page: Creating Certificate Authorities and self-signed SSL certificates and generate your CA Certificate and Key. Once you have these, generate your Server Certificate and Key. Create a Certificate Signing Request (CSR) and then sign the Server Key with the CA Certificate. Now install your Server Certificate and Key on the web server as usual, and import the CA Certificate into Internet Explorer's Trusted Root Certification Authority Store (used by the Flex uploader and Chrome as well) and into Firefox's Certificate Manager Authorities Store on each workstation that needs to access the server using the self-signed, CA-signed server key/certificate pair.
You now should not see any warning about using self-signed Certificates as the browsers will find the CA certificate in the Trust Store and verify the server key has been signed by this trusted certificate. Also in e-commerce applications like Magento, the Flex image uploader will now function in Firefox without the dreaded "Self-signed certificate" error message.
Unfortunately the previous answers were no option for me so i researched for a while and found this solution:
http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method
I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.
substring('foo',number(not(normalize-space(/elements/the/element/)))*4)
Since you know how many pixels are occupied by the previous content, you can use the calc()
function:
height: calc(100% - 50px);
Usually the problem is not closing brackets (}) or missing semicolon (;)
Just wanted to add a bit of info, since I haven't seen it posted yet.
You'll very often see code in C headers like so:
#ifdef __cplusplus
extern "C" {
#endif
// all of your legacy C code here
#ifdef __cplusplus
}
#endif
What this accomplishes is that it allows you to use that C header file with your C++ code, because the macro "__cplusplus" will be defined. But you can also still use it with your legacy C code, where the macro is NOT defined, so it won't see the uniquely C++ construct.
Although, I have also seen C++ code such as:
extern "C" {
#include "legacy_C_header.h"
}
which I imagine accomplishes much the same thing.
Not sure which way is better, but I have seen both.
You can use both Font Awesome and Github Octicons as a free alternative for Glyphicons.
Bootstrap 4 also switched from Less to Sass, so you might integerate the font's Sass (SCSS) into you build process, to create a single CSS file for your projects.
Also see https://getbootstrap.com/docs/4.1/getting-started/build-tools/ to find out how to set up your tooling:
/bootstrap
directory and run npm install
to install our local dependencies listed in package.json.gem install bundler
, and finally run bundle install
. This will install all Ruby dependencies, such as Jekyll and plugins.Font Awesome
font-awesome/scss
folder into your /bootstrap folderOpen your SCSS /bootstrap/bootstrap.scss
and write down the following SCSS code at the end of this file:
$fa-font-path: "../fonts";
@import "../font-awesome/scss/font-awesome.scss";
Notice that you also have to copy the font file from font-awesome/fonts
to dist/fonts
or any other public folder set by $fa-font-path
in the previous step
npm run dist
to recompile your code with Font-AwesomeGithub Octicons
octicons
folder into your /bootstrap
folderOpen your SCSS /bootstrap/bootstrap.scss
and write down the following SCSS code at the end of this file:
$fa-font-path: "../fonts";
@import "../octicons/octicons/octicons.scss";
Notice that you also have to copy the font file from font-awesome/fonts
to dist/fonts
or any other public folder set by $fa-font-path
in the previous step
npm run dist
to recompile your code with OcticonsGlyphicons
On the Bootstrap website you can read:
Includes over 250 glyphs in font format from the Glyphicon Halflings set. Glyphicons Halflings are normally not available for free, but their creator has made them available for Bootstrap free of cost. As a thank you, we only ask that you include a link back to Glyphicons whenever possible.
As I understand you can use these 250 glyphs free of cost restricted for Bootstrap but not limited to version 3 exclusive. So you can use them for Bootstrap 4 too.
bootstrap/scss
folder$bootstrap-sass-asset-helper: false;
$icon-font-name: 'glyphicons-halflings-regular';
$icon-font-svg-id: 'glyphicons_halflingsregular';
$icon-font-path: '../fonts/';
@import "glyphicons";
npm run dist
to recompile your code with GlyphiconsNotice that Bootstrap 4 requires the post CSS Autoprefixer for compiling. When you are using a static Sass compiler to compile your CSS you should have to run the Autoprefixer afterwards.
You can find out more about mixing with the Bootstrap 4 SCSS in here.
You can also use Bower to install the fonts above. Using Bower Font Awesome installs your files in bower_components/components-font-awesome/
also notice that Github Octicons sets the octicons/octicons/octicons-.scss
as the main file whilst you should use octicons/octicons/sprockets-octicons.scss
.
All the above will compile all your CSS code including into a single file, which requires only one HTTP request. Alternatively you can also load the Font-Awesome font from CDN, which can be fast too in many situations. Both fonts on CDN also include the font files (using data-uri's, possible not supported for older browsers). So consider which solution best fits your situation depending on among others browsers to support.
For Font Awesome paste the following code into the <head>
section of your site's HTML:
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
Also try Yeoman generator to scaffold out a front-end Bootstrap 4 Web app to test Bootstrap 4 with Font Awesome or Github Octicons.
Bit
is also an option if tinyint
isn't to your liking. A few links:
Not surprisingly, more info about numeric types is available in the manual.
One more link: http://blog.mclaughlinsoftware.com/2010/02/26/mysql-boolean-data-type/
And a quote from the comment section of the article above:
- TINYINT(1) isn’t a synonym for bit(1).
- TINYINT(1) can store -9 to 9.
- TINYINT(1) UNSIGNED: 0-9
- BIT(1): 0, 1. (Bit, literally).
Edit: This edit (and answer) is only remotely related to the original question...
Additional quotes by Justin Rovang and the author maclochlainn (comment section of the linked article).
Excuse me, seems I’ve fallen victim to substr-ism: TINYINT(1): -128-+127 TINYINT(1) UNSIGNED: 0-255 (Justin Rovang 25 Aug 11 at 4:32 pm)
True enough, but the post was about what PHPMyAdmin listed as a Boolean, and there it only uses 0 or 1 from the entire wide range of 256 possibilities. (maclochlainn 25 Aug 11 at 11:35 pm)
Mockito has limitations testing final, static, and private methods.
with jMockit testing library, you can do few stuff very easy and straight-forward as below:
Mock constructor of a java.io.File class:
new MockUp<File>(){
@Mock
public void $init(String pathname){
System.out.println(pathname);
// or do whatever you want
}
};
Mock a static method:
Change
mAdapter = new RecordingsListAdapter(this, recordings);
to
mAdapter = new RecordingsListAdapter(getActivity(), recordings);
and also make sure that recordings!=null
at mAdapter = new RecordingsListAdapter(this, recordings);
I came here because I had funny-char-syndrome on my requests
output. I thought response.text
would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.
Turns out response.encoding
was empty somehow and so response
did not know how to properly decode the content and just treated it as ASCII (I guess).
My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8')
to it. The result was schöne Umlaute.
The correctly decoded
für
vs. the improperly decoded
fAzr
In order to get CurrentUserId in Asp.net Identity 2.0, at first import Microsoft.AspNet.Identity
:
C#:
using Microsoft.AspNet.Identity;
VB.NET:
Imports Microsoft.AspNet.Identity
And then call User.Identity.GetUserId()
everywhere you want:
strCurrentUserId = User.Identity.GetUserId()
This method returns current user id as defined datatype for userid in database (the default is String
).
Laravel 4
When the validation fails return back with the validation errors.
if($validator->fails()) {
return Redirect::back()->withErrors($validator);
}
You can catch the error on your view using
@if($errors->any())
{{ implode('', $errors->all('<div>:message</div>')) }}
@endif
UPDATE
To display error under each field you can do like this.
<input type="text" name="firstname">
@if($errors->has('firstname'))
<div class="error">{{ $errors->first('firstname') }}</div>
@endif
For better display style with css.
You can refer to the docs here.
UPDATE 2
To display all errors at once
@if($errors->any())
{!! implode('', $errors->all('<div>:message</div>')) !!}
@endif
To display error under each field.
@error('firstname')
<div class="error">{{ $message }}</div>
@enderror
WHERE id <> 2
should work fine...Is that what you are after?
This is fixed in npm 7. See npm/cli#PR169
If you're checking for explicit types, why are you declaring those variables as T
's?
T HowToCast<T>(T t)
{
if (typeof(T) == typeof(string))
{
var newT1 = "some text";
var newT2 = t; //this builds but I'm not sure what it does under the hood.
var newT3 = t.ToString(); //for sure the string you want.
}
return t;
}
Below Code only works if It contain Unique Value Data
public string getKey(string Value)
{
if (dictionary.ContainsValue(Value))
{
var ListValueData=new List<string>();
var ListKeyData = new List<string>();
var Values = dictionary.Values;
var Keys = dictionary.Keys;
foreach (var item in Values)
{
ListValueData.Add(item);
}
var ValueIndex = ListValueData.IndexOf(Value);
foreach (var item in Keys)
{
ListKeyData.Add(item);
}
return ListKeyData[ValueIndex];
}
return string.Empty;
}
It seems that your
$(".modal").on('shown.bs.modal') // One way Or
You can do this in a slight different way, like this
$('.btn').click(function(){
// Send the src on click of button to the iframe. Which will make it load.
$(".openifrmahere").find('iframe').attr("src","http://www.hf-dev.info");
$('.modal').modal({show:true});
// Hide the loading message
$(".openifrmahere").find('iframe').load(function() {
$('.loading').hide();
});
})
For C++, you could do:
export CXXFLAGS=-m32
This works with cmake.
Just try the code below:
As I see you have inserted 'r+' or this command open the file in read mode so you are not able to write into it, so you have to open file in write mode 'w' if you want to overwrite the file contents and write new data, otherwise you can append data to file by using 'a'
I hope this will help ;)
f = open('testfile.txt', 'w')# just put 'w' if you want to write to the file
x = f.readlines() #this command will read file lines
y = int(x)+1
print y
z = str(y) #making data as string to avoid buffer error
f.write(z)
f.close()
You can use gdb, but I would first try Valgrind. See the quick start guide.
Briefly, Valgrind instruments your program so it can detect several kinds of errors in using dynamically allocated memory, such as double frees and writes past the end of allocated blocks of memory (which can corrupt the heap). It detects and reports the errors as soon as they occur, thus pointing you directly to the cause of the problem.
Use the function Contains
from the strings package.
import (
"strings"
)
strings.Contains("something", "some") // true
/stop([a-zA-Z])+/
Will match any stop word (stop, stopped, stopping, etc)
However, if you just want to match "stop" at the start of a string
/^stop/
will do :D
7 years later, allow me to give a one-liner solution by building on a previous answer. You could do the followwing:
numbers = [1, 2, 3]
to Add [3, 4, 5]
into numbers
without repeating 3
, do the following:
numbers = list(set(numbers + [3, 4, 5]))
This results in 4
and 5
being added to numbers
as in [1, 2, 3, 4, 5]
Explanation:
Now let me explain what happens, starting from the inside of the set()
instruction, we took numbers
and added 3
, 4
, and 5
to it which makes numbers
look like [1, 2, 3, 3, 4, 5]
.
Then, we took that ([1, 2, 3, 3, 4, 5]
) and transformed it into a set which gets rid of duplicates, resulting in the following {1, 2, 3, 4, 5}
. Now since we wanted a list and not a set, we used the function list()
to make that set ({1, 2, 3, 4, 5}
) into a list, resulting in [1, 2, 3, 4, 5]
which we assigned to the variable numbers
This, I believe, will work for all types of data in a list, and objects as well if done correctly.
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '[Replacement]')
In your instance it would be
UPDATE [TableName]
SET [ColumnName] = Replace([ColumnName], '[StringToRemove]', '')
Because there is no replacement (you want to get rid of it).
This will run on every row of the specified table. No need for a WHERE clause unless you want to specify only certain rows.
Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.
I have implemented below workaround to resolve this issue.
I have set the ORACLE_HOME using command prompt (right click cmd.exe and Run as System administrator).
Used below command
set oracle_home="path to the oracle home"
Go to All programs --> Oracle -ora home1 --> Configuration migration tools --> Net Manager --> Listener
Select Database Services from dropdown. Both Global database name and SID are set to the same (ORCL in my case). Set Oracle Home Directory.
Oracle Net Manager window example from oracle documentation:
One more solution via htmlfile
ActiveX:
Function EncodeUriComponent(strText)
Static objHtmlfile As Object
If objHtmlfile Is Nothing Then
Set objHtmlfile = CreateObject("htmlfile")
objHtmlfile.parentWindow.execScript "function encode(s) {return encodeURIComponent(s)}", "jscript"
End If
EncodeUriComponent = objHtmlfile.parentWindow.encode(strText)
End Function
Declaring htmlfile
DOM document object as static variable gives the only small delay when called first time due to init, and makes this function very fast for numerous calls, e. g. for me it converts the string of 100 chars length 100000 times in 2 seconds approx..
Using a cookie to provide the CSRF token to the client does not allow a successful attack because the attacker cannot read the value of the cookie and therefore cannot put it where the server-side CSRF validation requires it to be.
The attacker will be able to cause a request to the server with both the auth token cookie and the CSRF cookie in the request headers. But the server is not looking for the CSRF token as a cookie in the request headers, it's looking in the payload of the request. And even if the attacker knows where to put the CSRF token in the payload, they would have to read its value to put it there. But the browser's cross-origin policy prevents reading any cookie value from the target website.
The same logic does not apply to the auth token cookie, because the server is expects it in the request headers and the attacker does not have to do anything special to put it there.
If your database is PostgreSQL and you have php7.2 you should run the following commands:
sudo apt-get install php7.2-pgsql
and
php artisan migrate
Since you are using bootstrap and you want alternating row colors for every screen sizes you need to write separate style rules for all the screen sizes.
/* For small screen */
.row :nth-child(even){
background-color: #dcdcdc;
}
.row :nth-child(odd){
background-color: #aaaaaa;
}
/* For medium screen */
@media (min-width: 768px) {
.row :nth-child(4n), .row :nth-child(4n-1) {
background: #dcdcdc;
}
.row :nth-child(4n-2), .row :nth-child(4n-3) {
background: #aaaaaa;
}
}
/* For large screen */
@media (min-width: 992px) {
.row :nth-child(6n), .row :nth-child(6n-1), .row :nth-child(6n-2) {
background: #dcdcdc;
}
.row :nth-child(6n-3), .row :nth-child(6n-4), .row :nth-child(6n-5) {
background: #aaaaaa;
}
}
Working FIDDLE
I have also included the bootstrap CSS here.
FWIW, I was able to setup a local RTSP server for testing purposes using simple-rtsp-server and ffmpeg following these steps:
rtsp-simple-server.yml
with this single line:
protocols: [tcp]
$ docker run --rm -it -v $PWD/rtsp-simple-server.yml:/rtsp-simple-server.yml -p 8554:8554 aler9/rtsp-simple-server
$ ffmpeg -re -stream_loop -1 -i test.mp4 -f rtsp -rtsp_transport tcp rtsp://localhost:8554/live.stream
Once you have that running you can use ffplay to view the stream:
$ ffplay -rtsp_transport tcp rtsp://localhost:8554/live.stream
Note that simple-rtsp-server can also handle UDP streams (i.s.o. TCP) but that's tricky running the server as a Docker container.
General way:
##text=List of strings to be written to file
with open('csvfile.csv','wb') as file:
for line in text:
file.write(line)
file.write('\n')
OR
Using CSV writer :
import csv
with open(<path to output_csv>, "wb") as csv_file:
writer = csv.writer(csv_file, delimiter=',')
for line in data:
writer.writerow(line)
OR
Simplest way:
f = open('csvfile.csv','w')
f.write('hi there\n') #Give your csv text here.
## Python will convert \n to os.linesep
f.close()
I couldn't find an answer with Swift 3 implementation. So here it goes.
static func screenshotOf(window: UIWindow) -> UIImage? {
UIGraphicsBeginImageContextWithOptions(window.bounds.size, true, UIScreen.main.scale)
guard let currentContext = UIGraphicsGetCurrentContext() else {
return nil
}
window.layer.render(in: currentContext)
guard let image = UIGraphicsGetImageFromCurrentImageContext() else {
UIGraphicsEndImageContext()
return nil
}
UIGraphicsEndImageContext()
return image
}
Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:
SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
You can also hide again advanced option after reconfigure:
-- show advanced options
EXEC sp_configure 'show advanced options', 1
GO
RECONFIGURE
GO
-- enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1
GO
RECONFIGURE
GO
-- hide advanced options
EXEC sp_configure 'show advanced options', 0
GO
RECONFIGURE
GO
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
value_counts work only for series. It won't work for entire DataFrame. Try selecting only one column and using this attribute. For example:
df['accepted'].value_counts()
It also won't work if you have duplicate columns. This is because when you select a particular column, it will also represent the duplicate column and will return dataframe instead of series. At that time remove duplicate column by using
df = df.loc[:,~df.columns.duplicated()]
df['accepted'].value_counts()
Short answer for dummies like me (stolen from Torek):
In case you want to train CNN's with the theano backend like the Keras mnist_cnn.py example:
You better use theano bleeding edge version. Otherwise there may occur assertion errors.
pip install --upgrade --no-deps git+git://github.com/Theano/Theano.git
pip install git+git://github.com/fchollet/keras.git
If your class extends JFrame then use this.setTitle(newTitle.getText());
If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());
Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:
JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
newTitle;
and:
public void createOptions()
{
options = new JPanel();
options.setLayout(null);
JLabel labelOptions = new JLabel("Change Company Name:");
labelOptions.setBounds(120, 10, 150, 20);
options.add(labelOptions);
newTitle = new JTextField("Some Title");
newTitle.setBounds(80, 40, 225, 20);
options.add(newTitle);
// myTitle = new JTextField("My Title...");
// myTitle.setBounds(80, 40, 225, 20);
// myTitle.add(labelOptions);
JButton newName = new JButton("Set New Name");
newName.setBounds(60, 80, 150, 20);
newName.addActionListener(this);
options.add(newName);
JButton Exit = new JButton("Exit");
Exit.setBounds(250, 80, 80, 20);
Exit.addActionListener(this);
options.add(Exit);
}
and:
private void New_Name()
{
this.setTitle(newTitle.getText());
}
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class AvoidNullExp {
public static void main(String[] args) {
List<File> fileList =new ArrayList<>();
final File folder = new File("g:/master");
new AvoidNullExp().listFilesForFolder(folder, fileList);
}
public void listFilesForFolder(final File folder,List<File> fileList) {
File[] filesInFolder = folder.listFiles();
if (filesInFolder != null) {
for (final File fileEntry : filesInFolder) {
if (fileEntry.isDirectory()) {
System.out.println("DIR : "+fileEntry.getName());
listFilesForFolder(fileEntry,fileList);
} else {
System.out.println("FILE : "+fileEntry.getName());
fileList.add(fileEntry);
}
}
}
}
}
You will have to do it in two steps:
UPDATE MyTable SET MyNullableColumn = 0
WHERE MyNullableColumn IS NULL
ALTER TABLE MyTable
ALTER COLUMN MyNullableColumn MyNullableColumnDatatype NOT NULL
Whevever you get a problem like this just go to the man page for the function in question and it will tell you what header you are missing, e.g.
$ man memset
MEMSET(3) BSD Library Functions Manual MEMSET(3)
NAME
memset -- fill a byte string with a byte value
LIBRARY
Standard C Library (libc, -lc)
SYNOPSIS
#include <string.h>
void *
memset(void *b, int c, size_t len);
Note that for C++ it's generally preferable to use the proper equivalent C++ headers, <cstring>
/<cstdio>
/<cstdlib>
/etc, rather than C's <string.h>
/<stdio.h>
/<stdlib.h>
/etc.
Also, your compare function is incorrect. It needs to return -1, 0, or 1, not a boolean as you have it. The correct compare function would be:
def compare(item1, item2):
if fitness(item1) < fitness(item2):
return -1
elif fitness(item1) > fitness(item2):
return 1
else:
return 0
# Calling
list.sort(key=compare)
May be you need Decimal
>>> from decimal import Decimal
>>> Decimal(2.675)
Decimal('2.67499999999999982236431605997495353221893310546875')
You can use native bootstrap validation states (No Custom CSS!):
<div class="form-group has-feedback">
<label class="control-label" for="inputSuccess2">Name</label>
<input type="text" class="form-control" id="inputSuccess2"/>
<span class="glyphicon glyphicon-search form-control-feedback"></span>
</div>
For a full discussion, see my answer to Add a Bootstrap Glyphicon to Input Box
You can use the .input-group
class like this:
<div class="input-group">
<input type="text" class="form-control"/>
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
For a full discussion, see my answer to adding Twitter Bootstrap icon to Input box
You can still use .input-group
for positioning but just override the default styling to make the two elements appear separate.
Use a normal input group but add the class input-group-unstyled
:
<div class="input-group input-group-unstyled">
<input type="text" class="form-control" />
<span class="input-group-addon">
<i class="fa fa-search"></i>
</span>
</div>
Then change the styling with the following css:
.input-group.input-group-unstyled input.form-control {
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
border-radius: 4px;
}
.input-group-unstyled .input-group-addon {
border-radius: 4px;
border: 0px;
background-color: transparent;
}
Also, these solutions work for any input size
TOP and square brackets are specific to Transact-SQL. In ANSI SQL one uses LIMIT and backticks (`).
select * from `Table_Name` LIMIT 5;
Simply use Path.GetFileName
Here - Extract folder name from the full path of a folder:
string folderName = Path.GetFileName(@"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"
Here is some extra - Extract folder name from the full path of a file:
string folderName = Path.GetFileName(Path.GetDirectoryName(@"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"
I was having the same problem, but using Long type. I changed for INT and it worked for me.
CREATE TABLE lists (
id INT NOT NULL AUTO_INCREMENT,
desc varchar(30),
owner varchar(20),
visibility boolean,
PRIMARY KEY (id)
);
Following @VonC great answer. Your GitHub company policy might not allow 'force push' on master.
remote: error: GH003: Sorry, force-pushing to master is not allowed.
If you get an error message like this one please try the following steps.
To effectively reset your fork you need to follow these steps :
git checkout master
git reset --hard upstream/master
git checkout -b tmp_master
git push origin
Open your fork on GitHub, in "Settings -> Branches -> Default branch" choose 'new_master' as the new default branch. Now you can force push on the 'master' branch :
git checkout master
git push --force origin
Then you must set back 'master' as the default branch in the GitHub settings. To delete 'tmp_master' :
git push origin --delete tmp_master
git branch -D tmp_master
Other answers warning about lossing your change still apply, be carreful.
I want to give a shoutout for using re
module for this. Specially in the case of case sensitivity.
We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.
>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']
However try to always use the in
operator for string comparison as detailed in this post
faster-operation-re-match-or-str
Also detailed in the one of the best books to start learning python with
Try:
mmatrix = np.zeros((nrows, ncols))
Since the shape parameter has to be an int or sequence of ints
http://docs.scipy.org/doc/numpy/reference/generated/numpy.zeros.html
Otherwise you are passing ncols
to np.zeros
as the dtype.
If you are ever wondering how to read a file from server this code might be helpful.
Restrictions :
<Head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.4/xlsx.core.min.js"></script>
</head>
<body>
<script>
/* set up XMLHttpRequest */
// replace it with your file path in local server
var url = "http://localhost/test.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
/* convert data to binary string */
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for (var i = 0; i != data.length; ++i) {
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var cfb = XLSX.read(bstr, { type: 'binary' });
cfb.SheetNames.forEach(function(sheetName, index) {
// Obtain The Current Row As CSV
var fieldsObjs = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);
fieldsObjs.map(function(field) {
$("#my_file_output").append('<input type="checkbox" value="' + field.Fields + '">' + field.Fields + '<br>');
});
});
}
oReq.send();
</script>
</body>
<div id="my_file_output">
</div>
</html>
Θ-notation (theta notation) is called tight-bound because it's more precise than O-notation and Ω-notation (omega notation).
If I were lazy, I could say that binary search on a sorted array is O(n2), O(n3), and O(2n), and I would be technically correct in every case. That's because O-notation only specifies an upper bound, and binary search is bounded on the high side by all of those functions, just not very closely. These lazy estimates would be useless.
Θ-notation solves this problem by combining O-notation and Ω-notation. If I say that binary search is Θ(log n), that gives you more precise information. It tells you that the algorithm is bounded on both sides by the given function, so it will never be significantly faster or slower than stated.
I would suggest everybody, who is looking for an answer to this question, go through this "slideshow".
I couldn't understand what REST is and why it is so cool, its pros and cons, differences from SOAP - but this slideshow was so brilliant and easy to understand, so it is much more clear to me now, than before.
A side from the very long complete accepted answer there is an important point to make about IndexOutOfRangeException
compared with many other exception types, and that is:
Often there is complex program state that maybe difficult to have control over at a particular point in code e.g a DB connection goes down so data for an input cannot be retrieved etc... This kind of issue often results in an Exception of some kind that has to bubble up to a higher level because where it occurs has no way of dealing with it at that point.
IndexOutOfRangeException
is generally different in that it in most cases it is pretty trivial to check for at the point where the exception is being raised. Generally this kind of exception get thrown by some code that could very easily deal with the issue at the place it is occurring - just by checking the actual length of the array. You don't want to 'fix' this by handling this exception higher up - but instead by ensuring its not thrown in the first instance - which in most cases is easy to do by checking the array length.
Another way of putting this is that other exceptions can arise due to genuine lack of control over input or program state BUT IndexOutOfRangeException
more often than not is simply just pilot (programmer) error.
While the above answers describe the situation well, while troubleshooting the issue check also that browser really gets the format DataTables expects. There maybe other reasons not to get the data
. For example, if the user does not have access to the data URL and gets some HTML instead. Or the remote system has some unfortunate "fix-ups" in place. Network tab in the browser's Debug tools helps.
Try looking for EPOLLHUP or EPOLLERR. How do I check client connection is still alive
Reading and looking for 0 will work in some cases, but not all.