I had faced the same issue because of some dll files were missing from References of VS13. I went to the location http://scn.sap.com/docs/DOC-7824 and installed the newest pack. It resolved the issue.
I resolved this by installing System.Data.SQLite with Nuget extension. This extension can use for Visual Studio 2010 or higher. First, you have to install Nuget extension. You can follow here:
Second, now, you can install SQLite:
And now, you can use System.Data.SQLite.
In the case, you see two folder x64 and, x86, these folders contain SQLite.Interop.dll. Now go to the properties windows of those dlls and set build action is content and Copy to output directory is Copy always.
So, that is my way.
Thanks. Kim Tho Pham, HoChiMinh City, Vietnam. Email: [email protected]
For those who don't want to use HTML agility pack and want to get HtmlDocument from string using native .net code only here is a good article on how to convert string to HtmlDocument
Here is the code block to use
public System.Windows.Forms.HtmlDocument GetHtmlDocument(string html)
{
WebBrowser browser = new WebBrowser();
browser.ScriptErrorsSuppressed = true;
browser.DocumentText = html;
browser.Document.OpenNew(true);
browser.Document.Write(html);
browser.Refresh();
return browser.Document;
}
I don't remember the specific source, but I am using:
/* Number of Cards by Row based on Viewport */
@media (min-width: 576px) {
.card-deck .card {
min-width: 50.1%; /* 1 Column */
margin-bottom: 12px;
}
}
@media (min-width: 768px) {
.card-deck .card {
min-width: 33.4%; /* 2 Columns */
}
}
@media (min-width: 1200px) {
.card-deck .card {
min-width: 25.1%; /* 3 Columns */
}
}
You may want to tinker with the specific values to fit your needs.
If you're a fan of NumPy
ish syntax, then there's tensor.shape
.
In [3]: ar = torch.rand(3, 3)
In [4]: ar.shape
Out[4]: torch.Size([3, 3])
# method-1
In [7]: list(ar.shape)
Out[7]: [3, 3]
# method-2
In [8]: [*ar.shape]
Out[8]: [3, 3]
# method-3
In [9]: [*ar.size()]
Out[9]: [3, 3]
P.S.: Note that tensor.shape
is an alias to tensor.size()
, though tensor.shape
is an attribute of the tensor in question whereas tensor.size()
is a function.
If you're using numpy for your arrays, you can also use
x = x[numpy.logical_not(numpy.isnan(x))]
Equivalently
x = x[~numpy.isnan(x)]
[Thanks to chbrown for the added shorthand]
Explanation
The inner function, numpy.isnan
returns a boolean/logical array which has the value True
everywhere that x
is not-a-number. As we want the opposite, we use the logical-not operator, ~
to get an array with True
s everywhere that x
is a valid number.
Lastly we use this logical array to index into the original array x
, to retrieve just the non-NaN values.
Have a look at fabric.transfer.
from fabric import Connection
with Connection(host="hostname",
user="admin",
connect_kwargs={"key_filename": "/home/myuser/.ssh/private.key"}
) as c:
c.get('/foo/bar/file.txt', '/tmp/')
You have to edit postgresql.conf file and change line with 'listen_addresses'.
This file you can find in the /etc/postgresql/9.3/main
directory.
Default Ubuntu config have allowed only localhost (or 127.0.0.1) interface, which is sufficient for using, when every PostgreSQL client work on the same computer, as PostgreSQL server. If you want connect PostgreSQL server from other computers, you have change this config line in this way:
listen_addresses = '*'
Then you have edit pg_hba.conf file, too. In this file you have set, from which computers you can connect to this server and what method of authentication you can use. Usually you will need similar line:
host all all 192.168.1.0/24 md5
Please, read comments in this file...
EDIT:
After the editing postgresql.conf and pg_hba.conf you have to restart postgresql server.
EDIT2: Highlited configuration files.
set -x
enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x
: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.
set +x
disables it.
You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.
Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
System.out.println(key + ": " + map.get(key));
}
As for what to use for someComparator
, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:
public static <K, V extends Comparable<? super V>>
Comparator<K> mapValueComparator(final Map<K, V> map) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return map.get(key1).compareTo(map.get(key2));
}
};
}
public static <K, V>
Comparator<K> mapValueComparator(final Map<K, V> map,
final Comparator<V> comparator) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return comparator.compare(map.get(key1), map.get(key2));
}
};
}
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
I would suggest to refer the page. Official suggestion
In my case, I was missing the /usr/lib/jni
directory entirely. Fixed by
sudo apt-get install libswt-gtk-3-jni libswt-gtk-3-java
No need to symlink afterwards. Eclipse started normally.
I have a similar problem (at least I think it is similar). In one of the replies here the solution is as follows:
select
A.*
from
table_A A
inner join table_B B
on A.id = B.id
where
B.tag = 'chair'
That WHERE clause I would like to be:
WHERE B.tag = A.<col_name>
or, in my specific case:
WHERE B.val BETWEEN A.val1 AND A.val2
More detailed:
Table A carries status information of a fleet of equipment. Each status record carries with it a start and stop time of that status. Table B carries regularly recorded, timestamped data about the equipment, which I want to extract for the duration of the period indicated in table A.
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt","someotherfile.txt"
)
) ELSE (
CALL :SUB
)
:SUB
ECHO Sorry... nothin' there.
GOTO:EOF
Is this feasible?
SETLOCAL ENABLEDELAYEDEXPANSION
IF EXIST "somefile.txt" (
SET var="somefile.txt"
IF EXIST "someotherfile.txt" (
SET var=!var!,"someotherfile.txt"
)
) ELSE (
IF EXIST "someotherfile.txt" (
SET var="someotherfile.txt"
) ELSE (
GOTO:EOF
)
)
You want a geocoding application. These are available either online or as an application backend.
Online applications:
Backend applications:
Five ways, 4 for bash and 1 addition for zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
(zsh only)You can put any of them to your if
clause. According to my tests (https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/), the 1st and 3rd method are recommended in bash and the 5th method is recommended in zsh in terms of speed.
Supposing you have a writable "uploads" folder in your application:
You can define a param like this:
Yii::$app->params['uploadPath'] = realpath(Yii::$app->basePath) . '/uploads/';
Then you can simply use the parameter as:
$path1 = Yii::$app->params['uploadPath'] . $filename;
Just depending on if you are using advanced or simple template the base path will be (following the link provided by phazei):
Simple @app: Your application root directory
Advanced @app: Your application root directory (either frontend or backend or console depending on where you access it from)
This way the application will be more portable than using realpath(dirname(__FILE__).'/../../'));
You should check for !test
, here is a fiddle showing that.
<span ng-if="!test">null</span>
I found this in the navbar example, and simplified it.
<ul class="nav">
<li><a>Default</a></li>
<li><a>Static top</a></li>
<li><b><a>Fixed top <span class="sr-only">(current)</span></a></b></li>
</ul>
You see which one is selected (sr-only
part is hidden):
You hear which one is selected if you use screen reader:
As a result of this technique blind people supposed to navigate easier on your website.
You can do this is in Scala, which runs on the JVM and is compatible with Java programs. http://www.scala-lang.org/
i.e.
class Foo(var prime: Boolean = false, val rib: String) {}
Hi this query works for me,
select * from person where dob between '2011-01-01' and '2011-01-31 23:59:59'
If you are using JavaScript, the solution provided by cletus, (?<=\[)(.*?)(?=\])
won't work because JavaScript doesn't support the lookbehind operator.
Edit: actually, now (ES2018) it's possible to use the lookbehind operator. Just add / to define the regex string, like this:
var regex = /(?<=\[)(.*?)(?=\])/;
Old answer:
Solution:
var regex = /\[(.*?)\]/;
var strToMatch = "This is a test string [more or less]";
var matched = regex.exec(strToMatch);
It will return:
["[more or less]", "more or less"]
So, what you need is the second value. Use:
var matched = regex.exec(strToMatch)[1];
To return:
"more or less"
Download whatever configuration script that your browser is using.
the script would have various host:port configuration. based on the domain you want to connect , one of the host:port is selected by the borwser.
in the eclipse network setting you can try to put on of the host ports and see if that works.
worked for me.
the config script looks like,
if (isPlainHostName(host))
return "DIRECT";
else if (dnsDomainIs(host, "<***sample host name *******>"))
return "PROXY ***some ip*****; DIRECT";
else if (dnsDomainIs(host, "address.com")
|| dnsDomainIs(host, "adress2..com")
|| dnsDomainIs(host, "address3.com")
|| dnsDomainIs(host, "address4.com")
return "PROXY <***some proxyhost****>:8080";
you would need to look for the host port in the return statement.
If you are using linux, and the data file is from windows. It probably because the character ^M Find it and delete. done!
You have basically two options here: add the self-signed certificate to your JVM truststore or configure your client to
Export the certificate from your browser and import it in your JVM truststore (to establish a chain of trust):
<JAVA_HOME>\bin\keytool -import -v -trustcacerts
-alias server-alias -file server.cer
-keystore cacerts.jks -keypass changeit
-storepass changeit
Disable Certificate Validation:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (GeneralSecurityException e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
Note that I do not recommend the Option #2 at all. Disabling the trust manager defeats some parts of SSL and makes you vulnerable to man in the middle attacks. Prefer Option #1 or, even better, have the server use a "real" certificate signed by a well known CA.
You can generate pairs like this:
{(x, x + 2) for x in r if x + 2 in r}
Then all that is left to do is to get a condition to make them prime, which you have already done in the first example.
A different way of doing it: (Although slower for large sets of primes)
{(x, y) for x in r for y in r if x + 2 == y}
This will give you what you want in a pop-up.
for(var i = 0; i < users.Count; i++){
alert(users[i].id);
}
The best way is probably to use the list method .index.
For the objects in the list, you can do something like:
def __eq__(self, other):
return self.Value == other.Value
with any special processing you need.
You can also use a for/in statement with enumerate(arr)
Example of finding the index of an item that has value > 100.
for index, item in enumerate(arr):
if item > 100:
return index, item
Visual studio community edition is bundled with xamarin and which is free as well.
You can also use vbNewLine
Object as in
MessageLabel.Text = "The Sales tax was:" & Format(douSales_tax, "Currency") & "." & vbNewLine & "The sale person: " & mstrSalesPerson
Ruby has a line by line loop over input files (the '-n' flag) from the commandline so it can be used like AWK. This Ruby one-liner:
ruby -ne 'END {puts $.}'
will count lines like the AWK one-liner:
awk 'END{print NR}'
Ruby gets feature this through Perl, which took it from AWK as a way of getting sysadmins on board with Perl without having to change the way they do things.
With the following you can insert multiple values and also have default values but you're creating a new dictionary.
d = {**{ key: value }, **default_values}
I've tested it with the most voted answer and on average this is faster as it can be seen in the following example, .
Speed test comparing a for loop based method with a dict comprehension with unpack operator method.
if no copy (d = default_vals.copy()
) is made on the first case then the most voted answer would be faster once we reach orders of magnitude of 10**5
and greater. Memory footprint of both methods are the same.
As Josh has stated above, you want to give each one the same name (letter, button, etc.) and all of them work. Then you want to surround all of these with a form tag:
<form name="myLetters" action="yourScript.php" method="POST">
<!-- Enter your values here with the following syntax: -->
<input type="radio" name="letter" value="A" /> A
<!-- Then add a submit value & close your form -->
<input type="submit" name="submit" value="Choose Letter!" />
</form>
Then, in the PHP script "yourScript.php" as defined by the action attribute, you can use:
$_POST['letter']
To get the value chosen.
EDITED after @ErdemKAYA comment.
To erase a variable, use the magic command:
%reset_selective <regular_expression>
The variables that are erased from the namespace are the one matching the given <regular_expression>
.
Therefore
%reset_selective -f a
will erase all the variables containing an a
.
Instead, to erase only a
and not aa
:
In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a # raise NameError
In: aa # returns 2
see as well %reset_selective?
for more examples and https://regexone.com/ for a regex tutorial.
To erase all the variables in the namespace see:
%reset?
I may be wrong, but I think the accepted answer by @amit has a bug.
from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]
# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]
# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)
# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))
Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:
public class ConsoleWriter
{
private static object _MessageLock= new object();
public void WriteMessage(string message)
{
lock (_MessageLock)
{
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine(message);
Console.ResetColor();
}
}
}
Here is an easy and convenient way of using something similar to the Java map:
var map = {
'map_name_1': map_value_1,
'map_name_2': map_value_2,
'map_name_3': map_value_3,
'map_name_4': map_value_4
}
And to get the value:
alert(map['map_name_1']); // Gives the value of map_value_1
... etc. ...
You need to give the absolute pathname to where the file exists.
File file = new File("C:\\Users\\User\\Documents\\Workspace\\FileRead\\hello.txt");
To access the tomcat manager from different machine you have to follow bellow steps:
1. Update conf/tomcat-users.xml file with user and some roles:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".
Here tomcat user and password is : admin
2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):
Default configuration:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .
2.a : Allow specefic IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />
Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address
2.b : Allow all IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow=".*" />
Here using allow=".*" you are allowing all IP.
Thanks :)
This might help you guys.(I've applied this to my Projects)
Here's the 3 easy steps.
That's it. It will sync/refresh your Model base on the changes on your database.
For detailed instructions. Please visit the link below.
EF Database First with ASP.NET MVC: Changing the Database and updating its model.
http://sourceforge.net/projects/eclipse-rbe/
as already stated property files should be encoded in ISO 8859-1
You can use the above plugin for eclipse IDE to make the Unicode conversion for you.
Several answers have pointed at uintptr_t
and #include <stdint.h>
as 'the' solution. That is, I suggest, part of the answer, but not the whole answer. You also need to look at where the function is called with the message ID of FOO.
Consider this code and compilation:
$ cat kk.c
#include <stdio.h>
static void function(int n, void *p)
{
unsigned long z = *(unsigned long *)p;
printf("%d - %lu\n", n, z);
}
int main(void)
{
function(1, 2);
return(0);
}
$ rmk kk
gcc -m64 -g -O -std=c99 -pedantic -Wall -Wshadow -Wpointer-arith \
-Wcast-qual -Wstrict-prototypes -Wmissing-prototypes \
-D_FILE_OFFSET_BITS=64 -D_LARGEFILE_SOURCE kk.c -o kk
kk.c: In function 'main':
kk.c:10: warning: passing argument 2 of 'func' makes pointer from integer without a cast
$
You will observe that there is a problem at the calling location (in main()
) — converting an integer to a pointer without a cast. You are going to need to analyze your function()
in all its usages to see how values are passed to it. The code inside my function()
would work if the calls were written:
unsigned long i = 0x2341;
function(1, &i);
Since yours are probably written differently, you need to review the points where the function is called to ensure that it makes sense to use the value as shown. Don't forget, you may be finding a latent bug.
Also, if you are going to format the value of the void *
parameter (as converted), look carefully at the <inttypes.h>
header (instead of stdint.h
— inttypes.h
provides the services of stdint.h
, which is unusual, but the C99 standard says [t]he header <inttypes.h>
includes the header <stdint.h>
and extends it with
additional facilities provided by hosted implementations) and use the PRIxxx macros in your format strings.
Also, my comments are strictly applicable to C rather than C++, but your code is in the subset of C++ that is portable between C and C++. The chances are fair to good that my comments apply.
You can use all()
:
my_list1 = [30,34,56]
my_list2 = [29,500,43]
if all(i >= 30 for i in my_list1):
print 'yes'
if all(i >= 30 for i in my_list2):
print 'no'
Note that this includes all numbers equal to 30 or higher, not strictly above 30.
A few things:
First, I don't think you really need a validation error for a radio fieldset because you could just have one of the fields checked by default. Most people would rather correct something then provide something. For instance:
Age: (*) 12 - 18 | () 19 - 30 | 31 - 50
is more likely to be changed to the right answer as the person DOESN'T want it to go to the default. If they see it blank, they are more likely to think "none of your business" and skip it.
Second, I was able to get the effect I think you are wanting without any positioning properties. You just add padding-right to the form (or the div of the form, whatever) to provide enough room for your error and make sure your error will fit in that area. Then, you have a pre-set up css class called "error" and you set it as having a negative margin-top roughly the height of your input field and a margin-left about the distance from the left to where your padding-right should start. I tried this out, it's not great, but it works with three properties and requires no floats or absolutes:
<style type="text/css">
.error {
width: 13em; /* Ensures that the div won't exceed right padding of form */
margin-top: -1.5em; /*Moves the div up to the same level as input */
margin-left: 11em; /*Moves div to the right */
font-size: .9em; /*Makes sure that the error div is smaller than input */
}
<form>
<label for="name">Name:</label><input id="name" type="textbox" />
<div class="error"><<< This field is required!</div>
<label for="numb">Phone:</label><input id="numb" type="textbox" />
<div class="error"><<< This field is required!</div>
</form>
Try this :
sc delete Apache2.4
or try this :
C:\Apache24\bin>httpd -k uninstall
hope this will be helpful
Try this:
INSERT INTO table1 SELECT "A string", 5, idTable2 FROM table2 WHERE ...
As shown by @Maglob, the basic approach is to test the conversion from string to date using SimpleDateFormat.parse. That will catch invalid day/month combinations like 2008-02-31.
However, in practice that is rarely enough since SimpleDateFormat.parse is exceedingly liberal. There are two behaviours you might be concerned with:
Invalid characters in the date string Surprisingly, 2008-02-2x will "pass" as a valid date with locale format = "yyyy-MM-dd" for example. Even when isLenient==false.
Years: 2, 3 or 4 digits? You may also want to enforce 4-digit years rather than allowing the default SimpleDateFormat behaviour (which will interpret "12-02-31" differently depending on whether your format was "yyyy-MM-dd" or "yy-MM-dd")
So a complete string to date test could look like this: a combination of regex match, and then a forced date conversion. The trick with the regex is to make it locale-friendly.
Date parseDate(String maybeDate, String format, boolean lenient) {
Date date = null;
// test date string matches format structure using regex
// - weed out illegal characters and enforce 4-digit year
// - create the regex based on the local format string
String reFormat = Pattern.compile("d+|M+").matcher(Matcher.quoteReplacement(format)).replaceAll("\\\\d{1,2}");
reFormat = Pattern.compile("y+").matcher(reFormat).replaceAll("\\\\d{4}");
if ( Pattern.compile(reFormat).matcher(maybeDate).matches() ) {
// date string matches format structure,
// - now test it can be converted to a valid date
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance();
sdf.applyPattern(format);
sdf.setLenient(lenient);
try { date = sdf.parse(maybeDate); } catch (ParseException e) { }
}
return date;
}
// used like this:
Date date = parseDate( "21/5/2009", "d/M/yyyy", false);
Note that the regex assumes the format string contains only day, month, year, and separator characters. Aside from that, format can be in any locale format: "d/MM/yy", "yyyy-MM-dd", and so on. The format string for the current locale could be obtained like this:
Locale locale = Locale.getDefault();
SimpleDateFormat sdf = (SimpleDateFormat)DateFormat.getDateInstance(DateFormat.SHORT, locale );
String format = sdf.toPattern();
I've been hearing about joda time recently and thought I'd compare. Two points:
It's quite simple to use:
import org.joda.time.format.*;
import org.joda.time.DateTime;
org.joda.time.DateTime parseDate(String maybeDate, String format) {
org.joda.time.DateTime date = null;
try {
DateTimeFormatter fmt = DateTimeFormat.forPattern(format);
date = fmt.parseDateTime(maybeDate);
} catch (Exception e) { }
return date;
}
The first thing you should do is to determine whether you want to keep the local changes before you delete the commit message.
Use git log
to show current commit messages, then find the commit_id
before the commit that you want to delete, not the commit you want to delete.
git reset --soft commit_id
git reset --hard commit_id
That's the difference of soft and hard
Try max(): http://php.net/manual/en/function.max.php See the first comment on that page
For Symfony 2.1:
This is my final solution putting in together many others solutions:
protected function getAllFormErrorMessages($form)
{
$retval = array();
foreach ($form->getErrors() as $key => $error) {
if($error->getMessagePluralization() !== null) {
$retval['message'] = $this->get('translator')->transChoice(
$error->getMessage(),
$error->getMessagePluralization(),
$error->getMessageParameters(),
'validators'
);
} else {
$retval['message'] = $this->get('translator')->trans($error->getMessage(), array(), 'validators');
}
}
foreach ($form->all() as $name => $child) {
$errors = $this->getAllFormErrorMessages($child);
if (!empty($errors)) {
$retval[$name] = $errors;
}
}
return $retval;
}
You don't want to have the collision check code inside the painting code. The painting needs to be fast. Collision can go in the game loop. Therefore you need an internal representation of the objects independent of their sprites.
You should check API
for these questions.
You can use remove methods.
a.remove(1);
OR
a.remove("acbd");
I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.
@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})
...and also validation works.
You should be aware that you should avoid file I/O from within Linux kernel when possible. The main idea is to go "one level deeper" and call VFS level functions instead of the syscall handler directly:
Includes:
#include <linux/fs.h>
#include <asm/segment.h>
#include <asm/uaccess.h>
#include <linux/buffer_head.h>
Opening a file (similar to open):
struct file *file_open(const char *path, int flags, int rights)
{
struct file *filp = NULL;
mm_segment_t oldfs;
int err = 0;
oldfs = get_fs();
set_fs(get_ds());
filp = filp_open(path, flags, rights);
set_fs(oldfs);
if (IS_ERR(filp)) {
err = PTR_ERR(filp);
return NULL;
}
return filp;
}
Close a file (similar to close):
void file_close(struct file *file)
{
filp_close(file, NULL);
}
Reading data from a file (similar to pread):
int file_read(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_read(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Writing data to a file (similar to pwrite):
int file_write(struct file *file, unsigned long long offset, unsigned char *data, unsigned int size)
{
mm_segment_t oldfs;
int ret;
oldfs = get_fs();
set_fs(get_ds());
ret = vfs_write(file, data, size, &offset);
set_fs(oldfs);
return ret;
}
Syncing changes a file (similar to fsync):
int file_sync(struct file *file)
{
vfs_fsync(file, 0);
return 0;
}
[Edit] Originally, I proposed using file_fsync, which is gone in newer kernel versions. Thanks to the poor guy suggesting the change, but whose change was rejected. The edit was rejected before I could review it.
If you want to store formatted as a string variable and reuse it to text view isn't possible
If you aren't applying formatting, you can set TextView text directly by calling setText(java.lang.CharSequence). In some cases, however, you may want to create a styled text resource that is also used as a format string. Normally, this doesn't work because the format(String, Object...) and getString(int, Object...) methods strip all the style information from the string. The work-around to this is to write the HTML tags with escaped entities, which are then recovered with fromHtml(String), after the formatting takes place.
by from docs so alternatively store the string id and everyttime bind get string from using Htlm.fromHtml().. method.
ex:
Kotlin extention
fun Context.getStringFromResource(stringId: Int): Spanned {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Html.fromHtml(java.lang.String.format(resources.getString(stringId)),
Html.FROM_HTML_MODE_COMPACT)
} else {
Html.fromHtml(java.lang.String.format(resources.getString(stringId)))
}
}
In code:
getStringFromResource(id)
Here's my overview about built-in zi/unzip (compress/decompress) capabilities in windows - How can I compress (/ zip ) and uncompress (/ unzip ) files and folders with batch file without using any external tools?
To unzip file you can use this script :
zipjs.bat unzip -source C:\myDir\myZip.zip -destination C:\MyDir -keep yes -force no
Have you tried Advanced Filter? Using your short list as the 'Criteria' and long list as the 'List Range'. Use the options: 'Filter in Place' and 'Unique Values'.
You should be presented with the list of unique values that only appear in your short list.
Alternatively, you can paste your Unique list to another location (on the same sheet), if you prefer. Choose the option 'Copy to another Location' and in the 'Copy to' box enter the cell reference (say F1) where you want the Unique list.
Note: this will work with the two columns (name/ID) too, if you select the two columns as both 'Criteria' and 'List Range'.
the best way to give a hint is placeholder like this:
<input.... placeholder="hint".../>
For Guzzle <= 4:
It's a raw post request so putting the JSON in the body solved the problem
$request = $this->client->post(
$url,
[
'content-type' => 'application/json'
],
);
$request->setBody($data); #set body!
$response = $request->send();
MSBuild usually works, but I've run into difficulties before. You may have better luck with
devenv YourSolution.sln /Build
Use Cast<T>
:
var suits = Enum.GetValues(typeof(Suit)).Cast<Suit>();
There you go, IEnumerable<Suit>
.
You can always check if the thread's id is different than std::thread::id() default constructed. A Running thread has always a genuine associated id. Try to avoid too much fancy stuff :)
Like this. Make sure you drop the temp table (at the end of the code block, after you're done with it) or it will error on subsequent runs.
SELECT
tblMEP_Sites.Name AS SiteName,
convert(varchar(10),BillingMonth ,101) AS BillingMonth,
SUM(Consumption) AS Consumption
INTO
#MyTempTable
FROM
tblMEP_Projects
JOIN tblMEP_Sites
ON tblMEP_Projects.ID = tblMEP_Sites.ProjectID
JOIN tblMEP_Meters
ON tblMEP_Meters.SiteID = tblMEP_Sites.ID
JOIN tblMEP_MonthlyData
ON tblMEP_MonthlyData.MeterID = tblMEP_Meters.ID
JOIN tblMEP_CustomerAccounts
ON tblMEP_CustomerAccounts.ID = tblMEP_Meters.CustomerAccountID
JOIN tblMEP_UtilityCompanies
ON tblMEP_UtilityCompanies.ID = tblMEP_CustomerAccounts.UtilityCompanyID
JOIN tblMEP_MeterTypes
ON tblMEP_UtilityCompanies.UtilityTypeID = tblMEP_MeterTypes.ID
WHERE
tblMEP_Projects.ID = @ProjectID
AND tblMEP_MonthlyData.BillingMonth Between @StartDate AND @EndDate
AND tbLMEP_MeterTypes.ID = @MeterTypeID
GROUP BY
BillingMonth, tblMEP_Sites.Name
DROP TABLE #MyTempTable
Find out the element which is larger than the body (element which is causing the page to scroll) and just set it's position to fixed. NOTE: I'm not talking to change the position of draggable elements. Draggable elements can be dragged out of body only when there's an element larger than body (mostly in width).
Dir.new('/my/dir').each do |name|
...
end
There is another scenario where this issue reproduces (as in my case). When THE CLIENT REQUEST doesn't contain the right extension on the url, the controller can't identify the desired result format.
For example: the controller is set to respond_to :json
(as a single option, without a HTML response)- while the client call is set to /reservations
instead of /reservations.json
.
Bottom line, change the client call to /reservations.json
.
Bash 3.0+ can use this syntax:
for i in {1..10} ; do ... ; done
..which avoids spawning an external program to expand the sequence (such as seq 1 10
).
Of course, this has the same problem as the for(())
solution, being tied to bash and even a particular version (if this matters to you).
Run away from store procedures as much as possible. They are pretty hard to maintain and are VERY OLD STUFF ;)
I've a workaround for NullPointerException
when remove fragment in on DestoryView
, Just put your code in onStop()
not onDestoryView
. It works fine!
@Override
public void onStop() {
super.onStop();
if (mMap != null) {
MainActivity.fragmentManager.beginTransaction()
.remove(MainActivity.fragmentManager.findFragmentById(R.id.location_map)).commit();
mMap = null;
}
}
Issue solved by adding commons-logging.jar
Imp files are ,
antlr-runtime-3.0.1
org.springframework.aop-3.1.0.M2
org.springframework.asm-3.1.0.M2
org.springframework.aspects-3.1.0.M2
org.springframework.beans-3.1.0.M2
org.springframework.context.support-3.1.0.M2
org.springframework.context-3.1.0.M2
org.springframework.core-3.1.0.M2
org.springframework.expression-3.1.0.M2
commons-logging-1.1.1
You can use setTimeout
to do this
function myFunction() {
// your code to run after the timeout
}
// stop for sometime if needed
setTimeout(myFunction, 5000);
In the Project’s Settings, add /FORCE:MULTIPLE
to the Linker’s Command Line options.
From MSDN: "Use /FORCE:MULTIPLE to create an output file whether or not LINK finds more than one definition for a symbol."
Function FileExists(fullFileName As String) As Boolean
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End Function
Works very well, almost, at my site. If I call it with "" the empty string, Dir returns "connection.odc"!! Would be great if you guys could share your result.
Anyway, I do like this:
Function FileExists(fullFileName As String) As Boolean
If fullFileName = "" Then
FileExists = False
Else
FileExists = VBA.Len(VBA.Dir(fullFileName)) > 0
End If
End Function
You can use another overload of the DropDownList
method. Pick the one you need and pass in
a object with your html attributes.
@Html.DropDownList("CategoryID", null, new { @onchange="location = this.value;" })
As of CMake 3.1+ the developers strongly discourage users from using file(GLOB
or file(GLOB_RECURSE
to collect lists of source files.
Note: We do not recommend using GLOB to collect a list of source files from your source tree. If no CMakeLists.txt file changes when a source is added or removed then the generated build system cannot know when to ask CMake to regenerate. The CONFIGURE_DEPENDS flag may not work reliably on all generators, or if a new generator is added in the future that cannot support it, projects using it will be stuck. Even if CONFIGURE_DEPENDS works reliably, there is still a cost to perform the check on every rebuild.
See the documentation here.
There are two goods answers ([1], [2]) here on SO detailing the reasons to manually list source files.
It is possible. E.g. with file(GLOB
:
cmake_minimum_required(VERSION 2.8)
file(GLOB helloworld_SRC
"*.h"
"*.cpp"
)
add_executable(helloworld ${helloworld_SRC})
Note that this requires manual re-running of cmake
if a source file is added or removed, since the generated build system does not know when to ask CMake to regenerate, and doing it at every build would increase the build time.
As of CMake 3.12, you can pass the CONFIGURE_DEPENDS
flag to file(GLOB
to automatically check and reset the file lists any time the build is invoked. You would write:
cmake_minimum_required(VERSION 3.12)
file(GLOB helloworld_SRC CONFIGURE_DEPENDS "*.h" "*.cpp")
This at least lets you avoid manually re-running CMake every time a file is added.
I was in the same boat as you recently, and here is what I did:
I used the phpwebsockets code as a reference for how to structure the server-side code. (You seem to already be doing this, and as you noted, the code doesn't actually work for a variety of reasons.)
I used PHP.net to read the details about every socket function used in the phpwebsockets code. By doing this, I was finally able to understand how the whole system works conceptually. This was a pretty big hurdle.
I read the actual WebSocket draft. I had to read this thing a bunch of times before it finally started to sink in. You will likely have to go back to this document again and again throughout the process, as it is the one definitive resource with correct, up-to-date information about the WebSocket API.
I coded the proper handshake procedure based on the instructions in the draft in #3. This wasn't too bad.
I kept getting a bunch of garbled text sent from the clients to the server after the handshake and I couldn't figure out why until I realized that the data is encoded and must be unmasked. The following link helped me a lot here: (original link broken) Archived copy.
Please note that the code available at this link has a number of problems and won't work properly without further modification.
I then came across the following SO thread, which clearly explains how to properly encode and decode messages being sent back and forth: How can I send and receive WebSocket messages on the server side?
This link was really helpful. I recommend consulting it while looking at the WebSocket draft. It'll help make more sense out of what the draft is saying.
I was almost done at this point, but had some issues with a WebRTC app I was making using WebSocket, so I ended up asking my own question on SO, which I eventually solved: What is this data at the end of WebRTC candidate info?
At this point, I pretty much had it all working. I just had to add some additional logic for handling the closing of connections, and I was done.
That process took me about two weeks total. The good news is that I understand WebSocket really well now and I was able to make my own client and server scripts from scratch that work great. Hopefully the culmination of all that information will give you enough guidance and information to code your own WebSocket PHP script.
Good luck!
Edit: This edit is a couple of years after my original answer, and while I do still have a working solution, it's not really ready for sharing. Luckily, someone else on GitHub has almost identical code to mine (but much cleaner), so I recommend using the following code for a working PHP WebSocket solution:
https://github.com/ghedipunk/PHP-Websockets/blob/master/websockets.php
Edit #2: While I still enjoy using PHP for a lot of server-side related things, I have to admit that I've really warmed up to Node.js a lot recently, and the main reason is because it's better designed from the ground up to handle WebSocket than PHP (or any other server-side language). As such, I've found recently that it's a lot easier to set up both Apache/PHP and Node.js on your server and use Node.js for running the WebSocket server and Apache/PHP for everything else. And in the case where you're on a shared hosting environment in which you can't install/use Node.js for WebSocket, you can use a free service like Heroku to set up a Node.js WebSocket server and make cross-domain requests to it from your server. Just make sure if you do that to set your WebSocket server up to be able to handle cross-origin requests.
Your tuples are basically key-value pairs--a python dict
--so:
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]
val = dict(l)[53]
Edit -- aha, you say you want the index value of (53, "xuxa"). If this is really what you want, you'll have to iterate through the original list, or perhaps make a more complicated dictionary:
d = dict((n,i) for (i,n) in enumerate(e[0] for e in l))
idx = d[53]
To see the keys:
for key in d.keys():
print(key)
To get the values that each key is referencing:
for key in d.keys():
print(d[key])
Add to a list:
for key in d.keys():
mylist.append(d[key])
You can use this extension:
extension String {
static func isNilOrEmpty(string: String?) -> Bool {
guard let value = string else { return true }
return value.trimmingCharacters(in: .whitespaces).isEmpty
}
}
and then use it like this:
let isMyStringEmptyOrNil = String.isNilOrEmpty(string: myString)
The only way I was able to do this is via this code (TD tables). I tested in outlook client 2010. I also tested via webmail client and it worked for both.
The only things you have to do is change your_image.jpg (there are two instances of this for the same image make sure you update both for your code) and #your_color.
<td bgcolor="#your_color" background="your_image.jpg">
<!--[if gte mso 9]>
<v:image xmlns:v="urn:schemas-microsoft-com:vml" id="theImage" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:0; left:0; border:0; z-index:1;' src="your_image.jpg"/>
<v:shape xmlns:v="urn:schemas-microsoft-com:vml" id="theText" style='behavior: url(#default#VML); display:inline-block; position:absolute; height:300px; width:600px; top:-5; left:-10; border:0; z-index:2;'>
<![endif]-->
<p>Text over background image.</p>
<!--[if gte mso 9]>
</v:shape>
<![endif]-->
</td>
Note that events may be attached to the document itself rather than the element in question. In that case, you'll want to use:
$._data( $(document)[0], "events" );
And find the event with the correct selector:
And then look at the handler > [[FunctionLocation]]
In my case I was following the documentation for react-fontawesome
package, but they aren't clear about how to call the icon when setting the icons into the library
this is was what I was doing:
App.js file
import {faCoffee} from "@fortawesome/pro-light-svg-icons";
library.add(faSearch, faFileSearch, faCoffee);
Component file
<FontAwesomeIcon icon={"coffee"} />
But I was getting this error
Then I added the alias when passing the icon prop like:
<FontAwesomeIcon icon={["fal", "coffee"]} />
And it is working, you can find the prefix value in the icon.js file, in my case was: faCoffee.js
#include<iostream>
using namespace std;
template<class t>
class base {
protected:
t a;
public:
base(t aa){
a = aa;
cout<<"base "<<a<<endl;
}
};
template <class t>
class derived: public base<t>{
public:
derived(t a): base<t>(a) {
}
//Here is the method in derived class
void sampleMethod() {
cout<<"In sample Method"<<endl;
}
};
int main() {
derived<int> q(1);
// calling the methods
q.sampleMethod();
}
Probable simplest and generally efficient:
#include <iostream>
int main()
{
std::cout << std::cin.rdbuf();
}
If needed, use stream of other types like std::ostringstream
as buffer instead of standard output stream here.
There does exist a split function based on regular expressions. It's not listed in the tutorial, but it is listed on the language manual on the wiki:
split(string str, string pat)
Split str around pat (pat is a regular expression)
In your case, the delimiter "|
" has a special meaning as a regular expression, so it should be referred to as "\\|
".
I prefer recycle.exe
from Frank P. Westlake. It provides a nice before and after status. (I've been using Frank's various utilities for well over ten years..)
C:\> recycle.exe /E /F
Recycle Bin: ALL
Recycle Bin C: 44 items, 42,613,970 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 44 items, 42,613,970 bytes.
Emptying Recycle Bin: ALL
Recycle Bin C: 0 items, 0 bytes.
Recycle Bin D: 0 items, 0 bytes.
Total: 0 items, 0 bytes.
It also has many more uses and options (output listed is from /?).
Recycle all files and folders in C:\TEMP:
RECYCLE C:\TEMP\*
List all DOC files which were recycled from any directory on the C: drive:
RECYCLE /L C:\*.DOC
Restore all DOC files which were recycled from any directory on the C: drive:
RECYCLE /U C:\*.DOC
Restore C:\temp\junk.txt to C:\docs\resume.txt:
RECYCLE /U "C:\temp\junk.txt" "C:\docs\resume.txt"
Rename in place C:\etc\config.cfg to C:\archive\config.2007.cfg:
RECYCLE /R "C:\etc\config.cfg" "C:\archive\config.2007.cfg"
I'll try to summarize the answers:
To get all nodes in the graph: (type tensorflow.core.framework.node_def_pb2.NodeDef
)
all_nodes = [n for n in tf.get_default_graph().as_graph_def().node]
To get all ops in the graph: (type tensorflow.python.framework.ops.Operation
)
all_ops = tf.get_default_graph().get_operations()
To get all variables in the graph: (type tensorflow.python.ops.resource_variable_ops.ResourceVariable
)
all_vars = tf.global_variables()
To get all tensors in the graph: (type tensorflow.python.framework.ops.Tensor
)
all_tensors = [tensor for op in tf.get_default_graph().get_operations() for tensor in op.values()]
To get all placeholders in the graph: (type tensorflow.python.framework.ops.Tensor
)
all_placeholders = [placeholder for op in tf.get_default_graph().get_operations() if op.type=='Placeholder' for placeholder in op.values()]
Tensorflow 2
To get the graph in Tensorflow 2, instead of tf.get_default_graph()
you need to instantiate a tf.function
first and access the graph
attribute, for example:
graph = func.get_concrete_function().graph
where func
is a tf.function
If you are using express
you can use the cors package to allow CORS like so instead of writing your middleware;
var express = require('express')
, cors = require('cors')
, app = express();
app.use(cors());
app.get(function(req,res){
res.send('hello');
});
If you are using Java 1.7, you can use java.nio.file.Files.walkFileTree(...)
.
For example:
public class WalkFileTreeExample {
public static void main(String[] args) {
Path p = Paths.get("/usr");
FileVisitor<Path> fv = new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
System.out.println(file);
return FileVisitResult.CONTINUE;
}
};
try {
Files.walkFileTree(p, fv);
} catch (IOException e) {
e.printStackTrace();
}
}
}
If you are using Java 8, you can use the stream interface with java.nio.file.Files.walk(...)
:
public class WalkFileTreeExample {
public static void main(String[] args) {
try (Stream<Path> paths = Files.walk(Paths.get("/usr"))) {
paths.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Based on @Dj S answer, using Swift 3. This works great on iOS 10.
func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
// Background color
view.tintColor = UIColor.black
// Text Color
let headerView = view as! UITableViewHeaderFooterView
headerView.textLabel?.textColor = UIColor.white
}
JSP and Servlet are Server side Programming. As it comes as an built in package inside a Server like Tomcat. The path may be like wise
C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\jsp-api.jar
C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar
Just you want to Do is Add this in the following way
Right Click> My Computer>Advanced>Environment Variables>System variables
Do> New..> Variable name:CLASSPATH
Variable value:CLASSPATH=.;C:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar;
This line of code might not work in IE 8 because of native support problems.
$(".hidden").attr("placeholder", "Type here to search");
You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.
$('input, textarea').placeholder();
Implementing my own functional interfaces resolved this for me (so instead of using java.util.function.* just create your own single-method interface with the parameters and return-type you want).
var groups = ["Test", "Prof","Off"];
$('#fruits option').filter(function() {
return groups.indexOf($(this).text()) > -1; //Options text exists in array
}).prop('selected', true); //Set selected
I wanted to see all the indices for the colnames because I needed to do a complicated column rearrangement, so I printed the colnames as a dataframe. The rownames are the indices.
as.data.frame(colnames(df))
1 A
2 B
3 C
cd /D "%APPDATA%\Mozilla\Firefox\Profiles" cd *.default set ffile=%cd% echo user_pref("network.proxy.http", "%1");>>"%ffile%\prefs.js" echo user_pref("network.proxy.http_port", 3128);>>"%ffile%\prefs.js" echo user_pref("network.proxy.type", 1);>>"%ffile%\prefs.js" set ffile= cd %windir%
This is nice ! Thanks for writing this. I needed this exact piece of code for Windows. My goal was to do this by learning to do it with Linux first and then learn the Windows shell which I was not happy about having to do so you saved me some time!
My Linux version is at the bottom of this post. I've been experimenting with which file to insert the prefs into. It seems picky. First I tried in ~/.mozilla/firefox/*.default/prefs.js but it didn't load very well. The about:config screen never showed my changes. Currently I've been trying to edit the actual Firefox defaults file. If someone has the knowledge off the top of their head could they rewrite the Windows code to only add the lines if they're not already in there? I have no idead how to do sed/awk stuff in Windows without installing Cygwin first.
The only change I was able to make to the Windows scripts is above in the quoted part. I change the IP to %1 so when you call the script from the command line you can give it an option instead of having to change the file.
#!/bin/bash
version="`firefox -v | awk '{print substr($3,1,3)}'`"
echo $version " is the version."
# Insert an ip into firefox for the proxy if there isn't one
if
! grep network.proxy.http /etc/firefox-$version/pref/firefox.js
then echo 'pref("network.proxy.http", "'"$1"'")";' >> /etc/firefox-$version/pref/firefox.js
fi
# Even if there is change it to what we want
sed -i s/^.*network.proxy.http\".*$/'pref("network.proxy.http", "'"$1"')";'/ /etc/firefox-$version/pref/firefox.js
# Set the port
if ! grep network.proxy.http_port /etc/firefox-$version/pref/firefox.js
then echo 'pref("network.proxy.http_port", 9980);' >> /etc/firefox-$version/pref/firefox.js
else sed -i s/^.*network.proxy.http_port.*$/'pref("network.proxy.http_port", 9980);'/ /etc/firefox-$version/pref/firefox.js
fi
# Turn on the proxy
if ! grep network.proxy.type /etc/firefox-$version/pref/firefox.js
then echo 'pref("network.proxy.type", 1);' >> /etc/firefox-$version/pref/firefox.js
else sed -i s/^.*network.proxy.type.*$/'pref("network.proxy.type", 1)";'/ /etc/firefox-$version/pref/firefox.js
fi
var ie = 0;
try { ie = navigator.userAgent.match( /(MSIE |Trident.*rv[ :])([0-9]+)/ )[ 2 ]; }
catch(e){}
How it works: The user-agent string for all IE versions includes a portion "MSIE space version" or "Trident other-text rv space-or-colon version". Knowing this, we grab the version number from a String.match()
regular expression. A try-catch
block is used to shorten the code, otherwise we'd need to test the array bounds for non-IE browsers.
Note: The user-agent can be spoofed or omitted, sometimes unintentionally if the user has set their browser to a "compatibility mode". Though this doesn't seem like much of an issue in practice.
var d = document, w = window;
var ie = ( !!w.MSInputMethodContext ? 11 : !d.all ? 99 : w.atob ? 10 :
d.addEventListener ? 9 : d.querySelector ? 8 : w.XMLHttpRequest ? 7 :
d.compatMode ? 6 : w.attachEvent ? 5 : 1 );
How it works: Each version of IE adds support for additional features not found in previous versions. So we can test for the features in a top-down manner. A ternary sequence is used here for brevity, though if-then
and switch
statements would work just as well. The variable ie
is set to an integer 5-11, or 1 for older, or 99 for newer/non-IE. You can set it to 0 if you just want to test for IE 1-11 exactly.
Note: Object detection may break if your code is run on a page with third-party scripts that add polyfills for things like document.addEventListener
. In such situations the user-agent is the best option.
If you're only interested in whether or not a browser supports most HTML 5 and CSS 3 standards, you can reasonably assume that IE 8 and lower remain the primary problem apps. Testing for window.getComputedStyle
will give you a fairly good mix of modern browsers, as well (IE 9, FF 4, Chrome 11, Safari 5, Opera 11.5). IE 9 greatly improves on standards support, but native CSS animation requires IE 10.
var isModernBrowser = ( !document.all || ( document.all && document.addEventListener ) );
Since someone mentioned efficiency, I've benchmarked the functions given so far out of curiosity:
function startsWith1($str, $char) {
return strpos($str, $char) === 0;
}
function startsWith2($str, $char) {
return stripos($str, $char) === 0;
}
function startsWith3($str, $char) {
return substr($str, 0, 1) === $char;
}
function startsWith4($str, $char){
return $str[0] === $char;
}
function startsWith5($str, $char){
return (bool) preg_match('/^' . $char . '/', $str);
}
function startsWith6($str, $char) {
if (is_null($encoding)) $encoding = mb_internal_encoding();
return mb_substr($str, 0, mb_strlen($char, $encoding), $encoding) === $char;
}
Here are the results on my average DualCore machine with 100.000 runs each
// Testing '_string'
startsWith1 took 0.385906934738
startsWith2 took 0.457293987274
startsWith3 took 0.412894964218
startsWith4 took 0.366240024567 <-- fastest
startsWith5 took 0.642996072769
startsWith6 took 1.39859509468
// Tested "string"
startsWith1 took 0.384965896606
startsWith2 took 0.445554971695
startsWith3 took 0.42377281189
startsWith4 took 0.373164176941 <-- fastest
startsWith5 took 0.630424022675
startsWith6 took 1.40699005127
// Tested 1000 char random string [a-z0-9]
startsWith1 took 0.430691003799
startsWith2 took 4.447286129
startsWith3 took 0.413349866867
startsWith4 took 0.368592977524 <-- fastest
startsWith5 took 0.627470016479
startsWith6 took 1.40957403183
// Tested 1000 char random string [a-z0-9] with '_' prefix
startsWith1 took 0.384054899216
startsWith2 took 4.41522812843
startsWith3 took 0.408898115158
startsWith4 took 0.363884925842 <-- fastest
startsWith5 took 0.638479948044
startsWith6 took 1.41304707527
As you can see, treating the haystack as array to find out the char at the first position is always the fastest solution. It is also always performing at equal speed, regardless of string length. Using strpos
is faster than substr
for short strings but slower for long strings, when the string does not start with the prefix. The difference is irrelevant though. stripos
is incredibly slow with long strings. preg_match
performs mostly the same regardless of string length, but is only mediocre in speed. The mb_substr
solution performs worst, while probably being more reliable though.
Given that these numbers are for 100.000 runs, it should be obvious that we are talking about 0.0000x seconds per call. Picking one over the other for efficiency is a worthless micro-optimization, unless your app is doing startsWith
checking for a living.
It is easy to modify the elements styles but kinda tricky to read the value.
JavaScript can't read any element style property (elem.style) coming from css(internal/external) unless you use the built in method call getComputedStyle in javascript.
getComputedStyle(element[, pseudo])
Element: The element to read the value for.
pseudo: A pseudo-element if required, for instance ::before. An empty string or no argument means the element itself.
The result is an object with style properties, like elem.style, but now with respect to all css classes.
For instance, here style doesn’t see the margin:
<head>
<style> body { color: red; margin: 5px } </style>
</head>
<body>
<script>
let computedStyle = getComputedStyle(document.body);
// now we can read the margin and the color from it
alert( computedStyle.marginTop ); // 5px
alert( computedStyle.color ); // rgb(255, 0, 0)
</script>
</body>
So modified your javaScript code to include the getComputedStyle of the element you wish to get it's width/height or other attribute
window.onload = function() {
var test = document.getElementById("test");
test.addEventListener("click", select);
function select(e) {
var elementID = e.target.id;
var element = document.getElementById(elementID);
let computedStyle = getComputedStyle(element);
var width = computedStyle.width;
console.log(element);
console.log(width);
}
}
Computed and resolved values
There are two concepts in CSS:
A computed style value is the value after all CSS rules and CSS inheritance is applied, as the result of the CSS cascade. It can look like height:1em or font-size:125%.
A resolved style value is the one finally applied to the element. Values like 1em or 125% are relative. The browser takes the computed value and makes all units fixed and absolute, for instance: height:20px or font-size:16px. For geometry properties resolved values may have a floating point, like width:50.5px.
A long time ago getComputedStyle was created to get computed values, but it turned out that resolved values are much more convenient, and the standard changed.
So nowadays getComputedStyle actually returns the resolved value of the property.
Please Note:
getComputedStyle requires the full property name
You should always ask for the exact property that you want, like paddingLeft or height or width. Otherwise the correct result is not guaranteed.
For instance, if there are properties paddingLeft/paddingTop, then what should we get for getComputedStyle(elem).padding? Nothing, or maybe a “generated” value from known paddings? There’s no standard rule here.
There are other inconsistencies. As an example, some browsers (Chrome) show 10px in the document below, and some of them (Firefox) – do not:
<style>
body {
margin: 30px;
height: 900px;
}
</style>
<script>
let style = getComputedStyle(document.body);
alert(style.margin); // empty string in Firefox
</script>
for more information https://javascript.info/styles-and-classes
Say we have two arrays: a and b.
a = np.array([[1,2,3],[4,5,6],[7,8,9]])
b = np.array([[9,1,1],[6,6,6],[4,2,0]])
We can first obtain row indices by permutating first dimension
indices = np.random.permutation(a.shape[0])
[1 2 0]
Then use advanced indexing. Here we are using the same indices to shuffle both arrays in unison.
a_shuffled = a[indices[:,np.newaxis], np.arange(a.shape[1])]
b_shuffled = b[indices[:,np.newaxis], np.arange(b.shape[1])]
This is equivalent to
np.take(a, indices, axis=0)
[[4 5 6]
[7 8 9]
[1 2 3]]
np.take(b, indices, axis=0)
[[6 6 6]
[4 2 0]
[9 1 1]]
I tried the @Alexander Farber and @Sino Raj answers. Both answers are nice, but I couldn't use the onCreateOptionsMenu inside my fragment, until I discover what was missing:
Add setSupportActionBar(toolbar) in my Activity, like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.id.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
I hope this answer can be helpful for someone with the same problem.
var firstFiveItems = myList.Take(5);
Or to slice:
var secondFiveItems = myList.Skip(5).Take(5);
And of course often it's convenient to get the first five items according to some kind of order:
var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);
import java.security.AlgorithmParameters;
import java.security.SecureRandom;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
class SecurityUtils {
private static final byte[] salt = { (byte) 0xA4, (byte) 0x0B, (byte) 0xC8,
(byte) 0x34, (byte) 0xD6, (byte) 0x95, (byte) 0xF3, (byte) 0x13 };
private static int BLOCKS = 128;
public static byte[] encryptAES(String seed, String cleartext)
throws Exception {
byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
return cipher.doFinal(cleartext.getBytes("UTF8"));
}
public static byte[] decryptAES(String seed, byte[] data) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes("UTF8"));
SecretKeySpec skeySpec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
return cipher.doFinal(data);
}
private static byte[] getRawKey(byte[] seed) throws Exception {
KeyGenerator kgen = KeyGenerator.getInstance("AES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(BLOCKS, sr); // 192 and 256 bits may not be available
SecretKey skey = kgen.generateKey();
byte[] raw = skey.getEncoded();
return raw;
}
private static byte[] pad(byte[] seed) {
byte[] nseed = new byte[BLOCKS / 8];
for (int i = 0; i < BLOCKS / 8; i++)
nseed[i] = 0;
for (int i = 0; i < seed.length; i++)
nseed[i] = seed[i];
return nseed;
}
public static byte[] encryptPBE(String password, String cleartext)
throws Exception {
SecretKeyFactory factory = SecretKeyFactory
.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secret);
AlgorithmParameters params = cipher.getParameters();
byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
return cipher.doFinal(cleartext.getBytes("UTF-8"));
}
public static String decryptPBE(SecretKey secret, String ciphertext,
byte[] iv) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(iv));
return new String(cipher.doFinal(ciphertext.getBytes()), "UTF-8");
}
}
With ES6 you can simply do:
for(const element of Results) {
element.Active = "false";
}
In my case, in a xamarin project, in visual studio error removed by selecting properties --> Android Options and check Use Share run Times and Use Fast Deployment, in some cases one of them
With Java 8 lambda expression you can do something like
cats.stream()
.filter( c -> c.getAge() == 3 && c.getFavoriteFood() == WHISKAS )
.collect(Collectors.toList());
Conceptually the same as the Guava Predicate approach, but it looks much cleaner with lambda
Probably not a valid answer for OP but worth to note for people with similar need. :)
/******************
Fit the body to the edges of the screen
******************/
body {
margin:0;
padding:0;
}
header {
background:black;
width:100%;
}
.header {
height:200px;
}
nav {
width:100%;
background:lightseagreen;
}
.nav {
padding:0;
margin:0;
}
.nav a {
padding:10px;
font-family:tahoma;
font-size:12pt;
color:white;
}
/******************
Centered wrapper, all other content divs will go inside this and will never exceed the width of 960px.
******************/
.wrapper {
width:960px;
max-width:100%;
margin:0 auto;
}
<!-------- Start HTML ---------->
<body>
<header>
<div id="header" class="wrapper">
</div>
</header>
<nav>
<div id="nav" class="wrapper">
</div>
</nav>
</body>
change your code to this
$start_date = new DateTime( "@" . $dbResult->db_timestamp );
and it will work fine
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
I have found simpler solution:
$('#clickToCreate').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title to Create"
})
.dialog('open');
});
$('#clickToEdit').live('click', function() {
$('#yourDialogId')
.dialog({
title: "Set the title To Edit"
})
.dialog('open');
});
Hope that helps!
You could implement it like this:
@SuppressWarnings("unchecked")
public <T extends Animal> T callFriend(String name) {
return (T)friends.get(name);
}
(Yes, this is legal code; see Java Generics: Generic type defined as return type only.)
The return type will be inferred from the caller. However, note the @SuppressWarnings
annotation: that tells you that this code isn't typesafe. You have to verify it yourself, or you could get ClassCastExceptions
at runtime.
Unfortunately, the way you're using it (without assigning the return value to a temporary variable), the only way to make the compiler happy is to call it like this:
jerry.<Dog>callFriend("spike").bark();
While this may be a little nicer than casting, you are probably better off giving the Animal
class an abstract talk()
method, as David Schmitt said.
Perfectly good example in the Autocomplete docs with source code.
jQuery
<script>
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#city" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "http://gd.geobytes.com/AutoCompleteCity",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
minLength: 3,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.label :
"Nothing selected, input was " + this.value);
},
open: function() {
$( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
},
close: function() {
$( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
}
});
});
</script>
HTML
<div class="ui-widget">
<label for="city">Your city: </label>
<input id="city">
Powered by <a href="http://geonames.org">geonames.org</a>
</div>
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="log" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
Bulk inserts in Mongoose can be done with .insert() unless you need to access middleware.
Model.collection.insert(docs, options, callback)
https://github.com/christkv/node-mongodb-native/blob/master/lib/mongodb/collection.js#L71-91
you can use this command
mysql> UPDATE mysql.user SET Password=PASSWORD('Your new Password') WHERE User='root';
check the links http://www.kirupa.com/forum/showthread.php?279644-How-to-reset-password-in-WAMP-server http://www.phpmytutor.com/blogs/2012/08/27/change-mysql-root-password-in-wamp-server/
Find your config.inc.php file under the phpMyAdmin installation directory and update the line that looks like
this:
$cfg['Servers'][$i]['password'] = 'password';
... to this:
$cfg['Servers'][$i]['password'] = 'newpassword';
do this on a new thread (seperate it from main thread)
new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
}
}).run();
Here's a nice easy way I found:
h <- hist(g, breaks = 10, density = 10,
col = "lightgray", xlab = "Accuracy", main = "Overall")
xfit <- seq(min(g), max(g), length = 40)
yfit <- dnorm(xfit, mean = mean(g), sd = sd(g))
yfit <- yfit * diff(h$mids[1:2]) * length(g)
lines(xfit, yfit, col = "black", lwd = 2)
Try this:
<?php
/*
Template Name: [contact us]
*/
get_header();
echo do_shortcode('[CONTACT-US-FORM]');
?>
If you want to uncheck the checkbox that you have selected first under the condition of 3 checkboxes allowed. With vanilla javascript; you need to assign onclick = "checking(this)" in your html input checkbox
var queue = [];
function checking(id){
queue.push(id)
if (queue.length===3){
queue[0].checked = false
queue.shift()
}
}
Depending on your Color Model, there are different methods to create a darker (shaded) or lighter (tinted) color:
RGB
:
To shade:
newR = currentR * (1 - shade_factor)
newG = currentG * (1 - shade_factor)
newB = currentB * (1 - shade_factor)
To tint:
newR = currentR + (255 - currentR) * tint_factor
newG = currentG + (255 - currentG) * tint_factor
newB = currentB + (255 - currentB) * tint_factor
More generally, the color resulting in layering a color RGB(currentR,currentG,currentB)
with a color RGBA(aR,aG,aB,alpha)
is:
newR = currentR + (aR - currentR) * alpha
newG = currentG + (aG - currentG) * alpha
newB = currentB + (aB - currentB) * alpha
where (aR,aG,aB) = black = (0,0,0)
for shading, and (aR,aG,aB) = white = (255,255,255)
for tinting
HSV
or HSB
:
Value
/ Brightness
or increase the Saturation
Saturation
or increase the Value
/ Brightness
HSL
:
Lightness
Lightness
There exists formulas to convert from one color model to another. As per your initial question, if you are in RGB
and want to use the HSV
model to shade for example, you can just convert to HSV
, do the shading and convert back to RGB
. Formula to convert are not trivial but can be found on the internet. Depending on your language, it might also be available as a core function :
RGB
has the advantage of being really simple to implement, but:
HSV
or HSB
is kind of complex because you need to play with two parameters to get what you want (Saturation
& Value
/ Brightness
)HSL
is the best from my point of view:
50%
means an unaltered Hue>50%
means the Hue is lighter (tint)<50%
means the Hue is darker (shade)Lightness
part)I'm going to assume your host is using C-Panel - and that it's probably HostGator or GoDaddy. In both cases they use C-Panel (in fact, a lot of hosts do) to make the Server administration as easy as possible on you, the end user. Even if you are hosting through someone else - see if you can log in to some kind of admin panel and find an .htaccess file that you can edit. (Note: The period before just means that it's a "hidden" file/directory).
Once you find the htaccess file add the following line:
Header set Access-Control-Allow-Origin "*"
Just to see if it works.
Warning: Do not use this line on a production serverIt should work. If not, call your host and ask them why the line isn't working - they'll probably be able to help you quickly from there.
*
to the address of the requesting domain http://cyclistinsuranceaustralia.com.au/
. You may find an issue with canonical addressing (including the www) and if so you may need to configure your host for a redirect. That's a different and smaller bridge to cross though. You'll at least be in the right place.select convert(char(5), tbl_CustomerBooking.CheckInTime, 108) AS [time]
from tbl_CustomerBooking
The .length
property only tracks properties with numeric indexes (keys). You're using strings for keys.
You can do this:
var arr_jq_TabContents = {}; // no need for an array
arr_jq_TabContents["Main"] = jq_TabContents_Main;
arr_jq_TabContents["Guide"] = jq_TabContents_Guide;
arr_jq_TabContents["Articles"] = jq_TabContents_Articles;
arr_jq_TabContents["Forum"] = jq_TabContents_Forum;
for (var key in arr_jq_TabContents) {
console.log(arr_jq_TabContents[key]);
}
To be safe, it's a good idea in loops like that to make sure that none of the properties are unexpected results of inheritance:
for (var key in arr_jq_TabContents) {
if (arr_jq_TabContents.hasOwnProperty(key))
console.log(arr_jq_TabContents[key]);
}
edit — it's probably a good idea now to note that the Object.keys()
function is available on modern browsers and in Node etc. That function returns the "own" keys of an object, as an array:
Object.keys(arr_jq_TabContents).forEach(function(key, index) {
console.log(this[key]);
}, arr_jq_TabContents);
The callback function passed to .forEach()
is called with each key and the key's index in the array returned by Object.keys()
. It's also passed the array through which the function is iterating, but that array is not really useful to us; we need the original object. That can be accessed directly by name, but (in my opinion) it's a little nicer to pass it explicitly, which is done by passing a second argument to .forEach()
— the original object — which will be bound as this
inside the callback. (Just saw that this was noted in a comment below.)
If selected more 1 file:
$("input[type="file"]").change(function() {
var files = $("input[type="file"]").prop("files");
var names = $.map(files, function(val) { return val.name; });
$(".some_div").text(names);
});
files
will be a FileList
object. names
is an array of strings (file names).
When migrating an OpenGL app from SDK 3 to 4, layoutSubviews was not called anymore. After a lot of trial and error I finally opened MainWindow.xib, selected the Window object, in the inspector chose Window Attributes tab (leftmost) and checked "Visible at launch". It seems that in SDK 3 it still used to cause a layoutSubViews call, but not in 4.
6 hours of frustration put to an end.
Several good solutions here. If you're still on Win2K and can't install anything on the remote computer, this also works:
Open the Computer Management Console (right click My Computer, choose Manage; open from Administrative Tools in the Start Menu; or open from the MMC using the snap-in).
Right click on your computer name and choose "Connect to Remote Computer"
Put in the computer name and credentials and you have full access to many admin functions including the services control panel.
It's been 4 months since asking this question, and I still haven't found a good solution.
However, I did find a decent workaround, which I will share in case others have the same issue.
I will try to update this answer, too, if I make further progress.
First of all, my research has shown that there are several possible combinations of user-settings and site settings that cause a variety of PDF display issues. These include:
I spent some time researching PDF display options at pdfobject.com, which is an EXCELLENT resource and I learned a lot.
The workaround I came up with is to embed the PDF file inside an empty HTML page. It is very simple: See some similar examples at pdfobject.com.
<html>
<head>...</head>
<body>
<object data="/pdf/sample.pdf" type="application/pdf" height="100%" width="100%"></object>
</body>
</html>
However, here's a list of caveats:
<object />
tag, ... but ...z-index
to show it ... but ...This is a huge list of caveats. I believe it covers all the bases, but I am definitely not comfortable applying this to EVERY user (most of whom do not have an issue).
Therefore, we decided to ONLY do this embedded
option if the user opts-in for it. On our PDF page, we have a section that says "Having trouble viewing PDFs?", which lets you change your setting to "embedded", and we store that setting in a cookie.
In our GetPDF
Action, we look for the embed=true
cookie. This determines whether we return the PDF file, or if we return a View of HTML with the embedded PDF.
Ugh. This was even less fun than writing IE6-compatible JavaScript.
I hope that others with the same problem can find comfort knowing that they're not alone!
The FULLY WORKING SOLUTION for both Android
or React-native
users facing this issue just add this
android:usesCleartextTraffic="true"
in AndroidManifest.xml file like this:
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
in between <application>
.. </application>
tag like this:
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"/>
</application>
OK, here is a step-by-step guide if you want to use COM.
using NsExcel = Microsoft.Office.Interop.Excel;
public void ListToExcel(List<string> list)
{
//start excel
NsExcel.ApplicationClass excapp = new Microsoft.Office.Interop.Excel.ApplicationClass();
//if you want to make excel visible
excapp.Visible = true;
//create a blank workbook
var workbook = excapp.Workbooks.Add(NsExcel.XlWBATemplate.xlWBATWorksheet);
//or open one - this is no pleasant, but yue're probably interested in the first parameter
string workbookPath = "C:\test.xls";
var workbook = excapp.Workbooks.Open(workbookPath,
0, false, 5, "", "", false, Excel.XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
//Not done yet. You have to work on a specific sheet - note the cast
//You may not have any sheets at all. Then you have to add one with NsExcel.Worksheet.Add()
var sheet = (NsExcel.Worksheet)workbook.Sheets[1]; //indexing starts from 1
//do something usefull: you select now an individual cell
var range = sheet.get_Range("A1", "A1");
range.Value2 = "test"; //Value2 is not a typo
//now the list
string cellName;
int counter = 1;
foreach (var item in list)
{
cellName = "A" + counter.ToString();
var range = sheet.get_Range(cellName, cellName);
range.Value2 = item.ToString();
++counter;
}
//you've probably got the point by now, so a detailed explanation about workbook.SaveAs and workbook.Close is not necessary
//important: if you did not make excel visible terminating your application will terminate excel as well - I tested it
//but if you did it - to be honest - I don't know how to close the main excel window - maybee somewhere around excapp.Windows or excapp.ActiveWindow
}
CAST(CONVERT(CHAR(8),GETUTCDATE(),114) AS DATETIME)
IN SQL Server 2008+
CAST(GETUTCDATE() AS TIME)
Use the format()
function with a '02x'
format.
>>> format(255, '02x')
'ff'
>>> format(2, '02x')
'02'
The 02
part tells format()
to use at least 2 digits and to use zeros to pad it to length, x
means lower-case hexadecimal.
The Format Specification Mini Language also gives you X
for uppercase hex output, and you can prefix the field width with #
to include a 0x
or 0X
prefix (depending on wether you used x
or X
as the formatter). Just take into account that you need to adjust the field width to allow for those extra 2 characters:
>>> format(255, '02X')
'FF'
>>> format(255, '#04x')
'0xff'
>>> format(255, '#04X')
'0XFF'
Here is my implementation using the Affix Bootstrap plugin http://getbootstrap.com/javascript/#affix
It includes some extra affix problems solved (see below).
HTML:
<nav class="navbar navbar-inverse navbar-fixed-top" id="top_navbar">
<div class="container-fluid">
... (typical Bootstrap top navbar)
</div>
</div>
...
...
...
<div id="parent-navbar-main" >
<div id="navbar-main">
... (here is your nav panel to get sticky on scroll)
</div>
</div>
Javascript:
function set_sticky_panel() {
var affixElement = $('#navbar-main');
var navbarElementHeight = $('#top_navbar').height();
// http://stackoverflow.com/questions/18683303/bootstrap-3-0-affix-with-list-changes-width
var width = affixElement.parent().width();
affixElement.width(width);
// http://stackoverflow.com/questions/3410765/get-full-height-of-element
var affixElementHeight = $('#navbar-main').outerHeight(true);
// https://finiteheap.com/webdev/2014/12/26/bootstrap-affix-flickering.html
affixElement.parent().height(affixElementHeight);
// http://stackoverflow.com/questions/23797241/resetting-changing-the-offset-of-bootstrap-affix
$(window).off('.affix')
affixElement.removeData('bs.affix').removeClass('affix affix-top affix-bottom')
affixElement.affix({
offset: {
// Distance of between element and top page
top: function () {
// how much scrolling is done until sticking the panel
return (this.top = affixElement.offset().top - parseInt(navbarElementHeight,10))
}
}
});
// The replacement for the css-file.
affixElement.on('affix.bs.affix', function (){
// the absolute position where the sticked panel is to be placed when the fixing event fires (e.g. the panel reached the top of the page).
affixElement.css('top', navbarElementHeight + 'px');
affixElement.css('z-index', 10);
});
}
$(document).on('ready', set_sticky_panel);
$(window).resize(set_sticky_panel);
CSS:
No css is required.
If to compare with the standart implementation my code additionaly solves these problems:
First of all create a model POJO
import javax.persistence.*;
@Entity
@Table(name = "sys_std_user")
public class StdUser {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "class_id")
public int classId;
@Column(name = "user_name")
public String userName;
//getter,setter
}
Controller
import com.example.demo.models.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.util.List;
@RestController
public class HomeController {
@PersistenceUnit
private EntityManagerFactory emf;
@GetMapping("/")
public List<StdUser> actionIndex() {
EntityManager em = emf.createEntityManager(); // Without parameter
List<StdUser> arr_cust = (List<StdUser>)em
.createQuery("SELECT c FROM StdUser c")
.getResultList();
return arr_cust;
}
@GetMapping("/paramter")
public List actionJoin() {
int id = 3;
String userName = "Suresh Shrestha";
EntityManager em = emf.createEntityManager(); // With parameter
List arr_cust = em
.createQuery("SELECT c FROM StdUser c WHERE c.classId = :Id ANd c.userName = :UserName")
.setParameter("Id",id)
.setParameter("UserName",userName)
.getResultList();
return arr_cust;
}
}
As I learned, no one of those several solutions are perfects. Using a favicon generator is indeed a good solution but their number is overwhelming and it's hard to choose. I d'like to add that if you want your website to be PWA enabled, you need to provide also a 512x512 icon as stated by Google Devs :
icons including a 192px and a 512px version
I didn't met a lot of favicon generators enforcing that criteria (firebase does, but there is a lot of things it doesn't do). So the solution must be a mix of many other solutions.
I don't know, today at the begining of 2020 if providing a 16x16, 32x32 still relevant. I guess it still matters in certain context like, for example, if your users still use IE for some reason (this stills happen in some privates companies which doesn't migrate to a newer browser for some reasons)
I finally found this solution from "Sven" and solved the problem. what I did was I included "bootstrap.min.js" with:
<script src="bootstrap.min.js"/>
instead of:
<script src="bootstrap.min.js"></script>
and it fixed the problem which looked really odd. can anyone explain why?
That is brilliant, the only answer I found that met my particular need, thanks SO much for putting it up!
I made just a minor addition to it so that the screen didn't flash and it removes and subsequently reapplies the password on each sheet as it cycles through [I have the same password for all sheets in the workbook]. In the spirit of your submission, I add this to assist anyone else....
Sub ClearFilters()
Application.ScreenUpdating = False
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
'Change the password to whatever is required
wrksheet.Unprotect Password:="Albuterol1"
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
'Change the password to whatever is required
wrksheet.Protect Password:="Albuterol1", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True, _
AllowFiltering:=True
Next 'Check next worksheet in the workbook
Next
Application.ScreenUpdating = True
End Sub
I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..
Hopefully this helps someone out there :)
Sub ResetFilters()
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
Next 'Check next worksheet in the workbook
Next
End Sub
In Eclipse Kepler,
JST Server Adapters
and JST Server Adapters Extensions
and install itAfter Eclipse restart, go to Window / Preferences / Server / Runtime Environments
You can return json in PHP this way:
header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;
For me, this was related to malformed ownership in my .git/
path. root
owned .git/HEAD
and .git/index
, preventing the jenkins
user from running the job.
If you only want to return a blank when B2 is blank you can use an additional IF function for that scenario specifically, i.e.
=IF(B2="","",VLOOKUP(B2,Index!A1:B12,2,FALSE))
or to return a blank with any error from the VLOOKUP (e.g. including if B2 is populated but that value isn't found by the VLOOKUP) you can use IFERROR function if you have Excel 2007 or later, i.e.
=IFERROR(VLOOKUP(B2,Index!A1:B12,2,FALSE),"")
in earlier versions you need to repeat the VLOOKUP, e.g.
=IF(ISNA(VLOOKUP(B2,Index!A1:B12,2,FALSE)),"",VLOOKUP(B2,Index!A1:B12,2,FALSE))
foreach ($Contents as $index=>$item) {
$item[$index];// if there are 15 $item[number] in this foreach, I want get the value : 15
}
MediaQuery.of(context).size.width
and MediaQuery.of(context).size.height
works great, but every time need to write expressions like width/20 to set specific height width.
I've created a new application on flutter, and I've had problems with the screen sizes when switching between different devices.
Yes, flutter_screenutil
plugin available for adapting screen and font size. Let your UI display a reasonable layout on different screen sizes!
Usage:
Add dependency:
Please check the latest version before installation.
dependencies:
flutter:
sdk: flutter
# add flutter_ScreenUtil
flutter_screenutil: ^0.4.2
Add the following imports to your Dart code:
import 'package:flutter_screenutil/flutter_screenutil.dart';
Initialize and set the fit size and font size to scale according to the system's "font size" accessibility option
//fill in the screen size of the device in the design
//default value : width : 1080px , height:1920px , allowFontScaling:false
ScreenUtil.instance = ScreenUtil()..init(context);
//If the design is based on the size of the iPhone6 ??(iPhone6 ??750*1334)
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
//If you wang to set the font size is scaled according to the system's "font size" assist option
ScreenUtil.instance = ScreenUtil(width: 750, height: 1334, allowFontScaling: true)..init(context);
Use:
//for example:
//rectangle
Container(
width: ScreenUtil().setWidth(375),
height: ScreenUtil().setHeight(200),
...
),
////If you want to display a square:
Container(
width: ScreenUtil().setWidth(300),
height: ScreenUtil().setWidth(300),
),
Please refer updated documentation for more details
Note: I tested and using this plugin, which really works great with all devices including iPad
Hope this will helps someone
innerHTML is fine and still valid. Use it all the time on projects big and small. I just flipped to an open tab in my IDE and there was one right there.
document.getElementById("data-progress").innerHTML = "<img src='../images/loading.gif'/>";
Not much has changed in js + dom manipulation since 2005, other than the addition of more libraries. You can easily set other properties such as
uploadElement.style.width = "100%";
Just use it like it was an object you defined. i.e.
$trends = $json_output->trends;
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
The \#include
files of gcc are stored in /usr/include
.
The standard include files of g++ are stored in /usr/include/c++
.
You can't access element like you did (document.frm_new_user_request
). You have to use the function getElementById
:
document.getElementById("frm_new_user_request")
So getting a value from an input could look like this:
var value = document.getElementById("frm_new_user_request").value
Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.
Getting a value from an input using jQuery would look like this:
var value = $("#element).value
var value = $(".element).value
This should technically be achievable using window.location.reload()
:
HTML:
<button (click)="refresh()">Refresh</button>
TS:
refresh(): void {
window.location.reload();
}
Update:
Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload()
is executed.
Tools > Manage Add-ons, right click "Name" header and enable the "In Folder" section. go to the directory for the plugin you're interested in. Right click the plugin file, and click "remove".
I think it should be R.color.black
Also take a look at Converting android color string in runtime into int
You can reset your branch to the state it was in just before the merge if you find the commit it was on then.
One way is to use git reflog
, it will list all the HEADs you've had.
I find that git reflog --relative-date
is very useful as it shows how long ago each change happened.
Once you find that commit just do a git reset --hard <commit id>
and your branch will be as it was before.
If you have SourceTree, you can look up the <commit id>
there if git reflog
is too overwhelming.
You can simply cast strings to DateTime:
[DateTime]"2020-7-16"
or
[DateTime]"Jul-16"
or
$myDate = [DateTime]"Jul-16";
And you can format the resulting DateTime variable by doing something like this:
'{0:yyyy-MM-dd}' -f [DateTime]'Jul-16'
or
([DateTime]"Jul-16").ToString('yyyy-MM-dd')
or
$myDate = [DateTime]"Jul-16";
'{0:yyyy-MM-dd}' -f $myDate
If you know for sure that your current encoding is pure ASCII, then you don't have to do anything because ASCII is already a valid UTF-8.
But if you still want to convert, just to be sure that its UTF-8, then you can use iconv
$string = iconv('ASCII', 'UTF-8//IGNORE', $string);
The IGNORE will discard any invalid characters just in case some were not valid ASCII.
In addition to the above posts, i'd like to point out that "man ls" will give you a nice manual about the "ls" ( List " command.
Also, using ls -la myFile will list & show all the facts about that file.
int a = 1;
char * c = (char*)(&a); //In C++ should be intermediate cst to void*
Personally, I just use JSON to convert things to strings and back. Strings I understand.
import json
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]
mydict = {}
hash = json.dumps(s)
mydict[hash] = "whatever"
print mydict
#{'[["yellow", 1], ["blue", 2], ["yellow", 3], ["blue", 4], ["red", 1]]': 'whatever'}
at -l
to list jobs, which gives return like this:
age2%> at -l
11 2014-10-21 10:11 a hoppent
10 2014-10-19 13:28 a hoppent
atrm 10
kills job 10
Or so my sysadmin told me, and it
use android:theme="@android:style/Theme.NoTitleBar
in manifest file's application tag to remove the title bar for whole application or put it in activity tag to remove the title bar from a single activity screen.
C++20 introduced a guarantee that time_since_epoch
is relative to the UNIX epoch, and cppreference.com gives an example that I've distilled to the relevant code, and changed to units of seconds rather than hours:
#include <iostream>
#include <chrono>
int main()
{
const auto p1 = std::chrono::system_clock::now();
std::cout << "seconds since epoch: "
<< std::chrono::duration_cast<std::chrono::seconds>(
p1.time_since_epoch()).count() << '\n';
}
Using C++17 or earlier, time()
is the simplest function - seconds since Epoch, which for Linux and UNIX at least would be the UNIX epoch. Linux manpage here.
The cppreference page linked above gives this example:
#include <ctime>
#include <iostream>
int main()
{
std::time_t result = std::time(nullptr);
std::cout << std::asctime(std::localtime(&result))
<< result << " seconds since the Epoch\n";
}
I have implemented a C# version, it is easily converted to C++.
public bool Intersects ( Rectangle rect )
{
float ulx = Math.Max ( x, rect.x );
float uly = Math.Max ( y, rect.y );
float lrx = Math.Min ( x + width, rect.x + rect.width );
float lry = Math.Min ( y + height, rect.y + rect.height );
return ulx <= lrx && uly <= lry;
}
IMHO, there is not much difference in case of web application if you look at it from the angle of responsibility assignment. However, keep the clarity in the layer. Keep anything purely for the presentation purpose in the presentation layer, like the control and code specific to the web controls. Just keep your entities in the business layer and all features (like add, edit, delete) etc in the business layer. However rendering them onto the browser to be handled in the presentation layer. For .Net, the ASP.NET MVC pattern is very good in terms of keeping the layers separated. Look into the MVC pattern.
Update: Visual Studio 2010 and Visual C++ 2010 Express both have stdint.h
. It can be found in C:\Program Files\Microsoft Visual Studio 10.0\VC\include
Following method checks whether 'validateTime' is between 'startTime' & 'endTime' or not while considering possibility that 'endTime' can be a next day. To use it properly parse your dates in "HH:mm" formant.
public static final boolean isBetweenValidTime(Date startTime, Date endTime, Date validateTime)
{
boolean validTimeFlag = false;
if(endTime.compareTo(startTime) <= 0)
{
if(validateTime.compareTo(endTime) < 0 || validateTime.compareTo(startTime) >= 0)
{
validTimeFlag = true;
}
}
else if(validateTime.compareTo(endTime) < 0 && validateTime.compareTo(startTime) >= 0)
{
validTimeFlag = true;
}
return validTimeFlag;
}
You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.
(gdb) info symbol 0x4005BDC
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
worked for me Thanks
Versions for reference
jquery-3.3.1.js
/1.10.19/js/jquery.dataTables.min.js
/buttons/1.5.2/js/dataTables.buttons.min.js
Given that canvas
is a canvas element,
const context = canvas.getContext('2d');
context.clearRect(0, 0, canvas.width, canvas.height);
Those who still have the problem with onAttach(Activity activity), Its just changed to Context -
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.context = context;
}
In most cases saving the context will be enough for you - for example if you want to do getResources() you can do it straight from the context. If you still need to make the context into your Activity do so -
@Override
public void onAttach(Context context) {
super.onAttach(context);
mActivity a; //Your activity class - will probably be a global var.
if (context instanceof mActivity){
a=(mActivity) context;
}
}
As suggested by user1868713.
Thanks to everyone, each of your posts helped me a lot. rbierman code was pretty straight for my question, I have modified a bit and created a function to plot vectors from given arrays. I'd love to see any suggestions to improve it further.
import numpy as np
import matplotlib.pyplot as plt
def plotv(M):
rows,cols = M.T.shape
print(rows,cols)
#Get absolute maxes for axis ranges to center origin
#This is optional
maxes = 1.1*np.amax(abs(M), axis = 0)
colors = ['b','r','k']
fig = plt.figure()
fig.suptitle('Vectors', fontsize=10, fontweight='bold')
ax = fig.add_subplot(111)
fig.subplots_adjust(top=0.85)
ax.set_title('Vector operations')
ax.set_xlabel('x')
ax.set_ylabel('y')
for i,l in enumerate(range(0,cols)):
# print(i)
plt.axes().arrow(0,0,M[i,0],M[i,1],head_width=0.2,head_length=0.1,zorder=3)
ax.text(M[i,0],M[i,1], str(M[i]), style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':0.5})
plt.plot(0,0,'ok') #<-- plot a black point at the origin
# plt.axis('equal') #<-- set the axes to the same scale
plt.xlim([-maxes[0],maxes[0]]) #<-- set the x axis limits
plt.ylim([-maxes[1],maxes[1]]) #<-- set the y axis limits
plt.grid(b=True, which='major') #<-- plot grid lines
plt.show()
r = np.random.randint(4,size=[2,2])
print(r[0,:])
print(r[1,:])
r12 = np.add(r[0,:],r[1,:])
print(r12)
plotv(np.vstack((r,r12)))
As mentioned before, you might need GD library installed.
On a shell, check your php version first:
php -v
Then install accordingly. In my system (Linux-Ubuntu) it's php version 7.0:
sudo apt-get install php7.0-gd
Restart your webserver:
systemctl restart apache2
You should now have GD library installed and enabled.
Thanks WChoward for your answer. I expanded:
.nav-link, .dropdown-item {
color: blue !important;
}
.nav-link:hover, .dropdown-item:hover {
color: darkgreen !important;
}
alt
is text that is displayed when the image can't be loaded or the user's browser doesn't support images (e.g. readers for blind people).
Try using something like lightbox:
http://www.lokeshdhakar.com/projects/lightbox2/
update: This library maybe better as its based on jQuery which you have said your using http://leandrovieira.com/projects/jquery/lightbox/
You should use html():
$(document).ready(function(){
$("#date").html('<span>'+$("#date").text().substring(0, 2) + '</span><br />'+$("#date").text().substring(3));
});
From git reset
"pull" or "merge" always leaves the original tip of the current branch in
ORIG_HEAD
.git reset --hard ORIG_HEAD
Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.
git reset --merge ORIG_HEAD
After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "
git reset --hard ORIG_HEAD
" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge
" keeps your local changes.
Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am
' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).In addition, merge always sets '
.git/ORIG_HEAD
' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD
'.
Note: from here
HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.
So HEAD is NOT a synonym for "current branch" everywhere already.
HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).
But it almost always means the "current commit".
It is the commit "git commit
" builds on top of, and "git diff --cached
" and "git status
" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".
HEAD@{5.minutes.ago}
could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".
git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.
Instead of typing four capital letters "
HEAD
", you can say "@
" now,
e.g. "git log @
".
See commit cdfd948
Typing '
HEAD
' is tedious, especially when we can use '@
' instead.The reason for choosing '
@
' is that it follows naturally from theref@op
syntax (e.g.HEAD@{u}
), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD
'.So now we can use '
git show @~1
', and all that goody goodness.Until now '
@
' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.
You should use Merge: For example:
MERGE INTO employees e
USING (SELECT * FROM hr_records WHERE start_date > ADD_MONTHS(SYSDATE, -1)) h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
or
MERGE INTO employees e
USING hr_records h
ON (e.id = h.emp_id)
WHEN MATCHED THEN
UPDATE SET e.address = h.address
WHEN NOT MATCHED THEN
INSERT (id, address)
VALUES (h.emp_id, h.address);
From http://www.howtogeek.com/204166/how-to-configure-windows-to-work-with-powershell-scripts-more-easily:
Set the default value for the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell
to 0
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
Collection initializers are only available in VB.NET 2010, released 2010-04-12:
Dim theVar = New List(Of String) From { "one", "two", "three" }
I assume you want to pass the Order ID in. So:
CREATE PROCEDURE [dbo].[Procedure_Name]
(
@OrderID INT
) AS
BEGIN
Declare @OrderItemID AS INT
DECLARE @AppointmentID AS INT
DECLARE @PurchaseOrderID AS INT
DECLARE @PurchaseOrderItemID AS INT
DECLARE @SalesOrderID AS INT
DECLARE @SalesOrderItemID AS INT
SET @OrderItemID = (SELECT OrderItemID FROM [OrderItem] WHERE OrderID = @OrderID)
SET @AppointmentID = (SELECT AppoinmentID FROM [Appointment] WHERE OrderID = @OrderID)
SET @PurchaseOrderID = (SELECT PurchaseOrderID FROM [PurchaseOrder] WHERE OrderID = @OrderID)
END
When you run this command,
svn propedit svn:log --revprop -r NNN
and just in case you see this message:
DAV request failed; it's possible that the repository's pre-revprop-change hook either failed or is non-existent
Its because Subversion doesn’t allow you to modify log messages because they are unversioned and will be lost permanently.
Go to the hooks directory on your Subversion server (replace ~/svn/reponame with the directory of your repository)
cd ~/svn/reponame/hooks
Remove the extension
mv pre-revprop-change.tmpl pre-revprop-change
Make it executable (cannot do chmod +x!)
chmod 755 pre-revprop-change
The template files in the hooks directory cannot be used as they are Unix-specific. You need to copy a Windows batch file pre-revprop-change.bat
to the hooks directory, e.g. the one provided here.
Another option is to use numpy.full
, an option available in NumPy 1.8+
a = np.full([height, width, 9], np.nan)
This is pretty flexible and you can fill it with any other number that you want.
Follow the steps below in Oracle VM VirtualBox Manager:
To verify, start the Virtual device from Oracle VM VirtualBox. If all has gone well, the device boots up.
Close this device and open it from Genymotion.
Now in Android Studio v1.1.0 should be:
Run
> Run <your app>
<your app>\build\outputs\apk
I had the similar issue and the problem was in the config file pg_hba.conf. I had earlier made some changes which was causing the server to error out while trying to start it. Commenting out the extra additions solved the problem.
A different user name is the common cause for this, Nuget downloads everything into: "C:\Users\USER_NAME\source\repos"
and if you had the project previously setup on a different user name the .csproj file may still contain that old user name there, simply open it and do a search replace for "C:\Users\_OLD_USER_NAME\source\repos"
to "C:\Users\NEW_USER_NAME\source\repos"
.
As pointed above, BFS can only be used to find shortest path in a graph if:
There are no loops
All edges have same weight or no weight.
To find the shortest path, all you have to do is start from the source and perform a breadth first search and stop when you find your destination Node. The only additional thing you need to do is have an array previous[n] which will store the previous node for every node visited. The previous of source can be null.
To print the path, simple loop through the previous[] array from source till you reach destination and print the nodes. DFS can also be used to find the shortest path in a graph under similar conditions.
However, if the graph is more complex, containing weighted edges and loops, then we need a more sophisticated version of BFS, i.e. Dijkstra's algorithm.
Serialize both objects and compare the resulting strings by @JoelFan
So to do this, create a static class like so and use Extensions to extend ALL objects (so you can pass anytype of object, collection, etc into the method)
using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;
public static class MySerializer
{
public static string Serialize(this object obj)
{
var serializer = new DataContractJsonSerializer(obj.GetType());
using (var ms = new MemoryStream())
{
serializer.WriteObject(ms, obj);
return Encoding.Default.GetString(ms.ToArray());
}
}
}
Once you reference this static class in any other file, you can do this:
Person p = new Person { Firstname = "Jason", LastName = "Argonauts" };
Person p2 = new Person { Firstname = "Jason", LastName = "Argonaut" };
//assuming you have already created a class person!
string personString = p.Serialize();
string person2String = p2.Serialize();
Now you can simply use .Equals to compare them. I use this for checking if objects are in collections too. It works really well.
You should not define global variables in header files. You can declare them as extern
in header file and define them in a .c
source file.
(Note: In C, int i;
is a tentative definition, it allocates storage for the variable (= is a definition) if there is no other definition found for that variable in the translation unit.)
You don't want to redirect the system.out stream because that redirects for the ENTIRE JVM. Anything else running on the JVM can get messed up. There are better ways to test input/output. Look into stubs/mocks.
zxing does not (only) provide a web API; really, that is Google providing the API, from source code that was later open-sourced in the project.
As Rob says here you can use the Java source code for the QR code encoder to create a raw barcode and then render it as a Bitmap.
I can offer an easier way still. You can call Barcode Scanner by Intent to encode a barcode. You need just a few lines of code, and two classes from the project, under android-integration
. The main one is IntentIntegrator. Just call shareText()
.
Since this is a POD (essentially a C struct) there is little harm in initialising it the C way:
Snapshot s;
memset(&s, 0, sizeof (s));
or similarly
Snapshot *sp = new Snapshot;
memset(sp, 0, sizeof (*sp));
I wouldn't go so far as to use calloc()
in a C++ program though.
You can try this for DataGrid:
DataGridCellInfo cellInfo = new DataGridCellInfo(myDataGrid.Items[colRow], myDataGrid.Columns[colNum]);
DataGridCell cellToFocus = (DataGridCell)cellInfo.Column.GetCellContent(cellInfo.Item).Parent;
ViewControlHelper.SetFocus(cellToFocus, e);
I know inline code is bad style, but I didn't want to put this into a .js file. Works without jQuery!
<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>
You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.
import threading
import time
import inspect
class Thread(threading.Thread):
def __init__(self, t, *args):
threading.Thread.__init__(self, target=t, args=args)
self.start()
count = 0
lock = threading.Lock()
def incre():
global count
caller = inspect.getouterframes(inspect.currentframe())[1][3]
print "Inside %s()" % caller
print "Acquiring lock"
with lock:
print "Lock Acquired"
count += 1
time.sleep(2)
def bye():
while count < 5:
incre()
def hello_there():
while count < 5:
incre()
def main():
hello = Thread(hello_there)
goodbye = Thread(bye)
if __name__ == '__main__':
main()
Sample output:
...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...
The following steps could help:
you can try this
pip install opencv==2.4.9
An abstract function cannot have functionality. You're basically saying, any child class MUST give their own version of this method, however it's too general to even try to implement in the parent class.
A virtual function, is basically saying look, here's the functionality that may or may not be good enough for the child class. So if it is good enough, use this method, if not, then override me, and provide your own functionality.
As @Mehmet is pointing out, if your result is returning more then 1 elerment then you need to look into you data as i suspect that its not by design that you have customers sharing a customernumber.
But to the point i wanted to give you a quick overview.
//success on 0 or 1 in the list, returns dafault() of whats in the list if 0
list.SingleOrDefault();
//success on 1 and only 1 in the list
list.Single();
//success on 0-n, returns first element in the list or default() if 0
list.FirstOrDefault();
//success 1-n, returns the first element in the list
list.First();
//success on 0-n, returns first element in the list or default() if 0
list.LastOrDefault();
//success 1-n, returns the last element in the list
list.Last();
for more Linq expressions have a look at System.Linq.Expressions
better way is to reuse ANDROID_HOME variable in path variable. if your ANDROID_HOME variable changes you just have to make change at one place.
export ANDROID_HOME=/home/arshid/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
You should install these as devDependencies:
- gulp-util
- gulp-load-plugins
Then, you can use them either this way:
var plugins = require('gulp-load-plugins')();
Use gulp-util as : plugins.util()
or this:
var util = require('gulp-util')