To file under both 'established' and 'key-value store': Berkeley DB.
Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).
Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.
You can disable any Python warnings via the PYTHONWARNINGS
environment variable. In this case, you want:
export PYTHONWARNINGS="ignore:Unverified HTTPS request"
To disable using Python code (requests >= 2.16.0
):
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
For requests < 2.16.0
, see original answer below.
Original answer
The reason doing urllib3.disable_warnings()
didn't work for you is because it looks like you're using a separate instance of urllib3 vendored inside of requests.
I gather this based on the path here: /usr/lib/python2.6/site-packages/requests/packages/urllib3/connectionpool.py
To disable warnings in requests' vendored urllib3, you'll need to import that specific instance of the module:
import requests
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
<input type = "button" style ="background-color:green"/>
This seemed to work for me - across all browsers.
<script type="text/javascript">
window.onload = function(){
document.location = 'somefile.zip';
}
</script>
I've finally managed to do it. Answer in code snippet below:
var querystring = require('querystring');
var request = require('request');
var form = {
username: 'usr',
password: 'pwd',
opaque: 'opaque',
logintype: '1'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'http://myUrl',
body: formData,
method: 'POST'
}, function (err, res, body) {
//it works!
});
You haven't created a user db
. If its just a fresh install, the default user is postgres
and the password should be blank. After you access it, you can create the users you need.
public Bitmap TakeScreenshot(By by) {
// 1. Make screenshot of all screen
var screenshotDriver = _selenium as ITakesScreenshot;
Screenshot screenshot = screenshotDriver.GetScreenshot();
var bmpScreen = new Bitmap(new MemoryStream(screenshot.AsByteArray));
// 2. Get screenshot of specific element
IWebElement element = FindElement(by);
var cropArea = new Rectangle(element.Location, element.Size);
return bmpScreen.Clone(cropArea, bmpScreen.PixelFormat);
}
Here is my simple solution:
1 - Define your fragment
public class MyFragment extends Fragment {
private String parameter;
public MyFragment() {
}
public void setParameter(String parameter) {
this.parameter = parameter;
}
}
2 - Create your new fragment and populate the parameter
myfragment = new MyFragment();
myfragment.setParameter("here the value of my parameter");
3 - Enjoy it!
Obviously you can change the type and the number of parameters. Quick and easy.
To add to Silfheed's answer, which was useful, I needed to patch multiple methods of the object in question. I found it more elegant to do it this way:
Given the following function to test, located in module.a_function.to_test.py
:
from some_other.module import SomeOtherClass
def add_results():
my_object = SomeOtherClass('some_contextual_parameters')
result_a = my_object.method_a()
result_b = my_object.method_b()
return result_a + result_b
To test this function (or class method, it doesn't matter), one can patch multiple methods of the class SomeOtherClass
by using patch.object()
in combination with sys.modules
:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
mocked_other_class().method_a.return_value = 4
mocked_other_class().method_b.return_value = 7
self.assertEqual(add_results(), 11)
This works no matter the number of methods of SomeOtherClass
you need to patch, with independent results.
Also, using the same patching method, an actual instance of SomeOtherClass
can be returned if need be:
@patch.object(sys.modules['module.a_function.to_test'], 'SomeOtherClass')
def test__should_add_results(self, mocked_other_class):
other_class_instance = SomeOtherClass('some_controlled_parameters')
mocked_other_class.return_value = other_class_instance
...
This is to do with the encoding of your terminal not being set to UTF-8. Here is my terminal
$ echo $LANG
en_GB.UTF-8
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
(?????)?
>>>
On my terminal the example works with the above, but if I get rid of the LANG
setting then it won't work
$ unset LANG
$ python
Python 2.7.3 (default, Apr 20 2012, 22:39:59)
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> s = '(\xef\xbd\xa1\xef\xbd\xa5\xcf\x89\xef\xbd\xa5\xef\xbd\xa1)\xef\xbe\x89'
>>> s1 = s.decode('utf-8')
>>> print s1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 1-5: ordinal not in range(128)
>>>
Consult the docs for your linux variant to discover how to make this change permanent.
I know this is a pretty old question, but I found this question today, but the answers were not what I needed.
So here's what I needed.
If you, like me, are looking to display the current date in twig, you can use the following:
{{ "now"|date("m/d/Y") }}
See documentation about this:
You could put the credentials in a properties file and read it using something like this:
Properties props = new Properties()
props.load(new FileInputStream("yourPath/credentials.properties"))
project.setProperty('props', props)
Another approach is to define environment variables at the OS level and read them using:
System.getenv()['YOUR_ENV_VARIABLE']
A URL that starts with the URL scheme and scheme specific part (http://
, https://
, ftp://
, etc.) is an absolute URL.
Any other URL is a relative URL and needs a base URL the relative URL is resolved from (and thus depend on) that is the URL of the resource the reference is used in if not declared otherwise.
Take a look at RFC 2396 – Appendix C for examples of resolving relative URLs.
Just format after convert to a date (tested in SQL Server v.2017)
dd/mon/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MMM/yyyy')
dd/mm/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MM/yyyy')
dd/Month/yyyy
Select Format(cast('25/jun/2013' as date),'dd/MMMM/yyyy')
If you want a circle like this
Try using the code below:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:innerRadius="0dp"
android:shape="ring"
android:thicknessRatio="2"
android:useLevel="false" >
<solid android:color="@android:color/white" />
<stroke
android:width="1dp"
android:color="@android:color/darker_gray" />
</shape>
I had same issues, edited my hosts file 127.0.0.1 localhost, but noticed no difference.
I then disabled Compression in the IIS panel and applied, and problem appears to now be resolved.
IIS Manager > Compression > Uncheck 'Enable dynamic content compression' and uncheck 'Enable static content compression'. Then 'Apply'.
Hope this helps!
regards, Geoff
Here is a solution based on the answer by Henrik Karlsson but with proper event triggering (based on Bootstrap sources):
$(function(){
$('[data-hide]').on('click', function ___alert_hide(e) {
var $this = $(this)
var selector = $this.attr('data-target')
if (!selector) {
selector = $this.attr('href')
selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') // strip for ie7
}
var $parent = $(selector === '#' ? [] : selector)
if (!$parent.length) {
$parent = $this.closest('.alert')
}
$parent.trigger(e = $.Event('close.bs.alert'))
if (e.isDefaultPrevented()) return
$parent.hide()
$parent.trigger($.Event('closed.bs.alert'))
})
});
The answer mostly for me, as a note.
Use:
find . ! -readable -prune -o -print
or more generally
find <paths> ! -readable -prune -o <other conditions like -name> -print
Works with: find (GNU findutils) 4.4.2. Background:
-readable
test matches readable files. The !
operator returns true, when test is false. And ! -readable
matches not readable directories (&files).-prune
action does not descend into directory.! -readable -prune
can be translated to: if directory is not readable, do not descend into it.-readable
test takes into account access control lists and other permissions artefacts which the -perm
test ignores.See also find
(1) manpage for many more details.
Try this:
$("#location").change(function(){
var element = $("option:selected", this);
var myTag = element.attr("myTag");
$('#setMyTag').val(myTag);
});
In the callback function for change()
, this
refers to the select, not to the selected option.
If you are like me and have certain restrictions in a production environment, you may wish to use a table variable instead of temp table, and an ad-hoc query rather than a create procedure.
Of course depending on your sql server instance, it must support table variables.
I also added a USE statement to narrow the search scope
USE DATABASE_NAME
DECLARE @SearchStr nvarchar(100) = 'SEARCH_TEXT'
DECLARE @Results TABLE (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
SET NOCOUNT ON
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
WHILE @TableName IS NOT NULL
BEGIN
SET @ColumnName = ''
SET @TableName =
(
SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_TYPE = 'BASE TABLE'
AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
AND OBJECTPROPERTY(
OBJECT_ID(
QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
), 'IsMSShipped'
) = 0
)
WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
BEGIN
SET @ColumnName =
(
SELECT MIN(QUOTENAME(COLUMN_NAME))
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_SCHEMA = PARSENAME(@TableName, 2)
AND TABLE_NAME = PARSENAME(@TableName, 1)
AND DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
AND QUOTENAME(COLUMN_NAME) > @ColumnName
)
IF @ColumnName IS NOT NULL
BEGIN
INSERT INTO @Results
EXEC
(
'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630)
FROM ' + @TableName + ' (NOLOCK) ' +
' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
)
END
END
END
SELECT ColumnName, ColumnValue FROM @Results
Iterate over a copy instead, such as the one returned by items()
:
for k, v in list(mydict.items()):
OK, first of all ngOnInit
is part of Angular lifecycle, while constructor
is part of ES6 JavaScript class, so the major difference starts from right here!...
Look at the below chart I created which shows the lifecycle of Angular.
In Angular2+ we use constructor
to do the DI(Dependency Injection)
for us, while in Angular 1 it was happening through calling to String method and checking which dependency was injected.
As you see in the above diagram, ngOnInit
is happening after the constructor is ready and ngOnChnages
and get fired after the component is ready for us. All initialisation can happen in this stage, a simple sample is injecting a service and initials it on init.
OK, I also share a sample code for you to look, see how we get use of ngOnInit
and constructor
in the code below:
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'my-app',
template: `<h1>App is running!</h1>
<my-app-main [data]=data></<my-app-main>`,
styles: ['h1 { font-weight: normal; }']
})
class ExampleComponent implements OnInit {
constructor(private router: Router) {} //Dependency injection in the constructor
// ngOnInit, get called after Component initialised!
ngOnInit() {
console.log('Component initialised!');
}
}
The fact that the sort values in the OP are integers isn't relevant to the question per se. In other words, the accepted answer would work if the sort value was text. I bring this up to also point out that the sort can be modified during the sort (for example, to account for upper and lower case).
>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: x[1])
[(148, 'ABC'), (221, 'DEF'), (121, 'abc'), (231, 'def')]
>>> sorted([(121, 'abc'), (231, 'def'), (148, 'ABC'), (221, 'DEF')], key=lambda x: str.lower(x[1]))
[(121, 'abc'), (148, 'ABC'), (231, 'def'), (221, 'DEF')]
Python 3.6+ using f-string:
mys = '1362511338314'
f"{mys[:10]}_{mys[10:]}"
gives
'1362511338_314'
One other option that hasn't been mentioned yet: use Groovy. Groovy allows you to access private instance variables as a side effect of the design of the language. Whether or not you have a getter for the field, you can just use
def obj = new IWasDesignedPoorly()
def hashTable = obj.getStuffIWant()
Not yet mentioned, though it was the first in my search result: https://github.com/nlohmann/json
Perks listed:
Also, it's under the MIT License.
I'll be honest: I have yet to use it, but through some experience I have a knack for determining when I come across a really well-made c++ library.
I keep hearing people say they're forking code in git. Git "fork" sounds suspiciously like git "clone" plus some (meaningless) psychological willingness to forgo future merges. There is no fork command in git, right?
"Forking" is a concept, not a command specifically supported by any version control system.
The simplest kind of forking is synonymous with branching. Every time you create a branch, regardless of your VCS, you've "forked". These forks are usually pretty easy to merge back together.
The kind of fork you're talking about, where a separate party takes a complete copy of the code and walks away, necessarily happens outside the VCS in a centralized system like Subversion. A distributed VCS like Git has much better support for forking the entire codebase and effectively starting a new project.
Git (not GitHub) natively supports "forking" an entire repo (ie, cloning it) in a couple of ways:
origin
is created for youorigin
equivalentsGit makes contributing changes back to the source of the fork as simple as asking someone from the original project to pull from you, or requesting write access to push changes back yourself. This is the part that GitHub makes easier, and standardizes.
Any angst over Github extending git in this direction? Or any rumors of git absorbing the functionality?
There is no angst because your assumption is wrong. GitHub "extends" the forking functionality of Git with a nice GUI and a standardized way of issuing pull requests, but it doesn't add the functionality to Git. The concept of full-repo-forking is baked right into distributed version control at a fundamental level. You could abandon GitHub at any point and still continue to push/pull projects you've "forked".
I want to share my personal experience, calling a REST WS with Post JSON call:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URL;
import java.net.URLConnection;
public class HWS {
public static void main(String[] args) throws IOException {
URL url = new URL("INSERT YOUR SERVER REQUEST");
//Insert your JSON query request
String query = "{'PARAM1': 'VALUE','PARAM2': 'VALUE','PARAM3': 'VALUE','PARAM4': 'VALUE'}";
//It change the apostrophe char to double quote char, to form a correct JSON string
query=query.replace("'", "\"");
try{
//make connection
URLConnection urlc = url.openConnection();
//It Content Type is so important to support JSON call
urlc.setRequestProperty("Content-Type", "application/xml");
Msj("Conectando: " + url.toString());
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
Msj("Consulta: " + query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
Msj(l);
}
br.close();
} catch (Exception e){
Msj("Error ocurrido");
Msj(e.toString());
}
}
private static void Msj(String texto){
System.out.println(texto);
}
}
DECLARE @DDate date -- To store the current date
DECLARE @DTime time -- To store the current time
DECLARE @DateTime datetime -- To store the result of the concatenation
;
SET @DDate = GETDATE() -- Getting the current date
SET @DTime = GETDATE() -- Getting the current time
SET @DateTime = CONVERT(datetime, CONVERT(varchar(19), LTRIM(@DDate) + ' ' + LTRIM(@DTime) ));
;
/*
1. LTRIM the date and time do an automatic conversion of both types to string.
2. The inside CONVERT to varchar(19) is needed, because you cannot do a direct conversion to datetime
3. Once the inside conversion is done, the second do the final conversion to datetime.
*/
-- The following select shows the initial variables and the result of the concatenation
SELECT @DDate, @DTime, @DateTime
A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
1
2
Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.
So this is a Queue only if used in conjunction with add.
Try this :
@Test
public void testQueue() {
LinkedList<Integer> queue = new LinkedList<>();
queue.push(1);
queue.push(2);
System.out.println(queue.pop());
System.out.println(queue.pop());
}
Output :
2
1
Like what Volker mentioned, nested structs is the way to go. But if you really do not want nested structs, you can override the UnmarshalJSON func.
https://play.golang.org/p/dqn5UdqFfJt
type A struct {
FooBar string // takes foo.bar
FooBaz string // takes foo.baz
More string
}
func (a *A) UnmarshalJSON(b []byte) error {
var f interface{}
json.Unmarshal(b, &f)
m := f.(map[string]interface{})
foomap := m["foo"]
v := foomap.(map[string]interface{})
a.FooBar = v["bar"].(string)
a.FooBaz = v["baz"].(string)
a.More = m["more"].(string)
return nil
}
Please ignore the fact that I'm not returning a proper error. I left that out for simplicity.
UPDATE: Correctly retrieving "more" value.
This solution makes only one selection from YourTable, therefore it's faster. It works only for MySQL and SQLite(for SQLite remove DESC) according to test on sqlfiddle.com. Maybe it can be tweaked to work on other languages which I am not familiar with.
SELECT *
FROM ( SELECT *
FROM ( SELECT 1 as id, 1 as rev, 'content1' as content
UNION
SELECT 2, 1, 'content2'
UNION
SELECT 1, 2, 'content3'
UNION
SELECT 1, 3, 'content4'
) as YourTable
ORDER BY id, rev DESC
) as YourTable
GROUP BY id
So I'm a pretty critical person, and figure if I'm going to invest in a library, I'd better know what I'm getting myself into. I figure it's better to go heavy on the criticism and light on the flattery when scrutinizing; what's wrong with it has many more implications for the future than what's right. So I'm going to go overboard here a little bit to provide the kind of answer that would have helped me and I hope will help others who may journey down this path. Keep in mind that this is based on what little reviewing/testing I've done with these libs. Oh and I stole some of the positive description from Reed.
I'll mention up top that I went with GMTL despite it's idiosyncrasies because the Eigen2 unsafeness was too big of a downside. But I've recently learned that the next release of Eigen2 will contain defines that will shut off the alignment code, and make it safe. So I may switch over.
Update: I've switched to Eigen3. Despite it's idiosyncrasies, its scope and elegance are too hard to ignore, and the optimizations which make it unsafe can be turned off with a define.
Benefits: LGPL MPL2, Clean, well designed API, fairly easy to use. Seems to be well maintained with a vibrant community. Low memory overhead. High performance. Made for general linear algebra, but good geometric functionality available as well. All header lib, no linking required.
Idiocyncracies/downsides: (Some/all of these can be avoided by some defines that are available in the current development branch Eigen3)
Benefits: LGPL, Fairly Simple API, specifically designed for graphics engines. Includes many primitive types geared towards rendering (such as planes, AABB, quatenrions with multiple interpolation, etc) that aren't in any other packages. Very low memory overhead, quite fast, easy to use. All header based, no linking necessary.
Idiocyncracies/downsides:
vec1 - vec2
does not return a
normal vector so length( vecA - vecB )
fails even though vecC = vecA -
vecB
works. You must wrap like: length( Vec( vecA - vecB ) )
length( makeCross( vecA, vecB ) )
gmtl::length( gmtl::makeCross( vecA, vecB ) )
vecA.cross( vecB ).length()
Can't tell because they seem to be more interested in the fractal image header of their web page than the content. Looks more like an academic project than a serious software project.
Latest release over 2 years ago.
Apparently no documentation in English though supposedly there is something in French somewhere.
Cant find a trace of a community around the project.
Benefits: Old and mature.
Downsides:
Disk space is not the issue... but memory and performance will be. Double the page reads, double index size, strange LIKE and = constant behaviour etc
Do you need to store Chinese etc script? Yes or no...
And from MS BOL "Storage and Performance Effects of Unicode"
Edit:
Recent SO question highlighting how bad nvarchar performance can be...
SQL Server uses high CPU when searching inside nvarchar strings
For numerical data you have the solution. But it is categorical data, you said. Then life gets a bit more complicated...
Well, first : The amount of association between two categorical variables is not measured with a Spearman rank correlation, but with a Chi-square test for example. Which is logic actually. Ranking means there is some order in your data. Now tell me which is larger, yellow or red? I know, sometimes R does perform a spearman rank correlation on categorical data. If I code yellow 1 and red 2, R would consider red larger than yellow.
So, forget about Spearman for categorical data. I'll demonstrate the chisq-test and how to choose columns using combn(). But you would benefit from a bit more time with Agresti's book : http://www.amazon.com/Categorical-Analysis-Wiley-Probability-Statistics/dp/0471360937
set.seed(1234)
X <- rep(c("A","B"),20)
Y <- sample(c("C","D"),40,replace=T)
table(X,Y)
chisq.test(table(X,Y),correct=F)
# I don't use Yates continuity correction
#Let's make a matrix with tons of columns
Data <- as.data.frame(
matrix(
sample(letters[1:3],2000,replace=T),
ncol=25
)
)
# You want to select which columns to use
columns <- c(3,7,11,24)
vars <- names(Data)[columns]
# say you need to know which ones are associated with each other.
out <- apply( combn(columns,2),2,function(x){
chisq.test(table(Data[,x[1]],Data[,x[2]]),correct=F)$p.value
})
out <- cbind(as.data.frame(t(combn(vars,2))),out)
Then you should get :
> out
V1 V2 out
1 V3 V7 0.8116733
2 V3 V11 0.1096903
3 V3 V24 0.1653670
4 V7 V11 0.3629871
5 V7 V24 0.4947797
6 V11 V24 0.7259321
Where V1 and V2 indicate between which variables it goes, and "out" gives the p-value for association. Here all variables are independent. Which you would expect, as I created the data at random.
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);
css names must be consistent.
Names of jqueryUI css are not "jquery.ui.XXX" in Contents/themes/base folder .
so it should be :
wrong:
bundles.Add(new StyleBundle("~/Content/themes/base/css").Include(
"~/Content/themes/base/jquery.ui.core.css",
"~/Content/themes/base/jquery.ui.resizable.css",
"~/Content/themes/base/jquery.ui.selectable.css",
"~/Content/themes/base/jquery.ui.accordion.css",
"~/Content/themes/base/jquery.ui.autocomplete.css",
"~/Content/themes/base/jquery.ui.button.css",
"~/Content/themes/base/jquery.ui.dialog.css",
"~/Content/themes/base/jquery.ui.slider.css",
"~/Content/themes/base/jquery.ui.tabs.css",
"~/Content/themes/base/jquery.ui.datepicker.css",
"~/Content/themes/base/jquery.ui.progressbar.css",
"~/Content/themes/base/jquery.ui.theme.css"));
correct :
bundles.Add(new StyleBundle("~/Bundles/themes/base/css").Include(
"~/Content/themes/base/core.css",
"~/Content/themes/base/resizable.css",
"~/Content/themes/base/selectable.css",
"~/Content/themes/base/accordion.css",
"~/Content/themes/base/autocomplete.css",
"~/Content/themes/base/button.css",
"~/Content/themes/base/dialog.css",
"~/Content/themes/base/slider.css",
"~/Content/themes/base/tabs.css",
"~/Content/themes/base/datepicker.css",
"~/Content/themes/base/progressbar.css",
"~/Content/themes/base/theme.css"));
I tried in MVC5 and worked successfully.
Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using
keytool -list -v -keystore truststore.jks
Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:
{ "MyStringArray" : ["somestring1", "somestring2"] }
then you can ask for the value of "MyStringArray"
and you would get back a list of two strings, "somestring1"
and "somestring2"
.
If you are using jupyter notebook Try:
!python --version
If you are using terminal Try:
python --version
For those with a git gui bent, you can also use gitk.
Right click on the commit you want to return to and select "Reset master branch to here". Then choose hard from the next menu.
On Centos 6.5/PostgreSQL 9.3:
Change the value of "PGDATA=/var/lib/pgsql/data"
to whatever location you want in the initial script file /etc/init.d/postgresql
.
Remember to chmod 700
and chown postgres:postgres
to the new location and you're the boss.
In a console application, just return from the main program, in a UI-Application Close() all active Forms.
Memory from managed objects will be handled by the .NET Framework, you don't need to care about this.
If you use classes which implement IDisposable (like database connections, for example), you should call Dispose() on them when you no longer need them (preferred way: a using-Statement).
If you use such resources globally (like private members in your form), your form should implement the IDisposable pattern to release these resources on the Close()-call. See this article for details.
You have it exactly right, all you have to do is set selectedIndex in your ng-click.
ng-click="selectedIndex = 1"
Here is how I implemented a set of buttons that change the ng-view, and highlights the button of the currently selected view.
<div id="sidebar" ng-init="partial = 'main'">
<div class="routeBtn" ng-class="{selected:partial=='main'}" ng-click="router('main')"><span>Main</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view1'}" ng-click="router('view1')"><span>Resume</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view2'}" ng-click="router('view2')"><span>Code</span></div>
<div class="routeBtn" ng-class="{selected:partial=='view3'}" ng-click="router('view3')"><span>Game</span></div>
</div>
and this in my controller.
$scope.router = function(endpoint) {
$location.path("/" + ($scope.partial = endpoint));
};
var tv = findViewById(R.id.tv)
as TextView
tv.setOnClickListener {
val i = Intent(this@MainActivity, SecondActivity::class.java)
startActivity(i)
finish()
}
Append "_$folder$" to your folder name and call put.
String extension = "_$folder$";
s3.putObject("MyBucket", "MyFolder"+ extension, new ByteArrayInputStream(new byte[0]), null);
The next step would be FisherFaces. Try it and check whether they work for you.
Here is a nice comparison.
Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:
<T extends ClassA & InterfaceB>
See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName
for each one that you need.
This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max
, which (wrapped onto two lines) is:
public static <T extends Object & Comparable<? super T>> T
max(Collection<? extends T> coll)
why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.
It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:
class classB { }
interface interfaceC { }
public class MyClass<T extends classB & interfaceC> {
Class<T> variable;
}
to get variable
that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>
, the class name must come first, and interfaces follow. And of course you can only list a single class.
Use ftplugins or autocommands to set options.
In ~/.vim/ftplugin/python.vim:
setlocal shiftwidth=2 softtabstop=2 expandtab
And don't forget to turn them on in ~/.vimrc
:
filetype plugin indent on
(:h ftplugin
for more information)
In ~/.vimrc
:
autocmd FileType python setlocal shiftwidth=2 softtabstop=2 expandtab
You can replace any of the long commands or settings with their short versions:
autocmd
: au
setlocal
: setl
shiftwidth
: sw
tabstop
: ts
softtabstop
: sts
expandtab
: et
I would also suggest learning the difference between tabstop
and softtabstop
. A lot of people don't know about softtabstop
.
If you'd like to do it for all dialogs throughout the site try the following code...
$.extend( $.ui.dialog.prototype.options, {
open: function() {
var dialog = this;
$('.ui-widget-overlay').bind('click', function() {
$(dialog).dialog('close');
});
}
});
Can refer to here: https://ss64.com/nt/start.html
start "" /D F:\- Big Packets -\kitterengine\Common\ /W Template.bat
Try this
on change event
$("#jodSel").on('change',function(){
var getValue=$(this).val();
alert(getValue);
});
Note: In dropdownlist
if you want to set id,text relation from your database then, set id as value in option tag, not by adding extra id
attribute inside option its not standard paractise though i did both in my answer but i prefer example 1
HTML Markup
Example 1:
<select id="example1">
<option value="1">one</option>
<option value="2">two</option>
<option value="3">three</option>
<option value="4">four</option>
</select>
Example 2 :
<select id="example2">
<option id="1">one</option>
<option id="2">two</option>
<option id="3">three</option>
<option id="4">four</option>
</select>
Jquery:
$("#example1").on('change', function () {
alert($(this).val());
});
$("#example2").on('change', function () {
alert($(this).find('option:selected').attr('id'));
});
View Demo : For example 1 & 2
Blog Article : Get and Set dropdown list selected value with Jquery
My Blog : jQuery tutorials
First add an Enrty
and Category
class:
public class Entry { public string Id { get; set; } public string Title { get; set; } public string Updated { get; set; } public string Summary { get; set; } public string GPoint { get; set; } public string GElev { get; set; } public List<string> Categories { get; set; } } public class Category { public string Label { get; set; } public string Term { get; set; } }
Then use LINQ to XML
XDocument xDoc = XDocument.Load("path"); List<Entry> entries = (from x in xDoc.Descendants("entry") select new Entry() { Id = (string) x.Element("id"), Title = (string)x.Element("title"), Updated = (string)x.Element("updated"), Summary = (string)x.Element("summary"), GPoint = (string)x.Element("georss:point"), GElev = (string)x.Element("georss:elev"), Categories = (from c in x.Elements("category") select new Category { Label = (string)c.Attribute("label"), Term = (string)c.Attribute("term") }).ToList(); }).ToList();
I used Anaconda environment and had the same issue. I tried all the aforementioned approaches and, alas, it didn't help me. Accumulated the suggestions, here the way which helped me:
Delete all NumPy folders in the virtual environment or in the system if you don't use a virtual environment, for example in my case:
~/home/anaconda3/envs//lib/python/site-packages/numpy
~/home/anaconda3/envs//lib/python/site-packages/numpy.libs
~/home/anaconda3/envs//lib/python/site-packages/numpy-.dist-info
Install new Numpy with:
pip install numpy -U
Hope, it could help in the same case
Install Pillow (or PIL), e.g.:
$ pip install pillow
Now you can
from PIL import Image
with Image.open('path/to/file.jpg') as img:
img.show()
Other common alternatives include running xdg-open
or starting the browser with the image path:
import webbrowser
webbrowser.open('path/to/file.jpg')
If you really want to show the image inline in the console and not as a new window, you may do that but only in a Linux console using fbi
see ask Ubuntu or else use ASCII-art like CACA.
to join a windows path, try
mypath=os.path.join('c:\\', 'sourcedir')
basically, you will need to escape the slash
If you want to do something with Java Strings, Commons Lang StringUtils is a great place to look.
StringUtils.remove("TextX Xto modifyX", 'X');
You need to put "here" into a <div>
or <span>
with style="float: right"
.
I... don't think so. You can redirect the subdomain (such as blah.something.com
) to point to something.com:25566
, but I don't think you can actually set up the subdomain to be on a different port like that. I could be wrong, but it'd probably be easier to use a simple .htaccess or something to check %{HTTP_HOST} and redirect according to the subdomain.
^[A-Za-z](\W|\w)*
(\W|\w)
will ensure that every subsequent letter is word(\w
) or non word(\W
)
instead of (\W|\w)*
you can also use .*
where .
means absolutely anything just like (\w|\W)
If I use exit()
in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing.
See here
But sys.exit()
is better in this case. It closes the program and doesn't create any dialogue box.
You can find NLTK version simply by doing:
In [1]: import nltk
In [2]: nltk.__version__
Out[2]: '3.2.5'
And similarly for scikit-learn,
In [3]: import sklearn
In [4]: sklearn.__version__
Out[4]: '0.19.0'
I'm using python3 here.
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
The only command helped me to cleanup all gems and ignores default gems, which can't be uninstalled
for x in `gem list --no-versions`; do gem uninstall $x -a -x -I; done
Its not right to set default value in View. The View should perform display work, not more. This action breaks ideology of MVC pattern. So the right place to set defaults - create method of controller class.
Use sorted()
with a key
as follows -
>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
The lambda
returns the fourth element of each of the inner lists and the sorted
function uses that to sort those list. This assumes that int(elem)
will not fail for the list.
Or use itemgetter
(As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)
>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]
Use the parseJSON
method:
var json = '["City1","City2","City3"]';
var arr = $.parseJSON(json);
Then you have an array with the city names.
You can use an echo shortcut also instead of typing out "echo blah;" as shown below:
<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">
This code snippet is working properly
I have reproduced the issue in my system,
postgres=# alter user my-sys with password 'pass11';
ERROR: syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
^
Here is the issue,
psql is asking for input and you have given again the alter query see postgres-#
That's why it's giving error at alter
postgres-# alter user "my-sys" with password 'pass11';
ERROR: syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
^
Solution is as simple as the error,
postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE
It is actually possible to do it using .NET regular expressions, but it is not trivial, so read carefully.
You can read a nice article here. You also may need to read up on .NET regular expressions. You can start reading here.
Angle brackets <>
were used because they do not require escaping.
The regular expression looks like this:
<
[^<>]*
(
(
(?<Open><)
[^<>]*
)+
(
(?<Close-Open>>)
[^<>]*
)+
)*
(?(Open)(?!))
>
string radioListValue = RadioButtonList.Text;
Understand it's a very old post but I stumbled upon a similar problem trying to sort primitive int arrays, so posting my solution. Suggestions/comments welcome -
int[] arr = {3,2,1,3};
List<Integer> list = new ArrayList<>();
Arrays.stream(arr).forEach(i -> list.add(i));
list.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
If you only want to ssh a few times, such as on a borrowed or shared computer, try:
ssh buck@hostname
or
ssh -l buck hostname
In my opinion, varchar(n)
has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.
TL;DR:
If you use text
type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n)
, you can prevent it.
Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text
type or varchar(n)
where n
is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n)
where n
is not too much greater than 2712, you're safe from these errors.
The only way I could do it in VS 2010 IDE was to highlight the block of code and hit ctrl-E and then C
The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.
To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".
To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".
Explanation:
From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):
4.3.8 ‘Local echo’
With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)
Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.
4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.
If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.
Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)
Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.
Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.
First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.
If the interface works the way it did last I used it, you can select the region in Excel, copy it, open SQL Server and paste the data into the table as you would with Access.
Or you could setup an ODBC link between Excel and SQL Server.
FYI, if you'd like to get a list of recently checked out branches (as opposed to recently committed) you can use Git's reflog:
$ git reflog | egrep -io "moving from ([^[:space:]]+)" | awk '{ print $3 }' | head -n5
master
stable
master
some-cool-feature
feature/improve-everything
See also: How can I get a list of Git branches that I've recently checked out?
This one saves KEYS & VALUES
function array2string($data){
$log_a = "";
foreach ($data as $key => $value) {
if(is_array($value)) $log_a .= "[".$key."] => (". array2string($value). ") \n";
else $log_a .= "[".$key."] => ".$value."\n";
}
return $log_a;
}
Hope it helps someone.
This code checks if two intervals overlap.
---------|---|
---|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
-------|---|
---|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
------|---|
---|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|--| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
----|---|
---|-----| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|-| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|--| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
---|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
----|---| > TRUE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
-------|---| > FALSE
xxxxxxxxxxxxxxxxxxxxxxxxx
---|---|
--------|---| > FALSE
Algorithm:
x1 < y2
and
x2 > y1
example 12:00 - 12:30 is not overlapping with 12:30 13:00
Select *
FROM test_table
WHERE user_id = value
AND date_added = (select max(date_added)
from test_table
where user_id = value)
The following will produce, in the output directory,
But it does not contain all .NET Core runtime assemblies.
<PropertyGroup>
<Temp>$(SolutionDir)\packaging\</Temp>
</PropertyGroup>
<ItemGroup>
<BootStrapFiles Include="$(Temp)hostpolicy.dll;$(Temp)$(ProjectName).exe;$(Temp)hostfxr.dll;"/>
</ItemGroup>
<Target Name="GenerateNetcoreExe"
AfterTargets="Build"
Condition="'$(IsNestedBuild)' != 'true'">
<RemoveDir Directories="$(Temp)" />
<Exec
ConsoleToMSBuild="true"
Command="dotnet build $(ProjectPath) -r win-x64 /p:CopyLocalLockFileAssemblies=false;IsNestedBuild=true --output $(Temp)" >
<Output TaskParameter="ConsoleOutput" PropertyName="OutputOfExec" />
</Exec>
<Copy
SourceFiles="@(BootStrapFiles)"
DestinationFolder="$(OutputPath)"
/>
</Target>
I wrapped it up in a sample here: https://github.com/SimonCropp/NetCoreConsole
Just use substring: "apple".substring(3);
will return le
For people (like me) coming here via search engine and just looking for a solution which works out of the box, I recommend installing mpu
. Install it via pip install mpu --user
and use it like this to get the haversine distance:
import mpu
# Point one
lat1 = 52.2296756
lon1 = 21.0122287
# Point two
lat2 = 52.406374
lon2 = 16.9251681
# What you were looking for
dist = mpu.haversine_distance((lat1, lon1), (lat2, lon2))
print(dist) # gives 278.45817507541943.
An alternative package is gpxpy
.
If you don't want dependencies, you can use:
import math
def distance(origin, destination):
"""
Calculate the Haversine distance.
Parameters
----------
origin : tuple of float
(lat, long)
destination : tuple of float
(lat, long)
Returns
-------
distance_in_km : float
Examples
--------
>>> origin = (48.1372, 11.5756) # Munich
>>> destination = (52.5186, 13.4083) # Berlin
>>> round(distance(origin, destination), 1)
504.2
"""
lat1, lon1 = origin
lat2, lon2 = destination
radius = 6371 # km
dlat = math.radians(lat2 - lat1)
dlon = math.radians(lon2 - lon1)
a = (math.sin(dlat / 2) * math.sin(dlat / 2) +
math.cos(math.radians(lat1)) * math.cos(math.radians(lat2)) *
math.sin(dlon / 2) * math.sin(dlon / 2))
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
d = radius * c
return d
if __name__ == '__main__':
import doctest
doctest.testmod()
The other alternative package is [haversine][1]
from haversine import haversine, Unit
lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
haversine(lyon, paris)
>> 392.2172595594006 # in kilometers
haversine(lyon, paris, unit=Unit.MILES)
>> 243.71201856934454 # in miles
# you can also use the string abbreviation for units:
haversine(lyon, paris, unit='mi')
>> 243.71201856934454 # in miles
haversine(lyon, paris, unit=Unit.NAUTICAL_MILES)
>> 211.78037755311516 # in nautical miles
They claim to have performance optimization for distances between all points in two vectors
from haversine import haversine_vector, Unit
lyon = (45.7597, 4.8422) # (lat, lon)
paris = (48.8567, 2.3508)
new_york = (40.7033962, -74.2351462)
haversine_vector([lyon, lyon], [paris, new_york], Unit.KILOMETERS)
>> array([ 392.21725956, 6163.43638211])
Besides listing the files explicitly as shown by unwind and Wienczny, you can setup change lists and checkin these. These allow you to manage disjunct sets of changes to the same working copy.
You can read about them in the online version of the excellent SVN book.
First screen
updateData=(data)=>{
console.log('Selected data',data)
}
this.props.navigation.navigate('FirstScreen',{updateData:this.updateData.bind(this)})
Second screen
// use this method to call FirstScreen method
execBack(param) {
this.props.navigation.state.params.updateData(param);
this.props.navigation.goBack();
}
This should work
gsub('\u009c','','\u009cYes yes for ever for ever the boys ')
"Yes yes for ever for ever the boys "
Here 009c is the hexadecimal number of unicode. You must always specify 4 hexadecimal digits. If you have many , one solution is to separate them by a pipe:
gsub('\u009c|\u00F0','','\u009cYes yes \u00F0for ever for ever the boys and the girls')
"Yes yes for ever for ever the boys and the girls"
Use the basename command. Its manpage is here: http://unixhelp.ed.ac.uk/CGI/man-cgi?basename
Your task declaration is incorrectly combining the Copy
task type and project.copy
method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy
isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File
API) will do. Assuming Project1
is the project directory:
task renABCToXYZ { doLast { file("ABC").renameTo(file("XYZ")) } }
Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast
task action) to the task that produces ABC
.
You Can do by Two ways,
1. Cloning the Remote Repo to your Local host
example: git clone https://github.com/user-name/repository.git
2. Pulling the Remote Repo to your Local host
First you have to create a git local repo by,
example: git init or git init repo-name then, git pull https://github.com/user-name/repository.git
That's all, All commits and branch in the remote repo now available in the local repository of your computer.
Happy Coding, cheers -:)
Try this:
$query = mysql_query("SELECT username FROM Users WHERE username='$username' ")
Don't add $con
to mysql_query()
function.
Disclaimer: using the username
variable in the string passed to mysql_query
, as shown above, is a trivial SQL injection attack vector in so far the username
depends on parameters of the Web request (query string, headers, request body, etc), or otherwise parameters a malicious entity may control.
How about this:
<a class="btn btn-primary" href="{% url 'url-name'%}">Button-Text</a>
The class is including bootstrap styles for primary button.
I was experiencing this issue... in my case, I'd run out of storage on my dedicated server. Check that if everything else fails and consider increasing disk space or removing unwanted data or files.
How about this?
people = []
until (info = gets.chomp).empty?
people += [Person.new(info)]
end
Say your project is structured this way:
+---MyPythonProject
| +---.gitignore
| +---run.py
| | +---subscripts
| | | +---script_one.py
| | | +---script_two.py
Inside run.py
, you can import scripts one and two by:
from subscripts import script_one as One
from subscripts import script_two as Two
Now, still inside run.py
, you'll be able to call their methods with:
One.method_from_one(param)
Two.method_from_two(other_param)
In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():
View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);
Now you can access your views via 'view' and cast them to your view type:
myImage = (ImageView) view.findViewById(R.id.my_image);
Yes, you can use what's known as :nth-child
selectors.
In this case you would use:
li:nth-child(3n) {
// Styling for every third element here.
}
:nth-child(3n):
3(0) = 0
3(1) = 3
3(2) = 6
3(3) = 9
3(4) = 12
:nth-child()
is compatible in Chrome, Firefox, and IE9+.
For a work around to use :nth-child()
amongst other pseudo-classes/attribute selectors in IE6 through to IE8, see this link.
To create a timeout you can use signals.
The best way to solve this case is probably to
try-except-finally
block.Here is some example code:
import signal
from time import sleep
class TimeoutException(Exception):
""" Simple Exception to be called on timeouts. """
pass
def _timeout(signum, frame):
""" Raise an TimeoutException.
This is intended for use as a signal handler.
The signum and frame arguments passed to this are ignored.
"""
# Raise TimeoutException with system default timeout message
raise TimeoutException()
# Set the handler for the SIGALRM signal:
signal.signal(signal.SIGALRM, _timeout)
# Send the SIGALRM signal in 10 seconds:
signal.alarm(10)
try:
# Do our code:
print('This will take 11 seconds...')
sleep(11)
print('done!')
except TimeoutException:
print('It timed out!')
finally:
# Abort the sending of the SIGALRM signal:
signal.alarm(0)
There are some caveats to this:
But, it's all in the standard python library! Except for the sleep function import it's only one import. If you are going to use timeouts many places You can easily put the TimeoutException, _timeout and the singaling in a function and just call that. Or you can make a decorator and put it on functions, see the answer linked below.
You can also set this up as a "context manager" so you can use it with the with
statement:
import signal
class Timeout():
""" Timeout for use with the `with` statement. """
class TimeoutException(Exception):
""" Simple Exception to be called on timeouts. """
pass
def _timeout(signum, frame):
""" Raise an TimeoutException.
This is intended for use as a signal handler.
The signum and frame arguments passed to this are ignored.
"""
raise Timeout.TimeoutException()
def __init__(self, timeout=10):
self.timeout = timeout
signal.signal(signal.SIGALRM, Timeout._timeout)
def __enter__(self):
signal.alarm(self.timeout)
def __exit__(self, exc_type, exc_value, traceback):
signal.alarm(0)
return exc_type is Timeout.TimeoutException
# Demonstration:
from time import sleep
print('This is going to take maximum 10 seconds...')
with Timeout(10):
sleep(15)
print('No timeout?')
print('Done')
One possible down side with this context manager approach is that you can't know if the code actually timed out or not.
Sources and recommended reading:
Seems like a lazy way to always know that your WHERE clause is already defined and allow you to keep adding conditions without having to check if it is the first one.
This worked for me:
double input = 104.8695412 //For example
long roundedInt = Math.round(input * 100);
double result = (double) roundedInt/100;
//result == 104.87
I personally like this version because it actually performs the rounding numerically, rather than by converting it to a String (or similar) and then formatting it.
Missing space between elif
and [
rest your program is correct. you need to correct it an check it out. here is fixed program:
#!/bin/bash
if [ "$seconds" -eq 0 ]; then
timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
echo "Unknown parameter"
fi
useful link related to this bash if else statement
The database.yml is the file where you set up all the information to connect to the database. It differs depending on the kind of DB you use. You can find more information about this in the Rails Guide or any tutorial explaining how to setup a rails project.
The information in the database.yml file is scoped by environment, allowing you to get a different setting for testing, development or production. It is important that you keep those distinct if you don't want the data you use for development deleted by mistake while running your test suite.
Regarding source control, you should not commit this file but instead create a template file for other developers (called database.yml.template
). When deploying, the convention is to create this database.yml file in /shared/config
directly on the server.
With SVN: svn propset svn:ignore config "database.yml"
With Git: Add config/database.yml
to the .gitignore file or with git-extra git ignore config/database.yml
... and now, some examples:
SQLite
adapter: sqlite3
database: db/db_dev_db.sqlite3
pool: 5
timeout: 5000
MYSQL
adapter: mysql
database: my_db
hostname: 127.0.0.1
username: root
password:
socket: /tmp/mysql.sock
pool: 5
timeout: 5000
MongoDB with MongoID (called mongoid.yml, but basically the same thing)
host: <%= ENV['MONGOID_HOST'] %>
port: <%= ENV['MONGOID_PORT'] %>
username: <%= ENV['MONGOID_USERNAME'] %>
password: <%= ENV['MONGOID_PASSWORD'] %>
database: <%= ENV['MONGOID_DATABASE'] %>
# slaves:
# - host: slave1.local
# port: 27018
# - host: slave2.local
# port: 27019
Add this to css
of your div: word-wrap: break-word;
Any of these methods will work:
name = 'Smith'
puts name.[0..0] # => S
puts name.[0] # => S
puts name.[0,1] # => S
puts name.[0].chr # => S
Use the below css to solve your issue
#footer{ text-align:center; height:58px;}
#footer ul { font-size:11px;}
#footer ul li {display:inline-block;}
Note: Don't use float:left
in li. it will make your li to align left.
In terms of networking and security, the Backend is by far the most (should be) secure node.
The middle-end portion, usually being a web server, will be somewhat in the wild and cut off in many respects from a company's network. The middle-end node is usually placed in the DMZ and segmented from the network with firewall settings. Most of the server-side code parsing of web pages is handled on the middle-end web server.
Getting to the backend means going through the middle-end, which has a carefully crafted set of rules allowing/disallowing access to the vital nummies which are stored on the database (backend) server.
Add the following lines to your ~/.bash_profile
or ~/.zshrc
file(s).
export LC_CTYPE=C
export LANG=C
I think the beginning to the resolution to this issue is the fact that the use of the for loop or any other function or action can not be done in the class definition but needs to be included in a method/constructor/block definition inside of a class.
in your server side the code looks like:
var request = require('request');
app.post('/add', function(req, res){
console.log(req.body);
request.post(
{
url:'http://localhost:6001/add',
json: {
unit_name:req.body.unit_name,
unit_price:req.body.unit_price
},
headers: {
'Content-Type': 'application/json'
}
},
function(error, response, body){
// console.log(error);
// console.log(response);
console.log(body);
res.send(body);
});
// res.send("body");
});
in receiving end server code looks like:
app.post('/add', function(req, res){
console.log('received request')
console.log(req.body);
let adunit = new AdUnit(req.body);
adunit.save()
.then(game => {
res.status(200).json({'adUnit':'AdUnit is added successfully'})
})
.catch(err => {
res.status(400).send('unable to save to database');
})
});
Schema is just two properties unit_name and unit_price.
Try this for the Firefox browser.
/* Open new tab in browser */
public void openNewTab()
{
driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
driver.switchTo().window(tabs.get(0));
}
I used flutter to create iOS project. When build for Simulator, failed with the same error message. It is solved by following work.
xCode 12.3 Build Settings->Build Active Architecture Only, set it to Yes.
For setting value in hidden field do in the following way:
@Html.HiddenFor(model => model.title,
new { id= "natureOfVisitField", Value = @Model.title})
It will work
The problem id because of inp.read();
method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.
What you can do simply
for(int i=0;i<T;i++) {
String s= inp.readLine();
String[] intValues = inp.readLine().split(" ");
int[] m= new int[2];
m[0]=Integer.parseInt(intValues[0]);
m[1]=Integer.parseInt(intValues[1]);
// Checking whether I am taking the inputs correctly
System.out.println(s);
System.out.println(m[0]);
System.out.println(m[1]);
}
As of npm version 3.8.6, you can use
npm install --prefix ./install/here <package>
to install in the specified directory. NPM automatically creates node_modules
folder even when a node_modules
directory already exists in the higher up hierarchy.
You can also have a package.json
in the current directory and then install it in the specified directory using --prefix
option:
npm install --prefix ./install/here
As of npm 6.0.0, you can use
npm install --prefix ./install/here ./
to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.
NOTE: NPM honours the path that you've specified through the --prefix
option. It resolves as per npm documentation on folders, only when npm install
is used without the --prefix
option.
FragmentActivity
gives you all of the functionality of Activity
plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.
If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity
and use the native Fragments introduced in v11 without issue. FragmentActivity
was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.
I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.
The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
html, body {
height:100%;
}
body {
background: url(images/bg.jpg) no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}
This should do it:
expect($('[ng-show=saving].icon-spin').isDisplayed()).toBe(true);
Remember protractor's $
isn't jQuery and :visible
is not yet a part of available CSS selectors + pseudo-selectors
More info at https://stackoverflow.com/a/13388700/511069
Ctrl + F12 also works well on linux(ubuntu).
Those who search capitalize first letter of a name here..
public static String capitaliseName(String name) {
String collect[] = name.split(" ");
String returnName = "";
for (int i = 0; i < collect.length; i++) {
collect[i] = collect[i].trim().toLowerCase();
if (collect[i].isEmpty() == false) {
returnName = returnName + collect[i].substring(0, 1).toUpperCase() + collect[i].substring(1) + " ";
}
}
return returnName.trim();
}
usase: capitaliseName("saurav khan");
output: Saurav Khan
If there are too many cookies cached, it breaks the server (the size of a request header is too big!). Clearing the cookies can fix this issue as well.
You can use jQuery click
instead of using onclick
attribute, Try the following:
$('table').on('click', 'input[type="button"]', function(e){
$(this).closest('tr').remove()
})
Functions are first-class variables in Python. You can declare a function, pass it around as an object, and overwrite it:
def func(): print "hello"
def another_func(f): f()
another_func(func)
def func2(): print "goodbye"
func = func2
This is a fundamental feature of modern scripting languages. JavaScript and Lua do this, too. Ruby doesn't treat functions this way; naming a function calls it.
Of course, there are ways to do these things in Ruby, but they're not first-class operations. For example, you can wrap a function with Proc.new to treat it as a variable--but then it's no longer a function; it's an object with a "call" method.
Ruby functions aren't first-class objects. Functions must be wrapped in an object to pass them around; the resulting object can't be treated like a function. Functions can't be assigned in a first-class manner; instead, a function in its container object must be called to modify them.
def func; p "Hello" end
def another_func(f); method(f)[] end
another_func(:func) # => "Hello"
def func2; print "Goodbye!"
self.class.send(:define_method, :func, method(:func2))
func # => "Goodbye!"
method(:func).owner # => Object
func # => "Goodbye!"
self.func # => "Goodbye!"
I wouldn't call those different kind of streams. The Stream class have CanRead and CanWrite properties that tell you if the particular stream can be read from and written to.
The major difference between different stream classes (such as MemoryStream vs FileStream) is the backing store - where the data is read from or where it's written to. It's kind of obvious from the name. A MemoryStream stores the data in memory only, a FileStream is backed by a file on disk, a NetworkStream reads data from the network and so on.
Try
<td style="text-align:center;">
<input type="checkbox" name="myTextEditBox" value="checked" />
</td>
Abstract methods means there is no default implementation for it and an implementing class will provide the details.
Essentially, you would have
abstract class AbstractObject {
public abstract void method();
}
class ImplementingObject extends AbstractObject {
public void method() {
doSomething();
}
}
So, it's exactly as the error states: your abstract method can not have a body.
There's a full tutorial on Oracle's site at: http://download.oracle.com/javase/tutorial/java/IandI/abstract.html
The reason you would do something like this is if multiple objects can share some behavior, but not all behavior.
A very simple example would be shapes:
You can have a generic graphic object, which knows how to reposition itself, but the implementing classes will actually draw themselves.
(This is taken from the site I linked above)
abstract class GraphicObject {
int x, y;
...
void moveTo(int newX, int newY) {
...
}
abstract void draw();
abstract void resize();
}
class Circle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
class Rectangle extends GraphicObject {
void draw() {
...
}
void resize() {
...
}
}
See also Git: discover which commits ever touched a range of lines.
Since Git 1.8.4, git log
has -L
to view the evolution of a range of lines.
For example, suppose you look at git blame
's output. Here -L 150,+11
means "only look at the lines 150 to 150+11":
$ git blame -L 150,+11 -- git-web--browse.sh
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 150) die "The browser $browser is not
a180055a git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:36 +0100 151) fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 152) fi
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 153)
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 154) case "$browser" in
81f42f11 git-web--browse.sh (Giuseppe Bilotta 2010-12-03 17:47:38 +0100 155) firefox|iceweasel|seamonkey|iceape)
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 156) # Check version because firefox < 2.0 do
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 157) vers=$(expr "$($browser_path -version)"
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 158) NEWTAB='-new-tab'
5d6491c7 git-browse-help.sh (Christian Couder 2007-12-02 06:07:55 +0100 159) test "$vers" -lt 2 && NEWTAB=''
a0685a4f git-web--browse.sh (Dmitry Potapov 2008-02-09 23:22:22 -0800 160) "$browser_path" $NEWTAB "$@" &
And you want to know the history of what is now line 155.
Then, use git log
. Here, -L 155,155:git-web--browse.sh
means "trace the evolution of lines 155 to 155 in the file named git-web--browse.sh
".
$ git log --pretty=short -u -L 155,155:git-web--browse.sh
commit 81f42f11496b9117273939c98d270af273c8a463
Author: Giuseppe Bilotta <[email protected]>
web--browse: support opera, seamonkey and elinks
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -143,1 +143,1 @@
-firefox|iceweasel)
+firefox|iceweasel|seamonkey|iceape)
commit a180055a47c6793eaaba6289f623cff32644215b
Author: Giuseppe Bilotta <[email protected]>
web--browse: coding style
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- a/git-web--browse.sh
+++ b/git-web--browse.sh
@@ -142,1 +142,1 @@
- firefox|iceweasel)
+firefox|iceweasel)
commit 5884f1fe96b33d9666a78e660042b1e3e5f9f4d9
Author: Christian Couder <[email protected]>
Rename 'git-help--browse.sh' to 'git-web--browse.sh'.
diff --git a/git-web--browse.sh b/git-web--browse.sh
--- /dev/null
+++ b/git-web--browse.sh
@@ -0,0 +127,1 @@
+ firefox|iceweasel)
The issubclass(sub, sup)
boolean function returns true if the given subclass sub
is indeed a subclass of the superclass sup
.
just add below two annotations to your POJO.
@ComponentScan
@Configuration
public class YourClass {
//TODO
}
This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:
var values = ["Red", "Green"],
colors = document.getElementById("colors");
_.each(colors.options, function (option) {
option.selected = ~_.indexOf(values, option.text);
});
If you're using jQuery, it could be even more terse:
var values = ["Red", "Green"];
$("#colors option").prop("selected", function () {
return ~$.inArray(this.text, values);
});
If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:
var color, i, j,
values = ["Red", "Green"],
options = document.getElementById("colors").options;
for ( i = 0; i < values.length; i++ ) {
for ( j = 0, color = values[i]; j < options.length; j++ ) {
options[j].selected = options[j].selected || color === options[j].text;
}
}
if(isset($_POST['form1']))
{
try
{
$user=$_POST['username'];
$pass=$_POST['password'];
$email=$_POST['email'];
$roll=$_POST['roll'];
$class=$_POST['class'];
if(empty($user)) throw new Exception("Name can not empty");
if(empty($pass)) throw new Exception("Password can not empty");
if(empty($email)) throw new Exception("Email can not empty");
if(empty($roll)) throw new Exception("Roll can not empty");
if(empty($class)) throw new Exception("Class can not empty");
$statement=$db->prepare("show table status like 'tbl_std_info'");
$statement->execute();
$result=$statement->fetchAll();
foreach($result as $row)
$new_id=$row[10];
$up_file=$_FILES["image"]["name"];
$file_basename=substr($up_file, 0 , strripos($up_file, "."));
$file_ext=substr($up_file, strripos($up_file, "."));
$f1="$new_id".$file_ext;
if(($file_ext!=".png")&&($file_ext!=".jpg")&&($file_ext!=".jpeg")&&($file_ext!=".gif"))
{
throw new Exception("Only jpg, png, jpeg or gif Logo are allow to upload / Empty Logo Field");
}
move_uploaded_file($_FILES["image"]["tmp_name"],"../std_photo/".$f1);
$statement=$db->prepare("insert into tbl_std_info (username,image,password,email,roll,class) value (?,?,?,?,?,?)");
$statement->execute(array($user,$f1,$pass,$email,$roll,$class));
$success="Registration Successfully Completed";
echo $success;
}
catch(Exception $e)
{
$msg=$e->getMessage();
}
}
Assuming, that you have root access on the box you can do:
sudo -u postgres psql
If that fails with a database "postgres" does not exists this block.
sudo -u postgres psql template1
Then sudo nano /etc/postgresql/11/main/pg_hba.conf file
local all postgres ident
For newer versions of PostgreSQL ident actually might be peer.
Inside the psql shell you can give the DB user postgres a password:
ALTER USER postgres PASSWORD 'newPassword';
Element is the only kind of node that can have child nodes and attributes.
Document also has child nodes, BUT
no attributes, no text, exactly one child element.
I believe the browser is looking for those assets FROM the root of the webserver. This is difficult because it is easy to start developing on your machine WITHOUT actually using a webserver ( just by loading local files through your browser)
You could start by packaging your html and css/js together?
a directory structure something like:
-yourapp
- index.html
- assets
- css
- js
- myPage.js
Then your script tag (from index.html) could look like
<script src="assets/js/myPage.js"></script>
An added benifit of packaging your html and assets in one directory is that you can copy the directory and give it to someone else or put it on another machine and it will work great.
If you experience this trying to access Web services deployed on a Glassfish3 server, you might want to tune your http-thread-pool settings. That fixed SocketExceptions we had when many concurrent threads was calling the web service.
See this question. LINQ Take() and Skip() are the most popular answers, as well as Array.CopyTo().
A purportedly faster extension method is described here.
_([1,2,3]).find(function(v){
return v if (v==2);
})
You use a function component:
const def = (props) => {
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>
<div ...>
<someComponent
do something
/>
if (some condition) {
do this
} else {
do that
}
</div>
};
In the function component, you have to write a return or just add parentheses. After the added return or parentheses your code should look like this:
const def = (props) => ({
<div>
<div className=" ..some classes..">{abc}</div>
<div className=" ..some classes..">{t('translation/something')}</div>
<div ...>
<someComponent
do something
/>
if (some condition) {
do this
} else {
do that
}
</div>
});
This link will be of interest to you: http://msdn.microsoft.com/en-us/library/ds8bxk2a.aspx
For http connections, the WebRequest and WebResponse classes use SSL to communicate with web hosts that support SSL. The decision to use SSL is made by the WebRequest class, based on the URI it is given. If the URI begins with "https:", SSL is used; if the URI begins with "http:", an unencrypted connection is used.
To reiterate the other answers with some additional info about what is a digit:
new Regex("^[7-9][0-9]{9}$")
Will match phone numbers written using roman numerals.
new Regex(@"^[7-9]\d{9}$", RegexOptions.ECMAScript)
Will match the same as the previous regex. When RegexOptions.ECMAScript
is specified \d
matches any roman numeral.
new Regex(@"^[7-9]\d{9}$")
Will match phone numbers written using any numerals for the last 9 digits.
The difference is that the first two patterns will only match phone numbers like 9123456789
while the third pattern also will match phone numbers like 9?????????
.
So you can use \d
to match native numerals. However, if you want to limit the match for native numerals to only some (like 7-9) you need an additional step. For punjabi (India) to be able to match ??????????
you can do it like this:
CultureInfo.GetCultureInfo("pa-IN").NumberFormat.NativeDigits.Skip(7).Take(3)
This will return the native numerals for 7-9. You can then join them together to form a "culture aware" regular expression for the digits 7-9.
sh -x script [arg1 ...]
bash -x script [arg1 ...]
These give you a trace of what is being executed. (See also 'Clarification' near the bottom of the answer.)
Sometimes, you need to control the debugging within the script. In that case, as Cheeto reminded me, you can use:
set -x
This turns debugging on. You can then turn it off again with:
set +x
(You can find out the current tracing state by analyzing $-
, the current flags, for x
.)
Also, shells generally provide options '-n
' for 'no execution' and '-v
' for 'verbose' mode; you can use these in combination to see whether the shell thinks it could execute your script — occasionally useful if you have an unbalanced quote somewhere.
There is contention that the '-x
' option in Bash is different from other shells (see the comments). The Bash Manual says:
-x
Print a trace of simple commands, for
commands, case
commands, select
commands, and arithmetic for
commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the PS4
variable is expanded and the resultant value is printed before the command and its expanded arguments.
That much does not seem to indicate different behaviour at all. I don't see any other relevant references to '-x
' in the manual. It does not describe differences in the startup sequence.
Clarification: On systems such as a typical Linux box, where '/bin/sh
' is a symlink to '/bin/bash
' (or wherever the Bash executable is found), the two command lines achieve the equivalent effect of running the script with execution trace on. On other systems (for example, Solaris, and some more modern variants of Linux), /bin/sh
is not Bash, and the two command lines would give (slightly) different results. Most notably, '/bin/sh
' would be confused by constructs in Bash that it does not recognize at all. (On Solaris, /bin/sh
is a Bourne shell; on modern Linux, it is sometimes Dash — a smaller, more strictly POSIX-only shell.) When invoked by name like this, the 'shebang' line ('#!/bin/bash
' vs '#!/bin/sh
') at the start of the file has no effect on how the contents are interpreted.
The Bash manual has a section on Bash POSIX mode which, contrary to a long-standing but erroneous version of this answer (see also the comments below), does describe in extensive detail the difference between 'Bash invoked as sh
' and 'Bash invoked as bash
'.
When debugging a (Bash) shell script, it will be sensible and sane — necessary even — to use the shell named in the shebang line with the -x
option. Otherwise, you may (will?) get different behaviour when debugging from when running the script.
Wrong syntax. Here you are:
insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');
or:
insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');
The second one is normally used for case-sensitive column names.
I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.
According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.
According to their documentation, here's what you would send:
http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>
And here's what you would receive back:
<?xml version="1.0"?>
<CityStateLookupResponse>
<ZipCode ID="0">
<Zip5>90210</Zip5>
<City>BEVERLY HILLS</City>
<State>CA</State>
</ZipCode>
</CityStateLookupResponse>
USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.
Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here
This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:
GET http://ziptasticapi.com/48867
And they will return a JSON object along the lines of:
{"country": "US", "state": "MI", "city": "OWOSSO"}
Indeed, it works. You can test this from a command line by doing something like:
curl http://ziptasticapi.com/48867
just see how DataInputStream.readInt() is implemented;
int ch1 = in.read();
int ch2 = in.read();
int ch3 = in.read();
int ch4 = in.read();
if ((ch1 | ch2 | ch3 | ch4) < 0)
throw new EOFException();
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
In my case (not necessarily be the solution for you, but it may be helpful for someone), the solution was:
Go menu Tools ? Extensions and Updates
Select the Online
tab from the right panel
Search for the words web tools
, and then select Microsoft ASP.NET and Web Tools
and install it.
In my case, this was missing from my computer because of a lot of repairing operations for Visual Studio.
If you have a list of lists, you only needed to use ...
import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)
per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.
Surprisingly, no one mentioned this alternative that uses only built-in bash commands:
i="$IFS";IFS='/';set -f;p=($PWD);set +f;IFS="$i";echo "${p[-1]}"
As an added bonus you can easily obtain the name of the parent directory with:
[ "${#p[@]}" -gt 1 ] && echo "${p[-2]}"
These will work on Bash 4.3-alpha or newer.
Click here Code Project! Its Code project example. Its working to me
Adding on to Carlos Calla's great answer.
The height of .modal-body must be set, BUT you can use media queries to make sure it's appropriate for the screen size.
.modal-body{
height: 250px;
overflow-y: auto;
}
@media (min-height: 500px) {
.modal-body { height: 400px; }
}
@media (min-height: 800px) {
.modal-body { height: 600px; }
}
Use break?
while(choice!=99)
{
cin>>choice;
if (choice==99)
break;
cin>>gNum;
}
What you need to do is this:
Settings | About Phone
Scroll to the bottom to build number
.
Tap on build number about 7 times. Each time you will get a popup message saying you are x steps away from being a developer
When you get to the final step you will get a message saying now you are a developer
Go back into settings and you will see a new setting Developer options
there you will see a lot of options for developers. Enable USB debugging
Re-connect you phone to the usb, and you should see you device under adb devices
.
I hope this answer helps someone else.
My solution is based on @Martijn Pieters' comment:
register_namespace
only influences serialisation, not search.
So the trick here is to use different dictionaries for serialization and for searching.
namespaces = {
'': 'http://www.example.com/default-schema',
'spec': 'http://www.example.com/specialized-schema',
}
Now, register all namespaces for parsing and writing:
for name, value in namespaces.iteritems():
ET.register_namespace(name, value)
For searching (find()
, findall()
, iterfind()
) we need a non-empty prefix. Pass these functions a modified dictionary (here I modify the original dictionary, but this must be made only after the namespaces are registered).
self.namespaces['default'] = self.namespaces['']
Now, the functions from the find()
family can be used with the default
prefix:
print root.find('default:myelem', namespaces)
but
tree.write(destination)
does not use any prefixes for elements in the default namespace.
You can try something like process.argv
, that is if you are using node.js
to run the program.
console.log(process.argv)
=> Would print an array containing
[
'/usr/bin/node',
'/home/user/path/filename.js',
'your_input'
]
You get the user provided input via array index, i.e., console.log(process.argv[3])
This should provide you with the input which you can store.
Example:
var somevariable = process.argv[3]; // input one
var somevariable2 = process.argv[4]; // input two
console.log(somevariable);
console.log(somevariable2);
If you are building a command-line program then the npm package yargs would be really helpful.
The following, with an additional dot before the index, works just as expected. Here, the square brackets are optional when the index is followed by another property:
{{people.[1].name}}
{{people.1.name}}
However, the square brackets are required in:
{{#with people.[1]}}
{{name}}
{{/with}}
In the latter, using the index number without the square brackets would get one:
Error: Parse error on line ...:
... {{#with people.1}}
-----------------------^
Expecting 'ID', got 'INTEGER'
As an aside: the brackets are (also) used for segment-literal syntax, to refer to actual identifiers (not index numbers) that would otherwise be invalid. More details in What is a valid identifier?
(Tested with Handlebars in YUI.)
You can now use the get
helper for this:
(get people index)
although if you get an error about index needing to be a string, do:
(get people (concat index ""))
I came across the same issue whilst resuming work on a old MEAN stack project. I was using nodemon
as my local development server and got the same error Resource interpreted as stylesheet but transferred with MIME type text/html
. I changed from nodemon
to http-server
which can be found here. It immediately worked for me.
My problem was in web.config: UnobtrusiveJavaScriptEnabled was turned off
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="false" />
</appSettings>
I changed to and now works:
`<add key="UnobtrusiveJavaScriptEnabled" value="true" />`
To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.
Use serialization to make deep copies. This is not the quickest solution but it does not depend on the type.
DateTime#to_date
does exist with ActiveSupport:
$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
from (irb):1
>> require 'active_support/core_ext'
=> true
>> DateTime.new.to_date
=> Mon, 01 Jan -4712
If you are using mcedit for makefile edit. you have to see the following mark.
Service
extends ContextWrapper
ContextWrapper
extends Context
So....
Context context = this;
(in Service or Activity Class)
This is an old question, but I'd say none of the answers really fits the OP's question. All he wanted/needed to do is this:
char c = std::fgetc(fp);
std::strcpy(buffer, &c);
The relevant aspect here is the fact, that the second argument of strcpy()
doesn't need to be a char array / c-string. In fact, none of the arguments is a char or char array at all. They are both char pointers:
strcpy(char* dest, const char* src);
dest :
A non-const char pointersrc :
A const char pointer\0
within its remaining elements (starting with src
), to mark the end of the c-string that should be copied.<td><input type="radio" name="gender" value="Male" id="male" <? if($gender=='Male')
{?> checked="" <? }?>/>Male
<input type="radio" name="gender" value="Female" id="female" <? if($gender=='Female') {?> checked="" <?}?>/>Female<br/> </td>
I'm not sure about Tomcat 7, but with Tomcat 6... once you start Tomcat:
By going into the bin directory and starting startup.bat
(win) or startup.sh
(Unix/osx) it will spin up a local instance of the server running usually on port 8080 by default. Then by going to http://localhost:8080/ and seeing that it is running, there is a link to the manager. If that page is not there, you can try loading the manager by going directly to manager/html, and that will load the Host Manager gui.
http://localhost:8080/manager/html
Make sure Tomcat is running first and that 8080 is the right port. These are just the defaults that tomcat usually runs with.
To login you need to edit the conf/tomcat-users.xml, and create a Manager GUI role
<role rolename="manager-gui"/>
and add that to a user
<user username="admin" password="password" roles="manager-gui"/>
Then when you go to Manager GUI app at http://localhost:8080/manager/html it will prompt you for a username/password, which you added to that config file.
Just remove css from your js fiddle, ng-show will controll it. AngularJS sets the display style to none (using an !important flag). And remove this class when it must be shown.
This is in RxJava2 in scenario when one user logout from your app and other users login (Same App) To regerate and call login (If user's device didn't have internet connection earlier at the time of activity start and we need to send token in login api )
Single.fromCallable(() -> FirebaseInstanceId.getInstance().getToken())
.flatMap( token -> Retrofit.login(userName,password,token))
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(simple -> {
if(simple.isSuccess){
loginedSuccessfully();
}
}, throwable -> Utils.longToast(context, throwable.getLocalizedMessage()));
Login
@FormUrlEncoded
@POST(Site.LOGIN)
Single<ResponseSimple> login(@Field("username") String username,
@Field("password") String pass,
@Field("token") String token
);
private void CleanForm(Control ctrl)
{
foreach (var c in ctrl.Controls)
{
if (c is TextBox)
{
((TextBox)c).Text = String.Empty;
}
if( c.Controls.Count > 0)
{
CleanForm(c);
}
}
}
When you initially call ClearForm, pass in this, or Page (I assume that is what 'this' is).
You are not returning. Change to
this.state.data.map(function(item, i){
console.log('test');
return <li>Test</li>;
})
Here is a class providing a cancel method for a delayed action
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
Here is a full working example using a button to switch between components
you can set a constructor as following
constructor(props)
{
super(props);
this.state={
currentView: ''
}
}
then you can render components as following
render()
{
const switchView = () => {
switch(this.state.currentView)
{
case "settings": return <h2>settings</h2>;
case "dashboard": return <h2>dashboard</h2>;
default: return <h2>dashboard</h2>
}
}
return (
<div>
<button onClick={(e) => this.setState({currentView: "settings"})}>settings</button>
<button onClick={(e) => this.setState({currentView: "dashboard"})}>dashboard</button>
<div className="container">
{ switchView() }
</div>
</div>
);
}
}
As you can see I am using a button to switch between states.
Just in case it helps someone, since these questions (and answers) helped me really much; I decided to create an alias that runs these 4 commands in a row:
Just add the following line to your ~/.bashrc
file (modify the main
keyword accordingly to the name of your .tex
and .bib
files)
alias texbib = 'pdflatex main.tex && bibtex main && pdflatex main.tex && pdflatex main.tex'
And now, by just executing the texbib
command (alias), all these commands will be executed sequentially.
nameContent
only exists within the first()
function, as you defined it within the first()
function.
To make its scope broader, define it outside of the functions:
var nameContent;
function first(){
nameContent=document.getElementById('full_name').value;
}
function second() {
first();
y=nameContent; alert(y);
}
second();
A slightly better approach would be to return
the value, as global variables get messy very quickly:
function getFullName() {
return document.getElementById('full_name').value;
}
function doStuff() {
var name = getFullName();
alert(name);
}
doStuff();
Create the thread object inside the first for loop.
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(new Runnable() {
public void run() {
// some code to run in parallel
}
});
threads[i].start();
}
And then so what everyone here is saying.
for(i = 0; i < threads.length; i++)
threads[i].join();
If someone is still looking at this issue, the easiest way to do is
var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));
it will add 2 hours in current time. Value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time) Value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time)
If your UIBarButtonItem is already allocated like in a storyboard. (printBtn)
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
btn.setImage(UIImage(named: Constants.ImageName.print)?.withRenderingMode(.alwaysTemplate), for: .normal)
btn.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handlePrintPress(tapGesture:))))
printBtn.customView = btn
Actually, you need to update your repo first, then an upgrade of your Glibc can fix this issue.
If it's too late at night and your table is already innoDB and you still don't see the link, maybe is due to the fact that now it's placed above the structure of the table, like in the picture is shown
Not hidden, but I think that a lot of developers are not using the HasValue and Value properties on the nullable types.
int? x = null;
int y;
if (x.HasValue)
y = x.Value;
One alternative would be to use a getter/setter methods.
For instance, if you only care about reading the calculated value:
var book = {}
Object.defineProperties(book,{
key1: { value: "it", enumerable: true },
key2: {
enumerable: true,
get: function(){
return this.key1 + " works!";
}
}
});
console.log(book.key2); //prints "it works!"
The above code, though, won't let you define another value for key2.
So, the things become a bit more complicated if you would like to also redefine the value of key2. It will always be a calculated value. Most likely that's what you want.
However, if you would like to be able to redefine the value of key2, then you will need a place to cache its value independently of the calculation.
Somewhat like this:
var book = { _key2: " works!" }
Object.defineProperties(book,{
key1: { value: "it", enumerable: true},
_key2: { enumerable: false},
key2: {
enumerable: true,
get: function(){
return this.key1 + this._key2;
},
set: function(newValue){
this._key2 = newValue;
}
}
});
console.log(book.key2); //it works!
book.key2 = " doesn't work!";
console.log(book.key2); //it doesn't work!
for(var key in book){
//prints both key1 and key2, but not _key2
console.log(key + ":" + book[key]);
}
Another interesting alternative is to use a self-initializing object:
var obj = ({
x: "it",
init: function(){
this.y = this.x + " works!";
return this;
}
}).init();
console.log(obj.y); //it works!
I know this question is old and has a lot of varying answers, with various bonuses and drawbacks. My take on it, is why not roll your own IPC implementation.
class IPC {
companion object {
private val appContext : Context by lazy { /*genericApplicationContext*/ }
fun initIPC(process: String){
var file : File? = null
file = File(appContext.cacheDir.absolutePath + "/$process")
var output : OutputStream? = null
try {
output = FileOutputStream(file!!)
output.write(0)
} finally {
output?.close()
}
}
fun destroyIPC(process: String){
var file : File? = null
file = File(appContext.cacheDir.absolutePath + "/$process")
file.delete()
}
fun checkForIPC(process: String) : Boolean {
var file : File? = null
file = File(appContext.cacheDir.absolutePath + "/$process")
if(file.exists()) return true
return false
}
}
}
This allows you to create the file before launching the activity, and then close out the "process/file" when you close the launched activity. This allows you to check in a background thread or current activity if your "process activity" is in the background to see if the file is still open signaling that the activity is alive. In my case I am calling an external API in succession but need to rate limit the calls, so use this to make sure only one activity is alive calling the APIs at a time.
Use a table variable if for a very small quantity of data (thousands of bytes)
Use a temporary table for a lot of data
Another way to think about it: if you think you might benefit from an index, automated statistics, or any SQL optimizer goodness, then your data set is probably too large for a table variable.
In my example, I just wanted to put about 20 rows into a format and modify them as a group, before using them to UPDATE / INSERT a permanent table. So a table variable is perfect.
But I am also running SQL to back-fill thousands of rows at a time, and I can definitely say that the temporary tables perform much better than table variables.
This is not unlike how CTE's are a concern for a similar size reason - if the data in the CTE is very small, I find a CTE performs as good as or better than what the optimizer comes up with, but if it is quite large then it hurts you bad.
My understanding is mostly based on http://www.developerfusion.com/article/84397/table-variables-v-temporary-tables-in-sql-server/, which has a lot more detail.
In my case there was a mismatch between the build path JRE and installed JRE on execution environment. I moved into Project > Properties > Java compiler. There was a warning message at the bottom.
I clicked on the links 'Installed JRE', 'Execution environment', 'Java build path' and changed the JDK version to 1.7 and the warning disappeared.
A lambda expression is like an anonymous method written in place of a delegate instance.
delegate int MyDelagate (int i);
MyDelagate delSquareFunction = x => x * x;
Consider the lambda expression x => x * x;
The input parameter value is x (on the left side of =>)
The function logic is x * x (on the right side of =>)
A lambda expression's code can be a statement block instead of an expression.
x => {return x * x;};
Example
Note: Func
is a predefined generic delegate.
Console.WriteLine(MyMethod(x => "Hi " + x));
public static string MyMethod(Func<string, string> strategy)
{
return strategy("Lijo").ToString();
}
References
I ended up using this solution.
decimal weeklyWage;
decimal.TryParse(items[2],NumberStyles.Any, new NumberFormatInfo() { NumberDecimalSeparator = "."}, out weeklyWage);
The above examples aren't simply written for Swift 3.0+
Update - Swift 3.0+ - Convert Date To String
let date = Date() // insert your date data here
var dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd" // add custom format if you'd like
var dateString = dateFormatter.string(from: date)
Django has method_decorator
which is a decorator that turns any decorator into a method decorator, you can see how it's implemented in django.utils.decorators
:
https://docs.djangoproject.com/en/3.0/topics/class-based-views/intro/#decorating-the-class
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
I was asking the same too. Another solution is you could overload your method:
void remove_id(EmployeeClass);
void remove_id(ProductClass);
void remove_id(DepartmentClass);
in the call the argument will fit accordingly the object you pass. but then you will have to repeat yourself
void remove_id(EmployeeClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(ProductClass _obj) {
int saveId = _obj->id;
...
};
void remove_id(DepartmentClass _obj) {
int saveId = _obj->id;
...
};
I am fairly new to Docker. I was cleaning up some initial testing mess and was not able to remove a volume either. I had stopped all the running instances, performed a docker rmi -f $(docker image ls -q)
, but still received the Error response from daemon: unable to remove volume: remove uuid: volume is in use
.
I did a docker system prune
and it cleaned up what was needed to remove the last volume:
[0]$ docker system prune
WARNING! This will remove:
- all stopped containers
- all networks not used by at least one container
- all dangling images
- all build cache
Are you sure you want to continue? [y/N] y
Deleted Containers:
... about 15 containers UUID's truncated
Total reclaimed space: 2.273MB
[0]$ docker volume ls
DRIVER VOLUME NAME
local uuid
[0]$ docker volume rm uuid
uuid
[0]$
The client and daemon API must both be at least 1.25 to use this command. Use the
docker version
command on the client to check your client and daemon API versions.
I created a Class in the Models directory called: myData with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
namespace Vidly.Models
{
public class MyDbContext : DbContext
{
public MyDbContext()
{
}
}
}
rebuilt the app with: control-shift-b
then ran the following in the nuGet Console:
Enable-Migrations -StartUpProjectName Vidly -ContextTypeName Vidly.Models.MyDbContext -Verbose
the Console returned:
Using StartUp project 'Vidly'. Using NuGet project 'Vidly'. Checking if the context targets an existing database... Code First Migrations enabled for project Vidly. Enable-Migrations -StartUpProjectName Vidly -ContextTypeName Vidly.Models.myData -Verbose
And the FrameWork created a Migrations directory and wrote a Configuration.cs template in there with the following code:
namespace Vidly.Migrations
{
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Vidly.Models.MyDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = false;
}
protected override void Seed(Vidly.Models.MyDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data.
}
}
}
Add this line under the dependencies in your gradle file
compile 'com.android.support:support-annotations:27.1.1'