Try indextank.
As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.
If you have a large index, you should use a default value
<field ... default="EMPTY" />
and then query for this default value. This is much more efficient than q=-id:["" TO *]
I have use Elasticsearch for 3 years and Solr for about a month, I feel elasticsearch cluster is quite easy to install as compared to Solr installation. Elasticsearch has a pool of help documents with great explanation. One of the use case I was stuck up with Histogram Aggregation which was available in ES however not found in Solr.
Good to see someone's chimed in about Lucene - because I've no idea about that.
Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.
I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.
I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.
Just to add another unexpected case, here is query that wasn't returning expected results:
*:* AND ( ( field_a:foo AND field_b:bar ) OR !field_b:bar )
field_b
in my case is something I perform faceting on, and needed to target the query term "foo" only on that type (bar)
I had to insert another *:*
after the or condition to get this to work, like so:
*:* AND ( ( field_a:foo AND field_b:bar ) OR ( *:* AND !field_b:bar ) )
edit: this is in solr 6.6.3
tchester said :
(2) Create a login for the non-sysadmin user that has public access to the master database
I went to my user's database list (server/security/connections/my user name/properties/user mapping, and wanted to check the box for master database. I got an error message telling that the user already exists in the master database. Went to master database, dropped the user, went back to "user mapping" and checked the box for master. Check the "public" box below.
After that, you need to re-issue the grant execute on xp_cmdshell to "my user name"
Yves
You could stil use @TEMP
if you quote the identifier "@TEMP"
:
declare @TEMP table (ID int, Name varchar(max));
insert into @temp SELECT 1 AS ID, 'a' Name;
SELECT * FROM @TEMP WHERE "@TEMP".ID = 1 ;
You must do:
ls -lart /var/run/mysqld/
mkdir /var/run/mysqld
touch /var/run/mysqld/myssqld.sock
ls -lart /var/run/mysqld/
chown -R mysql /var/run/mysqld/
ls -lart /var/run/mysqld/
/etc/init.d/mysql restart
Then access like so:
mysql -u root -p
mysql> show databases;
//How to start another application from the current application
Process runProg = new Process();
runProg.StartInfo.FileName = pathToFile; //the path of the application
runProg.StartInfo.Arguments = genArgs; //any arguments you want to pass
runProg.StartInfo.CreateNoWindow = true;
runProg.Start();
//How to end the same application from the current application
int IDstring = System.Convert.ToInt32(runProg.Id.ToString());
Process tempProc = Process.GetProcessById(IDstring);
tempProc.CloseMainWindow();
tempProc.WaitForExit();
function function_one()_x000D_
{_x000D_
alert("The function called 'function_one' has been called.")_x000D_
//Here u would like to call function_two._x000D_
function_two(); _x000D_
}_x000D_
_x000D_
function function_two()_x000D_
{_x000D_
alert("The function called 'function_two' has been called.")_x000D_
}
_x000D_
Don't use quotation in a field name or table name inside the query.
After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.
One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:
session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;
Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)
The ideal answer found in the forum mentioned above is this:
sed -i 's/facebook-android-sdk:4.+/facebook-android-sdk:4.22.1/g' ./node_modules/react-native-fbsdk/android/build.gradle
This works
This should do it. You were missing a )
and you only need """
not 4 of them. Also you don't need a elif at the end.
ans=True
while ans:
print("""
1.Add a Student
2.Delete a Student
3.Look Up Student Record
4.Exit/Quit
""")
ans=raw_input("What would you like to do? ")
if ans=="1":
print("\nStudent Added")
elif ans=="2":
print("\n Student Deleted")
elif ans=="3":
print("\n Student Record Found")
elif ans=="4":
print("\n Goodbye")
ans = None
else:
print("\n Not Valid Choice Try again")
I found solution. It works fine when I throw away next line from form:
enctype="multipart/form-data"
And now it pass all parameters at request ok:
<form action="/registration" method="post">
<%-- error messages --%>
<div class="form-group">
<c:forEach items="${registrationErrors}" var="error">
<p class="error">${error}</p>
</c:forEach>
</div>
All posted data will be in the $_POST superglobal.
For those using google tag manager to integrate with google analytics events you can do what the guys mentioned about to set the cookies flag to none from GTM it self
open GTM > variables > google analytics variables > and set the cookies tag to none
Here is a simplified function that returns a boolean and has no output pushed to stdout:
import subprocess, platform
def pingOk(sHost):
try:
output = subprocess.check_output("ping -{} 1 {}".format('n' if platform.system().lower()=="windows" else 'c', sHost), shell=True)
except Exception, e:
return False
return True
I'm using ASP.NET SPA Extensions which creates me a proxy on ports 5000 and 5001 that pass through to Angular's port 4200 during development.
I had had CORS correctly setup for https port 5001 and everything was fine, but I inadvertently went to an old bookmark which was for port 5000. Then suddenly this message arose. As others have said in the console there was a 'preflight' error message.
So regardless of your environment, if you're using CORS make sure you have all ports specified - as the host and port both matter.
One does not imply the other. For a language to be statically typed it means that the types of all variables are known or inferred at compile time.
A strongly typed language does not allow you to use one type as another. C is a weakly typed language and is a good example of what strongly typed languages don't allow. In C you can pass a data element of the wrong type and it will not complain. In strongly typed languages you cannot.
The problem is in your playerMovement
method. You are creating the string name of your room variables (ID1
, ID2
, ID3
):
letsago = "ID" + str(self.dirDesc.values())
However, what you create is just a str
. It is not the variable. Plus, I do not think it is doing what you think its doing:
>>>str({'a':1}.values())
'dict_values([1])'
If you REALLY needed to find the variable this way, you could use the eval
function:
>>>foo = 'Hello World!'
>>>eval('foo')
'Hello World!'
or the globals
function:
class Foo(object):
def __init__(self):
super(Foo, self).__init__()
def test(self, name):
print(globals()[name])
foo = Foo()
bar = 'Hello World!'
foo.text('bar')
However, instead I would strongly recommend you rethink you class(es). Your userInterface
class is essentially a Room
. It shouldn't handle player movement. This should be within another class, maybe GameManager
or something like that.
It means that no rows will be returned if @region
is NULL
, when used in your first example, even if there are rows in the table where Region
is NULL
.
When ANSI_NULLS
is on (which you should always set on anyway, since the option to not have it on is going to be removed in the future), any comparison operation where (at least) one of the operands is NULL
produces the third logic value - UNKNOWN
(as opposed to TRUE
and FALSE
).
UNKNOWN
values propagate through any combining boolean operators if they're not already decided (e.g. AND
with a FALSE
operand or OR
with a TRUE
operand) or negations (NOT
).
The WHERE
clause is used to filter the result set produced by the FROM
clause, such that the overall value of the WHERE
clause must be TRUE
for the row to not be filtered out. So, if an UNKNOWN
is produced by any comparison, it will cause the row to be filtered out.
@user1227804's answer includes this quote:
If both sides of the comparison are columns or compound expressions, the setting does not affect the comparison.
from SET ANSI_NULLS
*
However, I'm not sure what point it's trying to make, since if two NULL
columns are compared (e.g. in a JOIN
), the comparison still fails:
create table #T1 (
ID int not null,
Val1 varchar(10) null
)
insert into #T1(ID,Val1) select 1,null
create table #T2 (
ID int not null,
Val1 varchar(10) null
)
insert into #T2(ID,Val1) select 1,null
select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and t1.Val1 = t2.Val1
The above query returns 0 rows, whereas:
select * from #T1 t1 inner join #T2 t2 on t1.ID = t2.ID and (t1.Val1 = t2.Val1 or t1.Val1 is null and t2.Val1 is null)
Returns one row. So even when both operands are columns, NULL
does not equal NULL
. And the documentation for =
doesn't have anything to say about the operands:
When you compare two
NULL
expressions, the result depends on theANSI_NULLS
setting:If
ANSI_NULLS
is set toON
, the result isNULL
1, following the ANSI convention that aNULL
(or unknown) value is not equal to anotherNULL
or unknown value.If
ANSI_NULLS
is set toOFF
, the result ofNULL
compared toNULL
isTRUE
.Comparing
NULL
to a non-NULL
value always results inFALSE
2.
However, both 1 and 2 are incorrect - the result of both comparisons is UNKNOWN
.
*The cryptic meaning of this text was finally discovered years later. What it actually means is that, for those comparisons, the setting has no effect and it always acts as if the setting were ON. Would have been clearer if it had stated that SET ANSI_NULLS OFF
was the setting that had no affect.
You don't need a controller and when using .Net 5 (MVC 6) you can render the partial view async
@await Html.PartialAsync("_LoginPartial")
or
@{await Html.RenderPartialAsync("PartialName");}
or if you are using .net core 2.1 > you can just use:
<partial name="Shared/_ProductPartial.cshtml"
for="Product" />
sorry for reviving this thread, but thought my method was worth adding.
The list name in this example 'list'
list.sort()
print(list[-1])
That will print the highest value in the list easy as!
list.sort()
sorts the list by the value of the item in the ASCII table, so effectively sorts the list lowest to highest. I then just print the last value in the list (which will be the greatest number) by using print(list[-1])
.
Hope this helps!
I like the Infragistics controls. The WebDropDown has what you need. The only drawback is they can be a bit spendy.
Box Selecting
Windows & Linux: Shift + Alt + 'Mouse Left Button'
macOS: Shift + option + 'Click'
Esc to exit selection.
MacOS: Shift + Alt/Option + Command + 'arrow key'
Googling gives me this:
Command A & Command B
Execute Command A, then execute Command B (no evaluation of anything)
Command A | Command B
Execute Command A, and redirect all its output into the input of Command B
Command A && Command B
Execute Command A, evaluate the errorlevel after running and if the exit code (errorlevel) is 0, only then execute Command B
Command A || Command B
Execute Command A, evaluate the exit code of this command and if it's anything but 0, only then execute Command B
xrange from Python 2 is a generator and implements iterator while range is just a function. In Python3 I don't know why was dropped off the xrange.
I like the concept of grouping RadioButtons in WPF. There is a property GroupName
that specifies which RadioButton controls are mutually exclusive (http://msdn.microsoft.com/de-de/library/system.windows.controls.radiobutton.aspx).
So I wrote a derived class for WinForms that supports this feature:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Windows.Forms.VisualStyles;
using System.Drawing;
using System.ComponentModel;
namespace Use.your.own
{
public class AdvancedRadioButton : CheckBox
{
public enum Level { Parent, Form };
[Category("AdvancedRadioButton"),
Description("Gets or sets the level that specifies which RadioButton controls are affected."),
DefaultValue(Level.Parent)]
public Level GroupNameLevel { get; set; }
[Category("AdvancedRadioButton"),
Description("Gets or sets the name that specifies which RadioButton controls are mutually exclusive.")]
public string GroupName { get; set; }
protected override void OnCheckedChanged(EventArgs e)
{
base.OnCheckedChanged(e);
if (Checked)
{
var arbControls = (dynamic)null;
switch (GroupNameLevel)
{
case Level.Parent:
if (this.Parent != null)
arbControls = GetAll(this.Parent, typeof(AdvancedRadioButton));
break;
case Level.Form:
Form form = this.FindForm();
if (form != null)
arbControls = GetAll(this.FindForm(), typeof(AdvancedRadioButton));
break;
}
if (arbControls != null)
foreach (Control control in arbControls)
if (control != this &&
(control as AdvancedRadioButton).GroupName == this.GroupName)
(control as AdvancedRadioButton).Checked = false;
}
}
protected override void OnClick(EventArgs e)
{
if (!Checked)
base.OnClick(e);
}
protected override void OnPaint(PaintEventArgs pevent)
{
CheckBoxRenderer.DrawParentBackground(pevent.Graphics, pevent.ClipRectangle, this);
RadioButtonState radioButtonState;
if (Checked)
{
radioButtonState = RadioButtonState.CheckedNormal;
if (Focused)
radioButtonState = RadioButtonState.CheckedHot;
if (!Enabled)
radioButtonState = RadioButtonState.CheckedDisabled;
}
else
{
radioButtonState = RadioButtonState.UncheckedNormal;
if (Focused)
radioButtonState = RadioButtonState.UncheckedHot;
if (!Enabled)
radioButtonState = RadioButtonState.UncheckedDisabled;
}
Size glyphSize = RadioButtonRenderer.GetGlyphSize(pevent.Graphics, radioButtonState);
Rectangle rect = pevent.ClipRectangle;
rect.Width -= glyphSize.Width;
rect.Location = new Point(rect.Left + glyphSize.Width, rect.Top);
RadioButtonRenderer.DrawRadioButton(pevent.Graphics, new System.Drawing.Point(0, rect.Height / 2 - glyphSize.Height / 2), rect, this.Text, this.Font, this.Focused, radioButtonState);
}
private IEnumerable<Control> GetAll(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
}
}
Instead of putting in root folder as given in docs of firebase, just copy the google-json file in the projectname/app 's root folder and it works fine then . Its just simple !
It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.
public class MyParameters
{
public string a { get; set; }
public string b { get; set; }
}
public MyController : ApiController
{
public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}
Then you go to:
http://localhost:12345/api/MyController?a=par1&b=par2
Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".
See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
You can also use REGEXP
's synonym RLIKE
as well.
For example:
SELECT *
FROM TABLE_NAME
WHERE COLNAME RLIKE 'REGEX1|REGEX2|REGEX3'
You can use:
Handler handler = new Handler()
handler.postDelayed(new Runnable())
Or you can use:
handler.removeCallbacksAndMessages(null);
Docs
public final void removeCallbacksAndMessages (Object token)
Added in API level 1 Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed.
Or you could also do like the following:
Handler handler = new Handler()
Runnable myRunnable = new Runnable() {
public void run() {
// do something
}
};
handler.postDelayed(myRunnable,zeit_dauer2);
Then:
handler.removeCallbacks(myRunnable);
Docs
public final void removeCallbacks (Runnable r)
Added in API level 1 Remove any pending posts of Runnable r that are in the message queue.
public final void removeCallbacks (Runnable r, Object token)
Edit:
Change this:
@Override
public void onClick(View v) {
Handler handler = new Handler();
Runnable myRunnable = new Runnable() {
To:
@Override
public void onClick(View v) {
handler = new Handler();
myRunnable = new Runnable() { /* ... */}
Because you have the below. Declared before onCreate
but you re-declared and then initialized it in onClick
leading to a NPE.
Handler handler; // declared before onCreate
Runnable myRunnable;
i believe the following code will only run after form1
is closed
while (true)
{
if (form1.Visible == false)
form2.Show();
}
Why not start your form2
from form1
instead?
Form2 form2 = new Form2();
private void button1_Click_1(object sender, EventArgs e)
{
if (richTextBox1.Text != null)
{
form1.Visible=false;
form2.Show();
}
else MessageBox.Show("Insert Attributes First !");
}
If you in any doubt, have a look at JDK source code
ArrayList.clear()
source code:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
You will see that size
is set to 0 so you start from 0 position.
Please note that when adding elements to ArrayList
, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear()
you only remove references to array elements and sets size
to 0, however, capacity
stays as it was.
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
Note: This doesn't apply to Angular 6 and above as ElementRef
became ElementRef<T>
with T
denoting the type of nativeElement
.
I would like to add that if you are using ElementRef
, as recommended by all answers, then you will immediately encounter the problem that ElementRef
has an awful type declaration that looks like
export declare class ElementRef {
nativeElement: any;
}
this is stupid in a browser environment where nativeElement is an HTMLElement
.
To workaround this you can use the following technique
import {Inject, ElementRef as ErrorProneElementRef} from '@angular/core';
interface ElementRef {
nativeElement: HTMLElement;
}
@Component({...}) export class MyComponent {
constructor(@Inject(ErrorProneElementRef) readonly elementRef: ElementRef) { }
}
I use this simple utility function:
rows = function(tab) lapply(
seq_len(nrow(tab)),
function(i) unclass(tab[i,,drop=F])
)
Or a faster, less clear form:
rows = function(x) lapply(seq_len(nrow(x)), function(i) lapply(x,"[",i))
This function just splits a data.frame to a list of rows. Then you can make a normal "for" over this list:
tab = data.frame(x = 1:3, y=2:4, z=3:5)
for (A in rows(tab)) {
print(A$x + A$y * A$z)
}
Your code from the question will work with a minimal modification:
for (well in rows(dataFrame)) {
wellName <- well$name # string like "H1"
plateName <- well$plate # string like "plate67"
wellID <- getWellID(wellName, plateName)
cat(paste(wellID, well$value1, well$value2, sep=","), file=outputFile)
}
$("input[name='mygroup'][value='5']").attr("checked", true);
I hope this saves someone some hours of pain.
this code will disable Right-Click on Win or Click and hold on mac to open "contextmenu"
$("img").on("contextmenu",function(e){return false;});
It's so simple and always works fine. and it's not depends on OS or Browser that you're using.
This occurred for me when I had a source ip constraint on the policy being used by the user (access key / secret key) to create the s3 bucket. My IP was accurate--but for some reason it wouldn't work and gave this error.
<%!
private void myFunc(String Bits, javax.servlet.jsp.JspWriter myOut)
{
try{ myOut.println("<div>"+Bits+"</div>"); }
catch(Exception eek) { }
}
%>
...
<%
myFunc("more difficult than it should be",out);
%>
Try this, it worked for me!
master
is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.
You can add it back with git checkout -b master
.
Eclipse Juno, Indigo and Kepler when using the bundled maven version(m2e), are not suppressing the message SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". This behaviour is present from the m2e version 1.1.0.20120530-0009 and onwards.
Although, this is indicated as an error your logs will be saved normally. The highlighted error will still be present until there is a fix of this bug. More about this in the m2e support site.
The current available solution is to use an external maven version rather than the bundled version of Eclipse. You can find about this solution and more details regarding this bug in the question below which i believe describes the same problem you are facing.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error
DateTime.Now.ToString("HH:mm:ss tt");
this gives it to you as a string.
from datetime import date
def age(birth_date):
today = date.today()
y = today.year - birth_date.year
if today.month < birth_date.month or today.month == birth_date.month and today.day < birth_date.day:
y -= 1
return y
define() is part of the AMD spec of js
See:
Edit: Also see Claudio's answer below. Likely the more relevant explanation.
The OP is using Windows, and a much easier way to use GTest today is with vcpkg+cmake.
Install vcpkg as per https://github.com/microsoft/vcpkg , and make sure you can run vcpkg
from the cmd line. Take note of the vcpkg installation folder, eg. C:\bin\programs\vcpkg
.
Install gtest using vcpkg install gtest
: this will download, compile, and install GTest.
Use a CmakeLists.txt as below: note we can use targets instead of including folders.
cmake_minimum_required(VERSION 3.15)
project(sample CXX)
enable_testing()
find_package(GTest REQUIRED)
add_executable(test1 test.cpp source.cpp)
target_link_libraries(test1 GTest::GTest GTest::Main)
add_test(test-1 test1)
Run cmake with: (edit the vcpkg folder if necessary, and make sure the path to the vcpkg.cmake toolchain file is correct)
cmake -B build -DCMAKE_TOOLCHAIN_FILE=C:\bin\programs\vcpkg\scripts\buildsystems\vcpkg.cmake
and build using cmake --build build
as usual.
Note that, vcpkg will also copy the required gtest(d).dll/gtest(d)_main.dll from the install folder to the Debug/Release folders.
Test with cd build & ctest
.
Maybe this will help:
<select onchange="location = this.value;">
<option value="home.html">Home</option>
<option value="contact.html">Contact</option>
<option value="about.html">About</option>
</select>
You can indeed match all those characters, but it's safer to escape the -
so that it is clear that it be taken literally.
If you are using a POSIX variant you can opt to use:
([[:alnum:]\-_]+)
But a since you are including the underscore I would simply use:
([\w\-]+)
(works in all variants)
While everyone will generally agree that Javascript encryption is a bad idea, there are a few small use cases where slowing down the attack is better than nothing. You can start with YUI Compressor (as @Ben Alpert) said, or JSMin, Uglify, or many more.
However, the main case in which I want to really 'hide stuff' is when I'm publishing an email address. Note, there is the problem of Chrome when you click on 'inspect element'. It will show your original code: every time. This is why obfuscation is generally regarded as being a better way to go.
On that note, I take a two pronged attack, purely to slow down spam bots. I Obfuscate/minify the js and then run it again through an encoder (again, this second step is completely pointless in chrome).
While not exactly a pure Javascript encoder, the best html encoder I have found is http://hivelogic.com/enkoder/. It will turn this:
<script type="text/javascript">
//<![CDATA[
<!--
var c=function(e) { var m="mail" + "to:webmaster";var a="somedomain"; e.href = m+"@"+a+".com";
};
//-->
//]]>
</script>
<a href="#" onclick="return c(this);"><img src="images/email.png" /></a>
into this:
<script type="text/javascript">
//<![CDATA[
<!--
var x="function f(x){var i,o=\"\",ol=x.length,l=ol;while(x.charCodeAt(l/13)!" +
"=50){try{x+=x;l+=l;}catch(e){}}for(i=l-1;i>=0;i--){o+=x.charAt(i);}return o" +
".substr(0,ol);}f(\")87,\\\"meozp?410\\\\=220\\\\s-dvwggd130\\\\#-2o,V_PY420" +
"\\\\I\\\\\\\\_V[\\\\\\\\620\\\\o710\\\\RB\\\\\\\\610\\\\JAB620\\\\720\\\\n\\"+
"\\{530\\\\410\\\\WJJU010\\\\|>snnn|j5J(771\\\\p{}saa-.W)+T:``vk\\\"\\\\`<02" +
"0\\\\!610\\\\'Dr\\\\010\\\\630\\\\400\\\\620\\\\700\\\\\\\\\\\\N730\\\\,530" +
"\\\\2S16EF600\\\\;420\\\\9ZNONO1200\\\\/000\\\\`'7400\\\\%n\\\\!010\\\\hpr\\"+
"\\= -cn720\\\\a(ce230\\\\500\\\\f730\\\\i,`200\\\\630\\\\[YIR720\\\\]720\\\\"+
"r\\\\720\\\\h][P]@JHADY310\\\\t230\\\\G500\\\\VBT230\\\\200\\\\Clxhh{tzra/{" +
"g0M0$./Pgche%Z8i#p`v^600\\\\\\\\\\\\R730\\\\Q620\\\\030\\\\730\\\\100\\\\72" +
"0\\\\530\\\\700\\\\720\\\\M410\\\\N730\\\\r\\\\530\\\\400\\\\4420\\\\8OM771" +
"\\\\`4400\\\\$010\\\\t\\\\120\\\\230\\\\r\\\\610\\\\310\\\\530\\\\e~o120\\\\"+
"RfJjn\\\\020\\\\lZ\\\\\\\\CZEWCV771\\\\v5lnqf2R1ox771\\\\p\\\"\\\\tr\\\\220" +
"\\\\310\\\\420\\\\600\\\\OSG300\\\\700\\\\410\\\\320\\\\410\\\\120\\\\620\\" +
"\\q)5<: 0>+\\\"(f};o nruter};))++y(^)i(tAedoCrahc.x(edoCrahCmorf.gnirtS=+o;" +
"721=%y;++y)87<i(fi{)++i;l<i;0=i(rof;htgnel.x=l,\\\"\\\"=o,i rav{)y,x(f noit" +
"cnuf\")" ;
while(x=eval(x));
//-->
//]]>
</script>
Maybe it's enough to slow down a few spam bots. I haven't had any spam come through using this (!yet).
You can also use a union construct. I'm not sure if CASE is a common SQL construct ...
SELECT ID FROM tabName WHERE IDParent<1 OR IDParent IS NULL
UNION
SELECT IDParent FROM tabName WHERE IDParent>1
You can always use the
echo "Column1`tColumn2`tColumn3..." >> results.csv
You will need to put "`t" between the columns to separates the variables into their own column. Here is the way I wrote my script:
echo "Host`tState" >> results.csv
$names = Get-Content "hostlist.txt"
foreach ($name in $names) {
$count = 0
$count2 = 13490
if ( Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue ) {
echo "$name`tUp" >> results.csv
}
else {
echo "$name`tDown" >> results.csv
}
$count++
Write-Progress -Activity "Gathering Information" -status "Pinging Hosts..." -percentComplete ($count / $count2 *100)
}
This is the easiest way to me. The output I get is :
Host|State
----------
H1 |Up
H2 |UP
H3 |Down
You can play around with the look, but that's the basic idea. The $count is just a progress bar if you want to spice up the look
On ubuntu
sudo apt-get install librxtx-java then
add RXTX jars to the project which are in
usr/share/java
For Visual C:
std::wstring stringFormat(const wchar_t* fmt, ...)
{
if (!fmt) {
return L"";
}
std::vector<wchar_t> buff;
size_t size = wcslen(fmt) * 2;
buff.resize(size);
va_list ap;
va_start(ap, fmt);
while (true) {
int ret = _vsnwprintf_s(buff.data(), size, _TRUNCATE, fmt, ap);
if (ret != -1)
break;
else {
size *= 2;
buff.resize(size);
}
}
va_end(ap);
return std::wstring(buff.data());
}
In addition to the differences already noted, there's another extremely important difference that I just now discovered the hard way: unlike np.mean
, np.average
doesn't allow the dtype
keyword, which is essential for getting correct results in some cases. I have a very large single-precision array that is accessed from an h5
file. If I take the mean along axes 0 and 1, I get wildly incorrect results unless I specify dtype='float64'
:
>T.shape
(4096, 4096, 720)
>T.dtype
dtype('<f4')
m1 = np.average(T, axis=(0,1)) # garbage
m2 = np.mean(T, axis=(0,1)) # the same garbage
m3 = np.mean(T, axis=(0,1), dtype='float64') # correct results
Unfortunately, unless you know what to look for, you can't necessarily tell your results are wrong. I will never use np.average
again for this reason but will always use np.mean(.., dtype='float64')
on any large array. If I want a weighted average, I'll compute it explicitly using the product of the weight vector and the target array and then either np.sum
or np.mean
, as appropriate (with appropriate precision as well).
Alternatively you could replace all the contents in your .htaccess file
Options +FollowSymLinks -Indexes
RewriteEngine On
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
See the docs here. https://laravel.com/docs/5.8/installation#web-server-configuration
Arguments are passed by assignment. The rationale behind this is twofold:
So:
If you pass a mutable object into a method, the method gets a reference to that same object and you can mutate it to your heart's delight, but if you rebind the reference in the method, the outer scope will know nothing about it, and after you're done, the outer reference will still point at the original object.
If you pass an immutable object to a method, you still can't rebind the outer reference, and you can't even mutate the object.
To make it even more clear, let's have some examples.
Let's try to modify the list that was passed to a method:
def try_to_change_list_contents(the_list):
print('got', the_list)
the_list.append('four')
print('changed to', the_list)
outer_list = ['one', 'two', 'three']
print('before, outer_list =', outer_list)
try_to_change_list_contents(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['one', 'two', 'three']
got ['one', 'two', 'three']
changed to ['one', 'two', 'three', 'four']
after, outer_list = ['one', 'two', 'three', 'four']
Since the parameter passed in is a reference to outer_list
, not a copy of it, we can use the mutating list methods to change it and have the changes reflected in the outer scope.
Now let's see what happens when we try to change the reference that was passed in as a parameter:
def try_to_change_list_reference(the_list):
print('got', the_list)
the_list = ['and', 'we', 'can', 'not', 'lie']
print('set to', the_list)
outer_list = ['we', 'like', 'proper', 'English']
print('before, outer_list =', outer_list)
try_to_change_list_reference(outer_list)
print('after, outer_list =', outer_list)
Output:
before, outer_list = ['we', 'like', 'proper', 'English']
got ['we', 'like', 'proper', 'English']
set to ['and', 'we', 'can', 'not', 'lie']
after, outer_list = ['we', 'like', 'proper', 'English']
Since the the_list
parameter was passed by value, assigning a new list to it had no effect that the code outside the method could see. The the_list
was a copy of the outer_list
reference, and we had the_list
point to a new list, but there was no way to change where outer_list
pointed.
It's immutable, so there's nothing we can do to change the contents of the string
Now, let's try to change the reference
def try_to_change_string_reference(the_string):
print('got', the_string)
the_string = 'In a kingdom by the sea'
print('set to', the_string)
outer_string = 'It was many and many a year ago'
print('before, outer_string =', outer_string)
try_to_change_string_reference(outer_string)
print('after, outer_string =', outer_string)
Output:
before, outer_string = It was many and many a year ago
got It was many and many a year ago
set to In a kingdom by the sea
after, outer_string = It was many and many a year ago
Again, since the the_string
parameter was passed by value, assigning a new string to it had no effect that the code outside the method could see. The the_string
was a copy of the outer_string
reference, and we had the_string
point to a new string, but there was no way to change where outer_string
pointed.
I hope this clears things up a little.
EDIT: It's been noted that this doesn't answer the question that @David originally asked, "Is there something I can do to pass the variable by actual reference?". Let's work on that.
As @Andrea's answer shows, you could return the new value. This doesn't change the way things are passed in, but does let you get the information you want back out:
def return_a_whole_new_string(the_string):
new_string = something_to_do_with_the_old_string(the_string)
return new_string
# then you could call it like
my_string = return_a_whole_new_string(my_string)
If you really wanted to avoid using a return value, you could create a class to hold your value and pass it into the function or use an existing class, like a list:
def use_a_wrapper_to_simulate_pass_by_reference(stuff_to_change):
new_string = something_to_do_with_the_old_string(stuff_to_change[0])
stuff_to_change[0] = new_string
# then you could call it like
wrapper = [my_string]
use_a_wrapper_to_simulate_pass_by_reference(wrapper)
do_something_with(wrapper[0])
Although this seems a little cumbersome.
Doesn't log4j just use the application root directory if you don't specify a root directory in your FileAppender's path property? So you should just be able to use:
log4j.appender.file.File=logs/MyLog.log
It's been awhile since I've done Java web development, but this seems to be the most intuitive, and also doesn't collide with other unfortunately named logs writing to the ${catalina.home}/logs directory.
Judging by the declaration and description of the startsWith
Java function, the "most straight forward way" to implement it in VBA would either be with Left
:
Public Function startsWith(str As String, prefix As String) As Boolean
startsWith = Left(str, Len(prefix)) = prefix
End Function
Or, if you want to have the offset parameter available, with Mid
:
Public Function startsWith(str As String, prefix As String, Optional toffset As Integer = 0) As Boolean
startsWith = Mid(str, toffset + 1, Len(prefix)) = prefix
End Function
It's not so much about the language as the tools and libraries. The available libraries and compilers for C are much older than for newer languages. You might think this would make them slower, but au contraire.
These libraries were written at a time when processing power and memory were at a premium. They had to be written very efficiently in order to work at all. Developers of C compilers have also had a long time to work in all sorts of clever optimizations for different processors. C's maturity and wide adoption makes for a signficant advantage over other languages of the same age. It also gives C a speed advantage over newer tools that don't emphasize raw performance as much as C had to.
Hi,
You can also do as like below... In this way, your both functions should call and if both functions return true then it will return true else return false.
<input type="button"
onclick="var valFunc1 = func1(); var valFunc2 = func2(); if(valFunc1 == true && valFunc2 ==true) {return true;} else{return false;}"
value="Call2Functions" />
Thank you, Vishal Patel
There is a subtle issue here that is a bit of a gotcha.
The toString()
method has a base implementation in Object
. CharSequence
is an interface; and although the toString()
method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence
toString()
method's javadoc puts on the toString()
method; ie that it should return a string containing the characters in the order returned by charAt()
.
Your IDE won't even help you out by reminding that you that you probably should override toString()
. For example, in intellij, this is what you'll see if you create a new CharSequence
implementation: http://puu.sh/2w1RJ. Note the absence of toString()
.
If you rely on toString()
on an arbitrary CharSequence
, it should work provided the CharSequence
implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder
and append()
, like so:
final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();
By default p
tags are block
elements, which means they take 100% of the parent width
.
You can change their display property with:
#container p {
display:inline-block;
}
But it puts the elements side by side.
To keep each element on its own line you can use:
#container p {
clear:both;
float:left;
}
(If you use float and need to clear after floated elements, see this link for different techniques: http://css-tricks.com/all-about-floats/)
Demo: http://jsfiddle.net/CvJ3W/5/
Edit
If you go for the solution with display:inline-block
but want to keep each item in one line, you can just add a <br>
tag after each one:
<div id="container">
<p>Sample Text 1</p><br/>
<p>Sample Text 2</p><br/>
<p>Sample Text 3</p><br/>
</div>
New demo: http://jsfiddle.net/CvJ3W/7/
Actually, this is much more simple. You need only two things.
First, you need to find four orthogonal distances from the circle centre to each line of the rectangle. Then your circle will not intersect the rectangle if any three of them are larger than the circle radius.
Second, you need to find the distance between the circle centre and the rectangle centre, then you circle will not be inside of the rectangle if the distance is larger than a half of the rectangle diagonal length.
Good luck!
PEP 8 defines that it is better to use the is
operator when comparing singletons.
Credit to: curiousmind.jlion.com/exceltotextfile (Link no longer exists)
Script:
Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFileName As String)
Dim Q As String
Q = Chr$(34)
Dim sXML As String
sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
sXML = sXML & "<rows>"
''--determine count of columns
Dim iColCount As Integer
iColCount = 1
While Trim$(Cells(iCaptionRow, iColCount)) > ""
iColCount = iColCount + 1
Wend
Dim iRow As Integer
iRow = iDataStartRow
While Cells(iRow, 1) > ""
sXML = sXML & "<row id=" & Q & iRow & Q & ">"
For icol = 1 To iColCount - 1
sXML = sXML & "<" & Trim$(Cells(iCaptionRow, icol)) & ">"
sXML = sXML & Trim$(Cells(iRow, icol))
sXML = sXML & "</" & Trim$(Cells(iCaptionRow, icol)) & ">"
Next
sXML = sXML & "</row>"
iRow = iRow + 1
Wend
sXML = sXML & "</rows>"
Dim nDestFile As Integer, sText As String
''Close any open text files
Close
''Get the number of the next free text file
nDestFile = FreeFile
''Write the entire file to sText
Open sOutputFileName For Output As #nDestFile
Print #nDestFile, sXML
Close
End Sub
Sub test()
MakeXML 1, 2, "C:\Users\jlynds\output2.xml"
End Sub
I faced the similar issue, the main reason behind this was the memory(RAM) consumption by redis. My EC2 machine had 8GB RAM(arounf 7.4 available for consumption)
When my program was running the RAM usage went upto 7.2 GB leaving hardly ~100MB in RAM , this generally triggers the MISCONF Redis error ...
You can determine the RAM consumption using the htop
command. Look for the Mem attribute after running htop command. If it shows high consumtion (like in my case it was 7.2GB/7.4GB) It's better to upgrade the instance's with larger Memory.
In this scenario using config set stop-writes-on-bgsave-error no
will be a disaster for the server and may result in disrupting other services running on the server(if any). So, it better to avoid the config command and UPGRADE YOUR REDIS MACHINE.
FYI: You may need to install htop to make this work : sudo apt-get install htop
One more solution to this can be some other RAM heavy service running on your system, check for other service running on your server/machine/instance and stop it if its not necessary. To check all the services running on your machine use service --status-all
And a suggestion for people directly pasting the config command , please do reasearch a bit and atleast warn the user before using such commands. And as @Rodrigo mentioned in his comment : "It does not look cool to ignore the errors."
---UPDATE---
YOu can also configure maxmemory
and maxmemory-policy
to define the behavior of Redis when a specific limit of memory is reached.
For example, if I want to keep the memory limit of 6GB and delete the least recently used keys from the DB to make sure that redis mem usage do not exceed 6GB, then we can set these two parameters (in redis.conf or CONFIG SET command):
maxmemory 6gb
maxmemory-policy allkeys-lru
There are a lot of other values which you can set for these two parameters you can read about this from here: https://redis.io/topics/lru-cache
You can do:
timeStamp.toLocalDateTime().toLocalDate();
Note that
timestamp.toLocalDateTime()
will use theClock.systemDefaultZone()
time zone to make the conversion. This may or may not be what you want.
use menu Project -> Build Settings ->
then remove armv7s from the"valid architectures". If standard has been chosen then delete that and then add armv7.
When I need to keep the order, I use a list and a companion dict:
color = ['red','green','orange']
fruit = {'apple':0,'mango':1,'orange':2}
color[fruit['apple']]
for i in range(0,len(fruit)): # or len(color)
color[i]
The inconvenience is I don't get easily the fruit from the index. When I need it, I use a tuple:
fruitcolor = [('apple','red'),('mango','green'),('orange','orange')]
index = {'apple':0,'mango':1,'orange':2}
fruitcolor[index['apple']][1]
for i in range(0,len(fruitcolor)):
fruitcolor[i][1]
for f, c in fruitcolor:
c
Your data structures should be designed to fit your algorithm needs, so that it remains clean, readable and elegant.
Sometimes you need to see the width/height changes while resizing the window and inner content.
For that I've written a little script that adds a log box that dynamicly monitors all the resizing and almost immediatly updates.
It adds a valid HTML with fixed position and high z-index, but is small enough, so you can:
Tested on: Chrome 40, IE11, but it is highly possible to work on other/older browsers too ... :)
function gebID(id){ return document.getElementById(id); }
function gebTN(tagName, parentEl){
if( typeof parentEl == "undefined" ) var parentEl = document;
return parentEl.getElementsByTagName(tagName);
}
function setStyleToTags(parentEl, tagName, styleString){
var tags = gebTN(tagName, parentEl);
for( var i = 0; i<tags.length; i++ ) tags[i].setAttribute('style', styleString);
}
function testSizes(){
gebID( 'screen.Width' ).innerHTML = screen.width;
gebID( 'screen.Height' ).innerHTML = screen.height;
gebID( 'window.Width' ).innerHTML = window.innerWidth;
gebID( 'window.Height' ).innerHTML = window.innerHeight;
gebID( 'documentElement.Width' ).innerHTML = document.documentElement.clientWidth;
gebID( 'documentElement.Height' ).innerHTML = document.documentElement.clientHeight;
gebID( 'body.Width' ).innerHTML = gebTN("body")[0].clientWidth;
gebID( 'body.Height' ).innerHTML = gebTN("body")[0].clientHeight;
}
var table = document.createElement('table');
table.innerHTML =
"<tr><th>SOURCE</th><th>WIDTH</th><th>x</th><th>HEIGHT</th></tr>"
+"<tr><td>screen</td><td id='screen.Width' /><td>x</td><td id='screen.Height' /></tr>"
+"<tr><td>window</td><td id='window.Width' /><td>x</td><td id='window.Height' /></tr>"
+"<tr><td>document<br>.documentElement</td><td id='documentElement.Width' /><td>x</td><td id='documentElement.Height' /></tr>"
+"<tr><td>document.body</td><td id='body.Width' /><td>x</td><td id='body.Height' /></tr>"
;
gebTN("body")[0].appendChild( table );
table.setAttribute(
'style',
"border: 2px solid black !important; position: fixed !important;"
+"left: 50% !important; top: 0px !important; padding:10px !important;"
+"width: 150px !important; font-size:18px; !important"
+"white-space: pre !important; font-family: monospace !important;"
+"z-index: 9999 !important;background: white !important;"
);
setStyleToTags(table, "td", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
setStyleToTags(table, "th", "color: black !important; border: none !important; padding: 5px !important; text-align:center !important;");
table.style.setProperty( 'margin-left', '-'+( table.clientWidth / 2 )+'px' );
setInterval( testSizes, 200 );
EDIT: Now styles are applied only to logger table element - not to all tables - also this is a jQuery-free solution :)
The following steps are to reset the password for a user in case you forgot, this would also solve your mentioned error.
First, stop your MySQL:
sudo /etc/init.d/mysql stop
Now start up MySQL in safe mode and skip the privileges table:
sudo mysqld_safe --skip-grant-tables &
Login with root:
mysql -uroot
And assign the DB that needs to be used:
use mysql;
Now all you have to do is reset your root password of the MySQL user and restart the MySQL service:
update user set password=PASSWORD("YOURPASSWORDHERE") where User='root';
flush privileges;
quit and restart MySQL:
quit
sudo /etc/init.d/mysql stop sudo /etc/init.d/mysql start Now your root password should be working with the one you just set, check it with:
mysql -u root -p
Coming From a Hybrid Application POV. This is a javascript example, I have a Update Available footer on my main menu. If an update is available (ie. my version number within the config file is less than the version retrieved, display the footer) This will then direct the user to the app/play store, where the user can then click the update button.
I also get the whats new data (ie Release Notes) and display these in a modal on login if its the first time on this version.
On device Ready, set your store URL
if (device.platform == 'iOS')
storeURL = 'https://itunes.apple.com/lookup?bundleId=BUNDLEID';
else
storeURL = 'https://play.google.com/store/apps/details?id=BUNDLEID';
The Update Available method can be ran as often as you like. Mine is ran every time the user navigates to the home screen.
function isUpdateAvailable() {
if (device.platform == 'iOS') {
$.ajax(storeURL, {
type: "GET",
cache: false,
dataType: 'json'
}).done(function (data) {
isUpdateAvailable_iOS(data.results[0]);
}).fail(function (jqXHR, textStatus, errorThrown) {
commsErrorHandler(jqXHR, textStatus, false);
});
} else {
$.ajax(storeURL, {
type: "GET",
cache: false
}).done(function (data) {
isUpdateAvailable_Android(data);
}).fail(function (jqXHR, textStatus, errorThrown) {
commsErrorHandler(jqXHR, textStatus, false);
});
}
}
iOS Callback: Apple have an API, so very easy to get
function isUpdateAvailable_iOS (data) {
var storeVersion = data.version;
var releaseNotes = data.releaseNotes;
// Check store Version Against My App Version ('1.14.3' -> 1143)
var _storeV = parseInt(storeVersion.replace(/\./g, ''));
var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
$('#ft-main-menu-btn').off();
if (_storeV > _appV) {
// Update Available
$('#ft-main-menu-btn').text('Update Available');
$('#ft-main-menu-btn').click(function () {
openStore();
});
} else {
$('#ft-main-menu-btn').html(' ');
// Release Notes
settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
}
}
Android Callback: PlayStore you have to scrape, as you can see the version is relatively easy to grab and the whats new i take the html instead of the text as this way I can use their formatting (ie new lines etc)
function isUpdateAvailable_Android(data) {
var html = $(data);
var storeVersion = html.find('div[itemprop=softwareVersion]').text().trim();
var releaseNotes = html.find('.whatsnew')[0].innerHTML;
// Check store Version Against My App Version ('1.14.3' -> 1143)
var _storeV = parseInt(storeVersion.replace(/\./g, ''));
var _appV = parseInt(appVersion.substring(1).replace(/\./g, ''));
$('#ft-main-menu-btn').off();
if (_storeV > _appV) {
// Update Available
$('#ft-main-menu-btn').text('Update Available');
$('#ft-main-menu-btn').click(function () {
openStore();
});
} else {
$('#ft-main-menu-btn').html(' ');
// Release Notes
settings.updateReleaseNotes('v' + storeVersion, releaseNotes);
}
}
The open store logic is straight forward, but for completeness
function openStore() {
var url = 'https://itunes.apple.com/us/app/appname/idUniqueID';
if (device.platform != 'iOS')
url = 'https://play.google.com/store/apps/details?id=appid'
window.open(url, '_system')
}
Ensure Play Store and App Store have been Whitelisted:
<access origin="https://itunes.apple.com"/>
<access origin="https://play.google.com"/>
For Chrome via Chrome Fullscreen API
Note that for (Chrome) security reasons it cannot be called or executed automatically, there must be an interaction from the user first. (Such as button click, keydown/keypress etc.)
addEventListener("click", function() {
var
el = document.documentElement
, rfs =
el.requestFullScreen
|| el.webkitRequestFullScreen
|| el.mozRequestFullScreen
;
rfs.call(el);
});
Javascript Fullscreen API as demo'd by David Walsh that seems to be a cross browser solution
// Find the right method, call on correct element
function launchFullScreen(element) {
if(element.requestFullScreen) {
element.requestFullScreen();
} else if(element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if(element.webkitRequestFullScreen) {
element.webkitRequestFullScreen();
}
}
// Launch fullscreen for browsers that support it!
launchFullScreen(document.documentElement); // the whole page
launchFullScreen(document.getElementById("videoElement")); // any individual element
Use capital HH
to get hour of day format, instead of am/pm hours
If you attach the same event handler to several events, you often run into the issue of more than one of them firing at once (e.g. user presses tab after editing; keydown, change, and blur might all fire).
It sounds like what you actually want is something like this:
$('#ValidatedInput').keydown(function(evt) {
// If enter is pressed
if (evt.keyCode === 13) {
evt.preventDefault();
// If changes have been made to the input's value,
// blur() will result in a change event being fired.
this.blur();
}
});
$('#ValidatedInput').change(function(evt) {
var valueToValidate = this.value;
// Your validation callback/logic here.
});
function setWidth(width) {
var canvas = document.getElementById("myCanvas");
canvas.width = width;
}
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
Add
"aaSorting": []
And check if default value is not null
only set sortable column then
if ($('#table').DataTable().order().length == 1) {
d.SortColumn = $('#table').DataTable().order()[0][0];
d.SortOrder = $('#table').DataTable().order()[0][1];
}
BTW, if anyone want to get coordinates of element on screen without jQuery, please try this:
function getOffsetTop (el) {
if (el.offsetParent) return el.offsetTop + getOffsetTop(el.offsetParent)
return el.offsetTop || 0
}
function getOffsetLeft (el) {
if (el.offsetParent) return el.offsetLeft + getOffsetLeft(el.offsetParent)
return el.offsetleft || 0
}
function coordinates(el) {
var y1 = getOffsetTop(el) - window.scrollY;
var x1 = getOffsetLeft(el) - window.scrollX;
var y2 = y1 + el.offsetHeight;
var x2 = x1 + el.offsetWidth;
return {
x1: x1, x2: x2, y1: y1, y2: y2
}
}
Treat IllegalArgumentException
as a preconditions check, and consider the design principle: A public method should both know and publicly document its own preconditions.
I would agree this example is correct:
void setPercentage(int pct) {
if( pct < 0 || pct > 100) {
throw new IllegalArgumentException("bad percent");
}
}
If EmailUtil is opaque, meaning there's some reason the preconditions cannot be described to the end-user, then a checked exception is correct. The second version, corrected for this design:
import com.someoneelse.EmailUtil;
public void scanEmail(String emailStr, InputStream mime) throws ParseException {
EmailAddress parsedAddress = EmailUtil.parseAddress(emailStr);
}
If EmailUtil is transparent, for instance maybe it's a private method owned by the class under question, IllegalArgumentException
is correct if and only if its preconditions can be described in the function documentation. This is a correct version as well:
/** @param String email An email with an address in the form [email protected]
* with no nested comments, periods or other nonsense.
*/
public String scanEmail(String email)
if (!addressIsProperlyFormatted(email)) {
throw new IllegalArgumentException("invalid address");
}
return parseEmail(emailAddr);
}
private String parseEmail(String emailS) {
// Assumes email is valid
boolean parsesJustFine = true;
// Parse logic
if (!parsesJustFine) {
// As a private method it is an internal error if address is improperly
// formatted. This is an internal error to the class implementation.
throw new AssertError("Internal error");
}
}
This design could go either way.
ParseException
. The top level method here is named scanEmail
which hints the end user intends to send unstudied email through so this is likely correct.IllegalArgumentException
. Although not "checked" the "check" moves to the Javadoc documenting the function, which the client is expected to adhere to. IllegalArgumentException
where the client can't tell their argument is illegal beforehand is wrong.A note on IllegalStateException: This means "this object's internal state (private instance variables) is not able to perform this action." The end user cannot see private state so loosely speaking it takes precedence over IllegalArgumentException
in the case where the client call has no way to know the object's state is inconsistent. I don't have a good explanation when it's preferred over checked exceptions, although things like initializing twice, or losing a database connection that isn't recovered, are examples.
In order to set textColor, BottomNavigationView
has two style properties you can set directly from the xml:
itemTextAppearanceActive
itemTextAppearanceInactive
In your layout.xml file:
<com.google.android.material.bottomnavigation.BottomNavigationView
android:id="@+id/bnvMainNavigation"
style="@style/NavigationView"/>
In your styles.xml file:
<style name="NavigationView" parent="Widget.MaterialComponents.BottomNavigationView">
<item name="itemTextAppearanceActive">@style/ActiveText</item>
<item name="itemTextAppearanceInactive">@style/InactiveText</item>
</style>
<style name="ActiveText">
<item name="android:textColor">@color/colorPrimary</item>
</style>
<style name="InactiveText">
<item name="android:textColor">@color/colorBaseBlack</item>
</style>
Set it in the JAVA_OPTS
variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.
JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5
Managed code is what Visual Basic .NET and C# compilers create. It runs on the CLR (Common Language Runtime), which, among other things, offers services like garbage collection, run-time type checking, and reference checking. So, think of it as, "My code is managed by the CLR."
Visual Basic and C# can only produce managed code, so, if you're writing an application in one of those languages you are writing an application managed by the CLR. If you are writing an application in Visual C++ .NET you can produce managed code if you like, but it's optional.
Unmanaged code compiles straight to machine code. So, by that definition all code compiled by traditional C/C++ compilers is 'unmanaged code'. Also, since it compiles to machine code and not an intermediate language it is non-portable.
No free memory management or anything else the CLR provides.
Since you cannot create unmanaged code with Visual Basic or C#, in Visual Studio all unmanaged code is written in C/C++.
Since Visual C++ can be compiled to either managed or unmanaged code it is possible to mix the two in the same application. This blurs the line between the two and complicates the definition, but it's worth mentioning just so you know that you can still have memory leaks if, for example, you're using a third party library with some badly written unmanaged code.
Here's an example I found by googling:
#using <mscorlib.dll>
using namespace System;
#include "stdio.h"
void ManagedFunction()
{
printf("Hello, I'm managed in this section\n");
}
#pragma unmanaged
UnmanagedFunction()
{
printf("Hello, I am unmanaged through the wonder of IJW!\n");
ManagedFunction();
}
#pragma managed
int main()
{
UnmanagedFunction();
return 0;
}
Note that this answer is outdated! The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL. See the other answers for more current solutions.
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
Update
The procedure presented below gives an example of parsing XML with VBA using the XML DOM objects. Code is based on a beginners guide of the XML DOM.
Public Sub LoadDocument()
Dim xDoc As MSXML.DOMDocument
Set xDoc = New MSXML.DOMDocument
xDoc.validateOnParse = False
If xDoc.Load("C:\My Documents\sample.xml") Then
' The document loaded successfully.
' Now do something intersting.
DisplayNode xDoc.childNodes, 0
Else
' The document failed to load.
' See the previous listing for error information.
End If
End Sub
Public Sub DisplayNode(ByRef Nodes As MSXML.IXMLDOMNodeList, _
ByVal Indent As Integer)
Dim xNode As MSXML.IXMLDOMNode
Indent = Indent + 2
For Each xNode In Nodes
If xNode.nodeType = NODE_TEXT Then
Debug.Print Space$(Indent) & xNode.parentNode.nodeName & _
":" & xNode.nodeValue
End If
If xNode.hasChildNodes Then
DisplayNode xNode.childNodes, Indent
End If
Next xNode
End Sub
Nota Bene - This initial answer shows the simplest possible thing I could imagine (at the time I was working on a very specific issue) . Naturally using the XML facilities built into the VBA XML Dom would be much better. See the updates above.
Original Response
I know this is a very old post but I wanted to share my simple solution to this complicated question. Primarily I've used basic string functions to access the xml data.
This assumes you have some xml data (in the temp variable) that has been returned within a VBA function. Interestingly enough one can also see how I am linking to an xml web service to retrieve the value. The function shown in the image also takes a lookup value because this Excel VBA function can be accessed from within a cell using = FunctionName(value1, value2) to return values via the web service into a spreadsheet.
openTag = ""
closeTag = ""
' Locate the position of the enclosing tags
startPos = InStr(1, temp, openTag)
endPos = InStr(1, temp, closeTag)
startTagPos = InStr(startPos, temp, ">") + 1
' Parse xml for returned value
Data = Mid(temp, startTagPos, endPos - startTagPos)
According to CodeGuru:
CString
to std::string
:
CString cs("Hello");
std::string s((LPCTSTR)cs);
BUT: std::string
cannot always construct from a LPCTSTR
. i.e. the code will fail for UNICODE builds.
As std::string
can construct only from LPSTR
/ LPCSTR
, a programmer who uses VC++ 7.x or better can utilize conversion classes such as CT2CA
as an intermediary.
CString cs ("Hello");
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString (cs);
// construct a std::string using the LPCSTR input
std::string strStd (pszConvertedAnsiString);
std::string
to CString
: (From Visual Studio's CString FAQs...)
std::string s("Hello");
CString cs(s.c_str());
CStringT
can construct from both character or wide-character strings. i.e. It can convert from char*
(i.e. LPSTR
) or from wchar_t*
(LPWSTR
).
In other words, char-specialization (of CStringT
) i.e. CStringA
, wchar_t
-specilization CStringW
, and TCHAR
-specialization CString
can be constructed from either char
or wide-character, null terminated (null-termination is very important here) string sources.
Althoug IInspectable amends the "null-termination" part in the comments:
NUL-termination is not required.
CStringT
has conversion constructors that take an explicit length argument. This also means that you can constructCStringT
objects fromstd::string
objects with embeddedNUL
characters.
For anyone else coming across this thread I had this issue and was pulling my hair out. I had the service declaration OUTSIDE of the '< application>' end tag DUH!
RIGHT:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity ...>
...
</activity>
<service android:name=".Service"/>
<receiver android:name=".Receiver">
<intent-filter>
...
</intent-filter>
</receiver>
</application>
<uses-permission android:name="..." />
WRONG but still compiles without errors:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>
...
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity ...>
...
</activity>
</application>
<service android:name=".Service"/>
<receiver android:name=".Receiver">
<intent-filter>
...
</intent-filter>
</receiver>
<uses-permission android:name="..." />
This is quite simple:
my_data
is a before defined structure type.
So you want to declare an my_data
-array of some elements, as you would do with
char a[] = { 'a', 'b', 'c', 'd' };
So the array would have 4 elements and you initialise them as
a[0] = 'a', a[1] = 'b', a[1] = 'c', a[1] ='d';
This is called a designated initializer (as i remember right).
and it just indicates that data has to be of type my_dat
and has to be an array that needs to store so many my_data structures that there is a structure with each type member name Peter, James, John and Mike.
Another approach (based on docker-postgresql-workflow)
Local running database (not in docker, but same approach would work) to export:
pg_dump -F c -h localhost mydb -U postgres export.dmp
Container database to import:
docker run -d -v /local/path/to/postgres:/var/lib/postgresql/data postgres #ex runs container as `CONTAINERNAME` #find via `docker ps`
docker run -it --link CONTAINERNAME:postgres --volume $PWD/:/tmp/ postgres bash -c 'exec pg_restore -h postgres -U postgres -d mydb -F c /tmp/sonar.dmp'
I really enjoy a new literal string interpolation in Python 3.6+:
line_new = f'{word[0]:>12} {word[1]:>12} {word[2]:>12}'
Reference: PEP 498 -- Literal String Interpolation
You can use the Y-combinator: (Wikipedia)
// ES5 syntax
var Y = function Y(a) {
return (function (a) {
return a(a);
})(function (b) {
return a(function (a) {
return b(b)(a);
});
});
};
// ES6 syntax
const Y = a=>(a=>a(a))(b=>a(a=>b(b)(a)));
// If the function accepts more than one parameter:
const Y = a=>(a=>a(a))(b=>a((...a)=>b(b)(...a)));
And you can use it as this:
// ES5
var fn = Y(function(fn) {
return function(counter) {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
}
});
// ES6
const fn = Y(fn => counter => {
console.log(counter);
if (counter > 0) {
fn(counter - 1);
}
});
double click the button and add write // this.close();
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
Use a JSON library to parse the string and retrieve the value.
The following very basic example uses the built-in JSON parser from Android.
String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }";
JSONObject jsonObject = new JSONObject(jsonString);
int age = jsonObject.getInt("age");
More advanced JSON libraries, such as jackson, google-gson, json-io or genson, allow you to convert JSON objects to Java objects directly.
If your 13 digit "number" is really text, that is you don't intend to do any math on it, you can precede it with an apostrophe
Sheet3.Range("c" & k).Value = "'" & Sheet2.Range("c" & i).Value
But I don't see how a 13 digit number would ever get past the If statement because it would always be greater than 1000. Here's an alternate version
Sub CommandClick()
Dim rCell As Range
Dim rNext As Range
For Each rCell In Sheet2.Range("C1:C30000").Cells
If rCell.Value >= 100 And rCell.Value < 1000 Then
Set rNext = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Offset(1, 0)
rNext.Resize(1, 3).Value = rCell.Offset(0, -2).Resize(1, 3).Value
End If
Next rCell
End Sub
This is the simplest way you could test
$query = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");
if($query) // will return true if succefull else it will return false
{
// code here
}
Test2 test = new Test2();
...
frame.add(test, BorderLayout.CENTER);
Are you sure of this? test
is NOT a component!
To do what you're trying to do you should let Test2
extend JPanel
!
To sort by a property in the object, you have to specify a comparer or a method to get that property.
Using the List.Sort
method:
theList.Sort(Function(x, y) x.age.CompareTo(y.age))
Using the OrderBy
extension method:
theList = theList.OrderBy(Function(x) x.age).ToList()
This is for all those like me, which need to update the Viewpager from a service (or other background thread) and none of the proposals have worked: After a bit of logchecking i realized, that the notifyDataSetChanged() method never returns. getItemPosition(Object object) is called an all ends there without further processing. Then i found in the docs of the parent PagerAdapter class (is not in the docs of the subclasses), "Data set changes must occur on the main thread and must end with a call to notifyDataSetChanged() ". So, the working solution in this case was (using FragmentStatePagerAdapter and getItemPosition(Object object) set to return POSITION_NONE) :
and then the call to notifyDataSetChanged() :
runOnUiThread(new Runnable() {
@Override
public void run() {
pager.getAdapter().notifyDataSetChanged();
}
});
I know this is an older thread, but just to add another perspective. I'd assert that using overrides is really a bit of a code smell and will quickly get out of hand on larger projects. Today you're overriding Buttons, tomorrow Modals, the next day it Dropdowns, etc., etc.
I'd advise to try possibly commenting out the include for buttons.less
and either define my own, or, find another Buttons library that's more suitable to my project. Shameless plug: here's an example of how easy it is to mix our Buttons library with TB: Using Buttons with Twitter Bootstrap. In practice, again, you'd likely want to remove the buttons.less
include altogether to improve performance but this shows how you can make things look a bit less "generic". I haven't done this exercise yet myself but I'd imagine you could start by simply commenting out lines like:
https://github.com/twbs/bootstrap/blob/master/less/bootstrap.less#L17
And then recompiling using `lessc using one of your own buttons modules. That way you get the battle tested core of TB but can still customize things without resorting to major overrides. There's absolutely no reason not to use only parts of a library like Bootstrap. Of course the same applies to the Sass version of TB
The best way Using dirname(). Because SERVER['DOCUMENT_ROOT'] not working all servers, and also return server running path.
$root = dirname( __FILE__ );
$root = __DIR__;
$filePath = realpath(dirname(__FILE__));
$rootPath = realpath($_SERVER['DOCUMENT_ROOT']);
$htmlPath = str_replace($root, '', $filePath);
Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles Me.Shown
TextBox1.Select()
End Sub
void SomeClass::changeASettingAndCallAFunction() const {
someSetting = 0; //Can't do this
someFunctionThatUsesTheSetting();
}
Another solution is to call said function in-between making edits to variables that the const function uses. This idea was what solved my problem being as I was not inclined to change the signature of the function and had to use the "changeASettingAndCallAFunction" method as a mediator:
When you call the function you can first make edits to the setting before the call, or (if you aren't inclined to mess with the invoking place) perhaps call the function where you need the change to the variable to be propagated (like in my case).
void SomeClass::someFunctionThatUsesTheSetting() const {
//We really don't want to touch this functions implementation
ClassUsesSetting* classUsesSetting = ClassUsesSetting::PropagateAcrossClass(someSetting);
/*
Do important stuff
*/
}
void SomeClass::changeASettingAndCallAFunction() const {
someFunctionThatUsesTheSetting();
/*
Have to do this
*/
}
void SomeClass::nonConstInvoker(){
someSetting = 0;
changeASettingAndCallAFunction();
}
Now, when some reference to "someFunctionThatUsesTheSetting" is invoked, it will invoke with the change to someSetting.
The best option is to use the free community version of Intellij Idea 11+. The ADT eclipse plugin is always having problems.
You could upload via $resource
by assigning data to params attribute of resource actions
like so:
$scope.uploadFile = function(files) {
var fdata = new FormData();
fdata.append("file", files[0]);
$resource('api/post/:id', { id: "@id" }, {
postWithFile: {
method: "POST",
data: fdata,
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
}
}).postWithFile(fdata).$promise.then(function(response){
//successful
},function(error){
//error
});
};
Just in case you want to try something else. This is what worked for me:
Based on Ternary Operator which has following structure:
condition ? value-if-true : value-if-false
As result:
{{gallery.date?(gallery.date | date:'mediumDate'):"Various" }}
You can use "wildcards" with MATCH
so assuming "ASDFGHJK" in H1 as per Peter's reply you can use this regular formula
=INDEX(G:G,MATCH("*"&H1&"*",G:G,0)+3)
MATCH can only reference a single column or row so if you want to search 6 columns you either have to set up a formula with 6 MATCH functions or change to another approach - try this "array formula", assuming search data in A2:G100
=INDIRECT("R"&REPLACE(TEXT(MIN(IF(ISNUMBER(SEARCH(H1,A2:G100)),(ROW(A2:G100)+3)*1000+COLUMN(A2:G100))),"000000"),4,0,"C"),FALSE)
confirmed with Ctrl-Shift-Enter
If you are using Sql Server this should work
DECLARE @Table TABLE(
ID INT,
Val INT
)
INSERT INTO @Table (ID,Val) SELECT 1, 3
INSERT INTO @Table (ID,Val) SELECT 2, NULL
INSERT INTO @Table (ID,Val) SELECT 3, 5
INSERT INTO @Table (ID,Val) SELECT 4, NULL
INSERT INTO @Table (ID,Val) SELECT 5, NULL
INSERT INTO @Table (ID,Val) SELECT 6, 2
SELECT *,
ISNULL(Val, (SELECT TOP 1 Val FROM @Table WHERE ID < t.ID AND Val IS NOT NULL ORDER BY ID DESC))
FROM @Table t
I am not sure did you see this list of MS SQL Modules for Node JS
Share your experience after using one if possible .
Good Luck
@tux answer is great, just wanted to add that you can use go get to update a specific package:
go get -u full_package_name
Do dtEmp
on your current working DataTable:
DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);
It's nice.
List installed dependencies:
composer show -i
composer show -i -t
-i
short for --installed
.
-t
short for --tree
.
Actually if you need to test background fetch you need to enable one option in scheme:
Another way how you can test it:
Here is full information about this new feature: http://www.objc.io/issue-5/multitasking.html
I use this script for autocomplete...
$('#custmoers_name').autocomplete({
source: function (request, response) {
// $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
$.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
console.log(data);
response($.map(data, function (value, key) {
console.log(value);
return {
label: value.label,
value: value.value
};
}));
});
},
minLength: 1,
delay: 100
});
My json return :- [{"label":"Mahesh Arun Wani","value":"1"}]
after search m
but it display in dropdown [object object]
...
You can load an XML document into an XMLType, then query it, e.g.:
DECLARE
x XMLType := XMLType(
'<?xml version="1.0" ?>
<person>
<row>
<name>Tom</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
<row>
<name>Jim</name>
<Address>
<State>California</State>
<City>Los angeles</City>
</Address>
</row>
</person>');
BEGIN
FOR r IN (
SELECT ExtractValue(Value(p),'/row/name/text()') as name
,ExtractValue(Value(p),'/row/Address/State/text()') as state
,ExtractValue(Value(p),'/row/Address/City/text()') as city
FROM TABLE(XMLSequence(Extract(x,'/person/row'))) p
) LOOP
-- do whatever you want with r.name, r.state, r.city
END LOOP;
END;
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
There is only one public signature allowed for each controller method. If you try to overload it, it will compile, but you're getting the run-time error you've experienced.
If you're not willing to use different verbs (like the [HttpGet]
and [HttpPost]
attributes) to differentiate overloaded methods (which will work), or change the routing, then what remains is that you can either provide another method with a different name, or you can dispatch inside of the existing method. Here's how I did it:
I once came into a situation where I had to maintain backwards compatibility. The original method expected two parameters, but the new one had only one. Overloading the way I expected did not work because MVC didn't find the entry point any more.
To solve that, I did the following:
Created one new public method which contained "just" 2 string parameters. That one acted as a dispatcher, i.e.:
public ActionResult DoSomething(string param1, string param2)
{
if (string.IsNullOrEmpty(param2))
{
return DoSomething(ProductName: param1);
}
else
{
int oldId = int.Parse(param1);
return DoSomething(OldParam: param1, OldId: oldId);
}
}
private ActionResult DoSomething(string OldParam, int OldId)
{
// some code here
return Json(result);
}
private ActionResult DoSomething(string ProductName)
{
// some code here
return Json(result);
}
Of course, this is a hack and should be refactored later. But for the time being, it worked for me.
You can also create a dispatcher like:
public ActionResult DoSomething(string action, string param1, string param2)
{
switch (action)
{
case "update":
return UpdateAction(param1, param2);
case "remove":
return DeleteAction(param1);
}
}
You can see, that UpdateAction needs 2 parameters, while DeleteAction just needs one.
Just Add these 2 permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in your app's AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.networkusage"
...>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
...>
...
</application>
</manifest>
Happy Coding:)
Just use the size attribute:
<select name="sometext" size="5">
<option>text1</option>
<option>text2</option>
<option>text3</option>
<option>text4</option>
<option>text5</option>
</select>
To clarify, adding the size attribute did not remove the multiple selection.
The single selection works because you removed the multiple="multiple" attribute.
Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here
While your Sleep
method is async, Thread.Sleep
is not. The whole idea of async is to reuse a single thread, not to start multiple threads. Because you've blocked using a synchronous call to Thread.Sleep, it's not going to work.
I'm assuming that Thread.Sleep
is a simplification of what you actually want to do. Can your actual implementation be coded as async methods?
If you do need to run multiple synchronous blocking calls, look elsewhere I think!
You can use dateutil.parser.parse
(install with python -m pip install python-dateutil
) to parse strings into datetime objects.
dateutil.parser.parse
will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime
which you supply a format string to (see Brent Washburne's answer).
from dateutil.parser import parse
a = "2012-10-09T19:00:55Z"
b = parse(a)
print(b.weekday())
# 1 (equal to a Tuesday)
As the other commenters are suggesting the most efficient way to do it seems to be:
if ($(selector).length ) {
// Do something
}
If you absolutely must have an exists() function - which will be slower- you can do:
jQuery.fn.exists = function(){return this.length>0;}
Then in your code you can use
if ($(selector).exists()) {
// Do something
}
As answered here
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
For the folks that like me got here because they're trying to host aspnet.core mvc in a console application: The ONLY way I was able to solve this was by converting the .csproj to the new format and add the Sdk property to the Project tag on the very first line.
<Project Sdk="Microsoft.NET.Sdk.Razor">
from datetime import datetime
start_date = datetime.strptime('8/18/2008', "%m/%d/%Y")
end_date = datetime.strptime('9/26/2008', "%m/%d/%Y")
print abs((end_date-start_date).days)
My take on this for future people watching this:
This could also happen if you're using: <?
instead of <?php
.
Summary : Use an external script (batch file) that a) stops the server and b) Unlocks the .jar file before running maven-clean.
Steps:
Bind the maven-antrun-plugin:run goal to the pre-clean phase of mvn clean. See how to do this here
See how to use the antrun plugin to run an external batch file in Windows here : sblundy's answer to "Starting external process". Let's call this file unlock_handles.bat
Use the Sysinternals handle utility download link in the pre_clean.bat to a) stop the Tomcat server and b) unlock the .jar file. handle -c
and handle -p
would be useful here.
Whew! That's a bit of work, but it will reliably automate the process for you so that you do need to do it manually yourself each time!
OK, here's a rough, proof-of-concept version of unlock_handles.bat for you to try out:
REM "Use handle.exe to figure out the process id and handle ids, parse the output, then close the handle (again using handle.exe)"
cd "C:\Users\Nikolay_Tkachev\workspace\HHSystem\UI\target"
"c:/Program Files/Process Explorer/handle.exe" -p java.exe "C:\Users\Nikolay_Tkachev\workspace\HHSystem\UI\target" > handles.txt
@echo "O====== Going to unlock all the below file handles! =======O"
FOR /F "tokens=1-26 delims=: " %a in (handles.txt) DO @echo %h
FOR /F "tokens=1-26 delims=: " %a in (handles.txt) DO handle -p %c -c %f -y
Of course, you have to change the path to Sysinternals' handle.exe before giving this a try.
Use df.index.rename('foo', inplace=True)
to set the index name.
Seems this api is available since pandas 0.13.
if you can write a batch file that does not need to be interactive, try running that batch file as a service, to do what needs to be done.
Ditto for @Andreas_D, in addition if you say update Spring from 1 version to another in your project without doing a clean, you'll wind up with both in your artifact. Ran into this a lot when doing Flex development with Maven.
I've been using this function in my project.
function changeViewPort(key, val) {
var reg = new RegExp(key, "i"), oldval = document.querySelector('meta[name="viewport"]').content;
var newval = reg.test(oldval) ? oldval.split(/,\s*/).map(function(v){ return reg.test(v) ? key+"="+val : v; }).join(", ") : oldval+= ", "+key+"="+val ;
document.querySelector('meta[name="viewport"]').content = newval;
}
so just addEventListener:
if( /iPad|iPhone|iPod|Android/i.test(navigator.userAgent) ){
window.addEventListener("orientationchange", function() {
changeViewPort("maximum-scale", 1);
changeViewPort("maximum-scale", 10);
}
}
Use an explicit wait
for the element like this:
WebDriverWait wait1 = new WebDriverWait(driver, 500);
wait1.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("path of element"))).click();
I know this is an old Question, but it popped up when I was looking for a solution to the same issue, so I thought that I would post what worked for me.
<asp:BoundField DataField="Description" HeaderText="Bond Event" ItemStyle-Width="300px" />
I used the ItemStyle-Width
attribute on my BoundField
and it worked very nicely I haven't had any issues yet.
I didn't need to add anything else to the rest of the code to make this work either.
For a test task, you can use the environment property like this:
test {
environment "VAR", "val"
}
you can also use the environment property in an exec task
task dropDatabase(type: Exec) {
environment "VAR", "val"
commandLine "doit"
}
Note that with this method the environment variables are set only during the task.
Array starts from index 0 and ends at n-1.
static void Main(string[] args)
{
int[] arr = { 1, 2, 3, 4, 5 };
int length = arr.Length - 1; // starts from 0 to n-1
Console.WriteLine(length); // this will give the last index.
Console.Read();
}
The full paramiko distribution ships with a lot of good demos.
In the demos subdirectory, demo.py
and interactive.py
have full interactive TTY examples which would probably be overkill for your situation.
In your example above ssh_stdin
acts like a standard Python file object, so ssh_stdin.write
should work so long as the channel is still open.
I've never needed to write to stdin, but the docs suggest that a channel is closed as soon as a command exits, so using the standard stdin.write
method to send a password up probably won't work. There are lower level paramiko commands on the channel itself that give you more control - see how the SSHClient.exec_command
method is implemented for all the gory details.
Remember before you merge you need to update the tag, it's quite different from branches (git pull origin tag_name
won't update your local tags). Thus, you need the following command:
git fetch --tags origin
Then you can perform git merge tag_name
to merge the tag onto a branch.
Repurposing the pdf2txt.py code that comes with pdfminer; you can make a function that will take a path to the pdf; optionally, an outtype (txt|html|xml|tag) and opts like the commandline pdf2txt {'-o': '/path/to/outfile.txt' ...}. By default, you can call:
convert_pdf(path)
A text file will be created, a sibling on the filesystem to the original pdf.
def convert_pdf(path, outtype='txt', opts={}):
import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, process_pdf
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter, TagExtractor
from pdfminer.layout import LAParams
from pdfminer.pdfparser import PDFDocument, PDFParser
from pdfminer.pdfdevice import PDFDevice
from pdfminer.cmapdb import CMapDB
outfile = path[:-3] + outtype
outdir = '/'.join(path.split('/')[:-1])
debug = 0
# input option
password = ''
pagenos = set()
maxpages = 0
# output option
codec = 'utf-8'
pageno = 1
scale = 1
showpageno = True
laparams = LAParams()
for (k, v) in opts:
if k == '-d': debug += 1
elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )
elif k == '-m': maxpages = int(v)
elif k == '-P': password = v
elif k == '-o': outfile = v
elif k == '-n': laparams = None
elif k == '-A': laparams.all_texts = True
elif k == '-D': laparams.writing_mode = v
elif k == '-M': laparams.char_margin = float(v)
elif k == '-L': laparams.line_margin = float(v)
elif k == '-W': laparams.word_margin = float(v)
elif k == '-O': outdir = v
elif k == '-t': outtype = v
elif k == '-c': codec = v
elif k == '-s': scale = float(v)
#
CMapDB.debug = debug
PDFResourceManager.debug = debug
PDFDocument.debug = debug
PDFParser.debug = debug
PDFPageInterpreter.debug = debug
PDFDevice.debug = debug
#
rsrcmgr = PDFResourceManager()
if not outtype:
outtype = 'txt'
if outfile:
if outfile.endswith('.htm') or outfile.endswith('.html'):
outtype = 'html'
elif outfile.endswith('.xml'):
outtype = 'xml'
elif outfile.endswith('.tag'):
outtype = 'tag'
if outfile:
outfp = file(outfile, 'w')
else:
outfp = sys.stdout
if outtype == 'txt':
device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)
elif outtype == 'xml':
device = XMLConverter(rsrcmgr, outfp, codec=codec, laparams=laparams, outdir=outdir)
elif outtype == 'html':
device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale, laparams=laparams, outdir=outdir)
elif outtype == 'tag':
device = TagExtractor(rsrcmgr, outfp, codec=codec)
else:
return usage()
fp = file(path, 'rb')
process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password)
fp.close()
device.close()
outfp.close()
return
TiCPP is a "more c++" version of TinyXML.
'TiCPP' is short for the official name TinyXML++. It is a completely new interface to TinyXML (http://www.grinninglizard.com/tinyxml/) that uses MANY of the C++ strengths. Templates, exceptions, and much better error handling. It is also fully documented in doxygen. It is really cool because this version let's you interface tiny the exact same way as before or you can choose to use the new 'ticpp' classes. All you need to do is define TIXML_USE_TICPP. It has been tested in VC 6.0, VC 7.0, VC 7.1, VC 8.0, MinGW gcc 3.4.5, and in Linux GNU gcc 3+
Try this through random.shuffle
>>> import random
>>> nums = range(10)
>>> random.shuffle(nums)
>>> nums
[6, 3, 5, 4, 0, 1, 2, 9, 8, 7]
Here's an example to get ASM-7 using Maven 3.6:
mvn dependency:get -DremoteRepositories=maven.apache.org -Dartifact=org.ow2.asm:7.0:sources:jar
Or you can download the jar from here: https://search.maven.org/search?q=g:org.ow2.asm%20AND%20a:asm and then
mvn install:install-file -DgroupId=org.ow2.asm -DartifactId=asm -Dversion=7.0 -Dclassifier=sources -Dpackaging=jar -Dfile=/path/to/asm-7.0.jar
var customView = UIView()
@IBAction func drawView(_ sender: AnyObject) {
customView.frame = CGRect.init(x: 0, y: 0, width: 100, height: 200)
customView.backgroundColor = UIColor.black //give color to the view
customView.center = self.view.center
self.view.addSubview(customView)
}
Just wanted to mention, that you also may have to set the https_proxy
OS environment variable in case https URLs need to be accessed.
In my case it was not obvious to me and I tried for hours to discover this.
My use case: Win 7, jython-standalone-2.5.3.jar, setuptools installation via ez_setup.py
meld 3.14.0
[merge]
tool = meld
[mergetool "meld"]
path = C:/Program Files (x86)/Meld/Meld.exe
cmd = \"C:/Program Files (x86)/Meld/Meld.exe\" --diff \"$BASE\" \"$LOCAL\" \"$REMOTE\" --output \"$MERGED\"
This works in Mavericks (OSX 10.9.2).
sudo lsof -nP -iTCP:$PORT -sTCP:LISTEN
After setting the path of your jdk use JPS
.Then You can eaisly kill it by Task ManagerJPS
will give you all java processes
This will work fine with Linq to Objects. However, some LINQ providers have difficulty running CLR methods as part of the query. This is expecially true of some database providers.
The problem is that the DB providers try to move and compile the LINQ query as a database query, to prevent pulling all of the objects across the wire. This is a good thing, but does occasionally restrict the flexibility in your predicates.
Unfortunately, without checking the provider documentation, it's difficult to always know exactly what will or will not be supported directly in the provider. It looks like your provider allows comparisons, but not the string check. I'd guess that, in your case, this is probably about as good of an approach as you can get. (It's really not that different from the IsNullOrEmpty check, other than creating the "string.Empty" instance for comparison, but that's minor.)
Do whatever you want to do after the file loads successfully.just after the completion of your file processing set the value of file control to blank string.so the .change() will always be called even the file name changes or not. like for example you can do this thing and worked for me like charm
$('#myFile').change(function () {
LoadFile("myFile");//function to do processing of file.
$('#myFile').val('');// set the value to empty of myfile control.
});
ThreadLocalRandom
ThreadLocalRandom
has a nextLong(long bound)
method.
long v = ThreadLocalRandom.current().nextLong(100);
It also has nextLong(long origin, long bound)
if you need an origin other than 0. Pass the origin (inclusive) and the bound (exclusive).
long v = ThreadLocalRandom.current().nextLong(10,100); // For 2-digit integers, 10-99 inclusive.
SplittableRandom
has the same nextLong
methods and allows you to choose a seed if you want a reproducible sequence of numbers.
already their is enough help full answers but if you want to see the process then
[ click here ]
Steps in Short
update php.ini file with following lines :
[XDebug]
xdebug.remote_enable = 1
xdebug.remote_autostart = 1
zend_extension=path/to/xdebug
[ good to go ]
What's wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me
>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True
@kindall's solution is a quick example of how good the code would look.
You can call it three ways - with parameters, with DEFAULT and via EXECUTE
SET NOCOUNT ON;
DECLARE
@Table SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows INT;
SELECT dbo.TableRowCount( @Table, @Schema )
SELECT dbo.TableRowCount( @Table, DEFAULT )
EXECUTE @Rows = dbo.TableRowCount @Table
SELECT @Rows
I encountered this issue in a NodeJS Lambda function that was triggered by a file upload to S3.
My mistake was that I was not decoding the object key, which contained a colon. Corrected my code as follows:
let key = decodeURIComponent(event.Records[0].s3.object.key);
# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0
(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:
levels(df$species) <- c(levels(df$species), "unknown")
df$species[df$depth<10] <- "unknown"
Your quotes only need to surround the value part of the attribute-equals selector, [attr='val']
, like this:
$('a#check_var').click(function() {
alert($("input:radio[name='r']:checked").val()+ ' '+
$("input:radio[name='s']:checked").val());
});?
The photos
property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count
property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
Use the #
syntax for comments
From: https://docs.docker.com/engine/reference/builder/#format
# My comment here
RUN echo 'we are running some cool things'
A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
I know this question is very old, but just came up with the same problem and solved it myself, so I'm answering in case anyone finds this through google as I did. I based my solution on @Andrew's one, but basically modified everything afterwards.
EDIT: seeing how popular this has been lately, I decided to update also the styles to make it look more like 2014 and less like windows 95. I fixed the bugs @Quantico and @Trengot spotted so now it's a more solid answer.
EDIT 2: I set it up with StackSnippets as they're a really cool new feature. I leave the good jsfiddle here for reference thought (click on the 4th panel to see them work).
New Stack Snippet:
// JAVASCRIPT (jQuery)_x000D_
_x000D_
// Trigger action when the contexmenu is about to be shown_x000D_
$(document).bind("contextmenu", function (event) {_x000D_
_x000D_
// Avoid the real one_x000D_
event.preventDefault();_x000D_
_x000D_
// Show contextmenu_x000D_
$(".custom-menu").finish().toggle(100)._x000D_
_x000D_
// In the right position (the mouse)_x000D_
css({_x000D_
top: event.pageY + "px",_x000D_
left: event.pageX + "px"_x000D_
});_x000D_
});_x000D_
_x000D_
_x000D_
// If the document is clicked somewhere_x000D_
$(document).bind("mousedown", function (e) {_x000D_
_x000D_
// If the clicked element is not the menu_x000D_
if (!$(e.target).parents(".custom-menu").length > 0) {_x000D_
_x000D_
// Hide it_x000D_
$(".custom-menu").hide(100);_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
// If the menu element is clicked_x000D_
$(".custom-menu li").click(function(){_x000D_
_x000D_
// This is the triggered action name_x000D_
switch($(this).attr("data-action")) {_x000D_
_x000D_
// A case for each action. Your actions here_x000D_
case "first": alert("first"); break;_x000D_
case "second": alert("second"); break;_x000D_
case "third": alert("third"); break;_x000D_
}_x000D_
_x000D_
// Hide it AFTER the action was triggered_x000D_
$(".custom-menu").hide(100);_x000D_
});
_x000D_
/* CSS3 */_x000D_
_x000D_
/* The whole thing */_x000D_
.custom-menu {_x000D_
display: none;_x000D_
z-index: 1000;_x000D_
position: absolute;_x000D_
overflow: hidden;_x000D_
border: 1px solid #CCC;_x000D_
white-space: nowrap;_x000D_
font-family: sans-serif;_x000D_
background: #FFF;_x000D_
color: #333;_x000D_
border-radius: 5px;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
/* Each of the items in the list */_x000D_
.custom-menu li {_x000D_
padding: 8px 12px;_x000D_
cursor: pointer;_x000D_
list-style-type: none;_x000D_
transition: all .3s ease;_x000D_
user-select: none;_x000D_
}_x000D_
_x000D_
.custom-menu li:hover {_x000D_
background-color: #DEF;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>_x000D_
_x000D_
<ul class='custom-menu'>_x000D_
<li data-action="first">First thing</li>_x000D_
<li data-action="second">Second thing</li>_x000D_
<li data-action="third">Third thing</li>_x000D_
</ul>_x000D_
_x000D_
<!-- Not needed, only for making it clickable on StackOverflow -->_x000D_
Right click me
_x000D_
Note: you might see some small bugs (dropdown far from the cursor, etc), please make sure that it works in the jsfiddle, as that's more similar to your webpage than StackSnippets might be.
Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .
SELECT STUFF(( SELECT ',' + ModuleValue AS ModuleValue
FROM ModuleValue WHERE ModuleID=@ModuleID
FOR XML PATH('')
), 1, 1, '' )
Every enum has both a name() and a valueOf(String) method. The former returns the string name of the enum, and the latter gives the enum value whose name is the string. Is this like what you're looking for?
String name = Modes.mode1.name();
Modes mode = Modes.valueOf(name);
There's also a static valueOf(Class, String) on Enum itself, so you could also use
Modes mode = Enum.valueOf(Modes.class, name);
git push
doesn't push all of your local branches: how would it know which remote branches to push them to? It only pushes local branches which have been configured to push to a particular remote branch.
On my version of Git (1.6.5.3), when I run git remote show origin
it actually prints out which branches are configured for push:
Local refs configured for 'git push':
master pushes to master (up to date)
quux pushes to quux (fast forwardable)
Q. But I could push to master
without worrying about all this!
When you git clone
, by default it sets up your local master
branch to push to the remote's master
branch (locally referred to as origin/master
), so if you only commit on master
, then a simple git push
will always push your changes back.
However, from the output snippet you posted, you're on a branch called develop
, which I'm guessing hasn't been set up to push to anything. So git push
without arguments won't push commits on that branch.
When it says "Everything up-to-date", it means "all the branches you've told me how to push are up to date".
Q. So how can I push my commits?
If what you want to do is put your changes from develop
into origin/master
, then you should probably merge them into your local master
then push that:
git checkout master
git merge develop
git push # will push 'master'
If what you want is to create a develop
branch on the remote, separate from master
, then supply arguments to git push
:
git push origin develop
That will: create a new branch on the remote called develop
; and bring that branch up to date with your local develop
branch; and set develop
to push to origin/develop
so that in future, git push
without arguments will push develop
automatically.
If you want to push your local develop
to a remote branch called something other than develop
, then you can say:
git push origin develop:something-else
However, that form won't set up develop
to always push to origin/something-else
in future; it's a one-shot operation.
Along with making sure you install the 64bit version, also check to make sure that the symbolic link of '/usr/local/mysql' is pointing to the correct version of your installation:
lrwxr-xr-x 1 root wheel 27B Aug 29 01:24 mysql -> mysql-5.1.37-osx10.5-x86_64
drwxr-xr-x 3 root wheel 102B Aug 29 01:25 mysql-5.1.30-osx10.5-x86
drwxr-xr-x 11 root wheel 374B Aug 29 15:59 mysql-5.1.37-osx10.5-x86_64
drwxr-xr-x 17 root wheel 578B Jul 13 22:06 mysql-5.1.37-osx10.5-x86_64.old
Alos, I found that after my installation, even though I used the pkg file from MySQL various other libraries would not build against the installation. The solution was to follow the steps to build MySQL from source found here. You can manually start it as root with the command:
/usr/loca/mysql/bin/mysqld_safe [whatever options you use]
Now ... to get the preference pane working I did the following:
Executed the following command:
sudo cp -R /usr/local/mysql-5.1.37-osx10.5-x86_64.old/support-files /usr/local/mysql/.
Opened up the MySQL Preference Pane and tada! it works
After keep on running into this issue and keep on coming back to this question I thought I'd share what my problem was.
Everything that @Xeberdee is correct so follow that and see if that solves the issue, if not this was my issue:
In my apps.py this is what I had:
class AlgoExplainedConfig(AppConfig):
name = 'algo_explained'
verbose_name = "Explain_Algo"
....
And all I did was I added the project name in front of my app name like this:
class AlgoExplainedConfig(AppConfig):
name = '**algorithms_explained**.algo_explained'
verbose_name = "Explain_Algo"
and that solved my problem and I was able to run the makemigrations and migrate command after that! good luck
I experienced this exception using a SSL/TLS server Socket library on java 8. Updating the jdk to 14 (and also the VM to 14) solved the issue.
The simple way to do that in Angular 7+ is to:
Define a path in your ?-routing.module.ts
{ path: '/yourpage', component: component-name }
Import the ActivateRoute and Router module in your component and inject them in the constructor
contructor(private route: ActivateRoute, private router: Router){ ... }
Subscribe the ActivateRoute to the ngOnInit
ngOnInit() {
this.route.queryParams.subscribe(params => {
console.log(params);
// {page: '2' }
})
}
Provide it to a link:
<a [routerLink]="['/yourpage']" [queryParams]="{ page: 2 }">2</a>
Create a directive and put a watch on it.
app.directive("myApp", function(){
link:function(scope){
function:getTotal(){
..do your maths here
}
scope.$watch('one', getTotals());
scope.$watch('two', getTotals());
}
})
I'm not a big fan of any of the current answers, because they are either too verbose, or require you to jump around the code to understand what is going on.
I prefer doing this in a more react component centred way, by creating a <Switch/>
. The job of this component is to take a prop, and only render children whose child prop matches this one. So in the example below I have created a test
prop on the switch, and compared it to a value
prop on the children, only rendering the ones that match.
Example:
const Switch = props => {
const { test, children } = props
// filter out only children with a matching prop
return children.find(child => {
return child.props.value === test
})
}
const Sample = props => {
const someTest = true
return (
<Switch test={someTest}>
<div value={false}>Will display if someTest is false</div>
<div value={true}>Will display if someTest is true</div>
</Switch>
)
}
ReactDOM.render(
<Sample/>,
document.getElementById("react")
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
You can make the switch as simple or as complex as you want. Don't forget to perform more robust checking of the children and their value props.
Your setters are strange, which is why you may be seeing a problem.
First, consider whether you even need these setters - if so, they should take a List<string>
, not just a string
:
set
{
_subHead = value;
}
These lines:
newSec.subHead.Add("test string");
Are calling the getter and then call Add
on the returned List<string>
- the setter is not invoked.
$ git rev-parse --abbrev-ref HEAD
master
This should work with Git 1.6.3 or newer.
If you set up a click binding in Knockout the event is passed as the second parameter. You can use the event to obtain the element that the click occurred on and perform whatever action you want.
Here is a fiddle that demonstrates: http://jsfiddle.net/jearles/xSKyR/
Alternatively, you could create your own custom binding, which will receive the element it is bound to as the first parameter. On init you could attach your own click event handler to do any actions you wish.
http://knockoutjs.com/documentation/custom-bindings.html
HTML
<div>
<button data-bind="click: clickMe">Click Me!</button>
</div>
Js
var ViewModel = function() {
var self = this;
self.clickMe = function(data,event) {
var target = event.target || event.srcElement;
if (target.nodeType == 3) // defeat Safari bug
target = target.parentNode;
target.parentNode.innerHTML = "something";
}
}
ko.applyBindings(new ViewModel());
If you actually want your function to behave like the str()
built-in, but return an empty string when the argument is None, do this:
def xstr(s):
if s is None:
return ''
return str(s)
For Visual Studio 2019 users:
By the comment under accepted answer, link:
Well... This is "almost" still the same in VS 2019... if you already done that and seems not to work, go to: Tools > Options, and then Text Editor > Advanced > Uncheck "Use adaptive formatting" as seen here
in my case this was the solution = () => {}
methodName = (params) => {
//your code here with this.something
}
Instead of a size divisor of 1024 * 1024
you could use the <<
bitwise shifting operator, i.e. 1<<20
to get megabytes, 1<<30
to get gigabytes, etc.
In the simplest scenario you can have e.g. a constant MBFACTOR = float(1<<20)
which can then be used with bytes, i.e.: megas = size_in_bytes/MBFACTOR
.
Megabytes are usually all that you need, or otherwise something like this can be used:
# bytes pretty-printing
UNITS_MAPPING = [
(1<<50, ' PB'),
(1<<40, ' TB'),
(1<<30, ' GB'),
(1<<20, ' MB'),
(1<<10, ' KB'),
(1, (' byte', ' bytes')),
]
def pretty_size(bytes, units=UNITS_MAPPING):
"""Get human-readable file sizes.
simplified version of https://pypi.python.org/pypi/hurry.filesize/
"""
for factor, suffix in units:
if bytes >= factor:
break
amount = int(bytes / factor)
if isinstance(suffix, tuple):
singular, multiple = suffix
if amount == 1:
suffix = singular
else:
suffix = multiple
return str(amount) + suffix
print(pretty_size(1))
print(pretty_size(42))
print(pretty_size(4096))
print(pretty_size(238048577))
print(pretty_size(334073741824))
print(pretty_size(96995116277763))
print(pretty_size(3125899904842624))
## [Out] ###########################
1 byte
42 bytes
4 KB
227 MB
311 GB
88 TB
2 PB
I imagine a lot of data comes into Pandas from CSV files, in which case you can simply convert the date during the initial CSV read:
dfcsv = pd.read_csv('xyz.csv', parse_dates=[0])
where the 0 refers to the column the date is in.
You could also add , index_col=0
in there if you want the date to be your index.
See https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
Ask "What unit testing framework do you use? and why?"
You can decide if actually using a testing framework is really necessary, but the conversation might tell you a lot about how expert the person is.
if (/(^|;)\s*visited=/.test(document.cookie)) {
alert("Hello again!");
} else {
document.cookie = "visited=true; max-age=" + 60 * 60 * 24 * 10; // 60 seconds to a minute, 60 minutes to an hour, 24 hours to a day, and 10 days.
alert("This is your first time!");
}
is one way to do it. Note that document.cookie
is a magic property, so you don't have to worry about overwriting anything, either.
There are also more convenient libraries to work with cookies, and if you don’t need the information you’re storing sent to the server on every request, HTML5’s localStorage
and friends are convenient and useful.
What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...
1.question answer-In your mobile having Developer Option in settings and enable that one. after In android studio project source file in bin--> apk file .just copy the apk file and paste in mobile memory in ur pc.. after all finished .you click that apk file in your mobile is automatically installed.
2.question answer-Your mobile is Samsung are just add Samsung Kies software in your pc..its helps to android code run in your mobile ...
Your NewClass
inherits from UIViewController
. You declared signedIn
in ViewController
. If you want NewClass
to be able to identify that variable it will have to be declared in a class that your NewClass
inherits from.
I would use an asynchronous access using a completion block.
This example saves the Google logo to the document directory of the device. (iOS 5+, OSX 10.7+)
NSString *documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
NSString *filePath = [documentDir stringByAppendingPathComponent:@"GoogleLogo.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.google.com/images/srpr/logo11w.png"]];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(@"Download Error:%@",error.description);
}
if (data) {
[data writeToFile:filePath atomically:YES];
NSLog(@"File is saved to %@",filePath);
}
}];
When you do throw ex
, that thrown exception becomes the "original" one. So all previous stack trace will not be there.
If you do throw
, the exception just goes down the line and you'll get the full stack trace.
Unicode is not an encoding - to quote Kumar McMillan:
If ASCII, UTF-8, and other byte strings are "text" ...
...then Unicode is "text-ness";
it is the abstract form of text
Have a read of McMillan's Unicode In Python, Completely Demystified talk from PyCon 2008, it explains things a lot better than most of the related answers on Stack Overflow.
Start with the triangle...
*
**
***
****
representing 1+2+3+4 so far. Cut the triangle in half along one dimension...
*
**
* **
** **
Rotate the smaller part 180 degrees, and stick it on top of the bigger part...
**
*
*
**
**
**
Close the gap to get a rectangle.
At first sight this only works if the base of the rectangle has an even length - but if it has an odd length, you just cut the middle column in half - it still works with a half-unit-wide twice-as-tall (still integer area) strip on one side of your rectangle.
Whatever the base of the triangle, the width of your rectangle is (base / 2)
and the height is (base + 1)
, giving ((base + 1) * base) / 2
.
However, my base
is your n-1
, since the bubble sort compares a pair of items at a time, and therefore iterates over only (n-1) positions for the first loop.
Use following line to select using value:
mSpinner.setSelection(yourList.indexOf("value"));
You can either use
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
or
marshaller.setProperty("com.sun.xml.bind.xmlDeclaration", false)
to disable the default XML declaration, and then add your custom XML declaration,
<?xml version="1.0" encoding="UTF-8"?>
by
marshaller.setProperty("com.sun.xml.bind.xmlHeaders",
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
to the generated xml, thus avoiding the standalone="yes" property.
Starting iOS 14 there is no need to make a selector, you can pass a UIAction
with a closure instead:
let editingChanged = UIAction { _ in
// Do something when text changes...
}
myTextField.addAction(editingChanged, for: .editingChanged)
If you don't mind using a bit of JavaScript, jQuery's fadeTo() works nicely in every browser I've tried.
jQuery(selector).fadeTo(speed, opacity);
Try this:
WHERE a.Country = (CASE WHEN @Country > 0 THEN @Country ELSE a.Country END)
The li
tag has a property called list-style-position
. This makes your bullets inside or outside the list. On default, it’s set to inside
. That makes your text wrap around it. If you set it to outside
, the text of your li
tags will be aligned.
The downside of that is that your bullets won't be aligned with the text outside the ul
. If you want to align it with the other text you can use a margin.
ul li {
/*
* We want the bullets outside of the list,
* so the text is aligned. Now the actual bullet
* is outside of the list’s container
*/
list-style-position: outside;
/*
* Because the bullet is outside of the list’s
* container, indent the list entirely
*/
margin-left: 1em;
}
Edit 15th of March, 2014 Seeing people are still coming in from Google, I felt like the original answer could use some improvement
em
’sul
elementSimple Oriented Object solution
$file = new \SplFileObject('file.extension');
while($file->valid()) $file->fgets();
var_dump($file->key());
Another way to make this is with PHP_INT_MAX
in SplFileObject::seek
method.
$file = new \SplFileObject('file.extension', 'r');
$file->seek(PHP_INT_MAX);
echo $file->key() + 1;
Replace your "Save" button with an anchor link and set the new download
attribute dynamically. Works in Chrome and Firefox:
var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");
Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/
Here a compatibility table for download
attribute: http://caniuse.com/download
var queryObj = {};
if(url.split("?").length>0){
var queryString = url.split("?")[1];
}
now you have the query part in queryString
First replace will remove all the white spaces, second will replace all the '&' part with "," and finally the third replace will put ":" in place of '=' signs.
queryObj = JSON.parse('{"' + queryString.replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}')
So let say you had a query like abc=123&efg=456. Now before parsing, your query is being converted into something like {"abc":"123","efg":"456"}. Now when you will parse this, it will give you your query in json object.
The __del__
method, it will be called when the object is garbage collected. Note that it isn't necessarily guaranteed to be called though. The following code by itself won't necessarily do it:
del obj
The reason being that del
just decrements the reference count by one. If something else has a reference to the object, __del__
won't get called.
There are a few caveats to using __del__
though. Generally, they usually just aren't very useful. It sounds to me more like you want to use a close method or maybe a with statement.
See the python documentation on __del__
methods.
One other thing to note: __del__
methods can inhibit garbage collection if overused. In particular, a circular reference that has more than one object with a __del__
method won't get garbage collected. This is because the garbage collector doesn't know which one to call first. See the documentation on the gc module for more info.
To open a URL with the default browser, you can execute:
rundll32 url.dll,FileProtocolHandler https://www.google.com
I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.
You simply can't use View as a Header of ListView.
Because the view which is being passed in has to be inflated.
Look at my answer at Android ListView addHeaderView() nullPointerException for predefined Views for more info.
EDIT:
Look at this tutorial Android ListView and ListActivity - Tutorial .
EDIT 2: This link is broken Android ListActivity with a header or footer
I have tried all the above mentioned options but can not find the solution to this problem . Then I got its solution....
This error is flashed when we are trying to open mysql with out stating the service.
Follow the bellow mentioned steps..
STEP 1
Open cmd prompt
to start the service type
mysqld --console
this will start the mysql service
enter image description here
STEP 2
dont close this cmd prompt
now open new cmd prompt and
type
mysql -u root -p
then enter ur password
enter image description here
Use callbacks. Something like this should work based on your sample code.
function someFunc() {
callAjaxfunc(function() {
console.log('Pass2');
});
}
function callAjaxfunc(callback) {
//All ajax calls called here
onAjaxSuccess: function() {
callback();
};
console.log('Pass1');
}
This will print Pass1
immediately (assuming ajax request takes atleast a few microseconds), then print Pass2
when the onAjaxSuccess
is executed.
I know that this has been asked more than three years ago. But the answer accepted is not extremely useful.
The following code is more useful.
<?php
$File = 'loginevents.csv';
$arrResult = array();
$handle = fopen($File, "r");
if(empty($handle) === false) {
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult[] = $data;
}
fclose($handle);
}
print_r($arrResult);
?>
For Xamarin.Android I have created this extension.
public static class ViewExtensions
{
public static void FocusEditText(this EditText editText, Activity activity)
{
if (editText.RequestFocus())
{
InputMethodManager imm = (InputMethodManager)activity.GetSystemService(Context.InputMethodService);
imm.ShowSoftInput(editText, ShowFlags.Implicit);
}
}
}
The time zone should be something like "GMT+00:00" or 0000 in order to be properly parsed by the SimpleDateFormat - you can replace Z with this construction.