I'd suggest trying to avoid using return/exit if you don't have to. Some people will devoutly tell you to NEVER do it, but sometimes it just makes sense. However if you can structure you checks so that you don't have to enter into them, I think it makes it easier for people to follow your code later.
If you are trying to insert the therefore symbol into a WORD DOCUMENT
Hold down the ALT key and type 8756
Hope the answer ur question Regards Al~Hash.
App.Config is an XML file that is used as a configuration file for your application. In other words, you store inside it any setting that you may want to change without having to change code (and recompiling). It is often used to store connection strings.
See this MSDN article on how to do that.
None of the solutions above could solve my problem in Jupyter Notebook, so I use the following snippet code bellow from Cicoria, and issues solved.
import warnings
with warnings.catch_warnings():
warnings.filterwarnings("ignore",category=FutureWarning)
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
print('Done')
The listFiles
method, with or without a filter does not guarantee any order.
It does, however, return an array, which you can sort with Arrays.sort()
.
File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
This works because File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.
If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
Replace the System.out::println
with whatever you want to do with the file names. If you want only filenames that end with "xml"
just do:
Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
Again, replace the printing with whichever processing operation you would like.
Another difference not pointed out is that giving the struct a name (i.e. struct myStruct) also enables you to provide forward declarations of the struct. So in some other file, you could write:
struct myStruct;
void doit(struct myStruct *ptr);
without having to have access to the definition. What I recommend is you combine your two examples:
typedef struct myStruct{
int one;
int two;
} myStruct;
This gives you the convenience of the more concise typedef name but still allows you to use the full struct name if you need.
In Tensorflow 1.x
import tensorflow as tf
tf.enable_eager_execution()
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product) # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
With Tensorflow 2.x, eager mode is enabled by default. so the following code works with TF2.0.
import tensorflow as tf
matrix1 = tf.constant([[3., 3.]])
matrix2 = tf.constant([[2.],[2.]])
product = tf.matmul(matrix1, matrix2)
#print the product
print(product) # tf.Tensor([[12.]], shape=(1, 1), dtype=float32)
print(product.numpy()) # [[12.]]
nobody seem to have offered the option to get the JSON directly from the Postgresql server, using the postgres JSON capability https://www.postgresql.org/docs/9.4/static/functions-json.html
No parsing, looping or any memory consumption on the python side, which you may really want to consider if you're dealing with 100,000's or millions of rows.
from django.db import connection
sql = 'SELECT to_json(result) FROM (SELECT * FROM TABLE table) result)'
with connection.cursor() as cursor:
cursor.execute(sql)
output = cursor.fetchall()
a table like:
id, value
----------
1 3
2 7
will return a Python JSON Object
[{"id": 1, "value": 3},{"id":2, "value": 7}]
Then use json.dumps
to dump as a JSON string
Basically if you follow the issues in this link for 0.2 you'll likely get yourself fixed, I had the same problems with 0.2
Based on the recipe :
resulting_list = list(set().union(first_list, second_list))
Just window.location = "http://wherever.you.wanna.go.com/"
, or, for local links, window.location = "my_relative_link.html"
.
You can try it by typing it into your address bar as well, e.g. javascript: window.location = "http://www.google.com/"
.
Also note that the protocol part of the URL (http://
) is not optional for absolute links; omitting it will make javascript assume a relative link.
Try this:
getWindow().setFlags(LayoutParams.FLAG_SECURE, LayoutParams.FLAG_SECURE);
You could convert the dataframe to be a single column with stack
(this changes the shape from 5x3 to 15x1) and then take the standard deviation:
df.stack().std() # pandas default degrees of freedom is one
Alternatively, you can use values
to convert from a pandas dataframe to a numpy array before taking the standard deviation:
df.values.std(ddof=1) # numpy default degrees of freedom is zero
Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.
A couple of additional notes:
The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).
The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.
In Visual Studio 2012 I had the same error. Had to uninstall NuGet (Tools > Extensions and Updates > Installed > All: NuGet Package Manager: Uninstall button). Then closed Visual Studio. Then reopened Visual Studio and reinstalled NuGet (Tools > Extensions and Updates > Online > Visual Studio Gallery: NuGet Package Manager: Download button). Then in following windows: click Install button, then click close button. Then close and reopen Visual Studio.
Or can use the Extension Splitter Trickster::getExtention()
function of https://github.com/secrethash/trickster
Trickster::getExtention('some-funny.image.jpg');
It returns jpg
beforeShow: function(el) {
if ( el.getAttribute("readonly") !== null ) {
if ( (el.value == null) || (el.value == '') ) {
$(el).datepicker( "option", "minDate", +1 );
$(el).datepicker( "option", "maxDate", -1 );
} else {
$(el).datepicker( "option", "minDate", el.value );
$(el).datepicker( "option", "maxDate", el.value );
}
}
},
Using EntrySet() and for each loop
for(Map.Entry<String, String> entry: hashMap.entrySet()) {
System.out.println("Key Of map = "+ entry.getKey() +
" , value of map = " + entry.getValue() );
}
Using keyset() and for each loop
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using EntrySet() and java Iterator
for(String key : hashMap.keySet()) {
System.out.println("Key Of map = "+ key + " ,
value of map = " + hashMap.get(key) );
}
Using keyset() and java Iterator
Iterator<String> keysIterator = keySet.iterator();
while (keysIterator.hasNext()) {
String key = keysIterator.next();
System.out.println("Key Of map = "+ key + " , value of map = " + hashMap.get(key) );
}
Reference : How to iterate over Map or HashMap in java
There is an easier way to avoid the Strong Parameters at all, you just need to convert the parameters to a regular hash, as:
unlocked_params = ActiveSupport::HashWithIndifferentAccess.new(params)
model.create!(unlocked_params)
This defeats the purpose of strong parameters of course, but if you are in a situation like mine (I'm doing my own management of allowed params in another part of my system) this will get the job done.
min(df['some_property'])
max(df['some_property'])
The built-in functions work well with Pandas Dataframes.
Although the accepted answer here is technically correct, there seems to be some confusion amongst users based on the comments. When working with a ViewBag in a .cshtml file, you must use @Html.Raw
otherwise your data, after being unescaped by the ConfigurationManager, will become re-escaped once again. Use Html.Raw()
to prevent this from occurring.
//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
//Add an empty namespace and empty value
ns.Add("", "");
//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);
//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)
Normally, it's considered poor style to unnecessarily cast pointers to (void*). Here, however, you need the casts to (void*) on the printf arguments because printf is variadic. The prototype doesn't tell the compiler what type to convert the pointers to at the call site.
In case of numeric values you should use is_numeric function:
$var = 0;
if (is_numeric($var))
{
echo "Its not empty";
}
else
{
echo "Its empty";
}
As has been said before, the clone and attach elsewhere method does not guarantee the same results as styling may be different.
Below is my approach. It travels up the parents looking for the parent responsible for the hiding, then temporarily unhides it to calculate the required width, height, etc.
var width = parseInt($image.width(), 10);_x000D_
var height = parseInt($image.height(), 10);_x000D_
_x000D_
if (width === 0) {_x000D_
_x000D_
if ($image.css("display") === "none") {_x000D_
_x000D_
$image.css("display", "block");_x000D_
width = parseInt($image.width(), 10);_x000D_
height = parseInt($image.height(), 10);_x000D_
$image.css("display", "none");_x000D_
}_x000D_
else {_x000D_
_x000D_
$image.parents().each(function () {_x000D_
_x000D_
var $parent = $(this);_x000D_
if ($parent.css("display") === "none") {_x000D_
_x000D_
$parent.css("display", "block");_x000D_
width = parseInt($image.width(), 10);_x000D_
height = parseInt($image.height(), 10);_x000D_
$parent.css("display", "none");_x000D_
}_x000D_
});_x000D_
}_x000D_
}
_x000D_
I think the key is to copy the module to the standard paths.
Once that is done, modprobe only accepts the module name, so leave off the path and ".ko" extension.
Using sed:
$ [email protected]:/home/some/directory/file
$ echo $var | sed 's/.*://'
/home/some/directory/file
Use -1
index (negative indices count backward from the end of the array):
a[-1] # => 5
b[-1] # => 6
or Array#last
method:
a.last # => 5
b.last # => 6
RewriteRule ^(.*)foobar(.*)$ http://www.example.com/index.php [L,R=301]
(No space inside your website)
If you're checking for a function that is a jQuery plugin, you need to use $.fn.myfunction
if (typeof $.fn.mask === 'function') {
$('.zip').mask('00000');
}
To get the path of the "root" module, you can use:
import os
import sys
os.path.dirname(sys.modules['__main__'].__file__)
But more interestingly if you have an config "object" in your top-most module you could -read- from it like so:
app = sys.modules['__main__']
stuff = app.config.somefunc()
Why are you combining GET and POST? Use one or the other.
$.ajax({
type: 'post',
data: {
timestamp: timestamp,
uid: uid
...
}
});
php:
$uid =$_POST['uid'];
Or, just format your request properly (you're missing the ampersands for the get parameters).
url:"getdata.php?timestamp="+timestamp+"&uid="+id+"&uname="+name,
Add a float to dimens.xml:
<item format="float" name="my_dimen" type="dimen">1.2</item>
To reference from XML:
<EditText
android:lineSpacingMultiplier="@dimen/my_dimen"
...
To read this value programmatically you can use ResourcesCompat.getFloat
from androidx.core
Gradle dependency:
implementation("androidx.core:core:${version}")
Usage:
import androidx.core.content.res.ResourcesCompat;
...
float value = ResourcesCompat.getFloat(context.getResources(), R.dimen.my_dimen);
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
</Console>
<File name="MyFile" fileName="all.log" immediateFlush="false" append="false">
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>
Notes:
Logger logger = LogManager.getLogger();
to initialize your loggerHere's a way to do it in Python without NumPy. Create a function that returns what you want and use a list comprehension, or the map function.
>>> a = [1, 2, 3, -4, 5]
>>> def zero_if_negative(x):
... if x < 0:
... return 0
... return x
...
>>> [zero_if_negative(x) for x in a]
[1, 2, 3, 0, 5]
>>> map(zero_if_negative, a)
[1, 2, 3, 0, 5]
As already stated in earlier answers, ng-pristine
is for indicating that the field has not been modified, whereas ng-dirty
is for telling it has been modified. Why need both?
Let's say we've got a form with phone and e-mail address among the fields. Either phone or e-mail is required, and you also have to notify the user when they've got invalid data in each field. This can be accomplished by using ng-dirty
and ng-pristine
together:
<form name="myForm">
<input name="email" ng-model="data.email" ng-required="!data.phone">
<div class="error"
ng-show="myForm.email.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.email.$invalid && myForm.email.$dirty">
E-mail is invalid
</div>
<input name="phone" ng-model="data.phone" ng-required="!data.email">
<div class="error"
ng-show="myForm.phone.$invalid &&
myForm.email.$pristine &&
myForm.phone.$pristine">Phone or e-mail required</div>
<div class="error"
ng-show="myForm.phone.$invalid && myForm.phone.$dirty">
Phone is invalid
</div>
</form>
window.location.href=window.location.href;
I was facing the same issue, it was because of the cache. You just need to follow these Steps:
File -> Invalidate Caches / Restart
const destroy = container => {
document.getElementById(container).innerHTML = '';
};
Faster previous
const destroyFast = container => {
const el = document.getElementById(container);
while (el.firstChild) el.removeChild(el.firstChild);
};
It works for me, try it.
for /f "tokens=* delims=;" %g in ('echo %PATH%') do echo %g%
use this,it got fixed for me, over centOS 7
<Directory /usr/share/phpMyAdmin/>
Options Indexes FollowSymLinks MultiViews
AllowOverride all
Require all granted
</Directory>
Use single quote with single char as:
char ch = 'a';
here 'a'
is a char constant and is equal to the ASCII
value of char a.
Use double quote with strings as:
char str[] = "foo";
here "foo"
is a string literal.
Its okay to use "a"
but its not okay to use 'foo'
You need to iterate through all the enum values in Animal and return the value that matches the description you need.
From the documentation:
__file__
is the pathname of the file from which the module was loaded, if it was loaded from a file. The__file__
attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.
From the mailing list thread linked by @kindall in a comment to the question:
I haven't tried to repro this particular example, but the reason is that we don't want to have to call getpwd() on every import nor do we want to have some kind of in-process variable to cache the current directory. (getpwd() is relatively slow and can sometimes fail outright, and trying to cache it has a certain risk of being wrong.)
What we do instead, is code in site.py that walks over the elements of sys.path and turns them into absolute paths. However this code runs before '' is inserted in the front of sys.path, so that the initial value of sys.path is ''.
For the rest of this, consider sys.path
not to include ''
.
So, if you are outside the part of sys.path
that contains the module, you'll get an absolute path. If you are inside the part of sys.path
that contains the module, you'll get a relative path.
If you load a module in the current directory, and the current directory isn't in sys.path
, you'll get an absolute path.
If you load a module in the current directory, and the current directory is in sys.path
, you'll get a relative path.
I was having the same problem, finally figured out what to do:
#include <stdio.h>
#include <conio.h>
int main ()
{
int x;
float check;
reprocess:
printf ("enter a integer number:");
scanf ("%f", &check);
x=check;
if (x==check)
printf("\nYour number is %d", x);
else
{
printf("\nThis is not an integer number, please insert an integer!\n\n");
goto reprocess;
}
_getch();
return 0;
}
You will notice you have no value attr in the input
tags.
Also, although not shown, make sure the Javascript is run after the html is in place.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
you can also use $sce.trustAsHtml('"<h1>" + str + "</h1>"')
,if you want to know more detail, please refer to $sce
You cannot install an unsigned application on a phone. You can only use it to test with an emulator. If you still want to go ahead, you can try self-signing the application.
Also, since you are installing the application from an SD card, I hope you have the necessary permissions set. Do go through stackoverflow.com and look at questions regarding installation of applications from an SD card - there have been many and they have been asked before.
Hope that helps.
I was able to adapt these instructions take a table with an existing non-increment primary key, and add an incrementing primary key to the table and create a new composite primary key with both the old and new keys as a composite primary key using the following code:
DROP TABLE IF EXISTS SAKAI_USER_ID_MAP;
CREATE TABLE SAKAI_USER_ID_MAP (
USER_ID VARCHAR (99) NOT NULL,
EID VARCHAR (255) NOT NULL,
PRIMARY KEY (USER_ID)
);
INSERT INTO SAKAI_USER_ID_MAP VALUES ('admin', 'admin');
INSERT INTO SAKAI_USER_ID_MAP VALUES ('postmaster', 'postmaster');
ALTER TABLE SAKAI_USER_ID_MAP
DROP PRIMARY KEY,
ADD _USER_ID INT AUTO_INCREMENT NOT NULL FIRST,
ADD PRIMARY KEY ( _USER_ID, USER_ID );
When this is done, the _USER_ID field exists and has all number values for the primary key exactly as you would expect. With the "DROP TABLE" at the top, you can run this over and over to experiment with variations.
What I have not been able to get working is the situation where there are incoming FOREIGN KEYs that already point at the USER_ID field. I get this message when I try to do a more complex example with an incoming foreign key from another table.
#1025 - Error on rename of './zap/#sql-da07_6d' to './zap/SAKAI_USER_ID_MAP' (errno: 150)
I am guessing that I need to tear down all foreign keys before doing the ALTER table and then rebuild them afterwards. But for now I wanted to share this solution to a more challenging version of the original question in case others ran into this situation.
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
Maybe this works :
Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor')
EDIT: NO LONGER WORKING
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
In PHP the logic equivalent of the MySQL's function now() is time().
But time() return a Unix timestamp that is different from a MySQL DATETIME.
So you must convert the Unix timestamp returned from time() in the MySQL format.
You do it with: date("Y-m-d H:i:s");
But where is time() in the date() function? It's the second parameter: infact you should provide to date() a timestamp as second parameter, but if it is omissed it is defaulted to time().
This is the most complete answer I can imagine.
Greetings.
With es6 syntax you can use:
console.log(`x = ${x}`);
Same problem with Sourcetree On Mac
Solution: Delete the password in keychain access.
When you try to push again it will ask for your password.
I dicovered that my path environmental variable was pointing to java 1.7 while JAVA_HOME was pointing to 1.8, so i edited the path variable to 1.8 and i was fine.
Eloquent uses the query builder internally, so you can do:
$users = User::orderBy('name', 'desc')
->groupBy('count')
->having('count', '>', 100)
->get();
Great Start to learning login forms. You are right, fieldset may not be the best tag.
However, I highly suggest you code it in HTML5 by using its robust form features.
HTML5 is actually easier to learn than older HTML for creating forms.
For example, read the following.
<section class="loginform cf">
<form name="login" action="index_submit" method="get" accept-charset="utf-8">
<ul>
<li><label for="usermail">Email</label>
<input type="email" name="usermail" placeholder="[email protected]" required></li>
<li><label for="password">Password</label>
<input type="password" name="password" placeholder="password" required></li>
<li>
<input type="submit" value="Login"></li>
</ul>
</form>
</section>
Wasn't that easy for you to understand?
Try this http://www.hongkiat.com/blog/html5-loginpage/ and let me know if you have any questions.
Per the documentation from GitHub regarding GFM syntax highlighted code blocks
We use Linguist to perform language detection and syntax highlighting. You can find out which keywords are valid in the languages YAML file.
Rendered on GitHub, console
makes the lines after the console blue. bash
, sh
, or shell
don't seem to "highlight" much ...and you can use posh
for PowerShell or CMD.
An old question, I know, however, none of the answers here really do a good job of simply answer the question.
I just played around with php and the solution looks like this:
function myFunction($requiredArgument, $optionalArgument = "default"){
echo $requiredArgument . $optionalArgument;
}
This function can do two things:
If its called with only the required parameter: myFunction("Hi")
It will print "Hi default"
But if it is called with the optional parameter: myFunction("Hi","me")
It will print "Hi me";
I hope this helps anyone who is looking for this down the road.
Your web pages are served by an application pool. If you disable/stop the application pool, and anyone tries to browse the application, you will get a Service Unavailable. It can happen due to multiple reasons...
Your application may have crashed [check the event viewer and see if you can find event logs in your Application/System log]
Your application may be crashing very frequently. If an app pool crashes for 5 times in 5 minutes [check your application pool settings for rapid fail], your application pool is disabled by IIS and you will end up getting this message.
In either case, the issue is that your worker process is failing and you should troubleshoot it from crash perspective.
What is a Crash (technically)... in ASP.NET and what to do if it happens?
Another option is the sendEmail script http://caspian.dotconf.net/menu/Software/SendEmail/, it also allows you to set the message type as html and include a file as the message body. See the link for details.
Here's an example that reads a list of CSV strings into a list of lists and then loops through that list of lists and prints the CSV strings back out to the console.
import java.util.ArrayList;
import java.util.List;
public class ListExample
{
public static void main(final String[] args)
{
//sample CSV strings...pretend they came from a file
String[] csvStrings = new String[] {
"abc,def,ghi,jkl,mno",
"pqr,stu,vwx,yz",
"123,345,678,90"
};
List<List<String>> csvList = new ArrayList<List<String>>();
//pretend you're looping through lines in a file here
for(String line : csvStrings)
{
String[] linePieces = line.split(",");
List<String> csvPieces = new ArrayList<String>(linePieces.length);
for(String piece : linePieces)
{
csvPieces.add(piece);
}
csvList.add(csvPieces);
}
//write the CSV back out to the console
for(List<String> csv : csvList)
{
//dumb logic to place the commas correctly
if(!csv.isEmpty())
{
System.out.print(csv.get(0));
for(int i=1; i < csv.size(); i++)
{
System.out.print("," + csv.get(i));
}
}
System.out.print("\n");
}
}
}
Pretty straightforward I think. Just a couple points to notice:
I recommend using "List" instead of "ArrayList" on the left side when creating list objects. It's better to pass around the interface "List" because then if later you need to change to using something like Vector (e.g. you now need synchronized lists), you only need to change the line with the "new" statement. No matter what implementation of list you use, e.g. Vector or ArrayList, you still always just pass around List<String>
.
In the ArrayList constructor, you can leave the list empty and it will default to a certain size and then grow dynamically as needed. But if you know how big your list might be, you can sometimes save some performance. For instance, if you knew there were always going to be 500 lines in your file, then you could do:
List<List<String>> csvList = new ArrayList<List<String>>(500);
That way you would never waste processing time waiting for your list to grow dynamically grow. This is why I pass "linePieces.length" to the constructor. Not usually a big deal, but helpful sometimes.
Hope that helps!
shell_exec
- Execute command via shell and return the complete output as a string
exec
- Execute an external program.
The difference is that with shell_exec
you get output as a return value.
Here is a production ready pure JavaScript solution:
<View styles={{backgroundColor: `the main color you want`}}>
<Image source={`A white to transparent gradient png`}>
</View>
Here is the source code of a npm package using this solution: https://github.com/flyskywhy/react-native-smooth-slider/blob/0f18a8bf02e2d436503b9a8ba241440247ef1c44/src/Slider.js#L329
Here is the gradient palette screenshot of saturation and brightness using this npm package: https://github.com/flyskywhy/react-native-slider-color-picker
Try to resolve that with Context.Request:
<img width="150" height="60" src="@($"{Context.Request.Scheme}://{Context.Request.Host}{Context.Request.PathBase}/images/logo.png")" />
In my situation, when I used Content-ID I had that image as an attachment as well, and that was not the best solution.
To second Paul's response: yes, ctags (especially exuberant-ctags (http://ctags.sourceforge.net/)) is great. I have also added this to my vimrc, so I can use one tags file for an entire project:
set tags=tags;/
You can go for this :
getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
If you don't have to use a proxy to JBoss and mydomain.com:8080 can be "exposed" to the world, then I would do this.
<VirtualHost *:80>
ServerName mydomain.com
Redirect 301 / http://mydomain.com:8080/
</VirtualHost>
Trying to use underscore "once" function:
var initialize = _.once(createApplication);
initialize();
initialize();
// Application is only created once.
Just go to the project Properties->Project Facets
Uncheck the dynamic module, click apply.
Maven->update the project.
Answer provided by @jAndy should work but in Firefox you may face problem, window.location.reload(1); might not work, that's my personal experience.
So i would like to suggest:
setTimeout(function() { window.location=window.location;},5000);
This is tested and works fine.
These will also redirect both:
yourcommand &> /dev/null
yourcommand >& /dev/null
though the bash manual says the first is preferred.
The question is quite old so I feel like I need to give a more up to date response to this question.
Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is http://xamarin.com/
From Apple Docs
You can use subscript syntax to retrieve a value from the dictionary for a particular key. Because it is possible to request a key for which no value exists, a dictionary’s subscript returns an optional value of the dictionary’s value type. If the dictionary contains a value for the requested key, the subscript returns an optional value containing the existing value for that key. Otherwise, the subscript returns nil:
if let airportName = airports["DUB"] {
print("The name of the airport is \(airportName).")
} else {
print("That airport is not in the airports dictionary.")
}
// prints "The name of the airport is Dublin Airport."
For someone w/ TF 1.3:
Current TensorFlow 1.3
support Python 3.6
, and then you need cuDNN 6
(cudnn64_6.dll)
Based on Tensorflow on windows - ImportError: DLL load failed: The specified module could not be found and this: https://github.com/tensorflow/tensorflow/issues/7705
make is_edit
of type boolean.
<input [disabled]=is_edit id="name" type="text">
export class App {
name:string;
is_edit: boolean;
constructor() {
this.name = 'Angular2'
this.is_edit = true;
}
}
Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!
Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278
Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
Dim rw As Long, ref
With ThisWorkbook.Sheets(1)
.Cells.Clear
rw = 1
.Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
For Each ref In ThisWorkbook.VBProject.References
rw = rw + 1
.Range("A" & rw & ":D" & rw) = Array(ref.Description, _
"v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
Next ref
.Range("A:D").Columns.AutoFit
End With
End Sub
Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.
Sub ListReferencePaths()
'Macro purpose: To determine full path and Globally Unique Identifier (GUID)
'to each referenced library. Select the reference in the Tools\References
'window, then run this code to get the information on the reference's library
On Error Resume Next
Dim i As Long
Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID"
For i = 1 To ThisWorkbook.VBProject.References.Count
With ThisWorkbook.VBProject.References(i)
Debug.Print .Name & " | " & .FullPath & " | " & .GUID
End With
Next i
On Error GoTo 0
End Sub
This may be a little late; but someone will find it useful.
There's a Nuget Package for integrating AdminLTE - a popular Bootstrap template - to MVC5
Simply run this command in your Visual Studio Package Manager console
Install-Package AdminLteMvc
NB: It may take a while to install because it downloads all necessary files as well as create sample full and partial views (.cshtml files) that can guide you as you develop. A sample layout file _AdminLteLayout.cshtml
is also provided.
You'll find the files in ~/Views/Shared/
folder
Blowfish isn't better than MD5 or SHA512, as they serve different purposes. MD5 and SHA512 are hashing algorithms, Blowfish is an encryption algorithm. Two entirely different cryptographic functions.
Make sure that both projects have same target framework version here: right click on project -> properties -> application (tab) -> target framework
Also, make sure that the project "logger" (which you want to include in the main project) has the output type "Class Library" in: right click on project -> properties -> application (tab) -> output type
Finally, Rebuild the solution.
This will do what you want:
INSERT INTO table2 (st_id,uid,changed,status,assign_status)
SELECT st_id,from_uid,now(),'Pending','Assigned'
FROM table1
If you want to include all rows from table1. Otherwise you can add a WHERE statement to the end if you want to add only a subset of table1.
I hope this helps.
Here's another intuitive way. Suppose we have:
>>> a = np.array([1, 3, 4])
>>> a
array([1, 3, 4])
First we make a 2D array with that as the only row:
>>> a = np.array([a])
>>> a
array([[1, 3, 4]])
Then we can transpose it:
>>> a.T
array([[1],
[3],
[4]])
An improved solution:
# translate long options to short
# Note: This enable long options but disable "--?*" in $OPTARG, or disable long options after "--" in option fields.
for ((i=1;$#;i++)) ; do
case "$1" in
--)
# [ ${args[$((i-1))]} == ... ] || EndOpt=1 ;;& # DIRTY: we still can handle some execptions...
EndOpt=1 ;;&
--version) ((EndOpt)) && args[$i]="$1" || args[$i]="-V";;
# default case : short option use the first char of the long option:
--?*) ((EndOpt)) && args[$i]="$1" || args[$i]="-${1:2:1}";;
# pass through anything else:
*) args[$i]="$1" ;;
esac
shift
done
# reset the translated args
set -- "${args[@]}"
function usage {
echo "Usage: $0 [options] files" >&2
exit $1
}
# now we can process with getopt
while getopts ":hvVc:" opt; do
case $opt in
h) usage ;;
v) VERBOSE=true ;;
V) echo $Version ; exit ;;
c) source $OPTARG ;;
\?) echo "unrecognized option: -$opt" ; usage -1 ;;
:)
echo "option -$OPTARG requires an argument"
usage -1
;;
esac
done
shift $((OPTIND-1))
[[ "$1" == "--" ]] && shift
In that code you are inserting two column value. You can try this
INSERT INTO Data ( Col1 ) VALUES ('Hello'),
INSERT INTO Data ( Col1 ) VALUES ('World')
Sometimes it is not desirable to use interpolation on title attribute or on any other attributes as for that matter, because they get parsed before the interpolation takes place. So:
<!-- dont do this -->
<!-- <a title="{{product.shortDesc}}" ...> -->
If an attribute with a binding is prefixed with the ngAttr prefix (denormalized as ng-attr-) then during the binding will be applied to the corresponding unprefixed attribute. This allows you to bind to attributes that would otherwise be eagerly processed by browsers. The attribute will be set only when the binding is done. The prefix is then removed:
<!-- do this -->
<a ng-attr-title="{{product.shortDesc}}" ...>
(Ensure that you are not using a very earlier version of Angular). Here's a demo fiddle using v1.2.2:
Make sure you use latest rvm:
rvm get stable
Then you can do two things:
Update certificates:
rvm osx-ssl-certs update all
Update rubygems:
rvm rubygems latest
Find path for certificate:
cert_file=$(ruby -ropenssl -e 'puts OpenSSL::X509::DEFAULT_CERT_FILE')
Generate certificate:
security find-certificate -a -p /Library/Keychains/System.keychain > "$cert_file"
security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> "$cert_file"
The whole code: https://github.com/wayneeseguin/rvm/blob/master/scripts/functions/osx-ssl-certs
Make sure to update package ca-certificates
. (on old systems it might not be available - do not use an old system which does not receive security updates any more)
The Ruby Installer builds for windows are prepared by Luis Lavena and the path to certificates will be showing something like C:/Users/Luis/...
check https://github.com/oneclick/rubyinstaller/issues/249 for more details and this answer https://stackoverflow.com/a/27298259/497756 for fix.
Here is a static class implementing Start(), Stop(), and IsStarted() for IISExpress. It is parametrized by hard-coded static properties and passes invocation information via the command-line arguments to IISExpress. It uses the Nuget package, MissingLinq.Linq2Management, which surprisingly provides information missing from System.Diagnostics.Process, specifically, the command-line arguments that can then be used to help disambiguate possible multiple instances of IISExpress processes, since I don't preserve the process Ids. I presume there is a way to accomplish the same thing with just System.Diagnostics.Process, but life is short. Enjoy.
using System.Diagnostics;
using System.IO;
using System.Threading;
using MissingLinq.Linq2Management.Context;
using MissingLinq.Linq2Management.Model.CIMv2;
public static class IisExpress
{
#region Parameters
public static string SiteFolder = @"C:\temp\UE_Soln_7\Spc.Frm.Imp";
public static uint Port = 3001;
public static int ProcessStateChangeDelay = 10 * 1000;
public static string IisExpressExe = @"C:\Program Files (x86)\IIS Express\iisexpress.exe";
#endregion
public static void Start()
{
Process.Start(InvocationInfo);
Thread.Sleep(ProcessStateChangeDelay);
}
public static void Stop()
{
var p = GetWin32Process();
if (p == null) return;
var pp = Process.GetProcessById((int)p.ProcessId);
if (pp == null) return;
pp.Kill();
Thread.Sleep(ProcessStateChangeDelay);
}
public static bool IsStarted()
{
var p = GetWin32Process();
return p != null;
}
static readonly string ProcessName = Path.GetFileName(IisExpressExe);
static string Quote(string value) { return "\"" + value.Trim() + "\""; }
static string CmdLine =
string.Format(
@"/path:{0} /port:{1}",
Quote(SiteFolder),
Port
);
static readonly ProcessStartInfo InvocationInfo =
new ProcessStartInfo()
{
FileName = IisExpressExe,
Arguments = CmdLine,
WorkingDirectory = SiteFolder,
CreateNoWindow = false,
UseShellExecute = true,
WindowStyle = ProcessWindowStyle.Minimized
};
static Win32Process GetWin32Process()
{
//the linq over ManagementObjectContext implementation is simplistic so we do foreach instead
using (var mo = new ManagementObjectContext())
foreach (var p in mo.CIMv2.Win32Processes)
if (p.Name == ProcessName && p.CommandLine.Contains(CmdLine))
return p;
return null;
}
}
It is simple actually, like C programming you just need to pass the array indices on the right hand side while declaration. But yeah the syntax will be like [0:3] for 4 elements.
reg a[0:3];
This will create a 1D of array of single bit. Similarly 2D array can be created like this:
reg [0:3][0:2];
Now in C suppose you create a 2D array of int, then it will internally create a 2D array of 32 bits. But unfortunately Verilog is an HDL, so it thinks in bits rather then bunch of bits (though int datatype is there in Verilog), it can allow you to create any number of bits to be stored inside an element of array (which is not the case with C, you can't store 5-bits in every element of 2D array in C). So to create a 2D array, in which every individual element can hold 5 bit value, you should write this:
reg [0:4] a [0:3][0:2];
I know this is old, but i think i have good solution. Comparing to other answers and also comparing to accepted, mine accepts multiple values. Basically filter object with key:value search parameters (also object within object). Also it works with numbers etc, cause when comparing, it converts them to string.
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({name: 'filter'})
export class Filter implements PipeTransform {
transform(array: Array<Object>, filter: Object): any {
let notAllKeysUndefined = false;
let newArray = [];
if(array.length > 0) {
for (let k in filter){
if (filter.hasOwnProperty(k)) {
if(filter[k] != undefined && filter[k] != '') {
for (let i = 0; i < array.length; i++) {
let filterRule = filter[k];
if(typeof filterRule === 'object') {
for(let fkey in filterRule) {
if (filter[k].hasOwnProperty(fkey)) {
if(filter[k][fkey] != undefined && filter[k][fkey] != '') {
if(this.shouldPushInArray(array[i][k][fkey], filter[k][fkey])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
} else {
if(this.shouldPushInArray(array[i][k], filter[k])) {
newArray.push(array[i]);
}
notAllKeysUndefined = true;
}
}
}
}
}
if(notAllKeysUndefined) {
return newArray;
}
}
return array;
}
private shouldPushInArray(item, filter) {
if(typeof filter !== 'string') {
item = item.toString();
filter = filter.toString();
}
// Filter main logic
item = item.toLowerCase();
filter = filter.toLowerCase();
if(item.indexOf(filter) !== -1) {
return true;
}
return false;
}
}
Easy way, just write some wrong code and Run > Build it will show the error in output window.
I tried all of the above but no success, just this one worked.
Do something like this,
HTML :
<div style="width:500px;">
<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
</div>
CSS :
div button{
display:inline-block;
}
Or
HTML :
<div style="width:500px;" id="container">
<div><button type="submit" class="msgBtn" onClick="return false;" >Save</button></div>
<div><button type="submit" class="msgBtn2" onClick="return false;">Publish</button></div>
<div><button class="msgBtnBack">Back</button></div>
</div>
CSS :
#container div{
display:inline-block;
width:130px;
}
Download xcode 10.2 from below link https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_10.2/Xcode_10.2.xip
Edit: Minimum System Version* to 10.13.6 in Info.plist at below paths
Xcode.app/Contents/Info.plist
Xcode.app/Contents/Developer/Applications/Simulator.app/Contents/Info.plist
Replace: Xcode.app/Contents/Developer/usr/bin/xcodebuild
from Xcode 10
****OR*****
you can install disk image of 12.2 in your existing xcode to run on 12.2 devices Download disk image from here https://github.com/xushuduo/Xcode-iOS-Developer-Disk-Image/releases/download/12.2/12.2.16E5191d.zip
And paste at Path: /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/DeviceSupport
Note: Restart the Xcode
There is an open issue to only print this warning if there was actually something sanitized: https://github.com/angular/angular/pull/10272
I didn't read in detail when this warning is printed when nothing was sanitized.
You have to put file extension here
File file = new File("10_Random.txt");
Any class which extends Exception
class will be a user defined Checked exception class where as any class which extends RuntimeException
will be Unchecked exception class.
as mentioned in User defined exception are checked or unchecked exceptions
So, not throwing the checked exception(be it user-defined or built-in exception) gives compile time error.
Checked exception are the exceptions that are checked at compile time.
Unchecked exception are the exceptions that are not checked at compiled time
There's filter_var()
as well and it's the native function which checks range. It doesn't give exactly what you want (never returns true), but with "cheat" we can change it.
I don't think it's a good code as for readability, but I show it's as a possibility:
return (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]]) !== false)
Just fill $someNumber
, $min
and $max
. filter_var
with that filter returns either boolean false when number is outside range or the number itself when it's within range. The expression (!== false
) makes function return true, when number is within range.
If you want to shorten it somehow, remember about type casting. If you would use !=
it would be false for number 0 within range -5; +5 (while it should be true). The same would happen if you would use type casting ((bool)
).
// EXAMPLE OF WRONG USE, GIVES WRONG RESULTS WITH "0"
(bool)filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])
if (filter_var($someNumber, FILTER_VALIDATE_INT, ['options' => ['min_range' => $min, 'max_range' => $max]])) ...
Imagine that (from other answer):
if(in_array($userScore, range(-5, 5))) echo 'your score is correct'; else echo 'incorrect, enter again';
If user would write empty value ($userScore = ''
) it would be correct, as in_array
is set here for default, non-strict more and that means that range creates 0
as well, and '' == 0
(non-strict), but '' !== 0
(if you would use strict mode). It's easy to miss such things and that's why I wrote a bit about that. I was learned that strict operators are default, and programmer could use non-strict only in special cases. I think it's a good lesson. Most examples here would fail in some cases because non-strict checking.
Still I like filter_var and you can use above (or below if I'd got so "upped" ;)) functions and make your own callback which you would use as FILTER_CALLBACK
filter. You could return bool or even add openRange
parameter. And other good point: you can use other functions, e.g. checking range of every number of array or POST/GET values. That's really powerful tool.
In TypeScript or using Babel, you can import json file in your code.
// Babel
import * as data from './example.json';
const word = data.name;
console.log(word); // output 'testing'
Reference: https://hackernoon.com/import-json-into-typescript-8d465beded79
There is no standard unfortunately, this is one of the perils of installing from source. Some Makefiles will include an "uninstall", so
make uninstall
from the source directory may work. Otherwise, it may be a matter of manually undoing whatever the make install
did.
make clean
usually just cleans up the source directory - removing generated/compiled files and the like, probably not what you're after.
This expands on @Reigel's answer. It will return an answer for horizontal or vertical scrollbars.
(function($) {
$.fn.hasScrollBar = function() {
var e = this.get(0);
return {
vertical: e.scrollHeight > e.clientHeight,
horizontal: e.scrollWidth > e.clientWidth
};
}
})(jQuery);
Example:
element.hasScrollBar() // Returns { vertical: true/false, horizontal: true/false }
element.hasScrollBar().vertical // Returns true/false
element.hasScrollBar().horizontal // Returns true/false
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
Yes! By passing a stream context in the third parameter:
Here with a timeout of 1s:
file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));
Source in comment section of https://www.php.net/manual/en/function.file-get-contents.php
method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Other contexts: https://www.php.net/manual/en/context.php
For newer android versions that support setting permissions per app (since Marshmallow, 6.0) the permission for camera could be disabled and should be enabled from the app settings.
I just want to highlight the power of C#'s Split method and give a more detailed comparison, particularly from someone who comes from a Java background.
Whereas StringTokenizer in Java only allows a single delimiter, we can actually split on multiple delimiters making regular expressions less necessary (although if one needs regex, use regex by all means!) Take for example this:
str.Split(new char[] { ' ', '.', '?' })
This splits on three different delimiters returning an array of tokens. We can also remove empty arrays with what would be a second parameter for the above example:
str.Split(new char[] { ' ', '.', '?' }, StringSplitOptions.RemoveEmptyEntries)
One thing Java's String tokenizer does have that I believe C# is lacking (at least Java 7 has this feature) is the ability to keep the delimiter(s) as tokens. C#'s Split will discard the tokens. This could be important in say some NLP applications, but for more general purpose applications this might not be a problem.
Use this method:
app.run(debug=True)
It will auto-reload the flask app when a code change happens.
Sample code:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def index():
return "Hello World"
if __name__ == '__main__':
app.run(debug=True)
Well, if you want save time not reloading the webpage everytime when changes happen, then you can try the keyboard shortcut Ctrl + R
to reload the page quickly.
Something like this should do it:
.column-left{ float: left; width: 33.333%; }
.column-right{ float: right; width: 33.333%; }
.column-center{ display: inline-block; width: 33.333%; }
EDIT
To do this with a larger number of columns you could build a very simple grid system. For example, something like this should work for a five column layout:
.column {_x000D_
float: left;_x000D_
position: relative;_x000D_
width: 20%;_x000D_
_x000D_
/*for demo purposes only */_x000D_
background: #f2f2f2;_x000D_
border: 1px solid #e6e6e6;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.column-offset-1 {_x000D_
left: 20%;_x000D_
}_x000D_
.column-offset-2 {_x000D_
left: 40%;_x000D_
}_x000D_
.column-offset-3 {_x000D_
left: 60%;_x000D_
}_x000D_
.column-offset-4 {_x000D_
left: 80%;_x000D_
}_x000D_
_x000D_
.column-inset-1 {_x000D_
left: -20%;_x000D_
}_x000D_
.column-inset-2 {_x000D_
left: -40%;_x000D_
}_x000D_
.column-inset-3 {_x000D_
left: -60%;_x000D_
}_x000D_
.column-inset-4 {_x000D_
left: -80%;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="column column-one column-offset-2">Column one</div>_x000D_
<div class="column column-two column-inset-1">Column two</div>_x000D_
<div class="column column-three column-offset-1">Column three</div>_x000D_
<div class="column column-four column-inset-2">Column four</div>_x000D_
<div class="column column-five">Column five</div>_x000D_
</div>
_x000D_
Or, if you are lucky enough to be able to support only modern browsers, you can use flexible boxes:
.container {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
.column {_x000D_
flex: 1;_x000D_
_x000D_
/*for demo purposes only */_x000D_
background: #f2f2f2;_x000D_
border: 1px solid #e6e6e6;_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.column-one {_x000D_
order: 3;_x000D_
}_x000D_
.column-two {_x000D_
order: 1;_x000D_
}_x000D_
.column-three {_x000D_
order: 4;_x000D_
}_x000D_
.column-four {_x000D_
order: 2;_x000D_
}_x000D_
.column-five {_x000D_
order: 5;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="column column-one">Column one</div>_x000D_
<div class="column column-two">Column two</div>_x000D_
<div class="column column-three">Column three</div>_x000D_
<div class="column column-four">Column four</div>_x000D_
<div class="column column-five">Column five</div>_x000D_
</div>
_x000D_
HashMap<Emp, Emp> empHashMap = new HashMap<Emp, Emp>();
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp(1));
empHashMap.put(new Emp(1), new Emp());
empHashMap.put(new Emp(1), new Emp());
System.out.println(empHashMap.size());
}
}
class Emp{
public Emp(){
}
public Emp(int id){
this.id = id;
}
public int id;
@Override
public boolean equals(Object obj) {
return this.id == ((Emp)obj).id;
}
@Override
public int hashCode() {
return id;
}
}
OUTPUT : is 1
Means hash map wont allow duplicates, if you have properly overridden equals and hashCode() methods.
HashSet also uses HashMap internally, see the source doc
public class HashSet{
public HashSet() {
map = new HashMap<>();
}
}
If you get this from a Webserver, check out jQuery. You can load it, using the Ajax load function and select the node or text you want, using Selectors.
If you don't want to do this in a http environment or avoid using jQuery, please explain in greater detail.
I disagree with the predicate
if not orgs:
It should be
if not orgs.count():
I was having the same issue with a fairly large result set (~150k results). The operator is not overloaded in QuerySet, so the result is actually unpacked as a list before the check is made. In my case execution time went down by three orders.
You have to use the jquery's text() function. What it does is:
Get the combined text contents of all matched elements.
The result is a string that contains the combined text contents of all matched elements. This method works on both HTML and XML documents. Cannot be used on input elements. For input field text use the val attribute.
For example:
Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the bold is gone).
var str = $("p:first").text(); $("p:last").html(str);
Test Paragraph.
Test Paragraph.
With your markup you have to do:
$('a#a_tbnotesverbergen').text('new text');
and it will result in
<a id="a_tbnotesverbergen" href="#nothing">new text</a>
Ah, the following works and does what I want:
configurations {
runtime.exclude group: "org.slf4j", module: "slf4j-log4j12"
}
It seems that an Exclude Rule only has two attributes - group
and module
. However, the above syntax doesn't prevent you from specifying any arbitrary property as a predicate. When trying to exclude from an individual dependency you cannot specify arbitrary properties. For example, this fails:
dependencies {
compile ('org.springframework.data:spring-data-hadoop-core:2.0.0.M4-hadoop22') {
exclude group: "org.slf4j", name: "slf4j-log4j12"
}
}
with
No such property: name for class: org.gradle.api.internal.artifacts.DefaultExcludeRule
So even though you can specify a dependency with a group:
and name:
you can't specify an exclusion with a name:
!?!
Perhaps a separate question, but what exactly is a module then? I can understand the Maven notion of groupId:artifactId:version, which I understand translates to group:name:version in Gradle. But then, how do I know what module (in gradle-speak) a particular Maven artifact belongs to?
I could happen that if your array contains the string "hello", and if you are searching for "he", grep returns true, although, "he" may not be an array element.
Perhaps,
if (grep(/^$match$/, @array))
more apt.
You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.
To fix this, restart your interpreter.
Python 2.7.3 (default, Apr 20 2012, 22:44:07)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168
If you shadow the sum
builtin, you can get the error you are seeing
>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
Also, note that sum
will work fine on the set
there is no need to convert it to a list
It is ClassLoader responsible to load the class files.Let's see what happens when we write our own classes.
Example 1:
class StaticTest {
static int a;
int b;
int c;
}
Now we can see that class "StaticTest" has 3 fields.But actually there is no existence of b,c member variable.But why ???. OK Lest's see. Here b,c are instance variable.Since instance variable gets the memory at the time of object creation. So here b,c are not getting any memory yet. That's why there is no existence of b,c. So There is only existence of a. For ClassLoader it has only one information about a. ClassLoader yet not recognize b,c because it's object not instantiated yet.
Let's see another example: Example 2:
class StaticTest {
public void display() {
System.out.println("Static Test");
}
public static void main(String []cmd) {
display();
}
}
Now if we try to compile this code compiler will give CE error. CE: non-static method display() cannot be referenced from a static context.
Now For ClassLoader it looks like:
class StaticTest {
public static void main(String []cmd) {
display();
}
}
In Example 2 CE error is because we call non static method from a static context. So it is not possible for ClassLoader to recognize method display() at compile time.So compile time error is occurred.
Well nobody answered - which is in part the fault of the question : the input string contains eleven fields (this much can be inferred) but how many tabs ? Most possibly exactly 10. Then the answer is
String s = "\t2\t\t4\t5\t6\t\t8\t\t10\t";
String[] fields = s.split("\t", -1); // in your case s.split("\t", 11) might also do
for (int i = 0; i < fields.length; ++i) {
if ("".equals(fields[i])) fields[i] = null;
}
System.out.println(Arrays.asList(fields));
// [null, 2, null, 4, 5, 6, null, 8, null, 10, null]
// with s.split("\t") : [null, 2, null, 4, 5, 6, null, 8, null, 10]
If the fields happen to contain tabs this won't work as expected, of course.
The -1
means : apply the pattern as many times as needed - so trailing fields (the 11th) will be preserved (as empty strings (""
) if absent, which need to be turned to null
explicitly).
If on the other hand there are no tabs for the missing fields - so "5\t6"
is a valid input string containing the fields 5,6 only - there is no way to get the fields[]
via split.
You can use also archive this with the Fastify framework:
const { readFileSync } = require('fs')
const Fastify = require('fastify')
const fastify = Fastify({
https: {
key: readFileSync('./test/asset/server.key'),
cert: readFileSync('./test/asset/server.cert')
},
logger: { level: 'debug' }
})
fastify.listen(8080)
(and run openssl req -nodes -new -x509 -keyout server.key -out server.cert
to create the files if you need to write tests)
Alternatively YUI has http://yuilibrary.com/yui/docs/api/classes/QueryString.html#method_stringify.
For example:
var data = { one: 'first', two: 'second' };
var result = Y.QueryString.stringify(data);
A VIP swap is an internal change to Azure's routers/load balancers, not an external DNS change. They're just routing traffic to go from one internal [set of] server[s] to another instead. Therefore the DNS info for mysite.cloudapp.net doesn't change at all. Therefore the change for people accessing via the IP bound to mysite.cloudapp.net (and CNAME'd by you) will see the change as soon as the VIP swap is complete.
In C++11, you can do this as a one-liner with a call to regex_replace
:
#include <string>
#include <regex>
using std::string;
string do_replace( string const & in, string const & from, string const & to )
{
return std::regex_replace( in, std::regex(from), to );
}
string test = "Remove all spaces";
std::cout << do_replace(test, " ", "") << std::endl;
output:
Removeallspaces
You should make your audioSounds and minTime members static:
public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;
But I would consider using singleton objects instead of static members instead:
public class SoundManager : MonoBehaviour
{
public List<AudioSource> audioSounds = new List<AudioSource>();
public double minTime = 0.5;
public static SoundManager Instance { get; private set; }
void Awake()
{
Instance = this;
}
public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
{
bool playsound = false;
foreach (AudioSource sound in audioSounds) // Loop through List with foreach
{
if (sourceSound.name != sound.name && sound.time <= minTime)
{
playsound = true;
}
}
if(playsound) {
AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
}
}
}
Update from September 2020:
Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.
If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.
Try this in pure bash:
FRED="/some/random/file.csv:some string"
a=${FRED%:*}
echo $a
Here is some documentation that helps.
Is this what you're looking for?
If you start execution with gc logging turned on you get the info on file. Otherwise 'jmap -heap ' will give you what you want. See the jmap doc page for more.
Please note that jmap
should not be used in a production environment unless absolutely needed as the tool halts the application to be able to determine actual heap usage. Usually this is not desired in a production environment.
Using new api fetch:
const dataToSend = JSON.stringify({"email": "[email protected]", "password": "101010"});
let dataReceived = "";
fetch("", {
credentials: "same-origin",
mode: "same-origin",
method: "post",
headers: { "Content-Type": "application/json" },
body: dataToSend
})
.then(resp => {
if (resp.status === 200) {
return resp.json()
} else {
console.log("Status: " + resp.status)
return Promise.reject("server")
}
})
.then(dataJson => {
dataReceived = JSON.parse(dataJson)
})
.catch(err => {
if (err === "server") return
console.log(err)
})
console.log(`Received: ${dataReceived}`)
_x000D_
Use the traceback module:
import sys
import traceback
try:
assert True
assert 7 == 7
assert 1 == 2
# many more statements like this
except AssertionError:
_, _, tb = sys.exc_info()
traceback.print_tb(tb) # Fixed format
tb_info = traceback.extract_tb(tb)
filename, line, func, text = tb_info[-1]
print('An error occurred on line {} in statement {}'.format(line, text))
exit(1)
A dplyr
solution:
library(dplyr)
ID <- c(1,1,1,2,2,2,2,3,3)
Value <- c(2,3,5,2,5,8,17,3,5)
Event <- c(1,1,2,1,2,1,2,2,2)
group <- data.frame(Subject=ID, pt=Value, Event=Event)
group %>%
group_by(Subject) %>%
summarize(max.pt = max(pt))
This yields the following data frame:
Subject max.pt
1 1 5
2 2 17
3 3 5
You can use File.WriteAllBytes
Found method to see your own html file (from here (scroll down to answer from prac): https://productforums.google.com/forum/#!topic/drive/YY_fou2vo0A)
-- use Get Link to get URL with id=... substring -- put uc instead of open in URL
The problem you're running into is that most background thread / worker APIs will create the thread in a Multithreaded Apartment state. The error message indicates that the control requires the thread be a Single Threaded Apartment.
You can work around this by creating a thread yourself and specifying the STA apartment state on the thread.
var t = new Thread(MyThreadStartMethod);
t.SetApartmentState(ApartmentState.STA);
t.Start();
We have function that creates a table variable that you can join to:
ALTER FUNCTION [dbo].[Fn_sqllist_to_table](@list AS VARCHAR(8000),
@delim AS VARCHAR(10))
RETURNS @listTable TABLE(
Position INT,
Value VARCHAR(8000))
AS
BEGIN
DECLARE @myPos INT
SET @myPos = 1
WHILE Charindex(@delim, @list) > 0
BEGIN
INSERT INTO @listTable
(Position,Value)
VALUES (@myPos,LEFT(@list, Charindex(@delim, @list) - 1))
SET @myPos = @myPos + 1
IF Charindex(@delim, @list) = Len(@list)
INSERT INTO @listTable
(Position,Value)
VALUES (@myPos,'')
SET @list = RIGHT(@list, Len(@list) - Charindex(@delim, @list))
END
IF Len(@list) > 0
INSERT INTO @listTable
(Position,Value)
VALUES (@myPos,@list)
RETURN
END
So:
@Name varchar(8000) = null // parameter for search values
select * from Tags
where Name in (SELECT value From fn_sqllist_to_table(@Name,',')))
order by Count desc
I tried hard, but this seems to work (assuming \r
is biting you here):
printf "\r" | egrep -xv "[[:space:]]*"
For Linux Run this command
date -d '06/12/2012 07:21:22' +"%s"
For mac OSX run this command
date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"
I solved this by doing the following:
<body class="container-fluid">
<div class="row">
<div class="span6" style="float: none; margin: 0 auto;">
....
</div>
</div>
</body>
I use JarExplorer or JarVisualizer.
How about something like this.
function objectToArray( $object ){
if( !is_object( $object ) && !is_array( $object ) ){
return $object;
}
if( is_object( $object ) ){
$object = get_object_vars( $object );
}
return array_map( 'objectToArray', $object );
}
and call this function with your object
$array = objectToArray( $yourObject );
After the update you have done,
Earlier you were only returning JSON to browser without rendering any HTML. Now it has a HTML view rendered where it can get your JSON Data.
You can't directly render JSON its plain data not HTML.
str_replace('"', "", $string);
str_replace("'", "", $string);
I assume you mean quotation marks?
Otherwise, go for some regex, this will work for html quotes for example:
preg_replace("/<!--.*?-->/", "", $string);
C-style quotes:
preg_replace("/\/\/.*?\n/", "\n", $string);
CSS-style quotes:
preg_replace("/\/*.*?\*\//", "", $string);
bash-style quotes:
preg-replace("/#.*?\n/", "\n", $string);
Etc etc...
Update your Android Support Repository from sdk manager.
If you run docker run <NAME>
it will spawn a new image, which most likely isn't what you want.
If you want to change a current image do the following:
docker ps -a
Take the id of your target container and go to:
cd /var/lib/docker/containers/<conainerID><and then some:)>
Stop the container:
docker stop <NAME>
Change the files
vi config.v2.json
"Config": {
....
"ExposedPorts": {
"80/tcp": {},
"8888/tcp": {}
},
....
},
"NetworkSettings": {
....
"Ports": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
],
And change file
vi hostconfig.json
"PortBindings": {
"80/tcp": [
{
"HostIp": "",
"HostPort": "80"
}
],
"8888/tcp": [
{
"HostIp": "",
"HostPort": "8888"
}
]
}
Restart your docker and it should work.
I'd like to mention that there are alternatives to the global JSON object.
JSON.parse
and JSON.stringify
are both synchronous, so if you want to deal with big objects you might want to check out some of the asynchronous JSON modules.
Have a look: https://github.com/joyent/node/wiki/Modules#wiki-parsers-json
Well, it depends on what language you are using, but in general they are 2 separate configurations, each with its own settings. By default, Debug includes debug information in the compiled files (allowing easy debugging) while Release usually has optimizations enabled.
As far as conditional compilation goes, they each define different symbols that can be checked in your program, but they are language-specific macros.
You didn't include the priority argument
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3 5
You can replace 5 with any priority you want. A higher priority alternative takes precedence over lower priority.
you can use distutils.util.strtobool
>>> from distutils.util import strtobool
>>> strtobool('True')
1
>>> strtobool('False')
0
True
values are y
, yes
, t
, true
, on
and 1
; False
values are n
, no
, f
, false
, off
and 0
. Raises ValueError
if val is anything else.
Example with primitive array:
public static void permute(int[] intArray, int start) {
for(int i = start; i < intArray.length; i++){
int temp = intArray[start];
intArray[start] = intArray[i];
intArray[i] = temp;
permute(intArray, start + 1);
intArray[i] = intArray[start];
intArray[start] = temp;
}
if (start == intArray.length - 1) {
System.out.println(java.util.Arrays.toString(intArray));
}
}
public static void main(String[] args){
int intArr[] = {1, 2, 3};
permute(intArr, 0);
}
You did the right thing by checking from query plans. But I have 100% confidence in version 2. It is faster when the number off records are on the very high side.
My database has around 1,000,000 records and this is exactly the scenario where the query plan shows the difference between both the queries.
Further, instead of using a where clause, if you use it in the join itself, it makes the query faster :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID
WHERE p.isactive = 1
The better version of this query is :
SELECT p.Name, s.OrderQty
FROM Product p
INNER JOIN (SELECT ProductID, OrderQty FROM SalesOrderDetail) s on p.ProductID = s.ProductID AND p.isactive = 1
(Assuming isactive is a field in product table which represents the active/inactive products).
This is solution of a similar question from hackerrank. I hope this could help you.
import re
a = input()
b = input()
if b not in a:
print((-1,-1))
else:
#create two list as
start_indc = [m.start() for m in re.finditer('(?=' + b + ')', a)]
for i in range(len(start_indc)):
print((start_indc[i], start_indc[i]+len(b)-1))
Output:
aaadaa
aa
(0, 1)
(1, 2)
(4, 5)
catch (Exception ex)
{
if (!(
ex is FormatException ||
ex is OverflowException))
{
throw;
}
Console.WriteLine("Hello");
}
Strange but, Try with @Value
, capital "V"
e.g. (working on MVC4)
@Html.HiddenFor(m => m.Id, new { @Value = Model.Id })
Update:
Found that @Value (capital V) is creating another attribute with "Value" along with "value", using small @value seems to be working too!
Need to check the MVC source code to find more.
Update, After going through how it works internally:
First of all forget all these workarounds (I have kept in for the sake of continuity here), now looks silly :)
Basically, it happens when a model is posted and the model is returned back to same page.
The value is accessed (and formed into html) in InputHelper method (InputExtensions.cs) using following code fragment
string attemptedValue = (string)htmlHelper.GetModelStateValue(fullName, typeof(string));
The GetModelStateValue method (in Htmlelper.cs) retrieves the value as
ViewData.ModelState.TryGetValue(key, out modelState)
Here is the issue, since the value is accessed from ViewData.ModelState
dictionary.
This returns the value posted from the page instead of modified value!!
i.e. If your posted value of the variable (e.g. Person.Id) is 0 but you set the value inside httpPost action (e.g. Person.Id = 2), the ModelState still retains the old value "0" and the attemptedValue contains "0" ! so the field in rendered page will contain "0" as value!!
Workaround if you are returning model to same page : Clear the item from ModelState,
e.g.
ModelState.Remove("Id");
This will remove the item from dictionary and the ViewData.ModelState.TryGetValue(key, out modelState) returns null, and the next statement (inside InputExtensions.cs) takes the actual value (valueParameter) passed to HiddenFor(m => m.Id)
this is done in the following line in InputExtensions.cs
tagBuilder.MergeAttribute("value", attemptedValue ?? ((useViewData) ? htmlHelper.EvalString(fullName, format) : valueParameter), isExplicitValue);
Summary:
Clear the item in ModelState using:
ModelState.Remove("...");
Hope this is helpful.
In newer Facebook SDK, the login and logout text name is :
<com.facebook.login.widget.LoginButton
xmlns:facebook="http://schemas.android.com/apk/res-auto"
facebook:com_facebook_login_text=""
facebook:com_facebook_logout_text=""/>
To build on JJC's helpful answer that builds on Louis's helpful answer...
With PhantomJS 2.1.1-windows this line works:
driver.execute_script("return navigator.userAgent")
If it doesn't work, you can still get the user agent via the log (to build on Mma's answer):
from selenium import webdriver
import json
from fake_useragent import UserAgent
dcap = dict(DesiredCapabilities.PHANTOMJS)
dcap["phantomjs.page.settings.userAgent"] = (UserAgent().random)
driver = webdriver.PhantomJS(executable_path=r"your_path", desired_capabilities=dcap)
har = json.loads(driver.get_log('har')[0]['message']) # get the log
print('user agent: ', har['log']['entries'][0]['request']['headers'][1]['value'])
auto
keyword is intended to use in such situation, it is absolutely safe. But unfortunately it available only in C++0x so you will have portability issues with it.
you can change the size of an icon using the font size rather than setting the height and width of an icon. Here is how you do it:
<i class="fa fa-minus-square-o" style="font-size: 0.73em;"></i>
There are 4 ways to specify the dimensions of the icon.
px : give fixed pixels to your icon
em : dimensions with respect to your current font. Say ur current font is 12px then 1.5em will be 18px (12px + 6px).
pt : stands for points. Mostly used in print media
% : percentage. Refers to the size of the icon based on its original size.
This is the key:
header("Content-Type: application/octet-stream");
Content-type application/x-pdf-document or application/pdf is sent while sending PDF file. Adobe Reader usually sets the handler for this MIME type so browser will pass the document to Adobe Reader when any of PDF MIME types is received.
There's no need to use a third-party library since Google introduced the TextInputLayout
as part of the design-support-library
.
Following a basic example:
<android.support.design.widget.TextInputLayout
android:id="@+id/text_input_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:errorEnabled="true">
<android.support.design.widget.TextInputEditText
android:id="@+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter your name" />
</android.support.design.widget.TextInputLayout>
Note: By setting app:errorEnabled="true"
as an attribute of the TextInputLayout
it won't change it's size once an error is displayed - so it basically blocks the space.
In order to show the Error below the EditText
you simply need to call #setError
on the TextInputLayout
(NOT on the child EditText
):
TextInputLayout til = (TextInputLayout) findViewById(R.id.text_input_layout);
til.setError("You need to enter a name");
To hide the error and reset the tint simply call til.setError(null)
.
In order to use the TextInputLayout
you have to add the following to your build.gradle
dependencies:
dependencies {
compile 'com.android.support:design:25.1.0'
}
By default the line of the EditText
will be red. If you need to display a different color you can use the following code as soon as you call setError
.
editText.getBackground().setColorFilter(getResources().getColor(R.color.red_500_primary), PorterDuff.Mode.SRC_ATOP);
To clear it simply call the clearColorFilter
function, like this:
editText.getBackground().clearColorFilter();
If you are running LOAD DATA LOCAL INFILE
from the windows shell, and you need to use OPTIONALLY ENCLOSED BY '"'
, you will have to do something like this in order to escape characters properly:
"C:\Program Files\MySQL\MySQL Server 5.6\bin\mysql" -u root --password=%password% -e "LOAD DATA LOCAL INFILE '!file!' INTO TABLE !table! FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"^""' LINES TERMINATED BY '\n' IGNORE 1 LINES" --verbose --show-warnings > mysql_!fname!.out
What about detached or unrelated shells and code [args]
support?
While other answers talk about how to configure and use the VScode integrated WSL bash
terminal support, they don't solve the problem of "detached shells": shells which were not launched from within VScode, or which somehow get "disconnected" from the VScode server instance associated with the IDE.
Such shells can give errors like:
Command is only available in WSL or inside a Visual Studio Code terminal.
or...
Unable to connect to VS Code server.
Error in request
Here's a script which makes it easy to solve this problem.
I use this daily to connect shells in a tmux
session with a specific VScode server instance, or to fix an integrated shell that's become detached from its hosting IDE.
#!/bin/bash
# codesrv-connect
#
# Purpose:
# Copies the vscode connection environment from one shell to another, so that you can use the
# vscode integrated terminal's "code [args]" command to communicate with that instance of vscode
# from an unrelated shell.
#
# Usage:
# 1. Open an integrated terminal in vscode, and run codesrv-connect
# 2. In the target shell, cd to the same directory and run
# ". .codesrv-connect", or follow the instruction printed by codesrv-connect.
#
# Setup:
# Put "codesrv-connect somewhere on your PATH (e.g. ~/bin)"
#
# Cleanup:
# - Delete abandoned .codesrv-connect files when their vscode sessions die.
# - Do not add .codesrv-connect files to git repositories.
#
# Notes:
# The VSCODE_IPC_HOOK_CLI environment variable points to a socket which is rather volatile, while the long path for the 'code' alias is more stable: vscode doesn't change the latter even across a "code -r ." reload. But the former is easily detached and so you need a fresh value if that happens. This is what codesrv-connect does: it captures the value of these two and writes them to .codesrv-connect in the current dir.
#
# Verinfo: v1.0.0 - [email protected] - 2020-03-31
#
function errExit {
echo "ERROR: $@" >&2
exit 1
}
[[ -S $VSCODE_IPC_HOOK_CLI ]] || errExit "VSCODE_IPC_HOOK_CLI not defined or not a pipe [$VSCODE_IPC_HOOK_CLI]"
if [[ $(which code) != *vscode-server* ]]; then
errExit "The 'code' command doesn't refer to something under .vscode-server: $(type -a code)"
fi
cat <<EOF >.codesrv-connect
# Temp file created by $(which codesrv-connect): source this into your working shell like '. .codesrv-connect'
# ( git hint: add ".codesrv-connect" to .gitignore )
#
cd "$PWD"
if ! test -S "$VSCODE_IPC_HOOK_CLI"; then
echo "ERROR: $VSCODE_IPC_HOOK_CLI not a socket. Dead session."
else
export VSCODE_IPC_HOOK_CLI="$VSCODE_IPC_HOOK_CLI"
alias code=$(which code)
echo "Done: the 'code' command will talk to socket \"$VSCODE_IPC_HOOK_CLI\" now."
echo "You can delete .codesrv-connect when the vscode server context dies, or reuse it in other shells until then."
fi
EOF
echo "# OK: run this to connect to vscode server in a destination shell:"
echo ". $PWD/.codesrv-connect"
To send to both remote with one command, you can create a alias for it:
git config alias.pushall '!git push origin devel && git push github devel'
With this, when you use the command git pushall
, it will update both repositories.
To create an array of unlimited items of any sort of type:
typedef struct STRUCT_SS_VECTOR {
size_t size;
void** items;
} ss_vector;
ss_vector* ss_init_vector(size_t item_size) {
ss_vector* vector;
vector = malloc(sizeof(ss_vector));
vector->size = 0;
vector->items = calloc(0, item_size);
return vector;
}
void ss_vector_append(ss_vector* vec, void* item) {
vec->size++;
vec->items = realloc(vec->items, vec->size * sizeof(item));
vec->items[vec->size - 1] = item;
};
void ss_vector_free(ss_vector* vec) {
for (int i = 0; i < vec->size; i++)
free(vec->items[i]);
free(vec->items);
free(vec);
}
and how to use it:
// defining some sort of struct, can be anything really
typedef struct APPLE_STRUCT {
int id;
} apple;
apple* init_apple(int id) {
apple* a;
a = malloc(sizeof(apple));
a-> id = id;
return a;
};
int main(int argc, char* argv[]) {
ss_vector* vector = ss_init_vector(sizeof(apple));
// inserting some items
for (int i = 0; i < 10; i++)
ss_vector_append(vector, init_apple(i));
// dont forget to free it
ss_vector_free(vector);
return 0;
}
This vector/array can hold any type of item and it is completely dynamic in size.
You could use label based using .loc or index based using .iloc method to do column-slicing including column ranges:
In [50]: import pandas as pd
In [51]: import numpy as np
In [52]: df = pd.DataFrame(np.random.rand(4,4), columns = list('abcd'))
In [53]: df
Out[53]:
a b c d
0 0.806811 0.187630 0.978159 0.317261
1 0.738792 0.862661 0.580592 0.010177
2 0.224633 0.342579 0.214512 0.375147
3 0.875262 0.151867 0.071244 0.893735
In [54]: df.loc[:, ["a", "b", "d"]] ### Selective columns based slicing
Out[54]:
a b d
0 0.806811 0.187630 0.317261
1 0.738792 0.862661 0.010177
2 0.224633 0.342579 0.375147
3 0.875262 0.151867 0.893735
In [55]: df.loc[:, "a":"c"] ### Selective label based column ranges slicing
Out[55]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
In [56]: df.iloc[:, 0:3] ### Selective index based column ranges slicing
Out[56]:
a b c
0 0.806811 0.187630 0.978159
1 0.738792 0.862661 0.580592
2 0.224633 0.342579 0.214512
3 0.875262 0.151867 0.071244
I have make combination of answers above and made my solution.
So..
First in razor block create one string variable which will contain name value of controller and action that is called by user.
@{
string controllerAction = ViewContext.RouteData.Values["Controller"].ToString() + ViewContext.RouteData.Values["Action"].ToString();
}
Then use combination of HTML and Razor code:
<ul class="nav navbar-nav">
<li class="@(controllerAction == "HomeIndex" ? "active" : "" )">@Html.ActionLink("Home", "Index", "Home")</li>
<li class="@(controllerAction == "AboutIndex" ? "active" : "" )">@Html.ActionLink("About", "Index", "About")</li>
<li class="@(controllerAction == "HomeContact" ? "active" : "" )">@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
I think, that this is good because you don't need to access "ViewContext.RouteData.Values" each time to get controller name and action name.
Try This :
In HTML and JS :
// Convert Password Field To Text On Hover._x000D_
var passField = $('input[type=password]');_x000D_
$('.show-pass').hover(function() {_x000D_
passField.attr('type', 'text');_x000D_
}, function() {_x000D_
passField.attr('type', 'password');_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
<!-- An Input PassWord Field With Eye Font-Awesome Class -->_x000D_
<input type="password" placeholder="Type Password">_x000D_
<i class="show-pass fa fa-eye fa-lg"></i>
_x000D_
Maybe it has nothing to do here, but it could be useful for someone.
I installed jdk on: D:\Program Files\Java\jdk1.7.0_06\bin
So I added it to %PATH%
variable and checked it on cmd and everything was ok, but Eclipse kept showing me that error.
I used quotation marks on %PATH%
so it reads something like:
%SYSTEMROOT%\System32;"D:\Program Files\Java\jdk1.7.0_06\bin"
and problem solved.
Each individual Web App under an IIS Web Site can use a different App Pool.
Verify the App Pool assigned to your app (not just the root site per your pictures) is .NET 4.0 compatible:
A global variable has to be initialized to a constant value, like 4
or 0.0
or @"constant string"
or nil
. A object constructor, such as init
, does not return a constant value.
If you want to have a global variable, you should initialize it to nil
and then return it using a class method:
NSImage *segment = nil;
+ (NSImage *)imageSegment
{
if (segment == nil) segment = [[NSImage alloc] initWithContentsOfFile:@"/user/asd.jpg"];
return segment;
}
Particular example: use a BindingResult object as an argument for a validate method of a Validator inside a Controller.
Then, you can check this object looking for validation errors:
validator.validate(modelObject, bindingResult);
if (bindingResult.hasErrors()) {
// do something
}
The answer marked is perfect but for one scenario, where in the dd and mm are actually single digits. the following regex is perfect in this case:
function validateDate(testdate) {_x000D_
var date_regex = /^(0?[1-9]|1[0-2])\/(0?[1-9]|1\d|2\d|3[01])\/(19|20)\d{2}$/ ;_x000D_
return date_regex.test(testdate);_x000D_
}
_x000D_
For anyone looking how to do this in Kotlin DSL, here's a working example for build.gradle.kts
:
tasks.register("bootRunDev") {
group = "application"
description = "Runs this project as a Spring Boot application with the dev profile"
doFirst {
tasks.bootRun.configure {
systemProperty("spring.profiles.active", "dev")
}
}
finalizedBy("bootRun")
}
This is my adaptation johnrefling's. This work also in WindowsXP; in my case i start the same application at the end, because i want reopen it with different parametrs. My application is a WindowForm .NET
@echo off
taskkill -im:MyApp.exe
:loop1
tasklist | find /i "MyApp.exe" >nul 2>&1
if errorlevel 1 goto cont1
echo "Waiting termination of process..."
:: timeout /t 1 /nobreak >nul 2>&1 ::this don't work in windows XP
:: from: https://stackoverflow.com/questions/1672338/how-to-sleep-for-five-seconds-in-a-batch-file-cmd/33286113#33286113
typeperf "\System\Processor Queue Length" -si 1 -sc 1 >nul s
goto loop1
:cont1
echo "Process terminated, start new application"
START "<SYMBOLIC-TEXT-NAME>" "<full-path-of-MyApp2.exe>" "MyApp2-param1" "MyApp2-param2"
pause
The LoadBalancer ServiceType will only work if the underlying infrastructure supports the automatic creation of Load Balancers and have the respective support in Kubernetes, as is the case with the Google Cloud Platform and AWS. If no such feature is configured, the LoadBalancer IP address field is not populated and still in pending status , and the Service will work the same way as a NodePort type Service
Just type the path of your local directory (Git project home directory) in the properties of Git Bash. I.e. set path C:\yourprojsctdirectory to Git Bash's properties field "Execute In" or (Ausführen in). That's it!
Now double click Git Bash. The Git header will be on your "yourprojsctdirectory".
FormBorderStyle = FormBorderStyle.Sizable;
TopMost = false;
WindowState = FormWindowState.Normal;
THIS CODE MAKE YOUR WINDOWS FULL SCREEN THIS WILL ALSO COVER WHOLE SCREEN
Just found this thread and posted an alternative answer (copied below) here: https://stackoverflow.com/a/37853766/1948625
Specifically on this question, if the dot ".
" used in the -S
value of the command line means the same as 127.0.0.1
, then it could be the same issue as the connection string of the other question. Use the hostname instead, or check your hosts file.
Old question, and my symptoms are slightly different, but same error. My connection string was correct (Integrated security, and I don't provide user and pwd) with data source
set to 127.0.0.1
. It worked fine for years.
But recently I added a line in the static host file for testing purposes (C:\Windows\System32\drivers\etc\hosts
)
127.0.0.1 www.blablatestsite.com
Removing this line and the error is gone.
I got a clue from this article (https://support.microsoft.com/en-gb/kb/896861) which talks about hostnames and loopback.
Other possible fix (if you need to keep that line in the hosts file) is to use the hostname (like MYSERVER01
) instead of 127.0.0.1
in the data source
of the connection string.
I ran into a nearly identical problem the other day, except that the partial view was a response to an AJAX request. In my situation, the partial was actually a full page, but I wanted it to be accessible as a partial from other pages.
If you want to render sections in a partial, the cleanest solution is to create a new layout and use a ViewBag variable. This does not work with @Html.Partial()
or the new <partial></partial>
, use AJAX.
Main view (that you want to be rendered as a partial elsewhere):
@if(ViewBag.Partial == true) {
Layout = "_layoutPartial";
}
<div>
[...]
</div>
@section Scripts {
<script type="text/javascript">
[...]
</script>
}
Controller:
public IActionResult GetPartial() {
ViewBag.Partial = true;
//Do not return PartialView!
return View("/path/to/view")
}
_layoutPartial.cshtml (new):
@RenderSection("Scripts")
@RenderBody()
Then use AJAX in your page.
If you want to render the page in the main layout (not a partial), then don't set ViewBag.Partial = true
. No HTML helpers necessary.
Now For AppCompatEditText
Note: We need to use app:backgroundTint instead of android:backgroundTint
<android.support.v7.widget.AppCompatEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Underline color change"
app:backgroundTint="@color/blue_gray_light" />
If you want to clear the input by using the HTML ONLY, then you can do something like this:
<input type="text"
(keyup)="0"
#searchCollectorInput
class="search-metrics"
placeholder="Find">
Notice the importance of (keyup)=0 and the reference to the input of course.
Then reset it like this:
<span *ngIf="searchCollectorInput.value.length > 0"
(click)="searchCollectorInput.value = ''"
class="fa fa-close" ></span>
As others have said, currentTimeMillis is clock time, which changes due to daylight saving time (not: daylight saving & time zone are unrelated to currentTimeMillis, the rest is true), users changing the time settings, leap seconds, and internet time sync. If your app depends on monotonically increasing elapsed time values, you might prefer nanoTime instead.
You might think that the players won't be fiddling with the time settings during game play, and maybe you'd be right. But don't underestimate the disruption due to internet time sync, or perhaps remote desktop users. The nanoTime API is immune to this kind of disruption.
If you want to use clock time, but avoid discontinuities due to internet time sync, you might consider an NTP client such as Meinberg, which "tunes" the clock rate to zero it in, instead of just resetting the clock periodically.
I speak from personal experience. In a weather application that I developed, I was getting randomly occurring wind speed spikes. It took a while for me to realize that my timebase was being disrupted by the behavior of clock time on a typical PC. All my problems disappeared when I started using nanoTime. Consistency (monotonicity) was more important to my application than raw precision or absolute accuracy.
There are two types of contexts we are dealing with:
1: root context (parent context. Typically include all jdbc(ORM, Hibernate) initialisation and other spring security related configuration)
2: individual servlet context (child context.Typically Dispatcher Servlet Context and initialise all beans related to spring-mvc (controllers , URL Mapping etc)).
Here is an example of web.xml which includes multiple application context file
<?xml version="1.0" encoding="UTF-8"?>_x000D_
<web-app xmlns="http://java.sun.com/xml/ns/javaee"_x000D_
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"_x000D_
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee_x000D_
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">_x000D_
_x000D_
<display-name>Spring Web Application example</display-name>_x000D_
_x000D_
<!-- Configurations for the root application context (parent context) -->_x000D_
<listener>_x000D_
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>_x000D_
</listener>_x000D_
<context-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/jdbc/spring-jdbc.xml <!-- JDBC related context -->_x000D_
/WEB-INF/spring/security/spring-security-context.xml <!-- Spring Security related context -->_x000D_
</param-value>_x000D_
</context-param>_x000D_
_x000D_
<!-- Configurations for the DispatcherServlet application context (child context) -->_x000D_
<servlet>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>_x000D_
<init-param>_x000D_
<param-name>contextConfigLocation</param-name>_x000D_
<param-value>_x000D_
/WEB-INF/spring/mvc/spring-mvc-servlet.xml_x000D_
</param-value>_x000D_
</init-param>_x000D_
</servlet>_x000D_
<servlet-mapping>_x000D_
<servlet-name>spring-mvc</servlet-name>_x000D_
<url-pattern>/admin/*</url-pattern>_x000D_
</servlet-mapping>_x000D_
_x000D_
</web-app>
_x000D_
Yes, in MS SQL Server, you can create scheduled jobs. In SQL Management Studio, navigate to the server, then expand the SQL Server Agent item, and finally the Jobs folder to view, edit, add scheduled jobs.
There may be a simpler option, but you can use VLOOKUP to check if a value appears in a list (and VLOOKUP is a powerful formula to get to grips with anyway).
So for A1, you can set a conditional format using the following formula:
=NOT(ISNA(VLOOKUP(A1,$B:$B,1,FALSE)))
Copy and Paste Special > Formats to copy that conditional format to the other cells in column A.
What the above formula is doing:
Take a look at this:
http://developer.android.com/reference/android/util/DisplayMetrics.html
You can get the heigth of the screen and it's simple math to calculate 68 percent of the screen.
I was having serious problems with
.data('property', value);
It was not setting the data-property
attribute.
Started using jQuery's .attr()
:
Get the value of an attribute for the first element in the set of matched elements or set one or more attributes for every matched element.
.attr('property', value)
to set the value and
.attr('property')
to retrieve the value.
Now it just works!
I had this error because of my stupidity. In the manifest.xml I have wrongly declared two Activity as Launcher. Make sure you have only one activity as Launcher.
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".WelcomeActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
You have add this code:
$mail->SMTPOptions = array(
'ssl' => array(
'verify_peer' => false,
'verify_peer_name' => false,
'allow_self_signed' => true
)
);
And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"
This work for me!
You have two objects both named bank_holiday
-- one a list and one a function. Disambiguate the two.
bank_holiday[month]
is raising an error because Python thinks bank_holiday
refers to the function (the last object bound to the name bank_holiday
), whereas you probably intend it to mean the list.
I will side with nategood's answer as it is complete and it seemed to have please your needs. Though, I would like to add a comment on identifying multiple (1 or more) resource that way:
http://our.api.com/Product/101404,7267261
In doing so, you:
Complexify the clients
by forcing them to interpret your response as an array, which to me is counter intuitive if I make the following request: http://our.api.com/Product/101404
Create redundant APIs with one API for getting all products and the one above for getting 1 or many. Since you shouldn't show more than 1 page of details to a user for the sake of UX, I believe having more than 1 ID would be useless and purely used for filtering the products.
It might not be that problematic, but you will either have to handle this yourself server side by returning a single entity (by verifying if your response contains one or more) or let clients manage it.
Example
I want to order a book from Amazing. I know exactly which book it is and I see it in the listing when navigating for Horror books:
After selecting the second book, I am redirected to a page detailing the book part of a list:
--------------------------------------------
Book #1
--------------------------------------------
Title: The return of the amazing monster
Summary:
Pages:
Publisher:
--------------------------------------------
Or in a page giving me the full details of that book only?
---------------------------------
The return of the amazing monster
---------------------------------
Summary:
Pages:
Publisher:
---------------------------------
My Opinion
I would suggest using the ID in the path variable when unicity is guarantied when getting this resource's details. For example, the APIs below suggest multiple ways to get the details for a specific resource (assuming a product has a unique ID and a spec for that product has a unique name and you can navigate top down):
/products/{id}
/products/{id}/specs/{name}
The moment you need more than 1 resource, I would suggest filtering from a larger collection. For the same example:
/products?ids=
Of course, this is my opinion as it is not imposed.
This is the NPM known Issue for windows that NPM is pretty much unusable under Windows. This is of course related to the path size limitations.
https://github.com/npm/npm/issues/5641
My main concern here is that there are no mention of these issues when installing node or npm via the website. Not being able to install prime packages makes npm fundamentally unusable for windows.
You probably need to continue running your DB process (by running mongod
) while running your node server.
you don't need to specify a "SimpleDateFormat", it's simple: You must do specify the constant "DatatypeConstants.FIELD_UNDEFINED" where you don't want to show
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendarDate(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED);
Response.Redirect()
will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
Server.Transfer()
does not change the address bar. You cannot hit back.
I use Server.Transfer()
when I don't want the user to see where I am going. Sometimes on a "loading" type page.
Otherwise I'll always use Response.Redirect()
.
Here are my techniques when I need to figure out if a branch has been merged, even if it may have been rebased to be up to date with our main branch, which is a common scenario for feature branches.
Neither of these approaches are fool proof, but I've found them useful many times.
Using a visual tool like gitk or TortoiseGit, or simply git log with --all, go through the history to see all the merges to the main branch. You should be able to spot if this particular feature branch has been merged or not.
If you have a good habit of always removing both the local and the remote branch when you merge in a feature branch, then you can simply update and prune remotes on your other computer and the feature branches will disappear.
To help remember doing this, I'm already using git flow extensions (AVH edition) to create and merge my feature branches locally, so I added the following git flow hook to ask me if I also want to auto-remove the remote branch.
Example create/finish feature branch
554 Andreas:MyRepo(develop)$ git flow start tmp
Switched to a new branch 'feature/tmp'
Summary of actions:
- A new branch 'feature/tmp' was created, based on 'develop'
- You are now on branch 'feature/tmp'
Now, start committing on your feature. When done, use:
git flow feature finish tmp
555 Andreas:MyRepo(feature/tmp)$ git flow finish
Switched to branch 'develop'
Your branch is up-to-date with 'if/develop'.
Already up-to-date.
[post-flow-feature-finish] Delete remote branch? (Y/n)
Deleting remote branch: origin/feature/tmp.
Deleted branch feature/tmp (was 02a3356).
Summary of actions:
- The feature branch 'feature/tmp' was merged into 'develop'
- Feature branch 'feature/tmp' has been locally deleted
- You are now on branch 'develop'
556 Andreas:ScDesktop (develop)$
.git/hooks/post-flow-feature-finish
NAME=$1
ORIGIN=$2
BRANCH=$3
# Delete remote branch
# Allows us to read user input below, assigns stdin to keyboard
exec < /dev/tty
while true; do
read -p "[post-flow-feature-finish] Delete remote branch? (Y/n) " yn
if [ "$yn" = "" ]; then
yn='Y'
fi
case $yn in
[Yy] )
echo -e "\e[31mDeleting remote branch: $2/$3.\e[0m" || exit "$?"
git push $2 :$3;
break;;
[Nn] )
echo -e "\e[32mKeeping remote branch.\e[0m" || exit "$?"
break;;
* ) echo "Please answer y or n for yes or no.";;
esac
done
# Stop reading user input (close STDIN)
exec <&-
exit 0
If you do not always remove the remote branch, you can still search for similar commits to determine if the branch has been merged or not. The pitfall here is if the remote branch has been rebased to the unrecognizable, such as squashing commits or changing commit messages.
Example commands on master branch:
gru
gls origin/feature/foo
glf "my message"
In my bash .profile config
alias gru='git remote update -p'
alias glf=findCommitByMessage
findCommitByMessage() {
git log -i --grep="$1"
}
I think that the fastest way to do this is to just clone the node, which will remove all event listeners:
var old_element = document.getElementById("btn");
var new_element = old_element.cloneNode(true);
old_element.parentNode.replaceChild(new_element, old_element);
Just be careful, as this will also clear event listeners on all child elements of the node in question, so if you want to preserve that you'll have to resort to explicitly removing listeners one at a time.
Side note: if you want to get the sum of all digits, you can simply do
print sum(int(digit) for digit in raw_input('Enter a number:'))
I am using this approach and it is working fine:
public class PushNotification
{
private static readonly ILog Logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
// firebase
private static Uri FireBasePushNotificationsURL = new Uri("https://fcm.googleapis.com/fcm/send");
private static string ServerKey = ConfigurationManager.AppSettings["FIREBASESERVERKEY"];
public static async Task<bool> SendPushNotification(List<SendNotificationModel> notificationData)
{
try
{
bool sent = false;
foreach (var data in notificationData)
{
var messageInformation = new Message()
{
notification = new Notification()
{
title = data.Title,
text = data.Message,
ClickAction = "FCM_PLUGIN_ACTIVITY"
},
data = data.data,
priority="high",
to =data.DeviceId
};
string jsonMessage = JsonConvert.SerializeObject(messageInformation);
//Create request to Firebase API
var request = new HttpRequestMessage(HttpMethod.Post, FireBasePushNotificationsURL);
request.Headers.TryAddWithoutValidation("Authorization", "key=" + ServerKey);
request.Content = new StringContent(jsonMessage, Encoding.UTF8, "application/json");
HttpResponseMessage result;
using (var client = new HttpClient())
{
result = await client.SendAsync(request);
sent = result.IsSuccessStatusCode;
}
}
return sent;
}
catch(Exception ex)
{
Logger.Error(ex);
return false;
}
}
}
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
static T DeserializeXml<T>(string sourceXML) where T : class
{
var serializer = new XmlSerializer(typeof(T));
T result = null;
using (TextReader reader = new StringReader(sourceXML))
{
result = (T) serializer.Deserialize(reader);
}
return result;
}