The uninstall
option didn't work for me when I tried to use the same command to the one I used in installing (as I was installing with the @latest
directive)
So for example, I installed a package like this:
npm install @ngtools/webpack@latest
And then I wanted to uninstall it, so I used the same command (including @latest):
npm uninstall @ngtools/webpack@latest
So the above uninstall didn't work. I have to remove the @latest
, and then it worked well:
npm uninstall @ngtools/webpack
Create an EditorTemplate for a specific set of Views (bound by one Controller):
In this example I have a template for a Date, but you can change it to whatever you want.
Here is the code in the Data.cshtml:
@model Nullable<DateTime>
@Html.TextBox("", @Model != null ? String.Format("{0:d}", ((System.DateTime)Model).ToShortDateString()) : "", new { @class = "datefield", type = "date", disabled = "disabled" @readonly = "readonly" })
and in the model:
[DataType(DataType.Date)]
public DateTime? BlahDate { get; set; }
this
in JavaScript always refers to the 'owner' of the function that is being executed.
If no explicit owner is defined, then the top most owner, the window object, is referenced.
So if I did
function someKindOfFunction() {
this.style = 'foo';
}
element.onclick = someKindOfFunction;
this
would refer to the element object. But be careful, a lot of people make this mistake.
<element onclick="someKindOfFunction()">
In the latter case, you merely reference the function, not hand it over to the element. Therefore, this
will refer to the window object.
For me, this type of error:
mingw-w64-x86_64/lib/gcc/x86_64-w64-mingw32/8.2.0/../../../../x86_64-w64-mingw32/bin/ld: mingw-w64-x86_64/x86_64-w64-mingw32/lib/libTransform360.a(VideoFrameTransform.cpp.obj):VideoFrameTransform.cpp:(.text+0xc7c):
undefined reference to `cv::Mat::Mat(cv::Mat const&, cv::Rect_<int> const&)'
meant load order, I had to do -lTransform360 -lopencv_dnn345 -lopencv...
just like that, that order.
And putting them right next to each other helped too, don't put -lTransform360
all the way at the beginning...or you'll get, for some freaky reason:
undefined reference to `VideoFrameTransform_new'
undefined reference to `VideoFrameTransform_generateMapForPlane'
...
you can check like this
declare @vchar varchar(50)
set @vchar ='34343';
select case when @vchar not like '%[^0-9]%' then 'Number' else 'Not a Number' end
BTW: Converting is highly important if you are serialized, mainly because the de-serialization breaks the type of objects and turns into stdclass, including DateTime objects.
I updated the example of @Jadrovski, now it allows objects and arrays.
example
$stdobj=new StdClass();
$stdobj->field=20;
$obj=new SomeClass();
fixCast($obj,$stdobj);
example array
$stdobjArr=array(new StdClass(),new StdClass());
$obj=array();
$obj[0]=new SomeClass(); // at least the first object should indicates the right class.
fixCast($obj,$stdobj);
code: (its recursive). However, i don't know if its recursive with arrays. May be its missing an extra is_array
public static function fixCast(&$destination,$source)
{
if (is_array($source)) {
$getClass=get_class($destination[0]);
$array=array();
foreach($source as $sourceItem) {
$obj = new $getClass();
fixCast($obj,$sourceItem);
$array[]=$obj;
}
$destination=$array;
} else {
$sourceReflection = new \ReflectionObject($source);
$sourceProperties = $sourceReflection->getProperties();
foreach ($sourceProperties as $sourceProperty) {
$name = $sourceProperty->getName();
if (is_object(@$destination->{$name})) {
fixCast($destination->{$name}, $source->$name);
} else {
$destination->{$name} = $source->$name;
}
}
}
}
You must use .clearAnimation(); method in UI thread:
runOnUiThread(new Runnable() {
@Override
public void run() {
v.clearAnimation();
}
});
You could use setUTCMilliseconds()
var _date = new Date();
_date.setUTCMilliseconds(1270544790922);
i was looking for the same. and found this solution.
Use negative regex assertion:
location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) {
.... # your stuff
}
Source Negated Regular Expressions in location
Explanation of Regex :
If URL does not match any of the following path
example.com/favicon.ico
example.com/resources
example.com/robots.txt
Then it will go inside that location block and will process it.
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
I faced the same problem. Searching in S3 should be much more easier than the current situation. That's why, I implemented this open source tool for searching in S3.
SSEARCH is full open source S3 search tool. It has been implemented always keeping mind that the performance is the critical factor and according to the benchmarks it searches the bucket which contains ~1000 files within seconds.
Installation is simple. You only download docker-compose file and running it with
docker-compose up
SSEARCH will be started and you can search anything in any bucket you have.
Check this out as well: using xml path
and pivot
| ACCOUNT | 2000 | 2001 | 2002 |
--------------------------------
| Asset | 205 | 142 | 421 |
| Equity | 365 | 214 | 163 |
| Profit | 524 | 421 | 325 |
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.period)
FROM demo c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT account, ' + @cols + ' from
(
select account
, value
, period
from demo
) x
pivot
(
max(value)
for period in (' + @cols + ')
) p '
execute(@query)
... And for those who - like me - are very early in their numpy learning curve,
import numpy as np
pure = np.linspace(-1, 1, 100)
noise = np.random.normal(0, 1, 100)
signal = pure + noise
Adding to unwinds post:
You can send multiple key-value args too.
def myfunc(**kwargs):
# kwargs is a dictionary.
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc(abc=123, efh=456)
# abc = 123
# efh = 456
And you can mix the two:
def myfunc2(*args, **kwargs):
for a in args:
print a
for k,v in kwargs.iteritems():
print "%s = %s" % (k, v)
myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123
They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.
Go to IIS manager and click on the server name. Then click on the "ISAPI and CGI Restrictions" icon under the IIS header. Change ASP.NET 4.0 from "Not Allowed" to "Allowed".
That can be caused by unicode or other charset mismatch. Try changing charset in your browser, in of the settings the text will look OK. Then it's question of how to convert your database contents to charset you use for displaying. (Which can actually be just adding utf-8 charset statement to your output.)
At the risk of irritating you;
You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.
Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.
What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.
It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.
In short, it's just unnecessarily conflating the matter when there is no need to.
Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit()
than ini_set()
.
Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)
The immediate problem is you have is with quoting: by using double quotes ("..."
), your variable references are instantly expanded, which is probably not what you want.
Use single quotes instead - strings inside single quotes are not expanded or interpreted in any way by the shell.
(If you want selective expansion inside a string - i.e., expand some variable references, but not others - do use double quotes, but prefix the $
of references you do not want expanded with \
; e.g., \$var
).
However, you're better off using a single here-doc[ument], which allows you to create multi-line stdin
input on the spot, bracketed by two instances of a self-chosen delimiter, the opening one prefixed by <<
, and the closing one on a line by itself - starting at the very first column; search for Here Documents
in man bash
or at http://www.gnu.org/software/bash/manual/html_node/Redirections.html.
If you quote the here-doc delimiter (EOF
in the code below), variable references are also not expanded. As @chepner points out, you're free to choose the method of quoting in this case: enclose the delimiter in single quotes or double quotes, or even simply arbitrarily escape one character in the delimiter with \
:
echo "creating new script file."
cat <<'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service: " ser
servicetest=`getsebool -a | grep ${ser}`
if [ $servicetest > /dev/null ]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi
EOF
As @BruceK notes, you can prefix your here-doc delimiter with -
(applied to this example: <<-"EOF"
) in order to have leading tabs stripped, allowing for indentation that makes the actual content of the here-doc easier to discern.
Note, however, that this only works with actual tab characters, not leading spaces.
Employing this technique combined with the afterthoughts regarding the script's content below, we get (again, note that actual tab chars. must be used to lead each here-doc content line for them to get stripped):
cat <<-'EOF' > "$servfile"
#!/bin/bash
read -p "Please enter a service name: " ser
if [[ -n $(getsebool -a | grep "${ser}") ]]; then
echo "We are now going to work with ${ser}."
else
exit 1
fi
EOF
Finally, note that in bash
even normal single- or double-quoted strings can span multiple lines, but you won't get the benefits of tab-stripping or line-block scoping, as everything inside the quotes becomes part of the string.
Thus, note how in the following #!/bin/bash
has to follow the opening '
immediately in order to become the first line of output:
echo '#!/bin/bash
read -p "Please enter a service: " ser
servicetest=$(getsebool -a | grep "${ser}")
if [[ -n $servicetest ]]; then
echo "we are now going to work with ${ser}"
else
exit 1
fi' > "$servfile"
Afterthoughts regarding the contents of your script:
$(...)
is preferred over `...`
for command substitution nowadays.${ser}
in the grep
command, as the command will likely break if the value contains embedded spaces (alternatively, make sure that the valued read contains no spaces or other shell metacharacters).[[ -n $servicetest ]]
to test whether $servicetest
is empty (or perform the command substitution directly inside the conditional) - [[ ... ]]
- the preferred form in bash
- protects you from breaking the conditional if the $servicetest
happens to have embedded spaces; there's NEVER a need to suppress stdout output inside a conditional (whether [ ... ]
or [[ ... ]]
, as no stdout output is passed through; thus, the > /dev/null
is redundant (that said, with a command substitution inside a conditional, stderr output IS passed through).rank() : It is used to rank a record within a group of rows.
dense_rank() : The DENSE_RANK function acts like the RANK function except that it assigns consecutive ranks.
Query -
select
ENAME,SAL,RANK() over (order by SAL) RANK
from
EMP;
Output -
+--------+------+------+
| ENAME | SAL | RANK |
+--------+------+------+
| SMITH | 800 | 1 |
| JAMES | 950 | 2 |
| ADAMS | 1100 | 3 |
| MARTIN | 1250 | 4 |
| WARD | 1250 | 4 |
| TURNER | 1500 | 6 |
+--------+------+------+
Query -
select
ENAME,SAL,dense_rank() over (order by SAL) DEN_RANK
from
EMP;
Output -
+--------+------+-----------+
| ENAME | SAL | DEN_RANK |
+--------+------+-----------+
| SMITH | 800 | 1 |
| JAMES | 950 | 2 |
| ADAMS | 1100 | 3 |
| MARTIN | 1250 | 4 |
| WARD | 1250 | 4 |
| TURNER | 1500 | 5 |
+--------+------+-----------+
Here's a way to generate consistent random colors using color-hash
const colorHash = new ColorHash()
const datasets = [{
label: 'Balance',
data: _.values(balances),
backgroundColor: _.keys(balances).map(name => colorHash.hex(name))
}]
As has already been mentioned, you’d want to do a foreach with the key, and unset using the key – but note that mutating an array during iteration is in general a bad idea, though I’m not sure on PHP’s rules on this offhand.
If this is a CORS request, you may see all headers in debug tools (such as Chrome->Inspect Element->Network), but the xHR object will only retrieve the header (via xhr.getResponseHeader('Header')
) if such a header is a simple response header:
Content-Type
Last-modified
Content-Language
Cache-Control
Expires
Pragma
If it is not in this set, it must be present in the Access-Control-Expose-Headers header returned by the server.
About the case in question, if it is a CORS request, one will only be able to retrieve the Location
header through the XMLHttpRequest
object if, and only if, the header below is also present:
Access-Control-Expose-Headers: Location
If its not a CORS request, XMLHttpRequest
will have no problem retrieving it.
It's a matter of operator precedence.
||
has a higher precedence than or
.
So, in between the two you have other operators including ternary (? :
) and assignment (=
) so which one you choose can affect the outcome of statements.
Here's a ruby operator precedence table.
See this question for another example using and
/&&
.
Also, be aware of some nasty things that could happen:
a = false || true #=> true
a #=> true
a = false or true #=> true
a #=> false
Both of the previous two statements evaluate to true
, but the second sets a
to false
since =
precedence is lower than ||
but higher than or
.
If you do not need to retrieve all the row and want to avoid to make a double query, you can probably try something like that:
using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
sqlCon.Open();
var com = sqlCon.CreateCommand();
com.CommandText = "select * from BigTable";
using (var reader = com.ExecuteReader())
{
//here you retrieve what you need
}
com.CommandText = "select @@ROWCOUNT";
var totalRow = com.ExecuteScalar();
sqlCon.Close();
}
You may have to add a transaction not sure if reusing the same command will automatically add a transaction on it...
The easiest way to convert a byte array to a stream is using the MemoryStream
class:
Stream stream = new MemoryStream(byteArray);
In my case, with GitHub Desktop for Windows (as of June 2, 2016) & Android Studio 2.1:
This folder ->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\
Contained a BATCH file called something like 'post-install.bat'. Run this file to create a folder 'cmd' with 'git.exe' inside.
This path-->
C:\Users\(UserName)\AppData\Local\GitHub\PortableGit_<hash>\cmd\git.exe
would be the location of 'git.exe' after running the post-install script.
this in your callback function refers to the clicked element.
$(".addressClick").click(function () {
var addressValue = $(this).attr("href");
alert(addressValue );
});
If you want to randomly rename images, and store both the image path on database as blob and the image itself on folders this solution will help you. Your website users can store as many images as they want while the images will be randomly renamed for security purposes.
Generate random varchars to use as image name.
function genhash($strlen) {
$h_len = $len;
$cstrong = TRUE;
$sslkey = openssl_random_pseudo_bytes($h_len, $cstrong);
return bin2hex($sslkey);
}
$randName = genhash(3);
#You can increase or decrease length of the image name (1, 2, 3 or more).
Get image data extension and base_64 part (part after data:image/png;base64,) from image .
$pos = strpos($base64_img, ';');
$imgExten = explode('/', substr($base64_img, 0, $pos))[1];
$extens = ['jpg', 'jpe', 'jpeg', 'jfif', 'png', 'bmp', 'dib', 'gif' ];
if(in_array($imgExten, $extens)) {
$imgNewName = $randName. '.' . $imgExten;
$filepath = "resources/images/govdoc/".$imgNewName;
$fileP = fopen($filepath, 'wb');
$imgCont = explode(',', $base64_img);
fwrite($fileP, base64_decode($imgCont[1]));
fclose($fileP);
}
# => $filepath <= This path will be stored as blob type in database.
# base64_decoded images will be written in folder too.
# Please don't forget to up vote if you like my solution. :)
If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :
For eg.
Dim dt As New DataTable
dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))
dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")
For me, I did mvn clean
and then restart the tomcat. It worked for me
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
Python habitually returns None
from functions and methods that mutate the data, such as list.sort
, list.append
, and random.shuffle
, with the idea being that it hints to the fact that it was mutating.
If you want to take an iterable and return a new, sorted list of its items, use the sorted
builtin function.
You can simply specify a series of images like this:
\includegraphics<1>{A}
\includegraphics<2>{B}
\includegraphics<3>{C}
This will produce three slides with the images A to C in exactly the same position.
You can fire the event simply with
document.getElementById("elementID").onchange();
I dont know if this doesnt work on some browsers, but it should work on FF 3 and IE 7+
As you know the string is coming in as Encoding.Default
you could simply use:
byte[] bytes = Encoding.Default.GetBytes(myString);
myString = Encoding.UTF8.GetString(bytes);
Another thing you may have to remember: If you are using Console.WriteLine to output some strings, then you should also write Console.OutputEncoding = System.Text.Encoding.UTF8;
!!! Or all utf8 strings will be outputed as gbk...
I think you should be using below Component Lifecycle as if you have an input property which on update needs to trigger your component update then this is the best place to do it as its will be called before render you even can do update component state to be reflected on the view.
componentWillReceiveProps: function(nextProps) {
this.setState({
likesIncreasing: nextProps.likeCount > this.props.likeCount
});
}
I have had the same problem. There is an answer:
Got it! Now u have Java 9!
My fellows,
In January 2019 I used a code made before:
<script type="text/javascript">
function imprimir() {
var divToPrint=document.getElementById("ConsutaBPM");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
</script>
To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...
The table mas be defined with BORDER and CELLPADDING:
<table border='1' cellpadding='1' id='Tablbpm1' >
It worked fine!!!
This is a quirk of the C grammar. A label (Cleanup:
) is not allowed to appear immediately before a declaration (such as char *str ...;
), only before a statement (printf(...);
). In C89 this was no great difficulty because declarations could only appear at the very beginning of a block, so you could always move the label down a bit and avoid the issue. In C99 you can mix declarations and code, but you still can't put a label immediately before a declaration.
You can put a semicolon immediately after the label's colon (as suggested by Renan) to make there be an empty statement there; this is what I would do in machine-generated code. Alternatively, hoist the declaration to the top of the function:
int main (void)
{
char *str;
printf("Hello ");
goto Cleanup;
Cleanup:
str = "World\n";
printf("%s\n", str);
return 0;
}
[Gray] introduced the ACD properties for a transaction in 1981. In 1983 [Haerder] added the Isolation property. In my opinion, the ACD properties would be have a more useful set of properties to discuss. One interpretation of Atomicity (that the transaction should be atomic as seen from any client any time) would actually imply the isolation property. The "isolation" property is useful when the transaction is not isolated; when the isolation property is relaxed. In ANSI SQL speak: if the isolation level is weaker then SERIALIZABLE. But when the isolation level is SERIALIZABLE, the isolation property is not really of interest.
I have written more about this in a blog post: "ACID Does Not Make Sense".
http://blog.franslundberg.com/2013/12/acid-does-not-make-sense.html
[Gray] The Transaction Concept, Jim Gray, 1981. http://research.microsoft.com/en-us/um/people/gray/papers/theTransactionConcept.pdf
[Haerder] Principles of Transaction-Oriented Database Recovery, Haerder and Reuter, 1983. http://www.stanford.edu/class/cs340v/papers/recovery.pdf
I recommend not using WebClient.DownloadString
. This is because (at least in .NET 3.5) DownloadString is not smart enough to use/remove the BOM, should it be present. This can result in the BOM (
) incorrectly appearing as part of the string when UTF-8 data is returned (at least without a charset) - ick!
Instead, this slight variation will work correctly with BOMs:
string ReadTextFromUrl(string url) {
// WebClient is still convenient
// Assume UTF8, but detect BOM - could also honor response charset I suppose
using (var client = new WebClient())
using (var stream = client.OpenRead(url))
using (var textReader = new StreamReader(stream, Encoding.UTF8, true)) {
return textReader.ReadToEnd();
}
}
(tomcat 7.0.32) I had problems to see debug messages althought was enabling TldLocationsCache row in tomcat/conf/logging.properties file. All I could see was a warning but not what libs were scanned. Changed every loglevel tried everything no luck. Then I went rogue debug mode (=remove one by one, clean install etc..) and finally found a reason.
My webapp had a customized tomcat/webapps/mywebapp/WEB-INF/classes/logging.properties file. I copied TldLocationsCache row to this file, finally I could see jars filenames.
# To see debug messages in TldLocationsCache, uncomment the following line: org.apache.jasper.compiler.TldLocationsCache.level = FINE
make sure you textbox is set for multiline then you wont need any extra dims vbnewline will work just fine
Another thing to consider is that, since there is no multiple inheritance, if you want a class to be able to implement/inherit from your interface/abstract class, but inherit from another base class, use an interface.
I wanted to select multiple lines and hit "something" to have a cursor for each select lines (similar to Ctrl + Shift + L in Sublime Text). This action in Visual Studio Code is called "Add Cursors to Line Ends".
This was tested in Visual Studio Code 1.51.1 and works on both Windows and Mac.
Here is the way:
You now have one cursor per selected line.
You need to add this in your build.gradle:
dependencies {
...
compile 'com.android.support:cardview-v7:+'
}
And then Sync Project with Gradle Files
. Finally, you can use CardView as it's described here.
Use RVM (Ruby Version Manager) to install and manage any versions of Ruby. You can have multiple versions of Ruby installed on the machine and you can easily select the one you want.
To install RVM type into terminal:
\curl -sSL https://get.rvm.io | bash -s stable
And let it work. After that you will have RVM along with Ruby installed.
Source: RVM Site
Validate the INPUT.
$time = strtotime($_POST['dateFrom']);
if ($time) {
$new_date = date('Y-m-d', $time);
echo $new_date;
} else {
echo 'Invalid Date: ' . $_POST['dateFrom'];
// fix it.
}
At the application level, the application uses TCP as a stream oriented protocol. TCP in turn has segments and abstracts away the details of working with unreliable IP packets.
TCP deals with segments instead of packets. Each TCP segment has a sequence number which is contained inside a TCP header. The actual data sent in a TCP segment is variable.
There is a value for getsockopt that is supported on some OS that you can use called TCP_MAXSEG which retrieves the maximum TCP segment size (MSS). It is not supported on all OS though.
I'm not sure exactly what you're trying to do but if you want to reduce the buffer size that's used you could also look into: SO_SNDBUF and SO_RCVBUF.
str.startswith
allows you to supply a tuple of strings to test for:
if link.lower().startswith(("js", "catalog", "script", "katalog")):
From the docs:
str.startswith(prefix[, start[, end]])
Return
True
if string starts with theprefix
, otherwise returnFalse
.prefix
can also be a tuple of prefixes to look for.
Below is a demonstration:
>>> "abcde".startswith(("xyz", "abc"))
True
>>> prefixes = ["xyz", "abc"]
>>> "abcde".startswith(tuple(prefixes)) # You must use a tuple though
True
>>>
As of Java 1.7 createTempDirectory(prefix, attrs)
and createTempDirectory(dir, prefix, attrs)
are included in java.nio.file.Files
Example:
File tempDir = Files.createTempDirectory("foobar").toFile();
Pointers in C#.
They can be used to do in-place string manipulation. This is an unsafe feature so the unsafe keyword is used to mark the region of unsafe code. Also note how the fixed keyword is used to indicate that the memory pointed to is pinned and cannot be moved by the GC. This is essential a pointers point to memory addresses and the GC can move the memory to different address otherwise resulting in an invalid pointer.
string str = "some string";
Console.WriteLine(str);
unsafe
{
fixed(char *s = str)
{
char *c = s;
while(*c != '\0')
{
*c = Char.ToUpper(*c++);
}
}
}
Console.WriteLine(str);
I wouldn't ever do it but just for the sake of this question to demonstrate this feature.
You can run your application with parameters such as app -something -somethingelse
. int argc
represents number of these parameters and char *argv[]
is an array with actual parameters being passed into your application. This way you can work with them inside of your application.
Since **kwargs
is used when the number of arguments is unknown, why not doing this?
class Exampleclass(object):
def __init__(self, **kwargs):
for k in kwargs.keys():
if k in [acceptable_keys_list]:
self.__setattr__(k, kwargs[k])
No need to make overcomplicated.
$('a').on('touchend', function() {
$(this).click();
});
Here's a test with multiple sample sizes in milliseconds.
public class Time {
public static String sysFile = "/sys/class/camera/rear/rear_flash";
public static String cmdString = "echo %s > " + sysFile;
public static void main(String[] args) {
int i = 1;
for(int run=1; run <= 12; run++){
for(int test =1; test <= 2 ; test++){
System.out.println(
String.format("\nTEST: %s, RUN: %s, Iterations: %s",run,test,i));
test(run, i);
}
System.out.println("\n____________________________");
i = i*3;
}
}
public static void test(int run, int iterations){
long start = System.nanoTime();
for( int i=0;i<iterations; i++){
String s = "echo " + i + " > "+ sysFile;
}
long t = System.nanoTime() - start;
String r = String.format(" %-13s =%10d %s", "Concatenation",t,"nanosecond");
System.out.println(r) ;
start = System.nanoTime();
for( int i=0;i<iterations; i++){
String s = String.format(cmdString, i);
}
t = System.nanoTime() - start;
r = String.format(" %-13s =%10d %s", "Format",t,"nanosecond");
System.out.println(r);
start = System.nanoTime();
for( int i=0;i<iterations; i++){
StringBuilder b = new StringBuilder("echo ");
b.append(i).append(" > ").append(sysFile);
String s = b.toString();
}
t = System.nanoTime() - start;
r = String.format(" %-13s =%10d %s", "StringBuilder",t,"nanosecond");
System.out.println(r);
}
}
TEST: 1, RUN: 1, Iterations: 1
Concatenation = 14911 nanosecond
Format = 45026 nanosecond
StringBuilder = 3509 nanosecond
TEST: 1, RUN: 2, Iterations: 1
Concatenation = 3509 nanosecond
Format = 38594 nanosecond
StringBuilder = 3509 nanosecond
____________________________
TEST: 2, RUN: 1, Iterations: 3
Concatenation = 8479 nanosecond
Format = 94438 nanosecond
StringBuilder = 5263 nanosecond
TEST: 2, RUN: 2, Iterations: 3
Concatenation = 4970 nanosecond
Format = 92976 nanosecond
StringBuilder = 5848 nanosecond
____________________________
TEST: 3, RUN: 1, Iterations: 9
Concatenation = 11403 nanosecond
Format = 287115 nanosecond
StringBuilder = 14326 nanosecond
TEST: 3, RUN: 2, Iterations: 9
Concatenation = 12280 nanosecond
Format = 209051 nanosecond
StringBuilder = 11818 nanosecond
____________________________
TEST: 5, RUN: 1, Iterations: 81
Concatenation = 54383 nanosecond
Format = 1503113 nanosecond
StringBuilder = 40056 nanosecond
TEST: 5, RUN: 2, Iterations: 81
Concatenation = 44149 nanosecond
Format = 1264241 nanosecond
StringBuilder = 34208 nanosecond
____________________________
TEST: 6, RUN: 1, Iterations: 243
Concatenation = 76018 nanosecond
Format = 3210891 nanosecond
StringBuilder = 76603 nanosecond
TEST: 6, RUN: 2, Iterations: 243
Concatenation = 91222 nanosecond
Format = 2716773 nanosecond
StringBuilder = 73972 nanosecond
____________________________
TEST: 8, RUN: 1, Iterations: 2187
Concatenation = 527450 nanosecond
Format = 10291108 nanosecond
StringBuilder = 885027 nanosecond
TEST: 8, RUN: 2, Iterations: 2187
Concatenation = 526865 nanosecond
Format = 6294307 nanosecond
StringBuilder = 591773 nanosecond
____________________________
TEST: 10, RUN: 1, Iterations: 19683
Concatenation = 4592961 nanosecond
Format = 60114307 nanosecond
StringBuilder = 2129387 nanosecond
TEST: 10, RUN: 2, Iterations: 19683
Concatenation = 1850166 nanosecond
Format = 35940524 nanosecond
StringBuilder = 1885544 nanosecond
____________________________
TEST: 12, RUN: 1, Iterations: 177147
Concatenation = 26847286 nanosecond
Format = 126332877 nanosecond
StringBuilder = 17578914 nanosecond
TEST: 12, RUN: 2, Iterations: 177147
Concatenation = 24405056 nanosecond
Format = 129707207 nanosecond
StringBuilder = 12253840 nanosecond
If you place your buttons inside a div with class "btn-group" the buttons inside will stretch to the same size as the largest button.
eg:
<div class="btn-group">
<button type="button" class="btn btn-default">Left</button>
<button type="button" class="btn btn-default">Middle</button>
<button type="button" class="btn btn-default">Right</button>
</div>
I just used the following code:
<form method="post">
<input id="user1" value="user1" name="invite[]" type="checkbox">
<input id="user2" value="user2" name="invite[]" type="checkbox">
<input type="submit">
</form>
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
print_r($invite);
}
?>
When I checked both boxes, the output was:
Array ( [0] => user1 [1] => user2 )
I know this doesn't directly answer your question, but it gives you a working example to reference and hopefully helps you solve the problem.
'nunique' is an option for .agg() since pandas 0.20.0, so:
df.groupby('date').agg({'duration': 'sum', 'user_id': 'nunique'})
There are many ways to wait in Unity. It is really simple but I think it's worth covering most ways to do these:
1.With a coroutine and WaitForSeconds
.
The is by far the simplest way. Put all the code that you need to wait for some time in a coroutine function then you can wait with WaitForSeconds
. Note that in coroutine function, you call the function with StartCoroutine(yourFunction)
.
Example below will rotate 90 deg, wait for 4 seconds, rotate 40 deg and wait for 2 seconds, and then finally rotate rotate 20 deg.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSeconds(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSeconds(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
2.With a coroutine and WaitForSecondsRealtime
.
The only difference between WaitForSeconds
and WaitForSecondsRealtime
is that WaitForSecondsRealtime
is using unscaled time to wait which means that when pausing a game with Time.timeScale
, the WaitForSecondsRealtime
function would not be affected but WaitForSeconds
would.
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
yield return new WaitForSecondsRealtime(4);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
yield return new WaitForSecondsRealtime(2);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
Wait and still be able to see how long you have waited:
3.With a coroutine and incrementing a variable every frame with Time.deltaTime
.
A good example of this is when you need the timer to display on the screen how much time it has waited. Basically like a timer.
It's also good when you want to interrupt the wait/sleep with a boolean
variable when it is true. This is where yield break;
can be used.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
float counter = 0;
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Wait for a frame so that Unity doesn't freeze
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
yield return null;
}
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
//Reset counter
counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
//Check if we want to quit this function
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
You can still simplify this by moving the while
loop into another coroutine function and yielding it and also still be able to see it counting and even interrupt the counter.
bool quit = false;
void Start()
{
StartCoroutine(waiter());
}
IEnumerator waiter()
{
//Rotate 90 deg
transform.Rotate(new Vector3(90, 0, 0), Space.World);
//Wait for 4 seconds
float waitTime = 4;
yield return wait(waitTime);
//Rotate 40 deg
transform.Rotate(new Vector3(40, 0, 0), Space.World);
//Wait for 2 seconds
waitTime = 2;
yield return wait(waitTime);
//Rotate 20 deg
transform.Rotate(new Vector3(20, 0, 0), Space.World);
}
IEnumerator wait(float waitTime)
{
float counter = 0;
while (counter < waitTime)
{
//Increment Timer until counter >= waitTime
counter += Time.deltaTime;
Debug.Log("We have waited for: " + counter + " seconds");
if (quit)
{
//Quit function
yield break;
}
//Wait for a frame so that Unity doesn't freeze
yield return null;
}
}
Wait/Sleep until variable changes or equals to another value:
4.With a coroutine and the WaitUntil
function:
Wait until a condition becomes true
. An example is a function that waits for player's score to be 100
then loads the next level.
float playerScore = 0;
int nextScene = 0;
void Start()
{
StartCoroutine(sceneLoader());
}
IEnumerator sceneLoader()
{
Debug.Log("Waiting for Player score to be >=100 ");
yield return new WaitUntil(() => playerScore >= 10);
Debug.Log("Player score is >=100. Loading next Leve");
//Increment and Load next scene
nextScene++;
SceneManager.LoadScene(nextScene);
}
5.With a coroutine and the WaitWhile
function.
Wait while a condition is true
. An example is when you want to exit app when the escape key is pressed.
void Start()
{
StartCoroutine(inputWaiter());
}
IEnumerator inputWaiter()
{
Debug.Log("Waiting for the Exit button to be pressed");
yield return new WaitWhile(() => !Input.GetKeyDown(KeyCode.Escape));
Debug.Log("Exit button has been pressed. Leaving Application");
//Exit program
Quit();
}
void Quit()
{
#if UNITY_EDITOR
UnityEditor.EditorApplication.isPlaying = false;
#else
Application.Quit();
#endif
}
6.With the Invoke
function:
You can call tell Unity to call function in the future. When you call the Invoke
function, you can pass in the time to wait before calling that function to its second parameter. The example below will call the feedDog()
function after 5
seconds the Invoke
is called.
void Start()
{
Invoke("feedDog", 5);
Debug.Log("Will feed dog after 5 seconds");
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
7.With the Update()
function and Time.deltaTime
.
It's just like #3 except that it does not use coroutine. It uses the Update
function.
The problem with this is that it requires so many variables so that it won't run every time but just once when the timer is over after the wait.
float timer = 0;
bool timerReached = false;
void Update()
{
if (!timerReached)
timer += Time.deltaTime;
if (!timerReached && timer > 5)
{
Debug.Log("Done waiting");
feedDog();
//Set to false so that We don't run this again
timerReached = true;
}
}
void feedDog()
{
Debug.Log("Now feeding Dog");
}
There are still other ways to wait in Unity but you should definitely know the ones mentioned above as that makes it easier to make games in Unity. When to use each one depends on the circumstances.
For your particular issue, this is the solution:
IEnumerator showTextFuntion()
{
TextUI.text = "Welcome to Number Wizard!";
yield return new WaitForSeconds(3f);
TextUI.text = ("The highest number you can pick is " + max);
yield return new WaitForSeconds(3f);
TextUI.text = ("The lowest number you can pick is " + min);
}
And to call/start the coroutine function from your start or Update function, you call it with
StartCoroutine (showTextFuntion());
I don't think there's anything wrong with either solutions you proposed in your question.
In my own code, I would implement it like this though:
(x for x in seq if predicate(x)).next()
The syntax with ()
creates a generator, which is more efficient than generating all the list at once with []
.
You should use Root
to refer to the root element:
xmlFile.Root.Elements("Band")
If you want to find elements anywhere in the document use Descendants
instead:
xmlFile.Descendants("Band")
Go to C:\app\insolution\product\11.2.0\client_1\BIN and find oci.dll. Right click on it -->Properties -->Under Security tab, click on Edit -->Then Click on Add Button --> Here add two new users with names IUSR and IIS_IUSRS and give them full controls. That's it.
You have three options:
In Java:
String regex = "[^-\\s]";
System.out.println("-".matches(regex)); // prints "false"
System.out.println(" ".matches(regex)); // prints "false"
System.out.println("+".matches(regex)); // prints "true"
The regex [^-\s]
works as expected. [^\s-]
also works.
The hyphen can be included right after the opening bracket, or right before the closing bracket, or right after the negating caret.
Just turn off your WiFi in Mac OSX this works a treat!
enum
type in Java 5 and onwards for the purpose you have described. It is type safe.If you are talking about the difference between instance variable and class variable, instance variable exist per object created. While class variable has only one copy per class loader regardless of the number of objects created.
Java 5 and up enum
type
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public String toString(){
return this.color;
}
}
If you wish to change the value of the enum you have created, provide a mutator method.
public enum Color{
RED("Red"), GREEN("Green");
private Color(String color){
this.color = color;
}
private String color;
public String getColor(){
return this.color;
}
public void setColor(String color){
this.color = color;
}
public String toString(){
return this.color;
}
}
Example of accessing:
public static void main(String args[]){
System.out.println(Color.RED.getColor());
// or
System.out.println(Color.GREEN);
}
Try this:
function delete_cookie( name, path, domain ) {
if( get_cookie( name ) ) {
document.cookie = name + "=" +
((path) ? ";path="+path:"")+
((domain)?";domain="+domain:"") +
";expires=Thu, 01 Jan 1970 00:00:01 GMT";
}
}
You can define get_cookie()
like this:
function get_cookie(name){
return document.cookie.split(';').some(c => {
return c.trim().startsWith(name + '=');
});
}
It's an eclipse setup issue, not a Jersey issue.
From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.
So Eclipse wasn't using the Gradle dependencies when Apache was starting .
In Windows 7
mysqld.exe --install
That's all
There is an easy, out of the box implementation: the HTML 5 input type="date"
and the other date-related input types.
Okay, you can't style the controls that much and it doesn't work on every browser, but still it can be a very good option in the long term if all modern browsers support it and don't want to include heavy libraries that don't always work that good on mobile devices.
You also can give a name to your script:
<script>
... (your code here)
//# sourceURL=somename.js
</script>
ofcourse replace "somename" by some name ;) and then you will see it in the chrome debugger at "Sources > top > (no domain) > somename.js" as a normal script and you will be able to debug it like other scripts
Hi you can use Renderer2 and elementRef with just a few lines of code:
constructor(private readonly elementRef: ElementRef,
private renderer: Renderer2) {
}
ngOnInit() {
const script = this.renderer.createElement('script');
script.src = 'http://iknow.com/this/does/not/work/either/file.js';
script.onload = () => {
console.log('script loaded');
initFile();
};
this.renderer.appendChild(this.elementRef.nativeElement, script);
}
the onload
function can be used to call the script functions after the script is loaded, this is very useful if you have to do the calls in the ngOnInit()
Step 1: Create a maven project in Eclipse and add the below dependency in the pom.xml
<dependencies>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.18</version>
</dependency>
Step 2: Run As --> Configuraitons --> Goto Arguments --> give arguments like below maven -clean install
Step 3: Run As --> maven clean
Once you do the maven clean you see Build Success and lombok jar file in the maven Dependencies
Step 4: Goto the jar location as shown in the below screen shot.
Step 5: Give command as shown like below after reaching in the .m2 folder
Step 6: Locate where is your eclipse folder once you this window.Once you see Install Successfull message click on Quit Installer option at the bottom.
Step 7 : We have finished installing the lombok.jar successfully .Now restart your Eclipse IDE and Start below Sample Code to check whether the data is coming or not in the getters and setters.
Step 8: Open Eclipse and create simple Java Maven project and see in the Outline section you can see getters and setters are created you can use either @Data or @Getter @Setter On top of class or you can give on top of variable
@Getter @Setter
privateString riverName;
{OR}
@Getter
@Setter
Class River{
String riverName;
}
[OR]
@Data
class River
{
Private String riverName;
}
You can see the project structure and Outline Structure how it got created in simple steps.
Here is an example that works on Chrome 5.0.375.125.
The page B (iframe content):
<html>
<head></head>
<body>
<script>
top.postMessage('hello', 'A');
</script>
</body>
</html>
Note the use of top.postMessage
or parent.postMessage
not window.postMessage
here
The page A:
<html>
<head></head>
<body>
<iframe src="B"></iframe>
<script>
window.addEventListener( "message",
function (e) {
if(e.origin !== 'B'){ return; }
alert(e.data);
},
false);
</script>
</body>
</html>
A and B must be something like http://domain.com
EDIT:
From another question, it looks the domains(A and B here) must have a /
for the postMessage
to work properly.
This might just help someone, in addition to what other answers have mentioned.
Clear the contents of AppData\Local\Microsoft\WebSiteCache
folder.
In my case I had VS 2015 pro update 3 and this is what helped me speed up VS.
"Sleep" state connections are most often created by code that maintains persistent connections to the database.
This could include either connection pools created by application frameworks, or client-side database administration tools.
As mentioned above in the comments, there is really no reason to worry about these connections... unless of course you have no idea where the connection is coming from.
(CAVEAT: If you had a long list of these kinds of connections, there might be a danger of running out of simultaneous connections.)
Adding up to other answers you need to export the class to use in a different class. This is a typescript version of it.
//Constants.tsx
const DEBUG: boolean = true;
export class Constants {
static get DEBUG(): boolean {
return DEBUG;
}
}
//Anotherclass.tsx
import { Constants } from "Constants";
if (Constants.DEBUG) {
console.log("debug mode")
}
_x000D_
This happened to me at VS 2010 and Win 7.. Case :
What I have tried:
Stop antivirus, check ridiculous running program using task manager and ProcessExplorer
run VS as administrator
If All that way is still not working.
Then, the last way to try:
In one line of code as below :
<p> cursor on text field shows text .if not password will be shown</p>_x000D_
<input type="password" name="txt_password" onmouseover="this.type='text'"_x000D_
onmouseout="this.type='password'" placeholder="password" />
_x000D_
Just be careful - in this case the first finally
is touched, but skipped too.
def a(z):
try:
100/z
except ZeroDivisionError:
try:
print('x')
finally:
return 42
finally:
return 1
In [1]: a(0)
x
Out[1]: 1
You can just modified the .bash_profile
by adding the MySQL $PATH
as the following:
export PATH=$PATH:/usr/local/mysql/bin
.
I did the following:
1- Open Terminal then $ nano .bash_profile
or $ vim .bash_profile
2- Add the following PATH code to the .bash_profile
# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc
3- Save the file.
4- Refresh Terminal using $ source ~/.bash_profile
5- To verify, type in Terminal $ mysql --version
6- It should print the output something like this:
$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)
The Terminal is now configured to read the MySQL commands from $PATH
which is placed in the .bash_profile
.
import cv2
camera = cv2.VideoCapture(0)
while True:
return_value,image = camera.read()
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow('image',gray)
if cv2.waitKey(1)& 0xFF == ord('s'):
cv2.imwrite('test.jpg',image)
break
camera.release()
cv2.destroyAllWindows()
Remember that in onClick={ ... }
, the ...
is a JavaScript expression. So
... onClick={this.handleRemove(id)}
is the same as
var val = this.handleRemove(id);
... onClick={val}
In other words, you call this.handleRemove(id)
immediately, and pass that value to onClick
, which isn't what you want.
Instead, you want to create a new function with one of the arguments already prefilled; essentially, you want the following:
var newFn = function() {
var args = Array.prototype.slice.call(arguments);
// args[0] contains the event object
this.handleRemove.apply(this, [id].concat(args));
}
... onClick={newFn}
There is a way to express this in ES5 JavaScript: Function.prototype.bind
.
... onClick={this.handleRemove.bind(this, id)}
If you use React.createClass
, React automatically binds this
for you on instance methods, and it may complain unless you change it to this.handleRemove.bind(null, id)
.
You can also simply define the function inline; this is made shorter with arrow functions if your environment or transpiler supports them:
... onClick={() => this.handleRemove(id)}
If you need access to the event, you can just pass it along:
... onClick={(evt) => this.handleRemove(id, evt)}
I wanted to achieve on-boot container startup on Windows.
Therefore, I just created a scheduled Task which launches on system boot. That task simply starts "Docker for Windows.exe" (or whatever is the name of your docker executable).
Then, all containers with a restart policy of "always" will start up.
The CSV "standard" (such as it is) does not dictate how comments should be handled, no, it's up to the application to establish a convention and stick with it.
As Lucas says, what you are describing is the intended behaviour for the float property. What confuses many people is that float has been pushed well beyond its original intended usage in order to make up for shortcomings in the CSS layout model.
Have a look at Floatutorial if you'd like to get a better understanding of how this property works.
Based on Peter Ajtai answer, here is a small jquery plugin that may help others. I didn't test on Opera and IE9 but is should work on these browsers too.
$.fn.rotate = function(until, step, initial, elt) {
var _until = (!until)?360:until;
var _step = (!step)?1:step;
var _initial = (!initial)?0:initial;
var _elt = (!elt)?$(this):elt;
var deg = _initial + _step;
var browser_prefixes = ['-webkit', '-moz', '-o', '-ms'];
for (var i=0, l=browser_prefixes.length; i<l; i++) {
var pfx = browser_prefixes[i];
_elt.css(pfx+'-transform', 'rotate('+deg+'deg)');
}
if (deg < _until) {
setTimeout(function() {
$(this).rotate(_until, _step, deg, _elt); //recursive call
}, 5);
}
};
$('.my-elt').rotate()
Once you have the flattened DataFrame
obtained by the accepted answer, you can make the columns a MultiIndex
("fancy multiline header") like this:
df.columns = pd.MultiIndex.from_tuples([tuple(c.split('.')) for c in df.columns])
You can use lodash's findIndex to get the index of the specific element and then splice using it.
myArray.splice(_.findIndex(myArray, function(item) {
return item.value === 'money';
}), 1);
Update
You can also use ES6's findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
const itemToRemoveIndex = myArray.findIndex(function(item) {
return item.field === 'money';
});
// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
myArray.splice(itemToRemoveIndex, 1);
}
The default value will be the value of your Model.Age
property. That's kind of the whole point.
find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash
bash 4 (recursive)
shopt -s globstar
for xls in /path/**/*.xls
do
xls2csv "$xls" "${xls%.xls}.csv"
done
Try this...
* {
transition: all .2s linear;
-webkit-transition: all .2s linear;
-moz-transition: all .2s linear;
-o-transition: all .2s linear;
}
a {
-webkit-transition: background-position 1ms linear;
-moz-transition: background-position 1ms linear;
-o-transition: background-position 1ms linear;
transition: background-position 1ms linear;
}
Here are a few simple examples to see the difference in action:
See the list of numbers here:
nums = [1, 9, -3, 4, 8, 5, 7, 14]
When calling sorted
on this list, sorted
will make a copy of the list. (Meaning your original list will remain unchanged.)
Let's see.
sorted(nums)
returns
[-3, 1, 4, 5, 7, 8, 9, 14]
Looking at the nums
again
nums
We see the original list (unaltered and NOT sorted.). sorted
did not change the original list
[1, 2, -3, 4, 8, 5, 7, 14]
Taking the same nums
list and applying the sort
function on it, will change the actual list.
Let's see.
Starting with our nums
list to make sure, the content is still the same.
nums
[-3, 1, 4, 5, 7, 8, 9, 14]
nums.sort()
Now the original nums list is changed and looking at nums we see our original list has changed and is now sorted.
nums
[-3, 1, 2, 4, 5, 7, 8, 14]
The solution that worked for me was to right click on the project --> Maven --> Update Project then click OK.
or in a better way we can have like this
Let's say your primary key is an Integer and object you save is "ticket", then you can get it like this. When you save the object, id is always returned
//unboxing will occur here so that id here will be value type not the reference type. Now you can check id for 0 in case of save failure. like below:
int id = (Integer) session.save(ticket);
if(id==0)
your session.save call was not success.
else '
your call to session.save was successful.
The vm module in Node.js provides the ability to execute JavaScript code within the current context (including global object). See http://nodejs.org/docs/latest/api/vm.html#vm_vm_runinthiscontext_code_filename
Note that, as of today, there's a bug in the vm module that prevenst runInThisContext from doing the right when invoked from a new context. This only matters if your main program executes code within a new context and then that code calls runInThisContext. See https://github.com/joyent/node/issues/898
Sadly, the with(global) approach that Fernando suggested doesn't work for named functions like "function foo() {}"
In short, here's an include() function that works for me:
function include(path) {
var code = fs.readFileSync(path, 'utf-8');
vm.runInThisContext(code, path);
}
join is not a jQuery function .Its a javascript function.
The join() method joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
If you are using the JQuery
, please use the bellow snippet for group of radio buttons.
var radioBtValue= $('input[type=radio][name=radiobt]:checked').val();
Careful not to use the input
function, unless you know what you're doing. Unlike raw_input
, input
will accept any python expression, so it's kinda like eval
This is not exactly the OP's scenario but an answer to those of some of the commenters. It is a solution based on Cordova and Angular 1, which should be adaptable to other frameworks like jQuery. It gives you a Blob from Base64 data which you can store somewhere and reference it from client side javascript / html.
It also answers the original question on how to get an image (file) from the Base 64 data:
The important part is the Base 64 - Binary conversion:
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
var sliceSize = 1024;
var byteCharacters = atob(base64Data);
var bytesLength = byteCharacters.length;
var slicesCount = Math.ceil(bytesLength / sliceSize);
var byteArrays = new Array(slicesCount);
for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
var begin = sliceIndex * sliceSize;
var end = Math.min(begin + sliceSize, bytesLength);
var bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Slicing is required to avoid out of memory errors.
Works with jpg and pdf files (at least that's what I tested). Should work with other mimetypes/contenttypes too. Check the browsers and their versions you aim for, they need to support Uint8Array, Blob and atob.
Here's the code to write the file to the device's local storage with Cordova / Android:
...
window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
// Setup filename and assume a jpg file
var filename = attachment.id + "-" + (attachment.fileName ? attachment.fileName : 'image') + "." + (attachment.fileType ? attachment.fileType : "jpg");
dirEntry.getFile(filename, { create: true, exclusive: false }, function(fileEntry) {
// attachment.document holds the base 64 data at this moment
var binary = base64toBlob(attachment.document, attachment.mimetype);
writeFile(fileEntry, binary).then(function() {
// Store file url for later reference, base 64 data is no longer required
attachment.document = fileEntry.nativeURL;
}, function(error) {
WL.Logger.error("Error writing local file: " + error);
reject(error.code);
});
}, function(errorCreateFile) {
WL.Logger.error("Error creating local file: " + JSON.stringify(errorCreateFile));
reject(errorCreateFile.code);
});
}, function(errorCreateFS) {
WL.Logger.error("Error getting filesystem: " + errorCreateFS);
reject(errorCreateFS.code);
});
...
Writing the file itself:
function writeFile(fileEntry, dataObj) {
return $q(function(resolve, reject) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function() {
WL.Logger.debug(LOG_PREFIX + "Successful file write...");
resolve();
};
fileWriter.onerror = function(e) {
WL.Logger.error(LOG_PREFIX + "Failed file write: " + e.toString());
reject(e);
};
// If data object is not passed in,
// create a new Blob instead.
if (!dataObj) {
dataObj = new Blob(['missing data'], { type: 'text/plain' });
}
fileWriter.write(dataObj);
});
})
}
I am using the latest Cordova (6.5.0) and Plugins versions:
I hope this sets everyone here in the right direction.
Here's a better option:
git remote set-head -a origin
From the documentation:
With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.
This has actually been around quite a while (since v1.6.3); not sure how I missed it!
You can use the following query to create a table to a particular database in MySql.
create database if not exists `test`;
USE `test`;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
/*Table structure for table `test` */
CREATE TABLE IF NOT EXISTS `tblsample` (
`id` int(11) NOT NULL auto_increment,
`recid` int(11) NOT NULL default '0',
`cvfilename` varchar(250) NOT NULL default '',
`cvpagenumber` int(11) NULL,
`cilineno` int(11) NULL,
`batchname` varchar(100) NOT NULL default '',
`type` varchar(20) NOT NULL default '',
`data` varchar(100) NOT NULL default '',
PRIMARY KEY (`id`)
);
Use:
git reset HEAD filepath
For example:
git reset HEAD om211/src/META-INF/persistence.xml
if( strpos( $url, "#" ) === false ) echo "NO HASH !";
else echo "HASH IS: #".explode( "#", $url )[1]; // arrays are indexed from 0
Or in "old" PHP you must pre-store the exploded to access the array:
$exploded_url = explode( "#", $url ); $exploded_url[1];
var forms = document.getElementsByTagName('form'); //get all forms on the site
for (var i = 0; i < forms.length; i++) { //to each form...
forms[i].addEventListener( // add a "listener"
'submit', // for an on-submit "event"
function () { //add a submit pre-processing function:
var input_name = "fragment"; // name form will use to send the fragment
// Try search whether we already done this or not
// in current form, find every <input ... name="fragment" ...>
var hiddens = form.querySelectorAll('[name="' + input_name + '"]');
if (hiddens.length < 1) { // if not there yet
//create an extra input element
var hidden = document.createElement("input");
//set it to hidden so it doesn't break view
hidden.setAttribute('type', 'hidden');
//set a name to get by it in PHP
hidden.setAttribute('name', input_name);
this.appendChild(hidden); //append it to the current form
} else {
var hidden = hiddens[0]; // use an existing one if already there
}
//set a value of #HASH - EVERY TIME, so we get the MOST RECENT #hash :)
hidden.setAttribute('value', window.location.hash);
}
);
}
Depending on your form
's method
attribute you get this hash in PHP by:
$_GET['fragment']
or $_POST['fragment']
Possible returns: 1. ""
[empty string] (no hash) 2. whole hash INCLUDING the #
[hash] sign (because we've used the window.location.hash
in JavaScript which just works that way :) )
...(not while considering regular HTTP requests)...
...Hope this helped :)
You can use the union() function in python.
joinedlist = union(listone, listtwo)
print(joinedlist)
Essentially what this is doing is its removing one of every duplicate in the two lists. Since your lists don't have any duplicates it, it just returns the concatenated version of the two lists.
Careful! Watch the accessibility of your classes. Public and protected classes and methods are by default accessible for everyone.
Also, Microsoft isn't very explicit in showing access modifiers (public, protected, etc.. keywords) when new classes in Visual Studio are created. So, take good care and think about the accessibility of your class because it's the door to your implementation internals.
Give your button a custom background: @drawable/material_btn_blue
You'll also get this error if your target element is inside a hidden element. If this is your HTML:
<div *ngIf="false">
<span #sp>Hello World</span>
</div>
Your @ViewChild('sp') sp
will be undefined.
In such a case, then don't use *ngIf
.
Instead use a class to show/hide your element being hidden.
<div [class.show]="shouldShow">...</div>
Maybe more clear:
Note that precision is the total number of digits, scale included
NUMBER(Precision,Scale)
Precision 8, scale 3 : 87654.321
Precision 5, scale 3 : 54.321
Precision 5, scale 1 : 5432.1
Precision 5, scale 0 : 54321
Precision 5, scale -1: 54320
Precision 5, scale -3: 54000
The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx
.
Unfortunately, it does not fit on a single line.
#!/bin/ksh
# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`
# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail
# Add several attachments
uuencode File1.pdf File1.pdf > attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail
# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail
# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail
This code may help you:
public class EN implements Serializable {
//... you don't need implement any methods when you implements Serializable
}
Putting data. Create new Activity with extra:
EN enumb = new EN();
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("en", enumb); //second param is Serializable
startActivity(intent);
Obtaining data from new activity:
public class NewActivity extends Activity {
private EN en;
@Override
public void onCreate(Bundle savedInstanceState) {
try {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
if (extras != null) {
en = (EN)getIntent().getSerializableExtra("en"); //Obtaining data
}
//...
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<b><centre>Redirecting to Google<br>");
response.setHeader("refresh,"5;https://www.google.com/"); // redirects to url after 5 seconds
pw.close();
}
}
For Mac sudo chmod 755 /Applications/XAMPP/xamppfiles/phpmyadmin/config.inc.php Worked for me
--save-dev: Package will appear in your devDependencies.
According to the npm install docs.
If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.
In other words, when you run npm install
, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).
According to the package.json docs
npm install
does:The other methods don't remove multiple extensions. Some also have problems with filenames that don't have extensions. This snippet deals with both instances and works in both Python 2 and 3. It grabs the basename from the path, splits the value on dots, and returns the first one which is the initial part of the filename.
import os
def get_filename_without_extension(file_path):
file_basename = os.path.basename(file_path)
filename_without_extension = file_basename.split('.')[0]
return filename_without_extension
Here's a set of examples to run:
example_paths = [
"FileName",
"./FileName",
"../../FileName",
"FileName.txt",
"./FileName.txt.zip.asc",
"/path/to/some/FileName",
"/path/to/some/FileName.txt",
"/path/to/some/FileName.txt.zip.asc"
]
for example_path in example_paths:
print(get_filename_without_extension(example_path))
In every case, the value printed is:
FileName
Since android doesnt support <ol>, <ul> or <li>
html elements, I had to do it like this
<string name="names"><![CDATA[<p><h2>List of Names:</h2></p><p>•name1<br />•name2<br /></p>]]></string>
if you want to maintain custom space then use </pre> tag
If you want to copy a source directory entirely with the same directory structure, Then don't use a star(*). Write COPY command in Dockerfile as below.
COPY . destinatio-directory/
Based on the answers provided, I decided to make a quick plugin to do this:
(function($){
$.fn.moveTo = function(selector){
return this.each(function(){
var cl = $(this).clone();
$(cl).appendTo(selector);
$(this).remove();
});
};
})(jQuery);
Usage:
$('#nodeToMove').moveTo('#newParent');
Better late than never.
I had difficulties reading files line by line in some circumstances. The method below is the best I found, so far, and I recommend it.
Usage: String yourData = LoadData("YourDataFile.txt");
Where YourDataFile.txt is assumed to reside in assets/
public String LoadData(String inFile) {
String tContents = "";
try {
InputStream stream = getAssets().open(inFile);
int size = stream.available();
byte[] buffer = new byte[size];
stream.read(buffer);
stream.close();
tContents = new String(buffer);
} catch (IOException e) {
// Handle exceptions here
}
return tContents;
}
In my case, in Xubuntu, I had to install libcurl3 libcurl3-dev libraries. With this command everything worked:
sudo apt-get install curl libcurl3 libcurl3-dev php5-curl
While the syntax is certainly different between Razor (.cshtml
/.vbhtml
) and WebForms (.aspx
/.ascx
), (Razor's being the more concise and modern of the two), nobody has mentioned that while both can be used as View Engines / Templating Engines, traditional ASP.NET Web Forms controls can be used on any .aspx or .ascx files, (even in cohesion with an MVC architecture).
This is relevant in situations where long standing solutions to a problem have been established and packaged into a pluggable component (e.g. a large-file uploading control) and you want to use it in an MVC site. With Razor, you can't do this. However, you can execute all of the same backend-processing that you would use with a traditional ASP.NET architecture with a Web Form view.
Furthermore, ASP.NET web forms views can have Code-Behind files, which allows embedding logic into a separate file that is compiled together with the view. While the software development community is growing to be see tightly coupled architectures and the Smart Client pattern as bad practice, it used to be the main way of doing things and is still very much possible with .aspx/.ascx files. Razor, intentionally, has no such quality.
This answer predates version 1.1.5 where a proper ternary in the $parse
function wasn't available. Use this answer if you're on a lower version, or as an example of filters:
angular.module('myApp.filters', [])
.filter('conditional', function() {
return function(condition, ifTrue, ifFalse) {
return condition ? ifTrue : ifFalse;
};
});
And then use it as
<i ng-class="checked | conditional:'icon-check':'icon-check-empty'"></i>
Forget about using success
and error
method.
Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.
With the following example, I'll try to demonstrate what I mean about success
and error
being not chainable-friendly. Suppose we call an API that returns a user object with an address:
User object:
{name: 'Igor', address: 'San Francisco'}
Call to the API:
$http.get('/user')
.success(function (user) {
return user.address; <---
}) | // you might expect that 'obj' is equal to the
.then(function (obj) { ------ // address of the user, but it is NOT
console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
});
};
What happened?
Because success
and error
return the original promise, i.e. the one returned by $http.get
, the object passed to the callback of the then
is the whole user object, that is to say the same input to the preceding success
callback.
If we had chained two then
, this would have been less confusing:
$http.get('/user')
.then(function (user) {
return user.address;
})
.then(function (obj) {
console.log(obj); // -> 'San Francisco'
});
};
NO, you can't do it other way than so.
We can use the formula method of aggregate
. The variables on the 'rhs' of ~
are the grouping variables while the .
represents all other variables in the 'df1' (from the example, we assume that we need the mean
for all the columns except the grouping), specify the dataset and the function (mean
).
aggregate(.~id1+id2, df1, mean)
Or we can use summarise_each
from dplyr
after grouping (group_by
)
library(dplyr)
df1 %>%
group_by(id1, id2) %>%
summarise_each(funs(mean))
Or using summarise
with across
(dplyr
devel version - ‘0.8.99.9000’
)
df1 %>%
group_by(id1, id2) %>%
summarise(across(starts_with('val'), mean))
Or another option is data.table
. We convert the 'data.frame' to 'data.table' (setDT(df1)
, grouped by 'id1' and 'id2', we loop through the subset of data.table (.SD
) and get the mean
.
library(data.table)
setDT(df1)[, lapply(.SD, mean), by = .(id1, id2)]
df1 <- structure(list(id1 = c("a", "a", "a", "a", "b", "b",
"b", "b"
), id2 = c("x", "x", "y", "y", "x", "y", "x", "y"),
val1 = c(1L,
2L, 3L, 4L, 1L, 4L, 3L, 2L), val2 = c(9L, 4L, 5L, 9L, 7L, 4L,
9L, 8L)), .Names = c("id1", "id2", "val1", "val2"),
class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6", "7", "8"))
You should edit your my.cnf
tmpdir = /whatewer/you/want
and after that restart mysql
P.S. Don't forget give write permissions to /whatewer/you/want
for mysql user
DROP IF EXISTS is a new feature of SQL Server 2016
DROP PROCEDURE IF EXISTS dbo.[procname]
Same issue on Ubuntu-MATE, but here you resolve it by:
gsettings set org.mate.Marco.general mouse-button-modifier "<Super>"
You should be able to do this with existing bootstrap classes and a little custom styling.
<form>
<div class="input-prepend">
<span class="add-on">
<i class="icon-user"></i>
</span>
<input class="span2" id="prependedInput" type="text" placeholder="Username" style="background-color: #eeeeee;border-left: #eeeeee;">
</div>
Edit The icon is referenced via the icon-user
class. This answer was written at the time of Bootstrap version 2. You can see the reference on the following page: http://getbootstrap.com/2.3.2/base-css.html#images
I have a function in my PowerShell profile named 'which'
function which {
get-command $args[0]| format-list
}
Here's what the output looks like:
PS C:\Users\fez> which python
Name : python.exe
CommandType : Application
Definition : C:\Python27\python.exe
Extension : .exe
Path : C:\Python27\python.exe
FileVersionInfo : File: C:\Python27\python.exe
InternalName:
OriginalFilename:
FileVersion:
FileDescription:
Product:
ProductVersion:
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language:
I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)
(**Important) : Get a full backup of your database before the process.
Run "checkpoint" on that database.
Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}
Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).
Attach the database (right click on Databases and chose Attach...)
On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)
After that, a new log file create with a size of 504 KB!!!.
In step 2, if you faced an error that database is used by another user, you can:
1.run this command on master database "sp_who2" and see what process using your database.
2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.
If the number of processes using your database is too much:
1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).
"Clear" JavaScript:
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
alert(String.fromCharCode(keynum));
}
_x000D_
<input type="text" onkeypress="return myKeyPress(event)" />
_x000D_
JQuery:
$("input").keypress(function(event){
alert(String.fromCharCode(event.which));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input/>
_x000D_
exec
and eval
exec
and eval
in Python is highly frowned upon.From the top answer (emphasis mine):
For statements, use
exec
.When you need the value of an expression, use
eval
.However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.
From Alternatives to exec/eval?
set and get values of variables with the names in strings
[while
eval
] would work, it is generally not advised to use variable names bearing a meaning to the program itself.Instead, better use a dict.
From http://lucumr.pocoo.org/2011/2/1/exec-in-python/ (emphasis mine)
Python is not PHP
Don't try to circumvent Python idioms because some other language does it differently. Namespaces are in Python for a reason and just because it gives you the tool
exec
it does not mean you should use that tool.
From http://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html (emphasis mine)
So eval is not safe, even if you remove all the globals and the builtins!
The problem with all of these attempts to protect eval() is that they are blacklists. They explicitly remove things that could be dangerous. That is a losing battle because if there's just one item left off the list, you can attack the system.
So, can eval be made safe? Hard to say. At this point, my best guess is that you can't do any harm if you can't use any double underscores, so maybe if you exclude any string with double underscores you are safe. Maybe...
From http://stupidpythonideas.blogspot.it/2013/05/why-evalexec-is-bad.html (emphasis mine):
First,
exec
makes it harder to human beings to read your code. In order to figure out what's happening, I don't just have to read your code, I have to read your code, figure out what string it's going to generate, then read that virtual code. So, if you're working on a team, or publishing open source software, or asking for help somewhere like StackOverflow, you're making it harder for other people to help you. And if there's any chance that you're going to be debugging or expanding on this code 6 months from now, you're making it harder for yourself directly.
Scanner.hasNextXXX
methodsjava.util.Scanner
has many hasNextXXX
methods that can be used to validate input. Here's a brief overview of all of them:
hasNext()
- does it have any token at all?hasNextLine()
- does it have another line of input?hasNextInt()
- does it have a token that can be parsed into an int
?hasNextDouble()
, hasNextFloat()
, hasNextByte()
, hasNextShort()
, hasNextLong()
, and hasNextBoolean()
hasNextBigInteger()
and hasNextBigDecimal()
hasNext(String pattern)
hasNext(Pattern pattern)
is the Pattern.compile
overloadScanner
is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern)
, which lets you define what pattern separates your tokens. There are also find
and skip
methods that ignores delimiters.
The following discussion will keep the regex as simple as possible, so the focus remains on Scanner
.
Here's a simple example of using hasNextInt()
to validate positive int
from the input.
Scanner sc = new Scanner(System.in);
int number;
do {
System.out.println("Please enter a positive number!");
while (!sc.hasNextInt()) {
System.out.println("That's not a number!");
sc.next(); // this is important!
}
number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);
Here's an example session:
Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5
Note how much easier Scanner.hasNextInt()
is to use compared to the more verbose try/catch
Integer.parseInt
/NumberFormatException
combo. By contract, a Scanner
guarantees that if it hasNextInt()
, then nextInt()
will peacefully give you that int
, and will not throw any NumberFormatException
/InputMismatchException
/NoSuchElementException
.
hasNextXXX
on the same tokenNote that the snippet above contains a sc.next()
statement to advance the Scanner
until it hasNextInt()
. It's important to realize that none of the hasNextXXX
methods advance the Scanner
past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!
This has two consequences:
hasNextXXX
test, then you need to advance the Scanner
one way or another (e.g. next()
, nextLine()
, skip
, etc).hasNextXXX
test fails, you can still test if it perhaps hasNextYYY
!Here's an example of performing multiple hasNextXXX
tests.
Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
System.out.println(
sc.hasNextInt() ? "(int) " + sc.nextInt() :
sc.hasNextLong() ? "(long) " + sc.nextLong() :
sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
"(String) " + sc.next()
);
}
Here's an example session:
5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit
Note that the order of the tests matters. If a Scanner
hasNextInt()
, then it also hasNextLong()
, but it's not necessarily true
the other way around. More often than not you'd want to do the more specific test before the more general test.
Scanner
has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.
Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
System.out.println("That's not a vowel!");
sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);
Here's an example session:
Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e
In regex, as a Java string literal, the pattern "[aeiou]"
is what is called a "character class"; it matches any of the letters a
, e
, i
, o
, u
. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner
.
hasNext(String pattern)
- Returns true
if the next token matches the pattern constructed from the specified string.java.util.regex.Pattern
Scanner
at onceSometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner
, where the second Scanner
takes the nextLine()
from the first Scanner
as input. Here's an example:
Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
Scanner lineSc = new Scanner(sc.nextLine());
int sum = 0;
while (lineSc.hasNextInt()) {
sum += lineSc.nextInt();
}
System.out.println("Sum is " + sum);
}
Here's an example session:
Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit
In addition to Scanner(String)
constructor, there's also Scanner(java.io.File)
among others.
Scanner
provides a rich set of features, such as hasNextXXX
methods for validation.hasNextXXX/nextXXX
in combination means that a Scanner
will NEVER throw an InputMismatchException
/NoSuchElementException
.hasNextXXX
does not advance the Scanner
past any input.Scanner
if necessary. Two simple Scanner
is often better than one overly complex Scanner
.Scanner
method that takes a String pattern
argument is regex-based.
String
into a literal pattern is to Pattern.quote
it.For versions below 12c, the plain answer is NO, at least not in the manner it is being done is SQL Server.
You can print the results, you can insert the results into tables, you can return the results as cursors from within function/procedure or return a row set from function -
but you cannot execute SELECT statement, without doing something with the results.
begin
select 1+1
select 2+2
select 3+3
end
/* 3 result sets returned */
SQL> begin
2 select 1+1 from dual;
3 end;
4 /
select * from dual;
*
ERROR at line 2:
ORA-06550: line 2, column 1:
PLS-00428: an INTO clause is expected in this SELECT statement
In conf/tomcat-users.xml you can see what's your actual user configuration, in my case is usually user="admin" and pass="1234"
The easiest and fastest way would be with phpmyadmin structure table.
There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.
document.querySelectorAll("#yourId");
returns all elements whose id is yourId
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
So you can use:
myvar = getURLParameter('myvar');
In my case, I had installed *ahem* OpenJDK, but the bin folder was full of symlinks to the bundled JRE and the actual JDK was nowhere to be found.
When I see a directory structure with bin
and jre
subdirectories I expect this to be the JDK installation, because JRE installations on Windows looked different. But in this case it was the JRE installation as found out by apt search
. After installing openjdk-8-jre the simlinks were replaced and the directory structure otherwise stayed the same.
In C/C++ you have header files (*.H). There you declare your functions/classes. So for example you will have to #include "second.h"
to your main.cpp
file.
In second.h
you just declare like this void yourFunction();
In second.cpp
you implement it like
void yourFunction() {
doSomethng();
}
Don't forget to #include "second.h"
also in the beginning of second.cpp
Hope this helps:)
Using onBackPressed()
method:
@Override
public void onBackPressed() {
android.os.Process.killProcess(android.os.Process.myPid());
}
or use the finish()
method, I have something like
//Password Error, I call function
Quit();
protected void Quit() {
super.finish();
}
With super.finish() you close the super class's activity.
On Windows Powershell:
Get-PSDrive
[System.IO.DriveInfo]::getdrives()
wmic diskdrive
wmic volume
Also the utility dskwipe: http://smithii.com/dskwipe
dskwipe.exe -l
You want to use %d
or %i
for integers. %@
is used for objects.
It's worth noting, though, that the following code will accomplish the same task and is much clearer.
label.intValue = count;
Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.
Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.
You can even edit most of the code while it is running.
Use Debug.Print
to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox
.
Use breakpoints or the Stop
keyword to automatically halt execution in interesting areas.
You can use Debug.Assert
to halt execution conditionally.
I recommend you to remove scipy via
apt-get purge scipy
and then to install it by
pip install scipy
If you do both then you might confuse you deb package manager due to possibly differing versions.
My problem was in wrong classes. I used custom .xib for my custom view. Correctly it has to be set like here:
To use Thickness
you need to create/change your project .NET framework
platform version to 4.5. becaus this method available only in version 4.5. (Also you can just download PresentationFramework.dll and give referense to this dll, without create/change your .NET framework
version to 4.5.)
But if you want to do this simple, You can use this code:
MyControl.Margin = new Padding(int left, int top, int right, int bottom);
also
MyControl.Margin = new Padding(int all);
This is simple and no needs any changes to your project
SRCS=$(wildcard *.c)
OBJS=$(SRCS:.c=.o)
all: $(OBJS)
// Bind combobox to dictionary
Dictionary<string, string>test = new Dictionary<string, string>();
test.Add("1", "dfdfdf");
test.Add("2", "dfdfdf");
test.Add("3", "dfdfdf");
comboBox1.DataSource = new BindingSource(test, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
// Get combobox selection (in handler)
string value = ((KeyValuePair<string, string>)comboBox1.SelectedItem).Value;
I tried this, it worked for me:
declare @b2 VARBINARY(MAX)
set @b2 = 0x54006800690073002000690073002000610020007400650073007400
SELECT CONVERT(nVARCHAR(1000), @b2, 0);
All you need is to give the AnchorPane
an ID, and then you can get the Stage
from that.
@FXML private AnchorPane ap;
Stage stage = (Stage) ap.getScene().getWindow();
From here, you can add in the Listener
that you need.
Edit: As stated by EarthMind below, it doesn't have to be the AnchorPane
element; it can be any element that you've defined.
I would recommend that you start by pulling your task apart into it's component parts.
Once you do that, it should be fairly trivial to use one of the libraries you link to (which most certainly will handle task #1). Then iterate through the returned values, and cast/convert each String value to the value you want.
If the question is how to convert strings to different objects, it's going to depend on what format you are starting with, and what format you want to wind up with.
DateFormat.parse(), for example, will parse dates from strings. See SimpleDateFormat for quickly constructing a DateFormat for a certain string representation. Integer.parseInt() will prase integers from strings.
Currency, you'll have to decide how you want to capture it. If you want to just capture as a float, then Float.parseFloat() will do the trick (just use String.replace() to remove all $ and commas before you parse it). Or you can parse into a BigDecimal (so you don't have rounding problems). There may be a better class for currency handling (I don't do much of that, so am not familiar with that area of the JDK).
This is also working, avoiding to call for an element id but calling it using as an array element.
The following code is based on the fact that an array, named as the radiobuttons group, is composed by radiobuttons elements in the same order as they where declared in the html document:
if(!document.yourformname.yourradioname[0].checked
&& !document.yourformname.yourradioname[1].checked){
alert('is this working for all?');
return false;
}
Try from tensorflow.python import keras
with this, you can easily change keras dependent code to tensorflow in one line change.
You can also try from tensorflow.contrib import keras
. This works on tensorflow 1.3
Edited: for tensorflow 1.10 and above you can use import tensorflow.keras as keras
to get keras in tensorflow.
More generic way in case qs
has more than one dictionaries:
[int(v) for lst in qs for k, v in lst.items()]
--
>>> qs = [{u'a': 15L, u'b': 9L, u'a': 16L}, {u'a': 20, u'b': 35}]
>>> result_list = [int(v) for lst in qs for k, v in lst.items()]
>>> result_list
[16, 9, 20, 35]
pgAdmin has GUI for data import since 1.16. You have to create your table first and then you can import data easily - just right-click on the table name and click on Import.
If you don't need two-way data-binding:
<select (change)="onChange($event.target.value)">
<option *ngFor="let i of devices">{{i}}</option>
</select>
onChange(deviceValue) {
console.log(deviceValue);
}
For two-way data-binding, separate the event and property bindings:
<select [ngModel]="selectedDevice" (ngModelChange)="onChange($event)" name="sel2">
<option [value]="i" *ngFor="let i of devices">{{i}}</option>
</select>
export class AppComponent {
devices = 'one two three'.split(' ');
selectedDevice = 'two';
onChange(newValue) {
console.log(newValue);
this.selectedDevice = newValue;
// ... do other stuff here ...
}
If devices
is array of objects, bind to ngValue
instead of value
:
<select [ngModel]="selectedDeviceObj" (ngModelChange)="onChangeObj($event)" name="sel3">
<option [ngValue]="i" *ngFor="let i of deviceObjects">{{i.name}}</option>
</select>
{{selectedDeviceObj | json}}
export class AppComponent {
deviceObjects = [{name: 1}, {name: 2}, {name: 3}];
selectedDeviceObj = this.deviceObjects[1];
onChangeObj(newObj) {
console.log(newObj);
this.selectedDeviceObj = newObj;
// ... do other stuff here ...
}
}
Plunker - does not use <form>
Plunker - uses <form>
and uses the new forms API
An enum
type is a special type of class
.
Your enum
will actually be compiled to something like
public final class MySingleton {
public final static MySingleton INSTANCE = new MySingleton();
private MySingleton(){}
}
When your code first accesses INSTANCE
, the class MySingleton
will be loaded and initialized by the JVM. This process initializes the static
field above once (lazily).
Use file this code
function move_file($path,$to){
if(copy($path, $to)){
unlink($path);
return true;
} else {
return false;
}
}
See:
The last in particular provides detailed initialization steps that spell out when static variables are initialized, and in what order (with the caveat that final
class variables and interface fields that are compile-time constants are initialized first.)
I'm not sure what your specific question about point 3 (assuming you mean the nested one?) is. The detailed sequence states this would be a recursive initialization request so it will continue initialization.
Your DateFormat
pattern does not match you input date String
. You could use
new SimpleDateFormat("dd-MMM-yyyy")
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
use position:fixed
instead of position:absolute
The first one is relative to your screen window. (not affected by scrolling)
The second one is relative to the page. (affected by scrolling)
Note : IE6 doesn't support position:fixed.
When you upload a file using FileField
, the file will have a URL that you can use to point to the file and use HTML download
attribute to download that file you can simply do this.
models.py
The model.py looks like this
class CsvFile(models.Model):
csv_file = models.FileField(upload_to='documents')
views.py
#csv upload
class CsvUploadView(generic.CreateView):
model = CsvFile
fields = ['csv_file']
template_name = 'upload.html'
#csv download
class CsvDownloadView(generic.ListView):
model = CsvFile
fields = ['csv_file']
template_name = 'download.html'
Then in your templates.
#Upload template
upload.html
<div class="container">
<form action="#" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<button class="btn btn-primary btn-sm" type="submit">Upload</button>
</form>
#download template
download.html
{% for document in object_list %}
<a href="{{ document.csv_file.url }}" download class="btn btn-dark float-right">Download</a>
{% endfor %}
I did not use forms, just rendered model but either way, FileField is there and it will work the same.
I had similar problem after updating SDK from r20 to r21, but all I missed was the SDK/AVD Manager and running into this post while searching for the answer.
I managed to solve it by going to Window -> Customize Perspective
, and under Command Groups Availability tab check the Android SDK and AVD Manager (not sure why it became unchecked because it was there before). I'm using Mac by the way, in case the menu option looks different.
LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'
I think you're missing a )
on both of the trims. Some SQL versions support just TRIM which does both L and R trims...
I like Microsoft's XML Notepad 2007, but I don't know how it handles very large files, sorry.
Replace
Into seems like an option. Or you can check with
IF NOT EXISTS(QUERY) Then INSERT
This will insert or delete then insert. I tend to go for a IF NOT EXISTS
check first.
To call the method, you need to qualify function with self.
. In addition to that, if you want to pass a filename, add a filename
parameter (or other name you want).
class MyHandler(FileSystemEventHandler):
def on_any_event(self, event):
srcpath = event.src_path
print (srcpath, 'has been ',event.event_type)
print (datetime.datetime.now())
filename = srcpath[12:]
self.dropbox_fn(filename) # <----
def dropbox_fn(self, filename): # <-----
print('In dropbox_fn:', filename)
Don't use spaces...
(Incorrect)
SPTH = '/home/Foo/Documents/Programs/ShellScripts/Butler'
(Correct)
SPTH='/home/Foo/Documents/Programs/ShellScripts/Butler'
Two Methods for Passing Multiple route params in Angular
Method-1
In app.module.ts
Set path as component2.
imports: [
RouterModule.forRoot(
[ {path: 'component2/:id1/:id2', component: MyComp2}])
]
Call router to naviagte to MyComp2 with multiple params id1 and id2.
export class MyComp1 {
onClick(){
this._router.navigate( ['component2', "id1","id2"]);
}
}
Method-2
In app.module.ts
Set path as component2.
imports: [
RouterModule.forRoot(
[ {path: 'component2', component: MyComp2}])
]
Call router to naviagte to MyComp2 with multiple params id1 and id2.
export class MyComp1 {
onClick(){
this._router.navigate( ['component2', {id1: "id1 Value", id2:
"id2 Value"}]);
}
}
I wrote this answer because I believe there are fundamental issues with the majority of answers already provided, and the ones that are acceptable are incomplete.
Mapping by enum integer value
This approach is bad simply because it assumes that the integer values of both MyGender
and TheirGender
will always remain comparable. In practice, it is very rare that you can guarantee this even within a single project, let alone a separate service.
The approach we take should be something that can be used for other enum-mapping cases. We should never assume that one enum identically relates to another - especially when we may not have control over one or another.
Mapping by enum string value
This is a little better, as MyGender.Male
will still convert to TheirGender.Male
even if the integer representation is changed, but still not ideal.
I would discourage this approach as it assumes the name values will not change, and will always remain identical. Considering future enhancements, you cannot guarantee that this will be the case; consider if MyGender.NotKnown
was added. It is likely that you would want this to map to TheirGender.Unknown
, but this would not be supported.
Also, it is generally bad to assume that one enum equates to another by name, as this might not be the case in some contexts. As mentioned earlier, an ideal approach would work for other enum-mapping requirements.
Explicitly mapping enums
This approach explictly maps MyGender
to TheirGender
using a switch statement.
This is better as:
MyGender
or TheirGender
.Assuming we have the following enums:
public enum MyGender
{
Male = 0,
Female = 1,
}
public enum TheirGender
{
Male = 0,
Female = 1,
Unknown = 2,
}
We can create the following function to "convert from their enum to mine":
public MyGender GetMyGender(TheirGender theirGender)
{
switch (theirGender)
{
case TheirGender.Male:
return MyGender.Male;
case TheirGender.Female:
return MyGender.Female;
default:
throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender));
}
}
A previous answer suggested returning a nullable enum (TheirGender?
) and returning null for any unmatched input. This is bad; null is not the same as an unknown mapping. If the input cannot be mapped, an exception should be thrown, else the method should be named more explictly to the behaviour:
public TheirGender? GetTheirGenderOrDefault(MyGender myGender)
{
switch (myGender)
{
case MyGender.Male:
return TheirGender.Male;
case MyGender.Female:
return TheirGender.Female;
default:
return default(TheirGender?);
}
}
Additional considerations
If it is likely that this method will be required more than once in various parts of the solution, you could consider creating an extension method for this:
public static class TheirGenderExtensions
{
public static MyGender GetMyGender(this TheirGender theirGender)
{
switch (theirGender)
{
case TheirGender.Male:
return MyGender.Male;
case TheirGender.Female:
return MyGender.Female;
default:
throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender));
}
}
}
If you are using C#8, you can use the syntax for switch expressions and expression bodies to neaten up the code:
public static class TheirGenderExtensions
{
public static MyGender GetMyGender(this TheirGender theirGender)
=> theirGender switch
{
TheirGender.Male => MyGender.Male,
TheirGender.Female => MyGender.Female,
_ => throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender))
};
}
If you will only ever be mapping the enums within a single class, then an extension method may be overkill. In this case, the method can be declared within the class itself.
Furthermore, if the mapping will only ever take place within a single method, then you can declare this as a local function:
public static void Main()
{
Console.WriteLine(GetMyGender(TheirGender.Male));
Console.WriteLine(GetMyGender(TheirGender.Female));
Console.WriteLine(GetMyGender(TheirGender.Unknown));
static MyGender GetMyGender(TheirGender theirGender)
=> theirGender switch
{
TheirGender.Male => MyGender.Male,
TheirGender.Female => MyGender.Female,
_ => throw new InvalidEnumArgumentException(nameof(theirGender), (int)theirGender, typeof(TheirGender))
};
}
Here's a dotnet fiddle link with the above example.
tl;dr:
Do not:
Do:
I have used this and it seems to work with outlook, not using html but you can format the text with line breaks at least when the body is added as output.
<a href="mailto:[email protected]?subject=Hello world&body=Line one%0DLine two">Email me</a>
In my case, I had opened a query from data context, like
Dim stores = DataContext.Stores _
.Where(Function(d) filter.Contains(d.code)) _
... and then subsequently queried the same...
Dim stores = DataContext.Stores _
.Where(Function(d) filter.Contains(d.code)).ToList
Adding the .ToList
to the first resolved my issue. I think it makes sense to wrap this in a property like:
Public ReadOnly Property Stores As List(Of Store)
Get
If _stores Is Nothing Then
_stores = DataContext.Stores _
.Where(Function(d) Filters.Contains(d.code)).ToList
End If
Return _stores
End Get
End Property
Where _stores is a private variable, and Filters is also a readonly property that reads from AppSettings.
Try below code
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<corners
android:bottomLeftRadius="30dp"
android:bottomRightRadius="30dp"
android:topLeftRadius="30dp"
android:topRightRadius="30dp" />
<solid android:color="#1271BB" />
<stroke
android:width="5dp"
android:color="#1271BB" />
<padding
android:bottom="1dp"
android:left="1dp"
android:right="1dp"
android:top="1dp" /></shape>
You're comparing the object references, and they are not the same. You need to compare the array contents.
An option is iterating through the array elements and call Equals()
for each element. Remember that you need to override the Equals()
method for the array elements, if they are not the same object reference.
An alternative is using this generic method to compare two generic arrays:
static bool ArraysEqual<T>(T[] a1, T[] a2)
{
if (ReferenceEquals(a1, a2))
return true;
if (a1 == null || a2 == null)
return false;
if (a1.Length != a2.Length)
return false;
var comparer = EqualityComparer<T>.Default;
for (int i = 0; i < a1.Length; i++)
{
if (!comparer.Equals(a1[i], a2[i])) return false;
}
return true;
}
Or use SequenceEqual if Linq is available for you (.NET Framework >= 3.5)
adding this worked for me.
compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'
You can try this:
You must follow the following format
$('element,id,class').on('click', function(){....});
*JQuery code*
$('body').addClass('.anything').on('click', function(){
//do some code here i.e
alert("ok");
});
Based on L.B.'s answer.
Usage:
var serializer = new DictionarySerializer<string, string>();
serializer.Serialize("dictionary.xml", _dictionary);
_dictionary = _titleDictSerializer.Deserialize("dictionary.xml");
Generic class:
public class DictionarySerializer<TKey, TValue>
{
[XmlType(TypeName = "Item")]
public class Item
{
[XmlAttribute("key")]
public TKey Key;
[XmlAttribute("value")]
public TValue Value;
}
private XmlSerializer _serializer = new XmlSerializer(typeof(Item[]), new XmlRootAttribute("Dictionary"));
public Dictionary<TKey, TValue> Deserialize(string filename)
{
using (FileStream stream = new FileStream(filename, FileMode.Open))
using (XmlReader reader = XmlReader.Create(stream))
{
return ((Item[])_serializer.Deserialize(reader)).ToDictionary(p => p.Key, p => p.Value);
}
}
public void Serialize(string filename, Dictionary<TKey, TValue> dictionary)
{
using (var writer = new StreamWriter(filename))
{
_serializer.Serialize(writer, dictionary.Select(p => new Item() { Key = p.Key, Value = p.Value }).ToArray());
}
}
}
you can send your DateTime value into SQL as a String with its special format. this format is "yyyy-MM-dd HH:mm:ss"
Example: CurrentTime is a variable as datetime Type in SQL. And dt is a DateTime variable in .Net.
DateTime dt=DateTime.Now;
string sql = "insert into Users (CurrentTime) values (‘{0}’)";
sql = string.Format(sql, dt.ToString("yyyy-MM-dd HH:mm:ss") );
Well, for starters, you might not wanna overuse echo, because (as is the problem in your case) you can very easily make mistakes on quotation marks.
This would fix your problem:
echo "<a href=\"http://www.whatever.com/$param\">Click Here</a>";
but you should really do this
<?php
$param = "test";
?>
<a href="http://www.whatever.com/<?php echo $param; ?>">Click Here</a>
%md
### <span style="color:red">text</span>
This works very well:
<template *ngFor="let item of items; let i=index" >
<ion-slide *ngIf="i<5" >
<img [src]="item.ItemPic">
</ion-slide>
</template>
This now works for IE FF Chrome properly... I have not tested for other browsers though
$(document).ready(function(){
$('#txtInput').on("cut copy paste",function(e) {
e.preventDefault();
});
});
Edit: As pointed out by webeno, .bind()
is deprecated hence it is recommended to use .on()
instead.
did you try
indices = Find(strs, 'KU')
see link
alternatively,
indices = strfind(strs, 'KU');
should also work if I'm not mistaken.
If you don't mind using gVim, you can launch a single instance, so that when a new file is opened with it it's automatically opened in a new tab in the currently running instance.
to do this you can write: gVim --remote-tab-silent file
You could always make an alias to this command so that you don't have to type so many words.
For example I use linux and bash and in my ~/.bashrc
file I have:
alias g='gvim --remote-tab-silent'
so instead of doing $ mate file
I do: $ g file
I put together, after having read the answers in this question, a simple function which can also do a callback, if you need that:
function waitFor(ms, cb) {
var waitTill = new Date(new Date().getTime() + ms);
while(waitTill > new Date()){};
if (cb) {
cb()
} else {
return true
}
}
To convert IQuerable
or IEnumerable
to a list, you can do one of the following:
IQueryable<object> q = ...;
List<object> l = q.ToList();
or:
IQueryable<object> q = ...;
List<object> l = new List<object>(q);
ONLY FOR WOOCOMMERCE VERSIONS 2.5.x AND 2.6.x
For WOOCOMMERCE VERSION 3.0+ see THIS UPDATE
Here is a custom function I have made, to make the things clear for you, related to get the data of an order ID. You will see all the different RAW outputs you can get and how to get the data you need…
Using print_r()
function (or var_dump()
function too) allow to output the raw data of an object or an array.
So first I output this data to show the object or the array hierarchy. Then I use different syntax depending on the type of that variable (string, array or object) to output the specific data needed.
IMPORTANT: With
$order
object you can use most ofWC_order
orWC_Abstract_Order
methods (using the object syntax)…
Here is the code:
function get_order_details($order_id){
// 1) Get the Order object
$order = wc_get_order( $order_id );
// OUTPUT
echo '<h3>RAW OUTPUT OF THE ORDER OBJECT: </h3>';
print_r($order);
echo '<br><br>';
echo '<h3>THE ORDER OBJECT (Using the object syntax notation):</h3>';
echo '$order->order_type: ' . $order->order_type . '<br>';
echo '$order->id: ' . $order->id . '<br>';
echo '<h4>THE POST OBJECT:</h4>';
echo '$order->post->ID: ' . $order->post->ID . '<br>';
echo '$order->post->post_author: ' . $order->post->post_author . '<br>';
echo '$order->post->post_date: ' . $order->post->post_date . '<br>';
echo '$order->post->post_date_gmt: ' . $order->post->post_date_gmt . '<br>';
echo '$order->post->post_content: ' . $order->post->post_content . '<br>';
echo '$order->post->post_title: ' . $order->post->post_title . '<br>';
echo '$order->post->post_excerpt: ' . $order->post->post_excerpt . '<br>';
echo '$order->post->post_status: ' . $order->post->post_status . '<br>';
echo '$order->post->comment_status: ' . $order->post->comment_status . '<br>';
echo '$order->post->ping_status: ' . $order->post->ping_status . '<br>';
echo '$order->post->post_password: ' . $order->post->post_password . '<br>';
echo '$order->post->post_name: ' . $order->post->post_name . '<br>';
echo '$order->post->to_ping: ' . $order->post->to_ping . '<br>';
echo '$order->post->pinged: ' . $order->post->pinged . '<br>';
echo '$order->post->post_modified: ' . $order->post->post_modified . '<br>';
echo '$order->post->post_modified_gtm: ' . $order->post->post_modified_gtm . '<br>';
echo '$order->post->post_content_filtered: ' . $order->post->post_content_filtered . '<br>';
echo '$order->post->post_parent: ' . $order->post->post_parent . '<br>';
echo '$order->post->guid: ' . $order->post->guid . '<br>';
echo '$order->post->menu_order: ' . $order->post->menu_order . '<br>';
echo '$order->post->post_type: ' . $order->post->post_type . '<br>';
echo '$order->post->post_mime_type: ' . $order->post->post_mime_type . '<br>';
echo '$order->post->comment_count: ' . $order->post->comment_count . '<br>';
echo '$order->post->filter: ' . $order->post->filter . '<br>';
echo '<h4>THE ORDER OBJECT (again):</h4>';
echo '$order->order_date: ' . $order->order_date . '<br>';
echo '$order->modified_date: ' . $order->modified_date . '<br>';
echo '$order->customer_message: ' . $order->customer_message . '<br>';
echo '$order->customer_note: ' . $order->customer_note . '<br>';
echo '$order->post_status: ' . $order->post_status . '<br>';
echo '$order->prices_include_tax: ' . $order->prices_include_tax . '<br>';
echo '$order->tax_display_cart: ' . $order->tax_display_cart . '<br>';
echo '$order->display_totals_ex_tax: ' . $order->display_totals_ex_tax . '<br>';
echo '$order->display_cart_ex_tax: ' . $order->display_cart_ex_tax . '<br>';
echo '$order->formatted_billing_address->protected: ' . $order->formatted_billing_address->protected . '<br>';
echo '$order->formatted_shipping_address->protected: ' . $order->formatted_shipping_address->protected . '<br><br>';
echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';
// 2) Get the Order meta data
$order_meta = get_post_meta($order_id);
echo '<h3>RAW OUTPUT OF THE ORDER META DATA (ARRAY): </h3>';
print_r($order_meta);
echo '<br><br>';
echo '<h3>THE ORDER META DATA (Using the array syntax notation):</h3>';
echo '$order_meta[_order_key][0]: ' . $order_meta[_order_key][0] . '<br>';
echo '$order_meta[_order_currency][0]: ' . $order_meta[_order_currency][0] . '<br>';
echo '$order_meta[_prices_include_tax][0]: ' . $order_meta[_prices_include_tax][0] . '<br>';
echo '$order_meta[_customer_user][0]: ' . $order_meta[_customer_user][0] . '<br>';
echo '$order_meta[_billing_first_name][0]: ' . $order_meta[_billing_first_name][0] . '<br><br>';
echo 'And so on ……… <br><br>';
echo '- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - <br><br>';
// 3) Get the order items
$items = $order->get_items();
echo '<h3>RAW OUTPUT OF THE ORDER ITEMS DATA (ARRAY): </h3>';
foreach ( $items as $item_id => $item_data ) {
echo '<h4>RAW OUTPUT OF THE ORDER ITEM NUMBER: '. $item_id .'): </h4>';
print_r($item_data);
echo '<br><br>';
echo 'Item ID: ' . $item_id. '<br>';
echo '$item_data["product_id"] <i>(product ID)</i>: ' . $item_data['product_id'] . '<br>';
echo '$item_data["name"] <i>(product Name)</i>: ' . $item_data['name'] . '<br>';
// Using get_item_meta() method
echo 'Item quantity <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_qty', true) . '<br><br>';
echo 'Item line total <i>(product quantity)</i>: ' . $order->get_item_meta($item_id, '_line_total', true) . '<br><br>';
echo 'And so on ……… <br><br>';
echo '- - - - - - - - - - - - - <br><br>';
}
echo '- - - - - - E N D - - - - - <br><br>';
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
Usage (if your order ID is 159 for example):
get_order_details(159);
This code is tested and works.
Updated code on November 21, 2016
You can just use the Select()
extension method:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());
Or in LINQ syntax:
IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
var strings = from i in integers
select i.ToString();
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP. Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title. courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only: Course1 Course2 Course3 ...... Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp
. "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
It works.
Simple tabulation of the output:
a = 0.3333333
b = 200/3
print("variable a variable b")
print("%10.2f %10.2f" % (a, b))
output:
variable a variable b
0.33 66.67
%10.2f: 10 is the minimum length and 2 is the number of decimal places.
Predicate<T>
is a functional construct providing a convenient way of basically testing if something is true of a given T
object.
For example suppose I have a class:
class Person {
public string Name { get; set; }
public int Age { get; set; }
}
Now let's say I have a List<Person> people
and I want to know if there's anyone named Oscar in the list.
Without using a Predicate<Person>
(or Linq, or any of that fancy stuff), I could always accomplish this by doing the following:
Person oscar = null;
foreach (Person person in people) {
if (person.Name == "Oscar") {
oscar = person;
break;
}
}
if (oscar != null) {
// Oscar exists!
}
This is fine, but then let's say I want to check if there's a person named "Ruth"? Or a person whose age is 17?
Using a Predicate<Person>
, I can find these things using a LOT less code:
Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };
Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);
Notice I said a lot less code, not a lot faster. A common misconception developers have is that if something takes one line, it must perform better than something that takes ten lines. But behind the scenes, the Find
method, which takes a Predicate<T>
, is just enumerating after all. The same is true for a lot of Linq's functionality.
So let's take a look at the specific code in your question:
Predicate<int> pre = delegate(int a){ return a % 2 == 0; };
Here we have a Predicate<int> pre
that takes an int a
and returns a % 2 == 0
. This is essentially testing for an even number. What that means is:
pre(1) == false;
pre(2) == true;
And so on. This also means, if you have a List<int> ints
and you want to find the first even number, you can just do this:
int firstEven = ints.Find(pre);
Of course, as with any other type that you can use in code, it's a good idea to give your variables descriptive names; so I would advise changing the above pre
to something like evenFinder
or isEven
-- something along those lines. Then the above code is a lot clearer:
int firstEven = ints.Find(evenFinder);
The attribute selector syntax is [name=value]
where name
is the attribute name and value
is the attribute value.
So if you want to select all input
elements with the attribute name
having the value inputName[]
:
$('input[name="inputName[]"]')
And if you want to check for two attributes (here: name
and value
):
$('input[name="inputName[]"][value=someValue]')
Java native code necessities:
hope these points answers your question :)
Had same error with code:
X509Certificate2 mycert = new X509Certificate2(@"C:\certificate.crt");
Solved by adding password:
X509Certificate2 mycert = new X509Certificate2(@"C:\certificate.crt", "password");