You can use the dynamic variable ViewBag
ViewBag.AnotherValue = valueToView;
In my case there was a conflict in the namespaces , I have:
using System.Web.Mvc;
and
using System.Collections.Generic;
I explicitly want to use the Mvc one so I declared it as :
new System.Web.Mvc.SelectList(...)
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.
Internally ViewBag properties are stored as name/value pairs in the ViewData dictionary.
Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel as noted in this snippet from MVC 3 release notes:
(edited 10-8-12) It was suggested I post the source of this info I posted, here is the source: http://www.asp.net/whitepapers/mvc3-release-notes#_Toc2_4
MVC 2 controllers support a ViewData property that enables you to pass data to a view template using a late-bound dictionary API. In MVC 3, you can also use somewhat simpler syntax with the ViewBag property to accomplish the same purpose. For example, instead of writing ViewData["Message"]="text", you can write ViewBag.Message="text". You do not need to define any strongly-typed classes to use the ViewBag property. Because it is a dynamic property, you can instead just get or set properties and it will resolve them dynamically at run time. Internally, ViewBag properties are stored as name/value pairs in the ViewData dictionary. (Note: in most pre-release versions of MVC 3, the ViewBag property was named the ViewModel property.)
INFORMATION_SCHEMA
is your friend. It has all kinds of views that show all kinds of schema information. Check your system views. You will find you have three views dealing with constraints, one being CHECK_CONSTRAINTS
.
I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :
https://gist.github.com/smalot/6183152
Hope it helps everone
img = cv2.imread('2015-05-27-191152.jpg',0)
The above line of code reads your image in grayscale color model, because of the 0 appended at the end. And if you again try to convert an already gray image to gray image it will show that error.
So either use above style or try undermentioned code:
img = cv2.imread('2015-05-27-191152.jpg')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Here they asked a similar question, and the answer seems more complete, I leave the source:
How to take partial screenshot with Selenium WebDriver in python?
from selenium import webdriver
from PIL import Image
from io import BytesIO
fox = webdriver.Firefox()
fox.get('http://stackoverflow.com/')
# now that we have the preliminary stuff out of the way time to get that image :D
element = fox.find_element_by_id('hlogo') # find part of the page you want image of
location = element.location
size = element.size
png = fox.get_screenshot_as_png() # saves screenshot of entire page
fox.quit()
im = Image.open(BytesIO(png)) # uses PIL library to open image in memory
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = im.crop((left, top, right, bottom)) # defines crop points
im.save('screenshot.png') # saves new cropped image
I would probably build the link manually, like this:
<a href="<%=Url.Action("Subcategory", "Category", new { categoryID = parent.ID }) %>#section12">link text</a>
One small addition to the answer by vasekt:
The provided solution with the SocketFactoryRegistry works when using PoolingHttpClientConnectionManager.
However, connections via plain http don't work any longer then. You have to add a PlainConnectionSocketFactory for the http protocol additionally to make them work again:
Registry<ConnectionSocketFactory> socketFactoryRegistry =
RegistryBuilder.<ConnectionSocketFactory> create()
.register("https", sslsf)
.register("http", new PlainConnectionSocketFactory()).build();
You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']
. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.
Site 1
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';
Includes under site one would be at:
echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';
Site 2
echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';
The actual code to access includes from site1 inside of site2 you would say:
include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');
It will only use the relative path of the file executing the query if you try to access it by excluding the document root
and the root
slash:
//(not as fool-proof or non-platform specific)
include('../includes/file_from_site_1.php');
Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.
Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:
<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>
You should use:
<a href='/contact/'>Contact</a>
For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt
file for ONLY site1:
User-agent: *
Disallow: /blog/
Look up your IP address and include this snippet of code:
function is_dev(){
//use the external IP from Google.
//If you're hosting locally it's 127.0.01 unless you've changed it.
$ip_address='xxx.xxx.xxx.xxx';
if ($_SERVER['REMOTE_ADDR']==$ip_address){
return true;
} else {
return false;
}
}
if(is_dev()){
echo $_SERVER['DOCUMENT_ROOT'];
}
Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.
If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:
if(is_dev()){
echo "<script>".PHP_EOL;
echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
echo "</script>".PHP_EOL;
}
The accepted answer didn't work in my situation, not sure why. I switched from JRE1.7 to JRE1.8 and that resolved the issue automatically. JRE1.8 uses TLS1.2 by default
your filter would work, but you need to return true on matching objects in the function passed to the filter for it to grab them.
var $previous = $('.navlink').filter(function() {
return $(this).data("selected") == true
});
The best way with the HTML you have would probably be to use the next
function, like so:
var div = $(this).next('.class2');
Since the click handler is happening to the <a>
, you could also traverse up to the parent DIV, then search down for the second DIV. You would do this with a combination of parent
and children
. This approach would be best if the HTML you put up is not exactly like that and the second DIV could be in another location relative to the link:
var div = $(this).parent().children('.class2');
If you wanted the "search" to not be limited to immediate children, you would use find
instead of children
in the example above.
Also, it is always best to prepend your class selectors with the tag name if at all possible. ie, if only <div>
tags are going to have those classes, make the selector be div.class1
, div.class2
.
copy('http://example.com/image.php', 'local/folder/flower.jpg');
You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."
Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.
Update:
The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg
Per this answer:
fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))
For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.
This is the equivalent if your browser isn't so modern:
fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})
If you are worried at all about speed, you should instead use:
mag = np.sqrt(x.dot(x))
Here are some benchmarks:
>>> import timeit
>>> timeit.timeit('np.linalg.norm(x)', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0450878
>>> timeit.timeit('np.sqrt(x.dot(x))', setup='import numpy as np; x = np.arange(100)', number=1000)
0.0181372
EDIT: The real speed improvement comes when you have to take the norm of many vectors. Using pure numpy functions doesn't require any for loops. For example:
In [1]: import numpy as np
In [2]: a = np.arange(1200.0).reshape((-1,3))
In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 4.23 ms per loop
In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 18.9 us per loop
In [5]: np.allclose([np.linalg.norm(x) for x in a],np.sqrt((a*a).sum(axis=1)))
Out[5]: True
What about Console.Readline();
?
you can use Simple java.util lib
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
Obligatory jQuery solution. Finds and sets the title
attribute to foo
. Note this selects a single element since I'm doing it by id, but you could easily set the same attribute on a collection by changing the selector.
$('#element').attr( 'title', 'foo' );
values method of enum
enum.values() method which returns all enum instances.
public class EnumTest {
private enum Currency {
PENNY("1 rs"), NICKLE("5 rs"), DIME("10 rs"), QUARTER("25 rs");
private String value;
private Currency(String brand) {
this.value = brand;
}
@Override
public String toString() {
return value;
}
}
public static void main(String args[]) {
Currency[] currencies = Currency.values();
// enum name using name method
// enum to String using toString() method
for (Currency currency : currencies) {
System.out.printf("[ Currency : %s,
Value : %s ]%n",currency.name(),currency);
}
}
}
http://javaexplorer03.blogspot.in/2015/10/name-and-values-method-of-enum.html
These answers were helpful in solving a similar issue while trying to define a named range with Workbook
scope. The "ah-HA!" for me is to use the Names Collection which is relative to the whole Workbook! This may be restating the obvious to many, but it wasn't clearly stated in my research, so I share for other's with similar questions.
' Local / Worksheet only scope
Worksheets("Sheet2").Names.Add Name:="a_test_rng1", RefersTo:=Range("A1:A4")
' Global / Workbook scope
ThisWorkbook.Names.Add Name:="a_test_rng2", RefersTo:=Range("B1:b4")
If you look at your list of names when Sheet2 is active, both ranges are there, but switch to any other sheet, and "a_test_rng1"
is not present.
Now I can happily generate a named range in my code with what ever scope I deem appropriate. No need mess around with the name manager or a plug in.
Aside, the name manager in Excel Mac 2011 is a mess, but I did discover that while there are no column labels to tell you what you're looking at while viewing your list of named ranges, if there is a sheet listed beside the name, that name is scoped to worksheet / local. See screenshot attached.
Full credit to this article for putting together the pieces.
I know this was posted about a year ago, but this is for users for future reference.
I came across similar issue. In my case (i will try to be brief, please do let me know if you would like more detail), i was trying to check if a string was empty or not (string is the subject of an email). It always returned the same error message no matter what i did. I knew i was doing it right but it still kept throwing the same error message. Then it dawned in me that, i was checking if the subject (string) of an email (instance/object), what if the email(instance) was already a null at the first place. How could i check for a subject of an email, if the email is already a null..i checked if the the email was empty, it worked fine.
while checking for the subject(string) i used IsNullorWhiteSpace(), IsNullOrEmpty() methods.
if (email == null)
{
break;
}
else
{
// your code here
}
I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.
Google for "Gideros Mobile"
As per your description, things don't add up. If aSourceDictionary
is a dictionary, then your for loop has to work properly.
>>> source = {'a': [1, 2], 'b': [2, 3]}
>>> target = {}
>>> for key in source:
... target[key] = []
... target[key].extend(source[key])
...
>>> target
{'a': [1, 2], 'b': [2, 3]}
>>>
This code example may do what you want:
Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x)
. The %c
format specification works for any integer type.
Here's a solution without Spring.
Constants are taken from org.hibernate.cfg.AvailableSettings
:
entityManagerFactory = new HibernatePersistenceProvider().createContainerEntityManagerFactory(
archiverPersistenceUnitInfo(),
ImmutableMap.<String, Object>builder()
.put(JPA_JDBC_DRIVER, JDBC_DRIVER)
.put(JPA_JDBC_URL, JDBC_URL)
.put(DIALECT, Oracle12cDialect.class)
.put(HBM2DDL_AUTO, CREATE)
.put(SHOW_SQL, false)
.put(QUERY_STARTUP_CHECKING, false)
.put(GENERATE_STATISTICS, false)
.put(USE_REFLECTION_OPTIMIZER, false)
.put(USE_SECOND_LEVEL_CACHE, false)
.put(USE_QUERY_CACHE, false)
.put(USE_STRUCTURED_CACHE, false)
.put(STATEMENT_BATCH_SIZE, 20)
.build());
entityManager = entityManagerFactory.createEntityManager();
And the infamous PersistenceUnitInfo
private static PersistenceUnitInfo archiverPersistenceUnitInfo() {
return new PersistenceUnitInfo() {
@Override
public String getPersistenceUnitName() {
return "ApplicationPersistenceUnit";
}
@Override
public String getPersistenceProviderClassName() {
return "org.hibernate.jpa.HibernatePersistenceProvider";
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return PersistenceUnitTransactionType.RESOURCE_LOCAL;
}
@Override
public DataSource getJtaDataSource() {
return null;
}
@Override
public DataSource getNonJtaDataSource() {
return null;
}
@Override
public List<String> getMappingFileNames() {
return Collections.emptyList();
}
@Override
public List<URL> getJarFileUrls() {
try {
return Collections.list(this.getClass()
.getClassLoader()
.getResources(""));
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return Collections.emptyList();
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return null;
}
@Override
public ValidationMode getValidationMode() {
return null;
}
@Override
public Properties getProperties() {
return new Properties();
}
@Override
public String getPersistenceXMLSchemaVersion() {
return null;
}
@Override
public ClassLoader getClassLoader() {
return null;
}
@Override
public void addTransformer(ClassTransformer transformer) {
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
};
}
replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"
The top answer is almost correct, but you also need to add an ampersand at the end of each line. For example write the batch file:
start /d "~\iexplore.exe" "www.google.com" &
start /d "~\iexplore.exe" "www.yahoo.com" &
start /d "~\iexplore.exe" "www.blackholesurfer.com" &
The ampersand allows the prompt to return to the shell and launch another tab. This is a windows solution only, but the ampersand has the same effect in linux shell.
You can use:
CREATE LOGIN <login name> WITH PASSWORD = '<password>' ; GO
To create the login (See here for more details).
Then you may need to use:
CREATE USER user_name
To create the user associated with the login for the specific database you want to grant them access too.
(See here for details)
You can also use:
GRANT permission [ ,...n ] ON SCHEMA :: schema_name
To set up the permissions for the schema's that you assigned the users to.
(See here for details)
Two other commands you might find useful are ALTER USER and ALTER LOGIN.
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
Hello If I understood it right you are doing an XMLHttpRequest to a different domain than your page is on. So the browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. A tutorial about how to achieve that is Using CORS.
When you are using postman they are not restricted by this policy. Quoted from Cross-Origin XMLHttpRequest:
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
I think this provides a more thorough approach:
button, input[type="submit"], input[type="reset"] {_x000D_
background: none;_x000D_
color: inherit;_x000D_
border: none;_x000D_
padding: 0;_x000D_
font: inherit;_x000D_
cursor: pointer;_x000D_
outline: inherit;_x000D_
}
_x000D_
<button>Example</button>
_x000D_
In HTML:
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
<input type="submit" id="btnDelete" name="btnDelete" value="Delete" />
In PHP:
if (isset($_POST["btnSubmit"])){
// "Save Changes" clicked
} else if (isset($_POST["btnDelete"])){
// "Delete" clicked
}
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
While searching for the best method to sum an array, I wrote a performance test.
In Chrome, "reduce" seems to be vastly superior
I hope this helps
// Performance test, sum of an array
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var result = 0;
// Eval
console.time("eval");
for(var i = 0; i < 10000; i++) eval("result = (" + array.join("+") + ")");
console.timeEnd("eval");
// Loop
console.time("loop");
for(var i = 0; i < 10000; i++){
result = 0;
for(var j = 0; j < array.length; j++){
result += parseInt(array[j]);
}
}
console.timeEnd("loop");
// Reduce
console.time("reduce");
for(var i = 0; i < 10000; i++) result = array.reduce(function(pv, cv) { return pv + parseInt(cv); }, 0);
console.timeEnd("reduce");
// While
console.time("while");
for(var i = 0; i < 10000; i++){
j = array.length;
result = 0;
while(j--) result += array[i];
}
console.timeEnd("while");
eval: 5233.000ms
loop: 255.000ms
reduce: 70.000ms
while: 214.000ms
I faced the same problem in eclipse with tomcat7 with the error javax.servlet cannot be resolved. If I select the server in targeted runtime mode and build project again, the error get's resolved.
Usually, if you are using bootstrap you can do this to set a min-height of 100%.
<div class="container-fluid min-vh-100"></div>
this will also solve the footer not sticking at the bottom.
you can also do this from CSS with the following class
.stickDamnFooter{min-height: 100vh;}
if this class does not stick your footer just add position: fixed; to that same css class and you will not have this issue in a lifetime. Cheers.
I think you want to set
tableView.alwaysBounceVertical = NO;
WAMP stands for Windows,Apache,Mysql,Php
XAMPP stands for X-os,Apache,Mysql,Php,Perl. (x-os means it can use for any operating system)
It is cross-platform software
It possesses many other essential modules such as phpMyAdmin, OpenSSL, MediaWiki, WordPress, Joomla and more.
it is easy to configure and use.
It is easy to Use. (Changing Configuration)
WAMP is Available for both 64 bit and 32-bit system.
if you are running projects which have specific version requirements WAMP is better choice because you can switch between multiple versions. for example 7x and PHP 5x or Magento2.2.4 won't work on php7.2 but Magento2.3.needs php7.2 or up to work.
i suggest using laragon :
Laragon works out of the box with not only MySQL/MariaDB but also PostgreSQL & MongoDB. With Laragon, they are portable & reliable so you can focus on what matters Laragon is a portable, isolated, fast & powerful universal development environment for PHP, Node.js, Python, Java, Go, Ruby. It is fast, lightweight, easy-to-use and easy-to-extend.
Laragon is great for building and managing modern web applications. It is focused on performance - designed around stability, simplicity, flexibility and freedom.
Laragon is very lightweight and will stay as lean as possible. The core binary itself is less than 2MB and uses less than 4MB RAM when running.
Laragon doesn’t use Windows services. It has its own service orchestration which manages services asynchronously and non-blocking so you’ll find things run fast & smoothly with Laragon.
Pretty URLs
Use app.test
instead of localhost/app
.
Portable
You can move Laragon folder around (to another disks, to another laptops, sync to Cloud,…) without any worries.
Isolated
Laragon has an isolated environment with your OS - it will keep your system clean.
Easy Operation
Unlike others which pre-config for you, Laragon auto-configsall
the complicated things. That why you can add another versions of PHP, Python, Ruby, Java, Go, Apache, Nginx, MySQL, PostgreSQL, MongoDB,… effortlessly.
Modern & Powerful
Laragon comes with modern architect which is suitable to build modern web apps. You can work with both Apache & Nginx as they are fully-managed.
Also, Laragon makes things a lot easier:Wanna have a Wordpress CMS? Just 1 click.Wanna show your local project to customers? Just 1 click.Wanna enable/disable a PHP extension? Just 1 click.
Warning, using the batch file for, tokens, and delims capability on unknown text input can be a disaster due to the special interpretation of chars like &, !, <, etc. Such methods should be reserved for only predictable text.
Here's a vectorized approach (assuming the dataframe, data_set
to be defined as df
instead) that returns a list
of tuples
as shown:
>>> df.set_index(['data_date'])[['data_1', 'data_2']].to_records().tolist()
produces:
[(datetime.datetime(2012, 2, 17, 0, 0), 24.75, 25.03),
(datetime.datetime(2012, 2, 16, 0, 0), 25.0, 25.07),
(datetime.datetime(2012, 2, 15, 0, 0), 24.99, 25.15),
(datetime.datetime(2012, 2, 14, 0, 0), 24.68, 25.05),
(datetime.datetime(2012, 2, 13, 0, 0), 24.62, 24.77),
(datetime.datetime(2012, 2, 10, 0, 0), 24.38, 24.61)]
The idea of setting datetime column as the index axis is to aid in the conversion of the Timestamp
value to it's corresponding datetime.datetime
format equivalent by making use of the convert_datetime64
argument in DF.to_records
which does so for a DateTimeIndex
dataframe.
This returns a recarray
which could be then made to return a list
using .tolist
More generalized solution depending on the use case would be:
df.to_records().tolist() # Supply index=False to exclude index
You can easily solve that in 2 steps:
1- Reach the child element using querySelector like that:
var target = element[0].querySelector('tbody tr:first-child td')
2- Transform it to an angular.element
object again by doing:
var targetElement = angular.element(target)
You will then have access to all expected methods on the targetElement
variable.
Add somewhere in body
<div class="hide">
<a href="#" class="list-group-item">
<table>
<tr>
<td><img src=""></td>
<td><p class="list-group-item-text"></p></td>
</tr>
</table>
</a>
</div>
then create css
.hide { display: none; }
and add to your js
$('#output').append( $('.hide').html() );
If you want a single expression, using native javascript, remember that the return value from a splice operation contains the element(s) that was removed.
var A = [1, 2, 3, 4, 5, 6, 7, 8, 9], x= 0, y= 1;
A[x] = A.splice(y, 1, A[x])[0];
alert(A); // alerts "2,1,3,4,5,6,7,8,9"
Edit:
The [0]
is necessary at the end of the expression as Array.splice()
returns an array, and in this situation we require the single element in the returned array.
I would do as below
rebase feature
git checkout -b feature2 origin/feature
git push -u origin feature2:feature2
Delete the old remote branch feature
git push -u origin feature:feature
Now the remote will have feature(rebased on latest master) and feature2(with old master head). This would allow you to compare later if you have done mistakes in reolving conflicts.
I'd re-iterate Donny V. answer and Josh's
"The only reason I wouldn't use the async version is if I were trying to support an older version of .NET that does not already have built in async support."
(and upvote if I had the reputation.)
I can't remember the last time if ever, I was grateful of the fact HttpWebRequest threw exceptions for status codes >= 400. To get around these issues you need to catch the exceptions immediately, and map them to some non-exception response mechanisms in your code...boring, tedious and error prone in itself. Whether it be communicating with a database, or implementing a bespoke web proxy, its 'nearly' always desirable that the Http driver just tell your application code what was returned, and leave it up to you to decide how to behave.
Hence HttpClient is preferable.
You can use the following for an awk solution -
awk '/^#/ {sub(/#.*/,"");getline;}1' inputfile
You can also download MySql workbench (31Mo) which includes mysql.exe
and mysqldump.exe
.
I successfully tested this when i had to run Perl scripts using DBD:MySql
module to run SQL statements against a distant MySql db.
adb shell getprop ro.build.version.sdk
If you want to see the whole list of parameters just type:
adb shell getprop
You can look at the Columns
property of a given DataTable
, it is a list of all columns in the table.
private void PrintValues(DataTable table)
{
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
Console.WriteLine(row[column]);
}
}
}
http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx
This works:
<img src="invalid_link"
onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Live demo: http://jsfiddle.net/oLqfxjoz/
As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;
.
With Gson, you'd just need to do something like:
List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());
You might also need to provide a no-arg constructor on the Video
class you're deserializing to.
In Xcode 4 and possibly before, in the run script build phase there is an option "Show enviroment variables in build phase". If selected this will show then on a olive green background in the build log.
Instead of recursive CTEs and while loops, has anyone considered a more set-based approach? Note that this function was written for the question, which was based on SQL Server 2008 and comma as the delimiter. In SQL Server 2016 and above (and in compatibility level 130 and above), STRING_SPLIT()
is a better option.
CREATE FUNCTION dbo.SplitString
(
@List nvarchar(max),
@Delim nvarchar(255)
)
RETURNS TABLE
AS
RETURN ( SELECT [Value] FROM
(
SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
FROM sys.all_columns) AS x WHERE Number <= LEN(@List)
AND SUBSTRING(@Delim + @List, [Number], DATALENGTH(@Delim)/2) = @Delim
) AS y
);
GO
If you want to avoid the limitation of the length of the string being <= the number of rows in sys.all_columns
(9,980 in model
in SQL Server 2017; much higher in your own user databases), you can use other approaches for deriving the numbers, such as building your own table of numbers. You could also use a recursive CTE in cases where you can't use system tables or create your own:
CREATE FUNCTION dbo.SplitString
(
@List nvarchar(max),
@Delim nvarchar(255)
)
RETURNS TABLE WITH SCHEMABINDING
AS
RETURN ( WITH n(n) AS (SELECT 1 UNION ALL SELECT n+1
FROM n WHERE n <= LEN(@List))
SELECT [Value] = SUBSTRING(@List, n,
CHARINDEX(@Delim, @List + @Delim, n) - n)
FROM n WHERE n <= LEN(@List)
AND SUBSTRING(@Delim + @List, n, DATALENGTH(@Delim)/2) = @Delim
);
GO
But you'll have to append OPTION (MAXRECURSION 0)
(or MAXRECURSION <longest possible string length if < 32768>
) to the outer query in order to avoid errors with recursion for strings > 100 characters. If that is also not a good alternative then see this answer as pointed out in the comments.
(Also, the delimiter will have to be NCHAR(<=1228)
. Still researching why.)
More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:
You can use
df <- read.csv("filename.csv", header=TRUE)
# To loop each column
for (i in 1:ncol(df))
{
dosomething(df[,i])
}
# To loop each row
for (i in 1:nrow(df))
{
dosomething(df[i,])
}
Also, you may want to have a look to the apply
function (type ?apply
or help(apply)
)if you want to use the same function on each row/column
This happens with images for which the script does not launch a service awaiting requests, therefore the container exits at the end of the script.
This is typically the case with most base OS images (centos, debian, etc.), or also with the node images.
Your best bet is to run the image in interactive mode. Example below with the node image:
docker run -it node /bin/bash
Output is
root@cacc7897a20c:/# echo $SHELL
/bin/bash
My personal favorite, and easier than the answers I have seen here (for multiple columns):
df.drop(df.columns[22:56], axis=1, inplace=True)
jQuery 'fixes up' events to account for browser differences. When it does so, you can always access the 'native' event with event.originalEvent
(see the Special Properties subheading on this page).
What happens when the string contains a duplicate character?
from my experience with index()
I saw that for duplicate you get back the same index.
For example:
s = 'abccde'
for c in s:
print('%s, %d' % (c, s.index(c)))
would return:
a, 0
b, 1
c, 2
c, 2
d, 4
In that case you can do something like that:
for i, character in enumerate(my_string):
# i is the position of the character in the string
Try this please
DELETE FROM messages,usersmessages
USING messages
INNER JOIN usermessages on (messages.messageid = usersmessages.messageid)
WHERE messages.messsageid='1'
You can select a code snippet and use right click menu to choose the action "Execute Selection in console".
I just needed to add the !important
attribute onto the the background-color tag in order for it to show up, did not need the webkit part:
background-color: #f5f5f5 !important;
I found this SF project today:
http://sourceforge.net/p/valgrind4win/wiki/Home/
They are porting valgrind to Windows. Probably in several years we will have a reliable valgrind on windows.
Assuming we're talking SQL Server DateTime
Note: BETWEEN includes both ends of the range, so technically this pattern will be wrong:
errorDate BETWEEN '12/20/2008' AND '12/21/2008'
My preferred method for a time range like that is:
'20081220' <= errorDate AND errordate < '20081221'
Works with common indexes (range scan, SARGable, functionless) and correctly clips off midnight of the next day, without relying on SQL Server's time granularity (e.g. 23:59:59.997)
Try setting position to absolute, ie.
#yourDiv{
position: absolute;
z-index: 10;
};
This also works....sometimes you may want to construct the definition of the parameters outside of the actual EXEC call.
DECLARE @Parmdef nvarchar (500)
DECLARE @SQL nvarchar (max)
DECLARE @xTxt1 nvarchar (100) = 'test1'
DECLARE @xTxt2 nvarchar (500) = 'test2'
SET @parmdef = '@text1 nvarchar (100), @text2 nvarchar (500)'
SET @SQL = 'PRINT @text1 + '' '' + @text2'
EXEC sp_executeSQL @SQL, @Parmdef, @xTxt1, @xTxt2
for w64-based computers you have to install mingw64. If pkg-config.exe is missing then, you can refer to http://ftp.acc.umu.se/pub/gnome/binaries/win64/dependencies/
Unzip and copy/merge pkg-config.exe into your C:\mingw-w64 installation, eg. into on my pc into C:\mingw-w64\x86_64-8.1.0-posix-seh-rt_v6-rev0\mingw64\bin
In order to display the results with the line numbers, you might try this
grep -nr "word to search for" /path/to/file/file
The result should be something like this:
linenumber: other data "word to search for" other data
CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.
You need to define the animation keyframes and apply it to the element:
@keyframes changewidth {
from {
width: 100px;
}
to {
width: 300px;
}
}
div {
animation-duration: 0.1s;
animation-name: changewidth;
animation-iteration-count: infinite;
animation-direction: alternate;
}
Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.
This seems a far easier method than those suggested elsewhere in this thread.
No, enums are supposed to be a complete static enumeration.
At compile time, you might want to generate your enum .java file from another source file of some sort. You could even create a .class file like this.
In some cases you might want a set of standard values but allow extension. The usual way to do this is have an interface
for the interface and an enum
that implements that interface
for the standard values. Of course, you lose the ability to switch
when you only have a reference to the interface
.
In Programming, an interface defines what the behavior a an object will have, but it will not actually specify the behavior. It is a contract, that will guarantee, that a certain class can do something.
Consider this piece of C# code here:
using System;
public interface IGenerate
{
int Generate();
}
// Dependencies
public class KnownNumber : IGenerate
{
public int Generate()
{
return 5;
}
}
public class SecretNumber : IGenerate
{
public int Generate()
{
return new Random().Next(0, 10);
}
}
// What you care about
class Game
{
public Game(IGenerate generator)
{
Console.WriteLine(generator.Generate())
}
}
new Game(new SecretNumber());
new Game(new KnownNumber());
The Game class requires a secret number. For the sake of testing it, you would like to inject what will be used as a secret number (this principle is called Inversion of Control).
The game class wants to be "open minded" about what will actually create the random number, therefore it will ask in its constructor for "anything, that has a Generate method".
First, the interface specifies, what operations an object will provide. It just contains what it looks like, but no actual implementation is given. This is just the signature of the method. Conventionally, in C# interfaces are prefixed with an I.
The classes now implement the IGenerate Interface. This means that the compiler will make sure, that they both have a method, that returns an int and is called Generate
.
The game now is being called two different object, each of which implementant the correct interface. Other classes would produce an error upon building the code.
Here I noticed the blueprint analogy you used:
A class is commonly seen as a blueprint for an object. An Interface specifies something that a class will need to do, so one could argue that it indeed is just a blueprint for a class, but since a class does not necessarily need an interface, I would argue that this metaphor is breaking. Think of an interface as a contract. The class that "signs it" will be legally required (enforced by the compiler police), to comply to the terms and conditions in the contract. This means that it will have to do, what is specified in the interface.
This is all due to the statically typed nature of some OO languages, as it is the case with Java or C#. In Python on the other hand, another mechanism is used:
import random
# Dependencies
class KnownNumber(object):
def generate(self):
return 5
class SecretNumber(object):
def generate(self):
return random.randint(0,10)
# What you care about
class SecretGame(object):
def __init__(self, number_generator):
number = number_generator.generate()
print number
Here, none of the classes implement an interface. Python does not care about that, because the SecretGame
class will just try to call whatever object is passed in. If the object HAS a generate() method, everything is fine. If it doesn't: KAPUTT!
This mistake will not be seen at compile time, but at runtime, so possibly when your program is already deployed and running. C# would notify you way before you came close to that.
The reason this mechanism is used, naively stated, because in OO languages naturally functions aren't first class citizens. As you can see, KnownNumber
and SecretNumber
contain JUST the functions to generate a number. One does not really need the classes at all. In Python, therefore, one could just throw them away and pick the functions on their own:
# OO Approach
SecretGame(SecretNumber())
SecretGame(KnownNumber())
# Functional Approach
# Dependencies
class SecretGame(object):
def __init__(self, generate):
number = generate()
print number
SecretGame(lambda: random.randint(0,10))
SecretGame(lambda: 5)
A lambda is just a function, that was declared "in line, as you go". A delegate is just the same in C#:
class Game
{
public Game(Func<int> generate)
{
Console.WriteLine(generate())
}
}
new Game(() => 5);
new Game(() => new Random().Next(0, 10));
Side note: The latter examples were not possible like this up to Java 7. There, Interfaces were your only way of specifying this behavior. However, Java 8 introduced lambda expressions so the C# example can be converted to Java very easily (Func<int>
becomes java.util.function.IntSupplier
and =>
becomes ->
).
How do I have to do in Python for calling an static method from another static method of the same class?
class Test() :
@staticmethod
def static_method_to_call()
pass
@staticmethod
def another_static_method() :
Test.static_method_to_call()
@classmethod
def another_class_method(cls) :
cls.static_method_to_call()
To highlight a block of code in Notepad++, please do the following steps
Style token
and select any of the five choices available ( styles from Using 1st style
to using 5th style
). Each is of different colors.If you want yellow color choose using 3rd style
.If you want to create your own style you can use Style Configurator
under Settings
menu.
This works for me to display code in frontend:
<style>
.content{
height:50vh;
width: 100%;
background: transparent;
border: none;
border-radius: 0;
resize: none;
outline: none;
}
.content:focus{
border: none;
-webkit-box-shadow: none;
-moz-box-shadow: none;
box-shadow: none;
}
</style>
<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>
View Live Demo: https://jsfiddle.net/bytxj50e/
Sometimes the page extends on scroll to buttom (for example in social networks), to scroll down to the end (ultimate buttom of the page) I use this script:
var scrollInterval = setInterval(function() {
document.documentElement.scrollTop = document.documentElement.scrollHeight;
}, 50);
And if you are in browser's javascript console, it might be useful to be able to stop the scrolling, so add:
var stopScroll = function() { clearInterval(scrollInterval); };
And then use stopScroll();
.
If you need to scroll to particular element, use:
var element = document.querySelector(".element-selector");
element.scrollIntoView();
Or universal script for autoscrolling to specific element (or stop page scrolling interval):
var notChangedStepsCount = 0;
var scrollInterval = setInterval(function() {
var element = document.querySelector(".element-selector");
if (element) {
// element found
clearInterval(scrollInterval);
element.scrollIntoView();
} else if((document.documentElement.scrollTop + window.innerHeight) != document.documentElement.scrollHeight) {
// no element -> scrolling
notChangedStepsCount = 0;
document.documentElement.scrollTop = document.documentElement.scrollHeight;
} else if (notChangedStepsCount > 20) {
// no more space to scroll
clearInterval(scrollInterval);
} else {
// waiting for possible extension (autoload) of the page
notChangedStepsCount++;
}
}, 50);
In case someone wants to rename all the keys at once providing a list with the new names:
def rename_keys(dict_, new_keys):
"""
new_keys: type List(), must match length of dict_
"""
# dict_ = {oldK: value}
# d1={oldK:newK,} maps old keys to the new ones:
d1 = dict( zip( list(dict_.keys()), new_keys) )
# d1{oldK} == new_key
return {d1[oldK]: value for oldK, value in dict_.items()}
I call a scheduled script who must connect to a list of Server this way:
Powershell.exe -File "YourScriptPath" "Par1,Par2,Par3"
Then inside the script:
param($list_of_servers)
...
Connect-Viserver $list_of_servers.split(",")
The split operator returns an array of string
Try this:
(select * from T1 minus select * from T2) -- all rows that are in T1 but not in T2
union all
(select * from T2 minus select * from T1) -- all rows that are in T2 but not in T1
;
No external tool. No performance issues with union all
.
here's your amended script
#!/bin/bash
folder="ABC" #no spaces between assignment
useracct='test'
day=$(date "+%d") # use $() to assign return value of date command to variable
month=$(date "+%B")
year=$(date "+%Y")
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir "$newfoldername"
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
rm "$folderToBeMoved";
fi
Here's a wrapper to pretty-fy it if you need it:
(function() {
var originalSetInterval = window.setInterval;
window.setInterval = function(fn, delay, runImmediately) {
if(runImmediately) fn();
return originalSetInterval(fn, delay);
};
})();
Set the third argument of setInterval to true and it'll run for the first time immediately after calling setInterval:
setInterval(function() { console.log("hello world"); }, 5000, true);
Or omit the third argument and it will retain its original behaviour:
setInterval(function() { console.log("hello world"); }, 5000);
Some browsers support additional arguments for setInterval which this wrapper doesn't take into account; I think these are rarely used, but keep that in mind if you do need them.
Use \W
which is equivalent to [^a-zA-Z0-9_]
. Check the documentation, https://docs.python.org/2/library/re.html
Import re
s = 'h^&ell`.,|o w]{+orld'
replaced_string = re.sub(r'\W+', '*', s)
output: 'h*ell*o*w*orld'
update: This solution will exclude underscore as well. If you want only alphabets and numbers to be excluded, then solution by nneonneo is more appropriate.
TryParse is faster...
The first of these functions, Parse, is one that should be familiar to any .Net developer. This function will take a string and attempt to extract an integer out of it and then return the integer. If it runs into something that it can’t parse then it throws a FormatException or if the number is too large an OverflowException. Also, it can throw an ArgumentException if you pass it a null value.
TryParse is a new addition to the new .Net 2.0 framework that addresses some issues with the original Parse function. The main difference is that exception handling is very slow, so if TryParse is unable to parse the string it does not throw an exception like Parse does. Instead, it returns a Boolean indicating if it was able to successfully parse a number. So you have to pass into TryParse both the string to be parsed and an Int32 out parameter to fill in. We will use the profiler to examine the speed difference between TryParse and Parse in both cases where the string can be correctly parsed and in cases where the string cannot be correctly parsed.
The Convert class contains a series of functions to convert one base class into another. I believe that Convert.ToInt32(string) just checks for a null string (if the string is null it returns zero unlike the Parse) then just calls Int32.Parse(string). I’ll use the profiler to confirm this and to see if using Convert as opposed to Parse has any real effect on performance.
Hope this helps.
Question has a good pagerank on google, so for anyone who's looking for answer to this question this might be helpful.
There is an extension in google chrome marketspace to do exactly that: https://chrome.google.com/webstore/detail/hccmhjmmfdfncbfpogafcbpaebclgjcp
Use NetworkCredential
Yep, just add these two lines to your code.
var credentials = new System.Net.NetworkCredential("username", "password");
client.Credentials = credentials;
The MyKey class must implement Serializable
if you are using @IdClass
I'm late to the party, but this is the solution I've crafted after reading a bunch of threads like this:
resolve_dir() {
(builtin cd `dirname "${1/#~/$HOME}"`'/'`basename "${1/#~/$HOME}"` 2>/dev/null; if [ $? -eq 0 ]; then pwd; fi)
}
This will resolve the absolute path of $1, play nice with ~, keep symlinks in the path where they are, and it won't mess with your directory stack. It returns the full path or nothing if it doesn't exist. It expects $1 to be a directory and will probably fail if it's not, but that's an easy check to do yourself.
No.
if ([[UIScreen mainScreen] bounds].size.height > 960)
on iPhone 5 is wrong
if ([[UIScreen mainScreen] bounds].size.height == 568)
In my case (macos, curl 7.54.0
), I have below proxy set with ~/.bash_profile
$ env |grep -i proxy |cut -d = -f1|sort
FTP_PROXY
HTTPS_PROXY
HTTP_PROXY
NO_PROXY
PROXY
ftp_proxy
http_proxy
https_proxy
no_proxy
With unknown reason, this version of curl
can't work with environment variables NO_PRXY
and no_proxy
properly, then I unset the proxy environment variables one by one, until to both HTTPS_PROXY
and https_proxy
.
unset HTTPS_PROXY
unset https_proxy
it starts working and can connect to internal urls
So I would recommend to unset all proxy variables if you have in your environment as temporary solution.
unset http_proxy https_proxy HTTP_PROXY HTTPS_PROXY
Try to use (focusout) instead of (blur)
If you already have Android SDK Platform Tool installed then go to File > Settings > System Settings > Android SDK > Launch Standalone SDK Manager.
There you will see in Tools Directory that Android SDK Platform-Tools is uninstalled. So deselect all and check that box and simply click on install button.
but what's the deal with new lines and carriage returns? What's the difference? Is \n\n the equivalent of \r\r or \n\r? Which should I use when I'm creating a line gap between lines?
No one here seemed to actualy answer this question, so here I am.
\r
represents 'carriage-return'
\n
represents 'line-feed'
The actual reason for them goes back to typewriters. As you typed the 'carriage' would slowly slide, character by character, to the right of the typewriter. When you got to the end of the line you would return the carriage and then go to a new line. To go to the new line, you would flip a lever which fed the lines to the type writer. Thus these actions, combined, were called carriage return line feed. So quite literally:
A line feed,\n
, means moving to the next line.
A carriage return, \r
, means moving the cursor to the beginning of the line.
Ultimately Hello\n\nWorld
should result in the following output on the screen:
Hello
World
Where as Hello\r\rWorld
should result in the following output.
It's only when combining the 2 characters \r\n
that you have the common understanding of knew line. I.E. Hello\r\nWorld
should result in:
Hello
World
And of course \n\r
would result in the same visual output as \r\n
.
Originally computers took \r
and \n
quite literally. However these days the support for carriage return is sparse. Usually on every system you can get away with using \n
on its own. It never depends on the OS, but it does depend on what you're viewing the output in.
Still I'd always advise using \r\n
wherever you can!
In Linux:
sudo docker ps -aqf "name=containername"
Or in OS X, Windows:
docker ps -aqf "name=containername"
where containername
is your container name.
To avoid getting false positives, as @llia Sidorenko notes, you can use regex anchors like so:
docker ps -aqf "name=^containername$"
explanation:
-q
for quiet. output only the ID-a
for all. works even if your container is not running-f
for filter.^
container name must start with this string$
container name must end with this stringYou are writing if(true)
so it will always show "Hello " message.
You should take decision on the basis of value of n
returned.
The problem is probably that you forgot to close the program and that you instead have the program running in the background.
Find the console window where the exe file program is running, and close it by clicking the X in the upper right corner. Then try to recompile the program. In my case this solved the problem.
I know this posting is old, but I am answering for the other people like me who find this through the search engines.
I would like to recommend using the scrollTo plugin
http://demos.flesler.com/jquery/scrollTo/
You can the set scrollto by jquery css selector.
$('html,body').scrollTo( $(target), 800 );
I have had great luck with the accuracy of this plugin and its methods, where other methods of achieving the same effect like using .offset()
or .position()
have failed to be cross browser for me in the past. Not saying you can't use such methods, I'm sure there is a way to do it cross browser, I've just found scrollTo to be more reliable.
You might want to check out Dean Edwards' Base Class: http://dean.edwards.name/weblog/2006/03/base/
Alternatively, there is this example / article by Douglas Crockford on classical inheritance in JavaScript: http://www.crockford.com/javascript/inheritance.html
PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.
To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy
Never mind, I found the answer.
This will do the trick.
Dim colIndex As Long
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)
1.84E-07 is the exact value, represented using scientific notation, also known as exponential notation.
1.845E-07 is the same as 0.0000001845. Excel will display a number very close to 0 as 0, unless you modify the formatting of the cell to display more decimals.
C# however will get the actual value from the cell. The ToString method use the e-notation when converting small numbers to a string.
You can specify a format string if you don't want to use the e-notation.
I had this error with VS 2015, in my case going to the project properties page, Web tab, and clicking on Create Virtual Directory
button in Servers section solved it
You should avoid hardcoding SQL statements in your application. If you don't use ADO nor EntityFramework, I would suggest you to ad a stored procedure to the database and call it from your c# application. A sample code can be found here: How to execute a stored procedure within C# program and here http://msdn.microsoft.com/en-us/library/ms171921%28v=vs.80%29.aspx.
The error log is straightforward. As it suggested,You need to add 198.211.99.20 to your ALLOWED_HOSTS
setting.
In your project settings.py file,set ALLOWED_HOSTS
like this :
ALLOWED_HOSTS = ['198.211.99.20', 'localhost', '127.0.0.1']
For further reading read from here.
The strcmp and strcmpi functions are the most direct way to do this. They search through arrays.
strs = {'HA' 'KU' 'LA' 'MA' 'TATA'}
ix = find(strcmp(strs, 'KU'))
What comes after the "Where" is a constraint on the generic type T you declared, so:
class means that the T should be a class and not a value type or a struct.
new() indicates that the T class should have a public parameter-free default constructor defined.
<input type="text" name='mobile_number' pattern=[0-9]{1}[0-9]{9}>
https://code.google.com/p/worlddb/downloads/list
This database has multi languages country names, region names, city names and they's latitude and longitude number and country's alpha2 code .
try
{
$conn = new PDO("sqlsrv:Server=$server_name;Database=$db_name;ConnectionPooling=0", "", "");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
$e->getMessage();
}
Don't use MD5
as it is insecure. I would recommend using SHA
or bcrypt
with a salt
:
SHA256('".$password."')
I've found many problems here, so I made my own.
Here it is in all it's glory, with tests:
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*([^a-zA-Z\d\s])).{9,}$
https://regex101.com/r/DCRR65/4/tests
Things to look out for:
\w
because that includes _
, which I'm testing for.Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http
argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.
So, you need to look to see whether /dvlpmnt/libPI-Http.a
is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32
option. Then you need to establish whether there is an alternative libPI-Http.a
or libPI-Http.so
file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where
argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.
To establish what is in that library, you may need to do:
mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk
The 'file
' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.
With react-router v2.8.1 (probably other 2.x.x versions as well, but I haven't tested it) you can use this implementation to do a Router redirect.
import { Router } from 'react-router';
export default class Foo extends Component {
static get contextTypes() {
return {
router: React.PropTypes.object.isRequired,
};
}
handleClick() {
this.context.router.push('/some-path');
}
}
This is a simple way of doing it:
Calendar cal = Calendar.getInstance();
SimpleDateFormat dateOnly = new SimpleDateFormat("MM/dd/yyyy");
System.out.println(dateOnly.format(cal.getTime()));
I tried find similiar as topic first post.
For my needs I find this
http://answers.oreilly.com/topic/217-how-to-match-whole-words-with-a-regular-expression/
"\b[a-zA-Z0-9]{3}\b"
3 char words only "iokldöajf asd alkjwnkmd asd kja wwda da aij ednm <.jkakla "
The semantics of Having
To better understand having, you need to see it from a theoretical point of view.
A group by is a query that takes a table and summarizes it into another table. You summarize the original table by grouping the original table into subsets (based upon the attributes that you specify in the group by). Each of these groups will yield one tuple.
The Having is simply equivalent to a WHERE clause after the group by has executed and before the select part of the query is computed.
Lets say your query is:
select a, b, count(*)
from Table
where c > 100
group by a, b
having count(*) > 10;
The evaluation of this query can be seen as the following steps:
You can extend this to any complex query there Table can be any complex query that return a table (a cross product, a join, a UNION, etc).
In fact, having is syntactic sugar and does not extend the power of SQL. Any given query:
SELECT list
FROM table
GROUP BY attrList
HAVING condition;
can be rewritten as:
SELECT list from (
SELECT listatt
FROM table
GROUP BY attrList) as Name
WHERE condition;
The listatt is a list that includes the GROUP BY attributes and the expressions used in list and condition. It might be necessary to name some expressions in this list (with AS). For instance, the example query above can be rewritten as:
select a, b, count
from (select a, b, count(*) as count
from Table
where c > 100
group by a, b) as someName
where count > 10;
The solution you need
Your solution seems to be correct:
SELECT s.sid, s.name
FROM Supplier s, Supplies su, Project pr
WHERE s.sid = su.sid AND su.jid = pr.jid
GROUP BY s.sid, s.name
HAVING COUNT (DISTINCT pr.jid) >= 2
You join the three tables, then using sid as a grouping attribute (sname is functionally dependent on it, so it does not have an impact on the number of groups, but you must include it, otherwise it cannot be part of the select part of the statement). Then you are removing those that do not satisfy your condition: the satisfy pr.jid is >= 2
, which is that you wanted originally.
Best solution to your problem
I personally prefer a simpler cleaner solution:
SELECT sid, sname from
(SELECT sid from supplies
GROUP BY sid, pid
HAVING count(DISTINCT jid) >= 2
) AS T1
NATURAL JOIN
Supliers;
It will also be faster to execute, because the join is only done when needed, not all the times.
--dmg
Looks like you need to add win32clipboard to your site-packages. It's part of the pywin32 package
An example based on Chuck's answer:
myIntToStr :: Int -> String
myIntToStr x
| x < 3 = show x ++ " is less than three"
| otherwise = "normal"
Note that without the show
the third line will not compile.
if(substr($str, -1, 1) == ',') {
$str = substr($str, 0, -1);
}
$("#element").validate().valid()
My approach:
<div class="left">Left</div>
<div class="right">Right</div>
CSS:
.left {
float: left;
width: calc(100% - 200px);
background: green;
}
.right {
float: right;
width: 200px;
background: yellow;
}
You need to give a function to be called after the time delay as the second argument to after
:
after(delay_ms, callback=None, *args)
Registers an alarm callback that is called after a given time.
So what you really want to do is this:
tiles_letter = ['a', 'b', 'c', 'd', 'e']
def add_letter():
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
root.after(0, add_letter) # add_letter will run as soon as the mainloop starts.
root.mainloop()
You also need to schedule the function to be called again by repeating the call to after
inside the callback function, since after
only executes the given function once. This is also noted in the documentation:
The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself
Note that your example will throw an exception as soon as you've exhausted all the entries in tiles_letter
, so you need to change your logic to handle that case whichever way you want. The simplest thing would be to add a check at the beginning of add_letter
to make sure the list isn't empty, and just return
if it is:
def add_letter():
if not tiles_letter:
return
rand = random.choice(tiles_letter)
tile_frame = Label(frame, text=rand)
tile_frame.pack()
root.after(500, add_letter)
tiles_letter.remove(rand) # remove that tile from list of tiles
Live-Demo: repl.it
Late to the party, but here is a simplification of @Tarek360's Kotlin answer that caters for RadioGroup
s that might contain non-RadioButtons:
val RadioGroup.checkedIndex: Int
get() = children
.filter { it is RadioButton }
.indexOfFirst { it.id == checkedRadioButtonId }
If you're RadioFroup
definitely only has RadioButton
s then this can be a simple as:
private val RadioGroup.checkedIndex =
children.indexOfFirst { it.id == checkedRadioButtonId }
Then you don't have the overhead of findViewById
.
/^[\w-_.]*$/
What is means By:
^ Start of string
[......] Match characters inside
\w Any word character so 0-9 a-z A-Z
-_. Matched by charecter - and _ and .
Zero or more of pattern or unlimited $ End of string If you want to limit the amount of characters:
/^[\w-_.]{0,5}$/
{0,5} Means 0-5 Numbers & characters
My 2cents, in a single system user you can set the port also on /etc/ssh/ssh_config then rsync will use the port set here
The quick and simple answer is No.
Javascript is quite a high level language and does not have access to this sort of information.
use this command php artisan migrate --path=/database/migrations/my_migration.php
it worked for me..
Fiddle link : http://jsfiddle.net/7LXPq/93/
Two problems in this:
Please follow the fiddle link for demo:
var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#datePicker').val(today);
In spite of all the answers you already received, it is worth noting that you do not need to write a plugin to use jQuery in a function. Certainly if it's a simple, one-time function, I believe writing a plugin is overkill. It could be done much more easily by just passing the selector to the function as a parameter. Your code would look something like this:
function myFunction($param) {
$param.hide(); // or whatever you want to do
...
}
myFunction($('#my_div'));
Note that the $
in the variable name $param
is not required. It is just a habit of mine to make it easy to remember that that variable contains a jQuery selector. You could just use param
as well.
This is due a conflict of versions, to solve it, just force an update of your support-annotations version, adding this line on your module: app gradle
implementation ('com.android.support:support-annotations:27.1.1')
Hope this solves your issue ;)
Edit
Almost forgot, you can declare a single extra property (https://docs.gradle.org/current/userguide/writing_build_scripts.html#sec:extra_properties) for the version, go to your project (or your top) gradle file, and declare your support, or just for this example, annotation version var
ext.annotation_version = "27.1.1"
Then in your module gradle replace it with:
implementation ("com.android.support:support-annotations:$annotation_version")
This is very similar to the @emadabel solution, which is a good alternative for doing it, but without the block, or the rootproject
prefix.
I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.
The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119
// This class implements a UITextView that has a UITextField behind it, where the
// UITextField provides the border.
//
class TextView : UITextView, UITextViewDelegate
{
var textField = TextField();
required init?(coder: NSCoder)
{
fatalError("This class doesn't support NSCoding.")
}
override init(frame: CGRect, textContainer: NSTextContainer?)
{
super.init(frame: frame, textContainer: textContainer);
self.delegate = self;
// Create a background TextField with clear (invisible) text and disabled
self.textField.borderStyle = UITextBorderStyle.RoundedRect;
self.textField.textColor = UIColor.clearColor();
self.textField.userInteractionEnabled = false;
self.addSubview(textField);
self.sendSubviewToBack(textField);
}
convenience init()
{
self.init(frame: CGRectZero, textContainer: nil)
}
override func layoutSubviews()
{
super.layoutSubviews()
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
// UITextViewDelegate - Note: If you replace delegate, your delegate must call this
func scrollViewDidScroll(scrollView: UIScrollView)
{
// Do not scroll the background textView
self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
}
}
If you want to extract from a
tag then
$('.dep_buttons').text().substr(0,25)
With the mouseover event,
$(this).text($(this).text().substr(0, 25));
The above will extract the text of a tag, then extract again assign it back.
You can use String arrays to add jComboBox items
String [] items = { "First item", "Second item", "Third item", "Fourth item" };
JComboBox comboOne = new JComboBox (items);
They have to do with the difference between DOS style line endings and Unix style. Check out the Wikipedia article. You may be able to find a dos2unix tool to help, or simply write a small script to fix them yourself.
Edit: I found the following Python sample code here:
string.replace( str, '\r', '' )
If you know you have a number of seconds, you can create a TimeSpan value by calling TimeSpan.FromSeconds:
TimeSpan ts = TimeSpan.FromSeconds(80);
You can then obtain the number of days, hours, minutes, or seconds. Or use one of the ToString overloads to output it in whatever manner you like.
for same height you should chage your css "display" Properties. For more detail see given example.
.list{_x000D_
display: table;_x000D_
flex-wrap: wrap;_x000D_
max-width: 500px;_x000D_
}_x000D_
_x000D_
.list-item{_x000D_
background-color: #ccc;_x000D_
display: table-cell;_x000D_
padding: 0.5em;_x000D_
width: 25%;_x000D_
margin-right: 1%;_x000D_
margin-bottom: 20px;_x000D_
}_x000D_
.list-content{_x000D_
width: 100%;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h2>box 1</h2>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. </p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit.</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h3>box 2</h3>_x000D_
<p>Lorem ipsum dolor</p>_x000D_
</div>_x000D_
</li>_x000D_
<li class="list-item">_x000D_
<div class="list-content">_x000D_
<h1>h1</h1>_x000D_
</div>_x000D_
</li>
_x000D_
I have used a tool in my work its LDRA tool suite
It is used for testing the c/c++ code but it also can check against coding standards such as MISRA etc.
Instead of using ">" to redirect like this:
java Foo > log
use ">>" to append normal "stdout" output to a new or existing file:
java Foo >> log
However, if you also want to capture "stderr" errors (such as why the Java program couldn't be started), you should also use the "2>&1" tag which redirects "stderr" (the "2") to "stdout" (the "1"). For example:
java Foo >> log 2>&1
If you have your radios in a container with id = radioButtonContainerId you can still use onClick and then check which one is selected and accordingly run some functions:
$('#radioButtonContainerId input:radio').click(function() {
if ($(this).val() === '1') {
myFunction();
} else if ($(this).val() === '2') {
myOtherFunction();
}
});
Recheck the package declarations in all your classes!
This behaviour has been observed in NetBeans, when the package declaration in one of the classes of the package refers to a non-existent or wrong package. NetBeans normally detects and highlights this error but has been known to fail and misleadingly report the package as free of errors when this is not the case.
If you want printable ascii characters you probably should correct your code to:
if ord(char) < 32 or ord(char) > 126: return ''
this is equivalent, to string.printable
(answer from @jterrace), except for the absence of returns and tabs ('\t','\n','\x0b','\x0c' and '\r') but doesnt correspond to the range on your question
>>> a = 147.234
>>> a % 1
0.23400000000000887
>>> a // 1
147.0
>>>
If you want the integer part as an integer and not a float, use int(a//1)
instead. To obtain the tuple in a single passage: (int(a//1), a%1)
EDIT: Remember that the decimal part of a float number is approximate, so if you want to represent it as a human would do, you need to use the decimal library
select DATEDIFF(dd, '12/30/1899', mydatefield)
Table: Table is a preliminary storage for storing data and information in RDBMS. A table is a collection of related data entries and it consists of columns and rows.
View: A view is a virtual table whose contents are defined by a query. Unless indexed, a view does not exist as a stored set of data values in a database. Advantages over table are
The lock event ID is 4800, and the unlock is 4801. You can find them in the Security logs. You probably have to activate their auditing using Local Security Policy (secpol.msc, Local Security Settings in Windows XP) -> Local Policies -> Audit Policy. For Windows 10 see the picture below.
Look in Description of security events in Windows 7 and in Windows Server 2008 R2 under Subcategory: Other Logon/Logoff Events.
Try adding
html {
overflow-x: hidden;
}
as well as
body {
overflow-x: hidden;
}
I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.
public void correctColumnWidths()
{
double remainingSpace = myList.ActualWidth;
if (remainingSpace > 0)
{
for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
if (i != 2)
remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;
//Leave 15 px free for scrollbar
remainingSpace -= 15;
(myList.View as GridView).Columns[2].Width = remainingSpace;
}
}
Reverting a merge commit has been exhaustively covered in other questions. When you do a fast-forward merge, the second one you describe, you can use git reset
to get back to the previous state:
git reset --hard <commit_before_merge>
You can find the <commit_before_merge>
with git reflog
, git log
, or, if you're feeling the moxy (and haven't done anything else): git reset --hard HEAD@{1}
You can probably just use the true
command:
if [ "$a" -ge 10 ]; then
true
elif [ "$a" -le 5 ]; then
echo "1"
else
echo "2"
fi
An alternative, in your example case (but not necessarily everywhere) is to re-order your if/else:
if [ "$a" -le 5 ]; then
echo "1"
elif [ "$a" -lt 10 ]; then
echo "2"
fi
In my case the mentioned "duplicate entry" error arised after settingmultiDexEnable=true
in the build.gradle.
In order to fully resolve the error first of all have a look at Configure Apps with Over 64K Methods (espescially "Configuring Your App for Multidex with Gradle").
Furthermore search for occurences of the class that causes the "duplicate entry" error using ctrl+n in Android Studio. Determine the module and dependency that contains the duplicate and exclude it from build, e.g.:
compile ('org.roboguice:roboguice:2.0') {
exclude module: 'support-v4'
}
I had to try multiple module labels till it worked. Excluding "support-v4" solves issues related to "java.util.zip.ZipException: duplicate entry: android/support/v4/*"
None of these will allow you to compile PHP with cURL enabled.
In order to compile with cURL, you need libcurl header files (.h files). They are usually found in /usr/include/curl
. They generally are bundled in a separate development package.
Per example, to install libcurl in Ubuntu:
sudo apt-get install libcurl4-gnutls-dev
Or CentOS:
sudo yum install curl-devel
Then you can just do:
./configure --with-curl # other options...
If you compile cURL manually, you can specify the path to the files without the lib
or include
suffix. (e.g.: /usr/local
if cURL headers are in /usr/local/include/curl
).
I believe that there can still be and valid logic on views. But for this kind of things I agree with @BigMike, it is better placed on the model. Having said that the problem can be solved in three ways:
Your answer (assuming this works, I haven't tried this):
<div class="details @(@Model.Details.Count > 0 ? "show" : "hide")">
Second option:
@if (Model.Details.Count > 0) {
<div class="details show">
}
else {
<div class="details hide">
}
Third option:
<div class="@("details " + (Model.Details.Count>0 ? "show" : "hide"))">
Here is an example from W3Schools:
function myFunction() {
var elements = document.getElementById("myForm").elements;
var obj ={};
for(var i = 0 ; i < elements.length ; i++){
var item = elements.item(i);
obj[item.name] = item.value;
}
document.getElementById("demo").innerHTML = JSON.stringify(obj);
}
The demo can be found here.
Consider using System.Windows.Forms.Timer
instead of System.Threading.Timer
for a GUI application, for timers that are based on the Windows message queue instead of on dedicated threads or the thread pool.
In your scenario, for the purpose of periodic updates of UI, it seems particularly appropriate since you don't really have a background work or long calculation to perform. You just want to do periodic small tasks that have to happen on the UI thread anyway.
Here's a different way of doing it.
If you're using Windows the following acts like double-clicking the file in Explorer, or giving the file name as an argument to the DOS "start" command: the file is opened with whatever application (if any) its extension is associated with.
filepath = 'textfile.txt'
import os
os.startfile(filepath)
Example:
import os
os.startfile('textfile.txt')
This will open textfile.txt with Notepad if Notepad is associated with .txt files.
There seems to be some confusion over how to get this set up for the Express version specifically. Using the Windows Desktop (WD) version of VS Express 2012, I followed the instructions in Steve B's and Rick Martin's answers with the modifications below.
"C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0"
, copy to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WDExpressExtensions\Microsoft\XNA Game Studio 4.0"
<Edition>WDExpress</Edition>
(you should be able to see where it makes sense)devenv.exe
with WDExpress.exe
"%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions"
with "%LocalAppData%\Microsoft\WDExpress\11.0\Extensions"
I haven't done a lot of work since then, but I did manage to create a new game project and it seems fine so far.
It's easy, You need to find index of [ and ] then substring. (Here [ is always at start and ] is at end) ,
String loginToken = "[wdsd34svdf]";
System.out.println( loginToken.substring( 1, loginToken.length() - 1 ) );
{ "scripts" :
{ "build": "node build.js"}
}
npm run build
ORnpm run-script build
{
"name": "build",
"version": "1.0.0",
"scripts": {
"start": "node build.js"
}
}
npm start
NB: you were missing the
{ brackets }
and the node command
folder structure is fine:
+ build
- package.json
- build.js
One liner answer to the above question is :-
let the two lists be list1 and list2, and your requirement is to ensure whether two lists have the same elements, then as per me, following will be the best approach :-
if ((len(list1) == len(list2)) and
(all(i in list2 for i in list1))):
print 'True'
else:
print 'False'
The above piece of code will work per your need i.e. whether all the elements of list1 are in list2 and vice-verse.
But if you want to just check whether all elements of list1 are present in list2 or not, then you need to use the below code piece only :-
if all(i in list2 for i in list1):
print 'True'
else:
print 'False'
The difference is, the later will print True, if list2 contains some extra elements along with all the elements of list1. In simple words, it will ensure that all the elements of list1 should be present in list2, regardless of whether list2 has some extra elements or not.
The documentation on split()
says:
Splits this string around matches of the given regular expression.
(Emphasis mine.)
A dot is a special character in regular expression syntax. Use Pattern.quote()
on the parameter to split() if you want the split to be on a literal string pattern:
String[] words = temp.split(Pattern.quote("."));
There's a way you can do this.
You will need ROOT access to edit the following file.
Navigate to
/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk
and open the fileSDKSettings.plist
.In that file, expand DefaultProperties and change CODE_SIGNING_REQUIRED to
NO
, while you are there, you can also change ENTITLEMENTS_REQUIRED toNO
also.
You will have to restart Xcode for the changes to take effect. Also, you must do this for every .sdk you want to be able to run on device.
Now, in your project settings, you can change Code Signing Identity
to Don't Code Sign
.
Your app should now build and install on your device successfully.
There are some issues with iOS 5.1 SDK that this method may not work exactly the same. Any other updates will be listed here when they become available.
You can find the correct path to SDKSettings.plist
with xcrun
.
xcrun --sdk iphoneos --show-sdk-path
New SDKSettings.plist location for the iOS 5.1 SDK:
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.1.sdk/SDKSettings.plist
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
In tables I have used \footnotetext.
You just said javascript in your tags, so @Wampie Driessen post could helps you.
I want also to contribute, so you can use the following when using jQuery if you need it.
//Firefox
$('#elem').bind('DOMMouseScroll', function(e){
if(e.detail > 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
//IE, Opera, Safari
$('#elem').bind('mousewheel', function(e){
if(e.wheelDelta< 0) {
//scroll down
console.log('Down');
}else {
//scroll up
console.log('Up');
}
//prevent page fom scrolling
return false;
});
Another example:
$(function(){
var _top = $(window).scrollTop();
var _direction;
$(window).scroll(function(){
var _cur_top = $(window).scrollTop();
if(_top < _cur_top)
{
_direction = 'down';
}
else
{
_direction = 'up';
}
_top = _cur_top;
console.log(_direction);
});
});?
In a similar vein to Travis vignon's answer, I required data from the eloquent model, and if conditions were correct, I needed to either delete or update the model. I wound up getting the minimum and maximum I'd field returned by my query (in case another field was added to the table that would meet my selection criteria) along with the original selection criteria to update the fields via one raw SQL query (as opposed to one eloquent query per object in the collection).
I know the use of raw SQL violates laravels beautiful code philosophy, but itd be hard to stomach possibly hundreds of queries in place of one.
As others have noted, Mongoose 4
supports this. It is very important to note that you can recurse deeper than one level too, if needed—though it is not noted in the docs:
Project.findOne({name: req.query.name})
.populate({
path: 'threads',
populate: {
path: 'messages',
model: 'Message',
populate: {
path: 'user',
model: 'User'
}
}
})
I ended up just making a short and sweet fsize
function(note, no error checking)
int fsize(FILE *fp){
int prev=ftell(fp);
fseek(fp, 0L, SEEK_END);
int sz=ftell(fp);
fseek(fp,prev,SEEK_SET); //go back to where we were
return sz;
}
It's kind of silly that the standard C library doesn't have such a function, but I can see why it'd be difficult as not every "file" has a size(for instance /dev/null
)
If you really need the right way then you can use Google's recently open sourced libphonenumber
There's the built-in trim function that is perfect for the purpose.
SELECT trim(both 'ag' from 'asdfg');
btrim
-------
sdf
(1 riga)
http://www.postgresql.org/docs/8.1/static/functions-string.html
Here is my solution.
///// find duplicates in an array and remove them
void unique(int* input, int n)
{
merge_sort(input, 0, n) ;
int prev = 0 ;
for(int i = 1 ; i < n ; i++)
{
if(input[i] != input[prev])
if(prev < i-1)
input[prev++] = input[i] ;
}
}
#define IsIOS8 (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1)
Mac version. From terminal run:
open /Applications/Google\ Chrome.app/ --args --allow-file-access-from-files
The first is type correct, and correct in some strict sense. (If you think about is, size can never be less than zero.) That warning strikes me as one of the good candidates for being ignored, though.
You can do the following. It also avoids buttons overlapping.
<div class="center-block" style="max-width:400px">
<a href="#" class="btn btn-success">Accept</a>
<a href="#" class="btn btn-danger"> Reject</a>
</div>
There is absolutely no way you can reliably check if there is an internet connection or not (I assume you mean access to the internet).
You can, however, request resources that are virtually never offline, like pinging google.com or something similar. I think this would be efficient.
try {
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 1000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
return (reply.Status == IPStatus.Success);
}
catch (Exception) {
return false;
}
Yes. If memory serves me, that should work. Our you could use:
DELETE FROM table WHERE id <> 2
Modulus operator gives the remainder. Modulus operator in c usually takes the sign of the numerator
Also modulus(remainder) operator can only be used with integer type and cannot be used with floating point.
I would recommend virtualenvwrapper as well. It works wonders for me and how I always have problems with activating. http://virtualenvwrapper.readthedocs.org/en/latest/
You urls are not in the same repository, so you can't do it with the svn diff
command.
svn: 'http://svn.boost.org/svn/boost/sandbox/boost/extension' isn't in the same repository as 'http://cloudobserver.googlecode.com/svn'
Another way you could do it, is export each repos using svn export
, and then use the diff command to compare the 2 directories you exported.
// Export repositories
svn export http://svn.boost.org/svn/boost/sandbox/boost/extension/ repos1
svn export http://cloudobserver.googlecode.com/svn/branches/v0.4/Boost.Extension.Tutorial/libs/boost/extension/ repos2
// Compare exported directories
diff repos1 repos2 > file.diff
In most situations, git fetch
should do what you want, which is 'get anything new from the remote repository and put it in your local copy without merging to your local branches'. git fetch --tags
does exactly that, except that it doesn't get anything except new tags.
In that sense, git fetch --tags
is in no way a superset of git fetch
. It is in fact exactly the opposite.
git pull
, of course, is nothing but a wrapper for a git fetch <thisrefspec>; git merge
. It's recommended that you get used to doing manual git fetch
ing and git merge
ing before you make the jump to git pull
simply because it helps you understand what git pull
is doing in the first place.
That being said, the relationship is exactly the same as with git fetch
. git pull
is the superset of git pull --tags
.
Alternatively in Java8 you can use Nullable or NotNull Annotations according to your need.
public class TestingNullable {
@Nullable
public Color nullableMethod(){
//some code here
return color;
}
public void usingNullableMethod(){
// some code
Color color = nullableMethod();
// Introducing assurance of not-null resolves the problem
if (color != null) {
color.toString();
}
}
}
public class TestingNullable {
public void foo(@NotNull Object param){
//some code here
}
...
public void callingNotNullMethod() {
//some code here
// the parameter value according to the explicit contract
// cannot be null
foo(null);
}
}
Just add this extension:
extension NSDate {
var stringValue: String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yourDateFormat"
return formatter.stringFromDate(self)
}
}
One can rename indexes the same way:
alter index owner.index_name rename to new_name;
For a class diagram using Oracle database, use the following steps:
File ? Data Modeler ? Import ? Data Dictionary ? select DB connection ? Next ? select database->select tabels -> Finish
You are trying to pass pointers (which you do not delete, thus leaking memory) where references are needed. You do not really need pointers here:
Complex firstComplexNumber(81, 93);
Complex secondComplexNumber(31, 19);
cout << "Numarul complex este: " << firstComplexNumber << endl;
// ^^^^^^^^^^^^^^^^^^ No need to dereference now
// ...
Complex::distanta(firstComplexNumber, secondComplexNumber);
If you can get access from a Windows machine, you can use xcopy with /T and /E to copy just the folder structure (the /E includes empty folders)
[EDIT!]
This one uses rsync to recreate the directory structure but without the files. http://psung.blogspot.com/2008/05/copying-directory-trees-with-rsync.html
Might actually be better :)
As you run the container, a directory on your host is created and mounted into the container. You can find out what directory this is with
$ docker inspect --format "{{ .Volumes }}" <ID>
map[/export:/var/lib/docker/vfs/dir/<VOLUME ID...>]
If you want to mount a directory from your host inside your container, you have to use the -v
parameter and specify the directory. In your case this would be:
docker run -v /export:/export data
SO you would use the hosts folder inside your container.
var culture = new CultureInfo( "en-GB" );
var dateValue = new DateTime( 2011, 12, 1 );
var result = dateValue.ToString( "d", culture ) );
How about this: Collections.list(Enumeration e) returns an ArrayList<T>
You can use RTRIM
or cast your value to VARCHAR
:
SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)
Or
SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)
Mongodb v3.4
You need to do the following to create a secure database:
Make sure the user starting the process has permissions and that the directories exist (/data/db
in this case).
1) Start MongoDB without access control.
mongod --port 27017 --dbpath /data/db
2) Connect to the instance.
mongo --port 27017
3) Create the user administrator (in the admin authentication database).
use admin
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
4) Re-start the MongoDB instance with access control.
mongod --auth --port 27017 --dbpath /data/db
5) Connect and authenticate as the user administrator.
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
6) Create additional users as needed for your deployment (e.g. in the test authentication database).
use test
db.createUser(
{
user: "myTester",
pwd: "xyz123",
roles: [ { role: "readWrite", db: "test" },
{ role: "read", db: "reporting" } ]
}
)
7) Connect and authenticate as myTester.
mongo --port 27017 -u "myTester" -p "xyz123" --authenticationDatabase "test"
I basically just explained the short version of the official docs here: https://docs.mongodb.com/master/tutorial/enable-authentication/
With jQuery:
$.post("test.php", { json_string:JSON.stringify({name:"John", time:"2pm"}) });
Without jQuery:
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "/json-handler");
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(JSON.stringify({name:"John Rambo", time:"2pm"}));
If you cannot use std::to_string
from C++11, you can write it as it is defined on cppreference.com:
std::string to_string( int value )
Converts a signed decimal integer to a string with the same content as whatstd::sprintf(buf, "%d", value)
would produce for sufficiently large buf.
Implementation
#include <cstdio>
#include <string>
#include <cassert>
std::string to_string( int x ) {
int length = snprintf( NULL, 0, "%d", x );
assert( length >= 0 );
char* buf = new char[length + 1];
snprintf( buf, length + 1, "%d", x );
std::string str( buf );
delete[] buf;
return str;
}
You can do more with it. Just use "%g"
to convert float or double to string, use "%x"
to convert int to hex representation, and so on.
Yes, there is a difference between ++i
and i++
in a for
loop, though in unusual use cases; when a loop variable with increment/decrement operator is used in the for block or within the loop test expression, or with one of the loop variables. No it is not simply a syntax thing.
As i
in a code means evaluate the expression i
and the operator does not mean an evaluation but just an operation;
++i
means increment value of i
by 1 and later evaluate i
,i++
means evaluate i
and later increment value of i
by 1.So, what are obtained from each two expressions differ because what is evaluated differs in each. All same for --i
and i--
For example;
let i = 0
i++ // evaluates to value of i, means evaluates to 0, later increments i by 1, i is now 1
0
i
1
++i // increments i by 1, i is now 2, later evaluates to value of i, means evaluates to 2
2
i
2
In unusual use cases, however next example sounds useful or not does not matter, it shows a difference
for(i=0, j=i; i<10; j=++i){
console.log(j, i)
}
for(i=0, j=i; i<10; j=i++){
console.log(j, i)
}
In Xcode 4.x press
(or click Menubar
> Product
> Scheme
> Edit Scheme
)
select the "Diagnostics" tab and click "Enable Zombie Objects":
This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.
A typical case is when you over-release an object and you don't know which one:
-[UITableView release]: message sent to deallocated instance
This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.
Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.
To filter on sytem based apps :
private boolean isSystemPackage(ResolveInfo ri) {
return (ri.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
}
---> Open Firefox
---> open page the video
---> Play Video
Click ---> Open menu
Click ---> open web developer tools
Click ---> Developer Toolbar
Click ---> Network
---> Go to Filter URLs ---> Write "M3u8" --> for Find "m3u8"
---> Copy URL ".m3u8"
========================
Now Download software "m3u8x" ----> https://tajaribsoft-en.blogspot.com/2016/06/m3u8x.html#downloadx12
---> open software "m3u8x"
---> paste URL "m3u8"
---> chose option "One...One"
---> Click Download
---> Start Download
========================
image "Open menu" ===>
image "Developer Toolbar" ===>
image "m3u8x" ===>
Here is the solution just copy your SDK Manager.exe
file at the root folder of your android studio's installation, Sync your project and cheers... here is the link for details.
running Android Studio on Windows 7 fails, no Android SDK found