Found a solution. This problem happens, when you import a project.
The solution is simple
Now you should see the web app libraries showing your jars added.
In python, the str()
method is similar to the toString()
method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__()
method of the parameter object to get its string representation.
In this case, however, you are comparing a UserProperty
author from the database, which is of type users.User
with the nickname string. You will want to compare the nickname
property of the author instead with todo.author.nickname
in your template.
EL expression:
${requestScope.Error_Message}
There are several implicit objects in JSP EL. See Expression Language under the "Implicit Objects" heading.
The following approach worked for me
Navigate to your android SDK/tools folder in the terminal window (in case you didn't added the path for it)
Make sure the virtual device you're planning to clean is powered off.
Run the command "./emulator -wipe-data -avd YourAvdName" where YourAvdName is the name of your virtual android device
git log --grep=<pattern>
Limit the commits output to ones with log message that matches the
specified pattern (regular expression).
string urlParameters = "param1=value1¶m2=value2";
string _endPointName = "your url post api";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";
System.Net.ServicePointManager.ServerCertificateValidationCallback +=
(se, cert, chain, sslerror) =>
{
return true;
};
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(urlParameters);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
I would consider this more of an old-school C style; it is not really good practice in JavaScript so you should avoid it.
There are several methods.
If you want just the consolidated string value returned, this is a good quick and easy approach
DECLARE @combinedString VARCHAR(MAX)
SELECT @combinedString = COALESCE(@combinedString + ', ', '') + stringvalue
FROM jira.customfieldValue
WHERE customfield = 12534
AND ISSUE = 19602
SELECT @combinedString as StringValue
Which will return your combined string.
You can also try one of the XML methods e.g.
SELECT DISTINCT Issue, Customfield, StringValues
FROM Jira.customfieldvalue v1
CROSS APPLY ( SELECT StringValues + ','
FROM jira.customfieldvalue v2
WHERE v2.Customfield = v1.Customfield
AND v2.Issue = v1.issue
ORDER BY ID
FOR XML PATH('') ) D ( StringValues )
WHERE customfield = 12534
AND ISSUE = 19602
What if onclick event is not directly on element, but from parent element? This should work:
$(".noclick").attr('onclick','').unbind('click');
$(".noclick").click(function(e){
e.preventDefault();
e.stopPropagation();
return false;
});
I you want to put the response of the request in the navItems
. Because http.get()
return an observable you will have to subscribe to it.
Look at this example:
// version without map_x000D_
this.http.get("../data/navItems.json")_x000D_
.subscribe((success) => {_x000D_
this.navItems = success.json(); _x000D_
});_x000D_
_x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
this.http.get("../data/navItems.json")_x000D_
.map((data) => {_x000D_
return data.json();_x000D_
})_x000D_
.subscribe((success) => {_x000D_
this.navItems = success; _x000D_
});
_x000D_
string Time = "16:23:01";
DateTime date = DateTime.Parse(Time, System.Globalization.CultureInfo.CurrentCulture);
string t = date.ToString("HH:mm:ss tt");
For me my mac OS is Mojave. and I'm facing the same issue for three days and in the end, I just write the correct path in the .bash_profile file which is like this:
export PATH=/Users/[YOURNAME]/development/flutter/bin:$PATH
Only CSS & bootstrap class
<div class="col-md-4 input-group">
<input class="form-control" type="text"/>
<div class="input-group-btn">
<label for="files" class="btn btn-default">browse</label>
<input id="files" type="file" class="btn btn-default" style="visibility:hidden;"/>
</div>
</div>
The mozilla docs for setDate() don't indicate that it will handle end of month scenarios. See https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
setDate()
That is why I use setTime() when I need to add days.
strsplit
to parse your input and, as Greg mentioned, assign
to assign the variables.
original_string <- c("x=123", "y=456")
pairs <- strsplit(original_string, "=")
lapply(pairs, function(x) assign(x[1], as.numeric(x[2]), envir = globalenv()))
ls()
Can be solved nicely by setting up a custom directive once:
Vue.directive('click-outside', {
bind () {
this.event = event => this.vm.$emit(this.expression, event)
this.el.addEventListener('click', this.stopProp)
document.body.addEventListener('click', this.event)
},
unbind() {
this.el.removeEventListener('click', this.stopProp)
document.body.removeEventListener('click', this.event)
},
stopProp(event) { event.stopPropagation() }
})
Usage:
<div v-click-outside="nameOfCustomEventToCall">
Some content
</div>
In the component:
events: {
nameOfCustomEventToCall: function (event) {
// do something - probably hide the dropdown menu / modal etc.
}
}
Working Demo on JSFiddle with additional info about caveats:
I've recently battled with this problem as well, and I've learned two things about the above suggestions.
The misleading aspect of this is that you now have a different value in the cell. Fortuately, when you copy/paste or export to CSV, the apostrophe is not included.
Conclusion: use the apostrophe, not the numberFormatting in order to retain the leading zeros.
If it is a valid change.
you can change the property.
Tools --> Options --> Designers --> Table and Database designers --> Uncheck --> Prevent saving changes that required table re-creation.
Now you can easily change the column name without recreating the table or losing u r records.
From Apple's Official Website :
// In body data for the 'application/x-www-form-urlencoded' content type,
// form fields are separated by an ampersand. Note the absence of a
// leading ampersand.
NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];
// Set the request's content type to application/x-www-form-urlencoded
[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
// Designate the request a POST request and specify its body data
[postRequest setHTTPMethod:@"POST"];
[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
// Initialize the NSURLConnection and proceed as described in
// Retrieving the Contents of a URL
From : code with chris
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];
// Specify that it will be a POST request
request.HTTPMethod = @"POST";
// This is how we set header fields
[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSString *stringData = @"some data";
NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = requestBodyData;
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
You can use "{}" for the target, then jsx will not cry
<Link target={"_blank"} to="your-link">Your Link</Link>
Here is how I add parameters:
sprocCommand.Parameters.Add(New SqlParameter("@Date_Of_Birth",Data.SqlDbType.DateTime))
sprocCommand.Parameters("@Date_Of_Birth").Value = DOB
I am assuming when you write out DOB there are no quotes.
Are you using a third-party control to get the date? I have had problems with the way the text value is generated from some of them.
Lastly, does it work if you type in the .Value attribute of the parameter without referencing DOB?
Spring Boot 2.0.*
or aboveIf you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary
, because various auto-configurations down the road expect to be able to get one by type.
If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
return new DataSourceProperties();
}
@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
return firstDataSourceProperties().initializeDataSourceBuilder().build();
}
@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
return DataSourceBuilder.create().type(BasicDataSource.class).build();
}
firstDataSourceProperties
has to be flagged as@Primary
so that the database initializer feature uses your copy (if you use the initializer).
And your application.propoerties
will look something like this:
app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver
app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver
The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.
Just because none of the answers above seemed to work in my matrix, I'm posting this here:
http://reportingservicestnt.blogspot.com/2011/09/alternate-colors-in-matrixpivot-table.html
You can also solve this problem by creating an array of values and assigning that array:
newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders
The two syntaxes are not equivalent and it can lead to unexpected errors. Here is a simple example showing the differences. If you have a model:
from django.db import models
class Test(models.Model):
added = models.DateTimeField(auto_now_add=True)
And you create a first object:
foo = Test.objects.create(pk=1)
Then you try to create an object with the same primary key:
foo_duplicate = Test.objects.create(pk=1)
# returns the error:
# django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'PRIMARY'")
foo_duplicate = Test(pk=1).save()
# returns the error:
# django.db.utils.IntegrityError: (1048, "Column 'added' cannot be null")
In my case i have used following code for enabling gzip compression in apache web server.
# Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.
tomcat is designed as JSP servlet container. Apache is designed PHP web server. Use apache as web server, responding for PHP request, and direct JSP servlet request to tomcat container. should be better implementation.
Full sync has few tasks:
git reset HEAD --hard
git clean -f
git pull origin master
Or else, what I prefer is that, I may create a new branch with the latest from the remote using:
git checkout origin/master -b <new branch name>
origin is my remote repository reference, and master is my considered branch name. These may different from yours.
For the creation add an empty object to the view.
return view('admin.profiles.create', ['profile' => new Profile()]);
Old function has a second parameter, default value, if you pass there the object's field, the input can be reused.
<input class="input" type="text" name="name" value="{{old('name', $profile->name)}}">
For the form action, you can use the correct endpoint.
<form action="{{ $profile->id == null ? '/admin/profiles' : '/admin/profiles/' . $profile->id }} " method="POST">
And for the update you have to use PATCH method.
@isset($profile->id)
{{ method_field('PATCH')}}
@endisset
try this:
sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
Simple: In Visual Studio Report designer
1. Open the report in design mode and delete the dataset from the RDLC File
2. Open solution Explorer and delete the actual (corrupted) XSD file
3. Add the dataset back to the RDLC file.
4. The above procedure will create the new XSD file.
5. More detailed is below.
In Visual Studio, Open your RDLC file Report in Design mode. Click on the report and then Select View and then Report Data from the top line menu. Select Datasets and then Right Click and delete the dataset from the report. Next Open Solution Explorer, if it is not already open in your Visual Studio. Locate the XSD file (It should be the same name as the dataset you just deleted from the report). Now go back and right click again on the report data Datasets, and select Add Dataset . This will create a new XSD file and write the dataset properties to the report. Now your error message will be gone and any missing data will now appear in your reports.
Piggybacking on what the other answers say, since you don't know how to do them at all, here's an example of how you might do it in JavaScript:
var charactersOnly = "This contains only characters";
var nonCharacters = "This has _@#*($()*@#$(*@%^_(#@!$ non-characters";
if (charactersOnly.search(/[^a-zA-Z]+/) === -1) {
alert("Only characters");
}
if (nonCharacters.search(/[^a-zA-Z]+/)) {
alert("There are non characters.");
}
The /
starting and ending the regular expression signify that it's a regular expression. The search
function takes both strings and regexes, so the /
are necessary to specify a regex.
From the MDN Docs, the function returns -1
if there is no match.
Also note: that this works for only a-z, A-Z. If there are spaces, it will fail.
Sounds like an ideal application for RegEx -- an engine designed for fast text manipulation. In this case:
Regex.Replace("He\"ll,o Wo'r.ld", "[@,\\.\";'\\\\]", string.Empty)
Consider this:
abstract class Product {
int value;
public Product( int val ) {
value= val;
}
abstract public int multiply();
}
class TimesTwo extends Product {
public int mutiply() {
return value * 2;
}
}
The superclass is abstract and has a constructor.
This worked for me:
HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "ImageName";
The preprocessor is looking for StdCUtil/split.h
in
./
(i.e. /root/Core/
, the directory that contains the #include statement). So ./
+ StdCUtil/split.h
= ./StdCUtil/split.h
and the file is missingand in
$INC_DIR
(i.e. ../StdCUtil/
= /root/Core/../StdCUtil/
= /root/StdCUtil/
). So ../StdCUtil/
+ StdCUtil/split.h
= ../StdCUtil/StdCUtil/split.h
and the file is missingYou can fix the error changing the $INC_DIR
variable (best solution):
$INC_DIR = ../
or the include directive:
#include "split.h"
but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.
Reference:
EDIT/UPDATE
It should also be
CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)
...
%.o: %.cpp $(DEPS)
$(CXX) -o $@ $< $(CXXFLAGS)
If you don't use the STL, then the code looks a lot bit like C.
#include <cstdlib>
#include <new>
template< class T >
void append_to_array( T *&arr, size_t &n, T const &obj ) {
T *tmp = static_cast<T*>( std::realloc( arr, sizeof(T) * (n+1) ) );
if ( tmp == NULL ) throw std::bad_alloc( __FUNCTION__ );
// assign things now that there is no exception
arr = tmp;
new( &arr[ n ] ) T( obj ); // placement new
++ n;
}
T
can be any POD type, including pointers.
Note that arr
must be allocated by malloc
, not new[]
.
For an excellent resource on how bash invocation works, what dotfiles do what, and how you should use/configure them, read this:
<div style="width:100%;">
<div style="margin-left:45px;">
<asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
</div>
</div>
If you look at the values returned by setInterval()
they are usually single digits, so you can usually disable all such interrupts with a single line of code:
for (var j = 0 ; j < 256 ; ++j) clearInterval(j)
Use the CSS white-space property instead of opening yourself up to XSS vulnerabilities!
<span style="white-space: pre-line">@Model.CommentText</span>
As others have said, it's macro recording, and you turn it off with q. Here's a nice article about how-to and why it's useful.
sed is line based, so I'm not sure why you want to do this with sed. The paradigm is more processing one line at a time( you could also programatically find the # of fields in the CSV and generate your header line with awk) Why not just
echo "c1, c2, ... " >> file
cat testfile.csv >> file
?
In fact you can use \input{filename}
and \include{filename}
which are latex commands,
directly in Pandoc
, because it supports nearly all html
and latex
syntax.
But beware, the included file will be treated as latex
file. But you can compile your markdown
to latex
with Pandox
easily.
I'd recommend the following solution.
It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.
from os import environ
REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
raise EnvironmentError(f'Failed because {diff} are not set')
In my case the problem was in a child jar which was not rebuilt since I have added a new class, pom.xml of that child jar was not related to my failed pom.xml as child-to-parent relation (using <parent>
tag). So I rebuilt the child jar after which the error had gone.
A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:
"JSON Syntax allows the representation of three types of values".
Regarding the one you're interested in, Arrays it says:
"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:
var values = [25, "hi", true];
You can represent this same array in JSON using a similar syntax:
[25, "hi", true]
Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:
{
"books":
[
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
"edition": 3,
"year": 2011
},
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C.Zakas"
],
"edition": 2,
"year": 2009
},
{
"title": "Professional Ajax",
"authors": [
"Nicholas C. Zakas",
"Jeremy McPeak",
"Joe Fawcett"
],
"edition": 2,
"year": 2008
}
]
}
This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."
To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:
var cars = [{
color: 'gray',
model: '1',
nOfDoors: 4
},
{
color: 'yellow',
model: '2',
nOfDoors: 4
}];
cars is now a JavaScript object. To convert it into a JSON object you could do:
var jsonCars = JSON.stringify(cars);
Which yields:
"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"
To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.
A keystore needs a keystore file. The KeyStore
class needs a FileInputStream
. But if you supply null (instead of FileInputStream
instance) an empty keystore will be loaded. Once you create a keystore, you can verify its integrity using keytool
.
Following code creates an empty keystore with empty password
KeyStore ks2 = KeyStore.getInstance("jks"); ks2.load(null,"".toCharArray()); FileOutputStream out = new FileOutputStream("C:\\mykeytore.keystore"); ks2.store(out, "".toCharArray());
Once you have the keystore, importing certificate is very easy. Checkout this link for the sample code.
Can I see (...) the real SQL
If you want to see the SQL sent directly to the database (that is formatted similar to your example), you'll have to use some kind of jdbc driver proxy like P6Spy (or log4jdbc).
Alternatively you can enable logging of the following categories (using a log4j.properties
file here):
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
The first is equivalent to hibernate.show_sql=true
, the second prints the bound parameters among other things.
To answer the question literally. It is not always true that x == x
double zero = 0.0;
double a[] = { 0,0,0,0,0, zero/zero}; // NaN
cout << (a[5] == 5[a] ? "true" : "false") << endl;
prints
false
Use the ViewTreeObserver on the View to wait for the first layout. Only after the first layout will getWidth()/getHeight()/getMeasuredWidth()/getMeasuredHeight() work.
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeOnGlobalLayoutListener(this);
viewWidth = view.getWidth();
viewHeight = view.getHeight();
}
});
}
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
To make sure that the current object's members are used. Cases where thread safety is a concern, some applications may change the wrong objects member values, for that reason this should be applied to the member so that the correct object member value is used.
If your object is not concerned with thread safety then there is no reason to specify which object member's value is used.
Autossh is best option - checking process is not working in all cases (e.g. zombie process, network related problems)
example:
autossh -M 2323 -c arcfour -f -N -L 8088:localhost:80 host2
This works if you want the first element, like my_list.get(0)
>>> my_list = [1,2,3]
>>> next(iter(my_list), 'fail')
1
>>> my_list = []
>>> next(iter(my_list), 'fail')
'fail'
I know it's not exactly what you asked for but it might help others.
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimaryDark"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>
Swift 3
let rootViewController = UIApplication.shared.keyWindow?.rootViewController
This code is from http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
function viewport() {
var e = window, a = 'inner';
if (!('innerWidth' in window )) {
a = 'client';
e = document.documentElement || document.body;
}
return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}
NB : to read the width, use console.log('viewport width'+viewport().width);
To solve this issue on my side, I had to use a combo of what was already proposed there
DECLARE
chunk1 CLOB; chunk2 CLOB; chunk3 CLOB;
BEGIN
chunk1 := 'very long literal part 1';
chunk2 := 'very long literal part 2';
chunk3 := 'very long literal part 3';
INSERT INTO table (MY_CLOB)
SELECT ( chunk1 || chunk2 || chunk3 ) FROM dual;
END;
Hope this helps.
It is not possible to use the RTMP protocol in HTML 5, because the RTMP protocol is only used between the server and the flash player. So you can use the other streaming protocols for viewing the streaming videos in HTML 5.
you can convert your datatable to list. check the following link
https://stackoverflow.com/a/35171050/1805776
public static class Helper
{
public static List<T> DataTableToList<T>(this DataTable dataTable) where T : new()
{
var dataList = new List<T>();
//Define what attributes to be read from the class
const System.Reflection.BindingFlags flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance;
//Read Attribute Names and Types
var objFieldNames = typeof(T).GetProperties(flags).Cast<System.Reflection.PropertyInfo>().
Select(item => new
{
Name = item.Name,
Type = Nullable.GetUnderlyingType(item.PropertyType) ?? item.PropertyType
}).ToList();
//Read Datatable column names and types
var dtlFieldNames = dataTable.Columns.Cast<DataColumn>().
Select(item => new
{
Name = item.ColumnName,
Type = item.DataType
}).ToList();
foreach (DataRow dataRow in dataTable.AsEnumerable().ToList())
{
var classObj = new T();
foreach (var dtField in dtlFieldNames)
{
System.Reflection.PropertyInfo propertyInfos = classObj.GetType().GetProperty(dtField.Name);
var field = objFieldNames.Find(x => x.Name == dtField.Name);
if (field != null)
{
if (propertyInfos.PropertyType == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, convertToDateTime(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(Nullable<DateTime>))
{
propertyInfos.SetValue
(classObj, convertToDateTime(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(int))
{
propertyInfos.SetValue
(classObj, ConvertToInt(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(long))
{
propertyInfos.SetValue
(classObj, ConvertToLong(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(decimal))
{
propertyInfos.SetValue
(classObj, ConvertToDecimal(dataRow[dtField.Name]), null);
}
else if (propertyInfos.PropertyType == typeof(String))
{
if (dataRow[dtField.Name].GetType() == typeof(DateTime))
{
propertyInfos.SetValue
(classObj, ConvertToDateString(dataRow[dtField.Name]), null);
}
else
{
propertyInfos.SetValue
(classObj, ConvertToString(dataRow[dtField.Name]), null);
}
}
else
{
propertyInfos.SetValue
(classObj, Convert.ChangeType(dataRow[dtField.Name], propertyInfos.PropertyType), null);
}
}
}
dataList.Add(classObj);
}
return dataList;
}
private static string ConvertToDateString(object date)
{
if (date == null)
return string.Empty;
return date == null ? string.Empty : Convert.ToDateTime(date).ConvertDate();
}
private static string ConvertToString(object value)
{
return Convert.ToString(ReturnEmptyIfNull(value));
}
private static int ConvertToInt(object value)
{
return Convert.ToInt32(ReturnZeroIfNull(value));
}
private static long ConvertToLong(object value)
{
return Convert.ToInt64(ReturnZeroIfNull(value));
}
private static decimal ConvertToDecimal(object value)
{
return Convert.ToDecimal(ReturnZeroIfNull(value));
}
private static DateTime convertToDateTime(object date)
{
return Convert.ToDateTime(ReturnDateTimeMinIfNull(date));
}
public static string ConvertDate(this DateTime datetTime, bool excludeHoursAndMinutes = false)
{
if (datetTime != DateTime.MinValue)
{
if (excludeHoursAndMinutes)
return datetTime.ToString("yyyy-MM-dd");
return datetTime.ToString("yyyy-MM-dd HH:mm:ss.fff");
}
return null;
}
public static object ReturnEmptyIfNull(this object value)
{
if (value == DBNull.Value)
return string.Empty;
if (value == null)
return string.Empty;
return value;
}
public static object ReturnZeroIfNull(this object value)
{
if (value == DBNull.Value)
return 0;
if (value == null)
return 0;
return value;
}
public static object ReturnDateTimeMinIfNull(this object value)
{
if (value == DBNull.Value)
return DateTime.MinValue;
if (value == null)
return DateTime.MinValue;
return value;
}
}
I think that what you have to check is:
if the target EXE is correctly configured in the project settings ("command", in the debugging tab). Since all individual projects run when you start debugging it's well possible that only the debugging target for the "ALL" solution is missing, check which project is currently active (you can also select the debugger target by changing the active project).
dependencies (DLLs) are also located at the target debugee directory or can be loaded (you can use the "depends.exe" tool for checking dependencies of an executable or DLL).
Array indexes in JavaScript start at zero for the first item, so try this:
var firstArrayItem = myValues[0]
Of course, if you actually want the second item in the array at index 1, then it's myValues[1]
.
See Accessing array elements for more info.
Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).
Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.
Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).
Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.
This is the best way I have found :
public class MainActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
// Let's first dynamically add a fragment into a frame container
getSupportFragmentManager().beginTransaction().
replace(R.id.flContainer, new DemoFragment(), "SOMETAG").
commit();
// Now later we can lookup the fragment by tag
DemoFragment fragmentDemo = (DemoFragment)
getSupportFragmentManager().findFragmentByTag("SOMETAG");
}
}
}
Node.js
itself offers an HTTP module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server
prototype.
Just make the anchor display: block
and width/height: 100%
. Eg:
.button a {
display: block;
width: 100%;
height: 100%;
}
jsFiddle: http://jsfiddle.net/4mHTa/
$(document).on('click', function(e) { // Hides the div by clicking any where in the screen
if ( $(e.target).closest('#suggest_input').length ) {
$(".suggest_div").show();
}else if ( ! $(e.target).closest('.suggest_container').length ) {
$('.suggest_div').hide();
}
});
Here #suggest_input in is the name of textbox and .suggest_container is the ul class name and .suggest_div is the main div element for my auto-suggest.
this code is for hiding the div elements by clicking any where in the screen. Before doing every thing please understand the code and copy it...
You may have come here for advice on when to use persist and when to use merge. I think that it depends the situation: how likely is it that you need to create a new record and how hard is it to retrieve persisted data.
Let's presume you can use a natural key/identifier.
Data needs to be persisted, but once in a while a record exists and an update is called for. In this case you could try a persist and if it throws an EntityExistsException, you look it up and combine the data:
try { entityManager.persist(entity) }
catch(EntityExistsException exception) { /* retrieve and merge */ }
Persisted data needs to be updated, but once in a while there is no record for the data yet. In this case you look it up, and do a persist if the entity is missing:
entity = entityManager.find(key);
if (entity == null) { entityManager.persist(entity); }
else { /* merge */ }
If you don't have natural key/identifier, you'll have a harder time to figure out whether the entity exist or not, or how to look it up.
The merges can be dealt with in two ways, too:
You're using span6
and span2
. Both of these classes are "float:left
" meaning, if possible they will always try to sit next to each other.
Twitter bootstrap is based on a 12 grid system. So you should generally always get the span**#**
to add up to 12.
E.g.: span4
+ span4
+ span4
OR span6
+ span6
OR span4
+ span3
+ span5
.
To force a span down though, without listening to the previous float you can use twitter bootstraps clearfix
class. To do this, your code should look like this:
<ul class="nav nav-tabs span2">
<li><a href="./index.html"><i class="icon-black icon-music"></i></a></li>
<li><a href="./about.html"><i class="icon-black icon-eye-open"></i></a></li>
<li><a href="./team.html"><i class="icon-black icon-user"></i></a></li>
<li><a href="./contact.html"><i class="icon-black icon-envelope"></i></a></li>
</ul>
<!-- Notice this following line -->
<div class="clearfix"></div>
<div class="well span6">
<h3>I wish this appeared on the next line without having to gratuitously use BR!</h3>
</div>
To understand circular dependencies, you need to remember that Python is essentially a scripting language. Execution of statements outside methods occurs at compile time. Import statements are executed just like method calls, and to understand them you should think about them like method calls.
When you do an import, what happens depends on whether the file you are importing already exists in the module table. If it does, Python uses whatever is currently in the symbol table. If not, Python begins reading the module file, compiling/executing/importing whatever it finds there. Symbols referenced at compile time are found or not, depending on whether they have been seen, or are yet to be seen by the compiler.
Imagine you have two source files:
File X.py
def X1:
return "x1"
from Y import Y2
def X2:
return "x2"
File Y.py
def Y1:
return "y1"
from X import X1
def Y2:
return "y2"
Now suppose you compile file X.py. The compiler begins by defining the method X1, and then hits the import statement in X.py. This causes the compiler to pause compilation of X.py and begin compiling Y.py. Shortly thereafter the compiler hits the import statement in Y.py. Since X.py is already in the module table, Python uses the existing incomplete X.py symbol table to satisfy any references requested. Any symbols appearing before the import statement in X.py are now in the symbol table, but any symbols after are not. Since X1 now appears before the import statement, it is successfully imported. Python then resumes compiling Y.py. In doing so it defines Y2 and finishes compiling Y.py. It then resumes compilation of X.py, and finds Y2 in the Y.py symbol table. Compilation eventually completes w/o error.
Something very different happens if you attempt to compile Y.py from the command line. While compiling Y.py, the compiler hits the import statement before it defines Y2. Then it starts compiling X.py. Soon it hits the import statement in X.py that requires Y2. But Y2 is undefined, so the compile fails.
Please note that if you modify X.py to import Y1, the compile will always succeed, no matter which file you compile. However if you modify file Y.py to import symbol X2, neither file will compile.
Any time when module X, or any module imported by X might import the current module, do NOT use:
from X import Y
Any time you think there may be a circular import you should also avoid compile time references to variables in other modules. Consider the innocent looking code:
import X
z = X.Y
Suppose module X imports this module before this module imports X. Further suppose Y is defined in X after the import statement. Then Y will not be defined when this module is imported, and you will get a compile error. If this module imports Y first, you can get away with it. But when one of your co-workers innocently changes the order of definitions in a third module, the code will break.
In some cases you can resolve circular dependencies by moving an import statement down below symbol definitions needed by other modules. In the examples above, definitions before the import statement never fail. Definitions after the import statement sometimes fail, depending on the order of compilation. You can even put import statements at the end of a file, so long as none of the imported symbols are needed at compile time.
Note that moving import statements down in a module obscures what you are doing. Compensate for this with a comment at the top of your module something like the following:
#import X (actual import moved down to avoid circular dependency)
In general this is a bad practice, but sometimes it is difficult to avoid.
This is Function which will convert most of the video formats to number of frames there are in the video. It works on Python3
with OpenCV 3+
import cv2
import time
import os
def video_to_frames(input_loc, output_loc):
"""Function to extract frames from input video file
and save them as separate frames in an output directory.
Args:
input_loc: Input video file.
output_loc: Output directory to save the frames.
Returns:
None
"""
try:
os.mkdir(output_loc)
except OSError:
pass
# Log the time
time_start = time.time()
# Start capturing the feed
cap = cv2.VideoCapture(input_loc)
# Find the number of frames
video_length = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) - 1
print ("Number of frames: ", video_length)
count = 0
print ("Converting video..\n")
# Start converting the video
while cap.isOpened():
# Extract the frame
ret, frame = cap.read()
# Write the results back to output location.
cv2.imwrite(output_loc + "/%#05d.jpg" % (count+1), frame)
count = count + 1
# If there are no more frames left
if (count > (video_length-1)):
# Log the time again
time_end = time.time()
# Release the feed
cap.release()
# Print stats
print ("Done extracting frames.\n%d frames extracted" % count)
print ("It took %d seconds forconversion." % (time_end-time_start))
break
if __name__=="__main__":
input_loc = '/path/to/video/00009.MTS'
output_loc = '/path/to/output/frames/'
video_to_frames(input_loc, output_loc)
It supports .mts
and normal files like .mp4
and .avi
. Tried and Tested on .mts
files. Works like a Charm.
If you want Rails 3 or Ruby 1.9 compatibility try the date_validator gem.
img {_x000D_
width: 200px;_x000D_
}
_x000D_
<img src="https://image.ibb.co/gmmneK/children_593313_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/e0RLzK/entrepreneur_1340649_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/cks4Rz/typing_849806_340.jpg"/>
_x000D_
please see the above code.
Basically onSaveInstanceState(Bundle outBundle) will give you a bundle. When you look at the Bundle class, you will see that you can put lots of different stuff inside it. At the next call of onCreate(), you just get that Bundle back as an argument. Then you can read your values again and restore your activity.
Lets say you have an activity with an EditText. The user wrote some text inside it. After that the system calls your onSaveInstanceState(). You read the text from the EditText and write it into the Bundle via Bundle.putString("edit_text_value", theValue).
Now onCreate is called. You check if the supplied bundle is not null. If thats the case, you can restore your value via Bundle.getString("edit_text_value") and put it back into your EditText.
Use .onclick
(all lowercase). Like so:
document.getElementById("foo").onclick = function () {
alert('foo'); // do your stuff
return false; // <-- to suppress the default link behaviour
};
Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.
Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.
Thanks to dee for the answer above with the Scrape() subroutine. The code worked perfectly as written, and I was able to then convert the code to work with the specific website I am trying to scrape.
I do not have enough reputation to upvote or to comment, but I do actually have some minor improvements to add to dee's answer:
You will need to add the VBA Reference via "Tools\References" to "Microsoft HTML Object Library in order for the code to compile.
I commented out the Browser.Visible line and added the comment as follows
'if you need to debug the browser page, uncomment this line:
'Browser.Visible = True
And I added a line to close the browser before Set Browser = Nothing:
Browser.Quit
Thanks again dee!
ETA: this works on machines with IE9, but not machines with IE8. Anyone have a fix?
Found the fix myself, so came back here to post it. The ClassName function is available in IE9. For this to work in IE8, you use querySelectorAll, with a dot preceding the class name of the object you are looking for:
'Set repList = doc.getElementsByClassName("reportList") 'only works in IE9, not in IE8
Set repList = doc.querySelectorAll(".reportList") 'this works in IE8+
Oddly, working on a .js file and Ctrl, Shift, += works to zoom in (and Ctrl - works to zoom out but you have to select 1 or 2 after Ctrl -). This only works when I'm in the js file but the zoom applies to all my open tabs. Using Eclipse Juno on Ubuntu.
I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).
It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.
This is how you use it:
$('.carousel').bcSwipe({ threshold: 50 });
To check the status of Hyper-v in Windows 10,
right click <"start"> ? Run ? OptionalFeatures.exe, ? look for the "Hyper-V" option.
The box should be empty, not checked or shaded.
Make sure to fully power down and reboot the host after changing the Hyper-v setting.
PS
Docker known for activating this "Hyper-V" without asking for user opinion and then Oracle VirtualBox does not want to work.
const button = document.getElementById(btnId);
button.addEventListener("click", function() {
// Submit form
}, {once : true});
// Disabling works too, but this is a more standard approach for general one-time events
select A, B, 'c' as C
from MyTable
I just found myself with this problem too, but I just solved it.
Surely when running the "react-native upgrade" command, it gave them the message that it was not necessary to update or with the command "react-native eject" that the command is not recognized.
react-native upgrade
Now you should use the react-native upgrade --legacy true
command to back up your android folders or ios as the case may be as this command will replace your files.
react-native upgrade --legacy true
Now it's just telling you not to replace your package.json
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
It's probably worth mentioning that for http/https some people proxy their browser traffic through Burp/ZAP or another intercepting "attack proxy". A thread that covers options for this on Android devices can be found here: https://android.stackexchange.com/questions/32366/which-browser-does-support-proxies
Use the raw_input()
function to get input from users (2.x):
print "Enter a file name:",
filename = raw_input()
or just:
filename = raw_input('Enter a file name: ')
or if in Python 3.x:
filename = input('Enter a file name: ')
You need to suffix your variable name with []
like this:
If that doesn't work, try not putting indexes in brackets:
my_array[] value1
my_array[] value2
Note:
If you are using the postman packaged app, you can send an array by selecting raw
/ json
(instead of form-data
). Also, make sure to set Content-Type
as application/json
in Headers
tab.
Here is example for raw data {"user_ids": ["123" "233"]}
, don't forget the quotes!
If you are using the postman REST client you have to use the method I described above because passing data as raw (json) won't work. There is a bug in the postman REST client (At least I get the bug when I use 0.8.4.6
).
Use jQuery. You need to capture the click
event and then go on to the website.
$("#myHref").on('click', function() {_x000D_
alert("inside onclick");_x000D_
window.location = "http://www.google.com";_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="myHref">Click me</a>
_x000D_
This work for me in bootstrap 4:
<div class="alert alert-info">
<a href="#" class="alert-link">Summary:Its some description.......testtesttest</a>
<button type="button" class="btn btn-primary btn-lg float-right">Large button</button>
</div>
By default, read.csv
checks the first few rows of your data to see whether to treat each variable as numeric. If it finds non-numeric values, it assumes the variable is character data, and character variables are converted to factors.
It looks like the PTS and MP variables in your dataset contain non-numerics, which is why you're getting unexpected results. You can force these variables to numeric with
point <- as.numeric(as.character(point))
time <- as.numeric(as.character(time))
But any values that can't be converted will become missing. (The R FAQ gives a slightly different method for factor -> numeric conversion but I can never remember what it is.)
I had another problem not described here, which drove me nuts.
class MyModel(models.Model):
name = models.CharField(max_length=64, null=True) # works
language_code = models.CharField(max_length=2, default='en') # works
is_dumb = models.BooleanField(default=False), # doesn't work
I had a trailing ',' in one line perhaps from copy&paste. The line with is_dumb doesn't created a model migration with './manage.py makemigrations' but also didn't throw an error. After removing the ',' it worked as expected.
So be careful when you do copy&paste :-)
A way to do this would be to set the color of the element to black, and then fade to the color of the background like this:
<style>
p {
animation-name: example;
animation-duration: 2s;
}
@keyframes example {
from {color:black;}
to {color:white;}
}
</style>
<p>I am FADING!</p>
I hope this is what you needed!
For those arriving here after updating phpunit to version 6 or greater released on 2017-02-03 (e.g. with composer), you may be getting this error because phpunit code is now namespaced (check changelog).
You will need to refactor things like \PHPUnit_Framework_TestCase
to \PHPUnit\Framework\TestCase
Mat image1;
IplImage* image2=cvCloneImage(&(IplImage)image1);
Guess this will do the job.
Edit: If you face compilation errors, try this way:
cv::Mat image1;
IplImage* image2;
image2 = cvCreateImage(cvSize(image1.cols,image1.rows),8,3);
IplImage ipltemp=image1;
cvCopy(&ipltemp,image2);
<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>
Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance
Another options with purrr
package:
library(dplyr)
df <- data.frame(a = NA,
b = seq(1:5),
c = c(rep(1, 4), NA))
df %>% purrr::discard(~all(is.na(.)))
df %>% purrr::keep(~!all(is.na(.)))
Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.
You could use lodash method _.uniqWith, it is available in the current version of lodash 4.17.2.
Example:
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual);
// => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
More info: https://lodash.com/docs/#uniqWith
The theoretical advantage of *.ico files is that they are containers than can hold more than one icon. You could for instance store an image with alpha channel and a 16 colour version for legacy systems, or you could add 32x32 and 48x48 icons (which would show up when e.g. dragging a link to Windows explorer).
This good idea, however, tends to clash with browser implementations.
Functions are not allowed to have side-effects such as altering table contents.
Stored Procedures are.
If a function called a stored procedure, the function would become able to have side-effects.
So, sorry, but no, you can't call a stored procedure from a function.
As others have pointed out, paste()
is the way to go. But it can get annoying to have to type paste(str1, str2, str3, sep='')
everytime you want the non-default separator.
You can very easily create wrapper functions that make life much simpler. For instance, if you find yourself concatenating strings with no separator really often, you can do:
p <- function(..., sep='') {
paste(..., sep=sep, collapse=sep)
}
or if you often want to join strings from a vector (like implode()
from PHP):
implode <- function(..., sep='') {
paste(..., collapse=sep)
}
Allows you do do this:
p('a', 'b', 'c')
#[1] "abc"
vec <- c('a', 'b', 'c')
implode(vec)
#[1] "abc"
implode(vec, sep=', ')
#[1] "a, b, c"
Also, there is the built-in paste0
, which does the same thing as my implode
, but without allowing custom separators. It's slightly more efficient than paste()
.
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
The $.getJSON()
method is shorthand that does not let you specify advanced options like that. To do that, you need to use the full $.ajax()
method.
Notice in the documentation at http://api.jquery.com/jQuery.getJSON/:
This is a shorthand Ajax function, which is equivalent to:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
So just use $.ajax()
and provide all the extra parameters you need.
Use a static AutoResetEvent in your spawned threads to call back to the main thread using the Set() method. This guy has a fairly good demo in SO on how to use it.
If you want a loop to execute while a condition is true, and not for a certain number of iterations, it is much easier for someone else to understand:
while (cond_true)
than something like this:
for (; cond_true ; )
The provided solution here is correct. However, the same error can also occur from a user error, where your endpoint request method is NOT matching the method your using when making the request.
For example, the server endpoint is defined with "RequestMethod.PUT" while you are requesting the method as POST.
I'm running ubuntu 11.10 and bundle executable was located in:
/var/lib/gems/1.8/bin
Because your update
uses PUT method, {entryId: $scope.entryId}
is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'}
when you define your update
, which means
return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method:'PUT', params: {entryId: '@entryId'}},
remove: {method:'DELETE'}
});
Fix: Was missing a closing curly brace on the update line.
Use the modulus operator %
, it returns the remainder.
int a = 5;
int b = 3;
if (a % b != 0) {
printf("The remainder is: %i", a%b);
}
Terminal > su
> password
> vim /etc/vimrc
Click here and edit as in line number (13):
set nu
I recommend looking at modern databases like NoSQL and also I agree with user1252434's post. For instance I am storing a few < 500kb PNGs as base64 on my Mongo db with binary set to true with no performance hit at all. Mongo can be used to store large files like 10MB videos and that can offer huge time saving advantages in metadata searches for those videos, see storing large objects and files in mongodb.
I managed to find network.http.connect.timeout for much older versions of Mozilla:
This preference was one of several added to allow low-level tweaking of the HTTP networking code. After a portion of the same code was significantly rewritten in 2001, the preference ceased to have any effect (as noted in all.js as early as September 2001).
Currently, the timeout is determined by the system-level connection establishment timeout. Adding a way to configure this value is considered low-priority.
It would seem that network.http.connect.timeout
hasn't done anything for some time.
I also saw references to network.http.request.timeout
, so I did a Google search. The results include lots of links to people recommending that others include it in about:config
in what appears to be a mistaken belief that it actually does something, since the same search turns up this about:config entries article:
Pref removed (unused). Previously: HTTP-specific network timeout. Default value is 120.
The same page includes additional information about network.http.connect.timeout
:
Pref removed (unused). Previously: determines how long to wait for a response until registering a timeout. Default value is 30.
Disclaimer: The information on the MozillaZine Knowledge Base may be incorrect, incomplete or out-of-date.
Try this:
jQuery('#main').css('opacity', '0.6');
or
jQuery('#main').css({'filter':'alpha(opacity=60)', 'zoom':'1', 'opacity':'0.6'});
if you want to support IE7, IE8 and so on.
To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19
let routerLink = this._aRoute.parent.snapshot.pathFromRoot
.map((s) => s.url)
.reduce((a, e) => {
//Do NOT add last path!
if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
return a.concat(e);
}
return a;
})
.map((s) => s.path);
this._router.navigate(routerLink);
This has the added bonus of being an absolute route you can use with the singleton Router.
(Angular 4+ for sure, probably Angular 2 too.)
You can use https://appery.io/ It is the same phonegap but in very convinient wrapper
Does this not work?
System.Reflection.MethodBase.GetCurrentMethod()
Returns a MethodBase object representing the currently executing method.
Namespace: System.Reflection
Assembly: mscorlib (in mscorlib.dll)
http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getcurrentmethod.aspx
I have no comment on the concatenation itself, but I'd like to point out that @Jakub Hampl's suggestion:
For building strings in the DOM, in some cases it might be better to iteratively add to the DOM, rather then add a huge string at once.
is wrong, because it's based on a flawed test. That test never actually appends into the DOM.
This fixed test shows that creating the string all at once before rendering it is much, MUCH faster. It's not even a contest.
(Sorry this is a separate answer, but I don't have enough rep to comment on answers yet.)
I had a similar issue myself, I think all you need to do is git reset --hard
and you will not lose your changes or any untracked changes.
If you read the docs in git stash --help
it states that apply is "Like pop, but do not remove the state from the stash list" so the state still resides there, you can get it back.
Alternatively, if you have no conflicts, you can just git stash
again after testing your changes.
If you do have conflicts, don't worry, git reset --hard
won't lose them, as
"Applying the state can fail with conflicts; in this case, it is not removed from the stash list. You need to resolve the conflicts by hand and call git stash drop manually afterwards."
-m 1
means return the first match in any given file. But it will still continue to search in other files. Also, if there are two or more matched in the same line, all of them will be displayed.
head -1
to solve this problem:grep -o -a -m 1 -h -r "Pulsanti Operietur" /path/to/dir | head -1
-o, --only-matching, print only the matched part of the line (instead of the entire line)
-a, --text, process a binary file as if it were text
-m 1, --max-count, stop reading a file after 1 matching line
-h, --no-filename, suppress the prefixing of file names on output
-r, --recursive, read all files under a directory recursively
Another possible way is to delete the project from Eclipse (but don't delete the project contents from disk!) and then use the New Java Project wizard to create a project in-place. That wizard will detect the Java code and set up build paths automatically.
To improve on @bgporter's answer, with Python-3 you will probably want to operate on bytes instead of needlessly converting things to utf-8:
>>> import shutil
>>> import sys
>>> with open("test.txt", "rb") as f:
... shutil.copyfileobj(f, sys.stdout.buffer)
You have to add one jar : jackson-annotations-2.1.2.jar
You can download it from here and add it to the class path
If you are using the gradle then add the following dependency.
compile 'com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:2.5.2'
I had this issue in an ASP web site project. Adding a "Content-Length" header caused downloads to start working again in Chrome.
Encountered this in Ubuntu for Windows, try running first
sudo apt-get update
sudo apt-get upgrade
then
sudo apt-get install npm
Yes there is a static nested class in java. When you declare a nested class static, it automatically becomes a stand alone class which can be instantiated without having to instantiate the outer class it belongs to.
Example:
public class A
{
public static class B
{
}
}
Because class B
is declared static you can explicitly instantiate as:
B b = new B();
Note if class B
wasn't declared static to make it stand alone, an instance object call would've looked like this:
A a= new A();
B b = a.new B();
In .NET5, I used DisplayTextFor without needing helper or extension methods:
@Html.DisplayTextFor(m => m.SomeEnumProperty)
Where SomeEnumProperty
has a value of:
public enum MyEnum
{
[Display(Name = "Not started")]
NotStarted = 0,
[Display(Name = "Weird display name instead of just 'Started'")]
Started = 1,
}
Use
a = sorted(a, key=lambda x: x.modified, reverse=True)
# ^^^^
On Python 2.x, the sorted
function takes its arguments in this order:
sorted(iterable, cmp=None, key=None, reverse=False)
so without the key=
, the function you pass in will be considered a cmp
function which takes 2 arguments.
Try this:
select * from your_table
where date >= '2020-10-01'
How much a stack can grow?
You can use a VM option named ss
to adjust the maximum stack size. A VM option is usually passed using -X{option}. So you can use java -Xss1M
to set the maximum of stack size to 1M.
Each thread has at least one stack. Some Java Virtual Machines(JVM) put Java stack(Java method calls) and native stack(Native method calls in VM) into one stack, and perform stack unwinding using a Managed to Native Frame, known as M2NFrame. Some JVMs keep two stacks separately. The Xss
set the size of the Java Stack in most cases.
For many JVMs, they put different default values for stack size on different platforms.
Can we limit this growth?
When a method call occurs, a new stack frame will be created on the stack of that thread. The stack will contain local variables, parameters, return address, etc. In java, you can never put an object on stack, only object reference can be stored on stack. Since array is also an object in java, arrays are also not stored on stack. So, if you reduce the amount of your local primitive variables, parameters by grouping them into objects, you can reduce the space on stack. Actually, the fact that we cannot explicitly put objects on java stack affects the performance some time(cache miss).
Does stack has some default minimum value or default maximum value?
As I said before, different VMs are different, and may change over versions. See here.
how does garbage collection work on stack?
Garbage collections in Java is a hot topic. Garbage collection aims to collect unreachable objects in the heap. So that needs a definition of 'reachable.' Everything on the stack constitutes part of the root set references in GC. Everything that is reachable from every stack of every thread should be considered as live. There are some other root set references, like Thread objects and some class objects.
This is only a very vague use of stack on GC. Currently most JVMs are using a generational GC. This article gives brief introduction about Java GC. And recently I read a very good article talking about the GC on .net. The GC on oracle jvm is quite similar so I think that might also help you.
If it's working from Postman, try new Spring version, becouse the 'org.springframework.boot' 2.2.2.RELEASE version can throw "Required request body content is missing" exception.
Try 2.2.6.RELEASE version.
This relies on widely available wget
, present almost everywhere, even on Alpine Linux.
wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'
The explanations are as follow :
--quiet
Turn off Wget's output.
Source - wget man pages
--spider
[ ... ] it will not download the pages, just check that they are there. [ ... ]
Source - wget man pages
--server-response
Print the headers sent by HTTP servers and responses sent by FTP servers.
Source - wget man pages
What they don't say about --server-response
is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.
The output sent to standard input, we can pipe it to awk
to extract the HTTP status code. That code is :
$2
) non-blank group of characters: {$2}
NR==1
And because we want to print it... {print $2}
.
wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'
The slightly modified version of COPY
below worked better for me, where I specify the CSV
format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT
.
COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );
If you are developing on Netbeans, you will not get the Third-Party add-ons. You can download the Skins directly from Samsung here: http://developer.samsung.com/android/tools-sdks
After download, unzip to ...\Android\android-sdk\add-ons[name of device]
Restart the Android SDK Manager, and the new device should be there under Extras.
It would be better to add the download site directly to the SDK...if anyone knows it, please post it.
Scott
my good friend Alessandro have a nice post regarding bit operators in C#, you should read about it so you know what to do.
It's pretty easy. If you break down the IP given to you to binary, the network address is the ip address where all of the host bits (the 0's in the subnet mask) are 0,and the last address, the broadcast address, is where all the host bits are 1.
For example:
ip 192.168.33.72 mask 255.255.255.192
11111111.11111111.11111111.11000000 (subnet mask)
11000000.10101000.00100001.01001000 (ip address)
The bolded parts is the HOST bits (the rest are network bits). If you turn all the host bits to 0 on the IP, you get the first possible IP:
11000000.10101000.00100001.01000000 (192.168.33.64)
If you turn all the host bits to 1's, then you get the last possible IP (aka the broadcast address):
11000000.10101000.00100001.01111111 (192.168.33.127)
So for my example:
the network is "192.168.33.64/26":
Network address: 192.168.33.64
First usable: 192.168.33.65 (you can use the network address, but generally this is considered bad practice)
Last useable: 192.168.33.126
Broadcast address: 192.168.33.127
A one-liner to extract the PID of the process using port 3000 and kill it.
lsof -ti:3000 | xargs kill
The -t flag removes everything but the PID from the lsof output, making it easy to kill it.
As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.
From tecadmin.net:
Download and install the rpmforge repository:
# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'
# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt
Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo
and change enabled = 0
to enabled = 1
under [rpmforge-extras]
. The file looks like this:
### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1
Once you've done this, then you can update git with
yum update git
I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0
) and then running yum clean all
.
Most likely you'll need to use sudo
for these commands.
It mostly depends on how big n
is.
If n==0
, nothing beats option#1 :)
If n is very large, toArray(new String[n])
is faster.
Index:
------------>
0 1 2 3 4
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
0 -4 -3 -2 -1
<------------
Slice:
<---------------|
|--------------->
: 1 2 3 4 :
+---+---+---+---+---+
| a | b | c | d | e |
+---+---+---+---+---+
: -4 -3 -2 -1 :
|--------------->
<---------------|
I hope this will help you to model the list in Python.
Reference: http://wiki.python.org/moin/MovingToPythonFromOtherLanguages
In addition to REMOTE_ADDR
and HTTP_X_FORWARDED_FOR
there are some other headers that can be set such as:
HTTP_CLIENT_IP
HTTP_X_FORWARDED_FOR
can be comma delimited list of IPsHTTP_X_FORWARDED
HTTP_X_CLUSTER_CLIENT_IP
HTTP_FORWARDED_FOR
HTTP_FORWARDED
I found the code on the following site useful:
http://www.grantburton.com/?p=97
You can also use a fadeIn/FadeOut Combo, too....
$('.test').bind('click', function(){
$('.div1').fadeIn(500);
$('.div2').fadeOut(500);
$('.div3').fadeOut(500);
return false;
});
If getData
is protected then try making it public. The problem could exist in JAVA 1.6 and be absent in 1.5x
I got this for your problem. Illegal access error
Wikipedia tells what comma operator does:
"In the C and C++ programming languages, the comma operator (represented by the token ,
) is a binary operator that evaluates its first operand and discards the result, and then evaluates the second operand and returns this value (and type)."
Kotlin Answer
for ((key, value) in map.entries) {
// do something with `key`
// so something with `value`
}
You may find other solutions that include filterValues. Just keep in mind that retrieving a Key value using filterValues will include braces [].
val key = map.filterValues {it = position}.keys
When we want to get multiple elements from a List into a new list (filter using a predicate) and remove them from the existing list, I could not find a proper answer anywhere.
Here is how we can do it using Java Streaming API partitioning.
Map<Boolean, List<ProducerDTO>> classifiedElements = producersProcedureActive
.stream()
.collect(Collectors.partitioningBy(producer -> producer.getPod().equals(pod)));
// get two new lists
List<ProducerDTO> matching = classifiedElements.get(true);
List<ProducerDTO> nonMatching = classifiedElements.get(false);
// OR get non-matching elements to the existing list
producersProcedureActive = classifiedElements.get(false);
This way you effectively remove the filtered elements from the original list and add them to a new list.
Refer the 5.2. Collectors.partitioningBy section of this article.
mingw32-make
package installed.PATH
in your command line and look for the folder. Or on windows 10 go to Control Panel\System and Security\System --> Advanced system settings --> Environment Variables --> System Variables
find Path
variable, select, Edit
and check if it is there. If not just add it!mingwstartup.bat
in the MinGW bin folder. write the line doskey make=mingw32-make.exe
inside, save and close it.regedit
. As explained here in HKEY_LOCAL_MACHINE
or HKEY_CURRENT_USER
go to \Software\Microsoft\Command Processor
right click on the right panel New --> Expandable String Value
and name it AutoRun
. double click and enter the path to your .bat file as the Value data (e.g. "C:\MinGW\bin\mingwstartup.bat"
) the result should look like this:now every time you open a new terminal make
command will run the mingw32-make.exe
. I hope it helps.
P.S. If you don't want to see the commands of the .bat
file to be printed out to the terminal put @echo off
at the top of the batch file.
Apologies for my previously mixed up answer.
Here is how to do:
myTreeView.SelectedNode = myTreeNode;
I have tested the code below and it works:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
treeView1.Nodes.Add("1", "1");
treeView1.Nodes.Add("2", "2");
treeView1.Nodes[0].Nodes.Add("1-1", "1-1");
TreeNode treeNode = treeView1.Nodes[0].Nodes.Add("1-2", "1-3");
treeView1.SelectedNode = treeNode;
MessageBox.Show(treeNode.IsSelected.ToString());
}
}
Prefer properties. It's what they're there for.
The reason is that all attributes are public in Python. Starting names with an underscore or two is just a warning that the given attribute is an implementation detail that may not stay the same in future versions of the code. It doesn't prevent you from actually getting or setting that attribute. Therefore, standard attribute access is the normal, Pythonic way of, well, accessing attributes.
The advantage of properties is that they are syntactically identical to attribute access, so you can change from one to another without any changes to client code. You could even have one version of a class that uses properties (say, for code-by-contract or debugging) and one that doesn't for production, without changing the code that uses it. At the same time, you don't have to write getters and setters for everything just in case you might need to better control access later.
There is several escaping options with same result:
body { width: ~"calc(100% - 250px - 1.5em)"; }
body { width: calc(~"100% - 250px - 1.5em"); }
body { width: calc(100% ~"-" 250px ~"-" 1.5em); }
here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.
https://dl-ssl.google.com/android/repository/docs-17_r02.zip (129 MB)
Let's say your variable is always integer. In that case this is easier:
<?PHP
$number = 4;
echo '<script>';
echo 'var number = ' . $number . ';';
echo 'alert(number);';
echo '</script>';
?>
Output:
<script>var number = 4;alert(number);</script>
Let's say your variable is not an integer, but if you try above method you will get something like this:
<script>var number = abcd;alert(number);</script>
But in JavaScript this is a syntax error.
So in PHP we have a function call json_encode
that encode string to a JSON object.
<?PHP
$number = 'abcd';
echo '<script>';
echo 'var number = ' . json_encode($number) . ';';
echo 'alert(number);';
echo '</script>';
?>
Since abcd
in JSON is "abcd"
, it looks like this:
<script>var number = "abcd";alert(number);</script>
You can use same method for arrays:
<?PHP
$details = [
'name' => 'supun',
'age' => 456,
'weight' => '55'
];
echo '<script>';
echo 'var details = ' . json_encode($details) . ';';
echo 'alert(details);';
echo 'console.log(details);';
echo '</script>';
?>
And your JavaScript code looks like this:
<script>var details = {"name":"supun","age":456,"weight":"55"};alert(details);console.log(details);</script>
Console output
This is worked for me using JAVA script for chrome extension.
document.body.innerHTML = myFunction();
function myFunction()
{
var phonedef = new RegExp("(?:(?:\\+|0{0,2})91(\\s*[\\- ]\\s*)?|[0 ]?)?[789]\\d{9}|(\\d[ -]?){10}\\d", "g");
var str = document.body.innerHTML;
var res = str.replace(phonedef, function myFunction(x){return "<a href='tel:"+x.replace( /(\s|-)/g, "")+"'>"+x+"</a>";});
return res;
}
This covers following numbers pattern
9883443344
8888564723
7856128945
09883443344
0 9883443344
0-9883443344
919883443344
91 8834433441
91-9883443344
91 -9883443344
91- 9883443344
91 - 9883443344
91 -9883443344
+917878525200
+91 8834433441
+91-9883443344
+91 -9883443344
+91- 9883443344
+91 - 9883443344
+91 -9883443344
0919883443344
0091-7779015989
0091 - 8834433440
022-24130000
080 25478965
0416-2565478
08172-268032
04512-895612
02162-240000
022-24141414
079-22892350
I usually do it this way:
$ gcc -dM -E - < /dev/null
Note that some preprocessor defines are dependent on command line options - you can test these by adding the relevant options to the above command line. For example, to see which SSE3/SSE4 options are enabled by default:
$ gcc -dM -E - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSSE3__ 1
and then compare this when -msse4
is specified:
$ gcc -dM -E -msse4 - < /dev/null | grep SSE[34]
#define __SSE3__ 1
#define __SSE4_1__ 1
#define __SSE4_2__ 1
#define __SSSE3__ 1
Similarly you can see which options differ between two different sets of command line options, e.g. compare preprocessor defines for optimisation levels -O0
(none) and -O3
(full):
$ gcc -dM -E -O0 - < /dev/null > /tmp/O0.txt
$ gcc -dM -E -O3 - < /dev/null > /tmp/O3.txt
$ sdiff -s /tmp/O0.txt /tmp/O3.txt
#define __NO_INLINE__ 1 <
> #define __OPTIMIZE__ 1
You could use the following snippet:
private void textBox1_TextChanged(object sender, EventArgs e)
{
if (!System.Text.RegularExpressions.Regex.IsMatch(textBox1.Text, "^[a-zA-Z ]"))
{
MessageBox.Show("This textbox accepts only alphabetical characters");
textBox1.Text.Remove(textBox1.Text.Length - 1);
}
}
You can do this the following two ways:
1) Using loop
attribute in video element (mentioned in the first answer):
2) and you can use the ended
media event:
window.addEventListener('load', function(){
var newVideo = document.getElementById('videoElementId');
newVideo.addEventListener('ended', function() {
this.currentTime = 0;
this.play();
}, false);
newVideo.play();
});
The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. User agents are free to support any video formats they feel are appropriate.
Try getppid()
if you want your C program to print your shell's PID.
I commonly like to use a slight variant on the standard for loop. I often use this to run a command on a series of remote hosts. I take advantage of bash's brace expansion to create for loops that allow me to create non-numerical for-loops.
Example:
I want to run the uptime command on frontend hosts 1-5 and backend hosts 1-3:
% for host in {frontend{1..5},backend{1..3}}.mycompany.com
do ssh $host "echo -n $host; uptime"
done
I typically run this as a single-line command with semicolons on the ends of the lines instead of the more readable version above. The key usage consideration are that braces allow you to specify multiple values to be inserted into a string (e.g. pre{foo,bar}post results in prefoopost, prebarpost) and allow counting/sequences by using the double periods (you can use a..z etc.). However, the double period syntax is a new feature of bash 3.0; earlier versions will not support this.
This could be done with a recursive function in Bash too.
Let F be a function that displays the time of file which must be lexicographically sortable yyyy-mm-dd, etc., (OS-dependent?)
F(){ stat --format %y "$1";} # Linux
F(){ ls -E "$1"|awk '{print$6" "$7}';} # SunOS: maybe this could be done easier
R, the recursive function that runs through directories:
R(){ local f;for f in "$1"/*;do [ -d "$f" ]&&R $f||F "$f";done;}
And finally
for f in *;do [ -d "$f" ]&&echo `R "$f"|sort|tail -1`" $f";done
You will have to write a wrapper for C in C++ if you want to do this. C++ is backwards compatible, but C is not forwards compatible.
First, I recommend that you use WCF, .NET Remoting, or some other higher-level communication abstraction. The learning curve for "simple" sockets is nearly as high as WCF, because there are so many non-obvious pitfalls when using TCP/IP directly.
If you decide to continue down the TCP/IP path, then review my .NET TCP/IP FAQ, particularly the sections on message framing and application protocol specifications.
Also, use asynchronous socket APIs. The synchronous APIs do not scale and in some error situations may cause deadlocks. The synchronous APIs make for pretty little example code, but real-world production-quality code uses the asynchronous APIs.
res/
mipmap-mdpi/ic_launcher.png (48x48 pixels)
mipmap-hdpi/ic_launcher.png (72x72)
mipmap-xhdpi/ic_launcher.png (96x96)
mipmap-xxhdpi/ic_launcher.png (144x144)
mipmap-xxxhdpi/ic_launcher.png (192x192)
MipMap for app icon for launcher
http://android-developers.blogspot.co.uk/2014/10/getting-your-apps-ready-for-nexus-6-and.html
https://androidbycode.wordpress.com/2015/02/14/goodbye-launcher-drawables-hello-mipmaps/
Putting the various suggestions together, the cleanest version I was able to come up with (without unreliable grep which triggers parts of words) is:
kill -0 $(pidof mysql) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
kill -0 doesn't kill the process but checks if it exists and then returns true, if you don't have pidof on your system, store the pid when you launch the process:
$ mysql &
$ echo $! > pid_stored
then in the script:
kill -0 $(cat pid_stored) 2> /dev/null || echo "Mysql ain't runnin' message/actions"
As theMarko suggests:
BASEDIR=$(dirname $0)
echo $BASEDIR
This works unless you execute the script from the same directory where the script resides, in which case you get a value of '.'
To get around that issue use:
current_dir=$(pwd)
script_dir=$(dirname $0)
if [ $script_dir = '.' ]
then
script_dir="$current_dir"
fi
You can now use the variable current_dir throughout your script to refer to the script directory. However this may still have the symlink issue.
git branch --set-upstream-to=origin/main
Yahoo! This is really possible. I found it.
For Bottom Border:
div {box-shadow: 0px -3px 0px red inset; }
For Top Border:
div {box-shadow: 0px 3px 0px red inset; }
I'd make a new view class and derive from the existing ProgressBar. Then override the onDraw function. You're going to need to make direct draw calls to the canvas for this, since its so custom- a combination of drawText, drawArc, and drawOval should do it- an oval for the outer ring and empty portions, and an arc for the colored in parts. You may end up needing to override onMeasure and onLayout as well. Then in your xml, reference this view by class name like this when you want to use it.
Just to add to @Anshul Singh Suryan's answer:
When we split the dataframe to just get the last column:
If we split like:
y = df.iloc[:,-1:] - y
remains a dataframe
However, if we split like
y = df.iloc[:,-1] - y
becomes a Series
.
This is a notable difference that I've found in the two approaches. If you don't care about the resultant type, you can use either of the two. Otherwise you need to take care of the above findings.
This is applicable for any number of rows you want to extract and not just the last row.
For example, if you want last n
number of rows of a dataframe, where n is any integer less than or equal to the number of columns present in the dataframe, then you can easily do the following:
y = df.iloc[:,n:]
Replace n
by the number of columns you want. Same is true for rows as well.
friend is your friend.
class A{
friend void foo(A arg);
int iData;
};
void foo(A arg){
// can access a.iData here
}
If you're doing this regularly you should probably reconsider your design though.
If you're on a given branch, and you want to compare your working copy with the upstream branch you're tracking, use:
git diff @{upstream}
If you want to compare your current HEAD with the upstream branch (thanks @Arijoon):
git diff @ @{upstream}
If your upstream isn't set, you can use @{push}
to get a diff against the branch you are set to push to (also from @Arijoon's comment):
git diff @{push}
Courtesy of this answer, the git documentation for specifying revisions has:
<branchname>@{upstream}
, e.g.master@{upstream}
,@{u}
The suffix@{upstream}
to a branchname (short form<branchname>@{u}
) refers to the branch that the branch specified bybranchname
is set to build on top of (configured withbranch.<name>.remote
andbranch.<name>.merge
). A missingbranchname
defaults to the current one.
You can achieve what you want with the padding-bottom: 100%; margin-bottom: -100%;
trick, has you can see in this fiddle.
I change your HTML a little bit, but you can achieve the same result with your own HTML with the following code
.col-md-9 {
overflow: hidden;
}
.col-md-3 {
padding-bottom: 100%;
margin-bottom: -100%;
}
I was looking for the answer on internet and I found the following
@Value("#{new java.text.SimpleDateFormat('${aDateFormat}').parse('${aDateStr}')}")
Date myDate;
So in your case you could try with this
@Value("#{new Integer('${api.orders.pingFrequency}')}")
private Integer pingFrequency;
Dragan B. solution is correct. In my case I needed the buttons to be spaced vertically when stacking so I added the mb-2 property to them.
<div class="btn-toolbar">
<button type="button" class="btn btn-primary mr-2 mb-2">First</button>
<button type="button" class="btn btn-primary mr-2 mb-2">Second</button>
<button type="button" class="btn btn-primary mr-2 mb-2">Third</button>
</div>
Here's the version I ended up writing that replaces all instances of the target string in a given string. Works on any string type.
template <typename T, typename U>
T &replace (
T &str,
const U &from,
const U &to)
{
size_t pos;
size_t offset = 0;
const size_t increment = to.size();
while ((pos = str.find(from, offset)) != T::npos)
{
str.replace(pos, from.size(), to);
offset = pos + increment;
}
return str;
}
Example:
auto foo = "this is a test"s;
replace(foo, "is"s, "wis"s);
cout << foo;
Output:
thwis wis a test
Note that even if the search string appears in the replacement string, this works correctly.
I was trying Viachaslau's answer since I like the idea of not removing the button but disabling it, but for some reason it did not always work: the close button was still enabled but no errors whatsoever.
This on the other hand always worked (error checking omitted):
[DllImport( "user32.dll" )]
private static extern IntPtr GetSystemMenu( IntPtr hWnd, bool bRevert );
[DllImport( "user32.dll" )]
private static extern bool EnableMenuItem( IntPtr hMenu, uint uIDEnableItem, uint uEnable );
private const uint MF_BYCOMMAND = 0x00000000;
private const uint MF_GRAYED = 0x00000001;
private const uint SC_CLOSE = 0xF060;
private const int WM_SHOWWINDOW = 0x00000018;
protected override void OnSourceInitialized( EventArgs e )
{
base.OnSourceInitialized( e );
var hWnd = new WindowInteropHelper( this );
var sysMenu = GetSystemMenu( hWnd.Handle, false );
EnableMenuItem( sysMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED );
}
Jerryf's answer is fine, except for one flaw.
The onload event should be set before the src. Sometimes the src can be loaded instantly and never fire the onload event.
(Like Totty.js pointed out.)
var canvas = document.getElementById("c");
var ctx = canvas.getContext("2d");
var image = new Image();
image.onload = function() {
ctx.drawImage(image, 0, 0);
};
image.src = "data:image/ png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAIAAAACDbGyAAAAAXNSR0IArs4c6QAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB9oMCRUiMrIBQVkAAAAZdEVYdENvbW1lbnQAQ3JlYXRlZCB3aXRoIEdJTVBXgQ4XAAAADElEQVQI12NgoC4AAABQAAEiE+h1AAAAAElFTkSuQmCC";
Actually you dont need to call document.getElementById()
function to get access to your div
.
You can use this object
directly by id
:
text = test.textContent || test.innerText;
alert(text);
May be the "\" char, try this one:
sed 's/\"http:\/\/www.fubar.com\"/URL_FUBAR/g'
There is also http://appyframework.org/pod.html which takes a LibreOffice or OpenOffice document as template and can generate pdf, rtf, odt ... To generate pdf it requires a headless OOo on some server. Documentation is concise but relatively complete. http://appyframework.org/podWritingTemplates.html If you need advice, the author is rather helpful.
Partial mocking using Mockito's spy method could be the solution to your problem, as already stated in the answers above. To some degree I agree that, for your concrete use case, it may be more appropriate to mock the DB lookup. From my experience this is not always possible - at least not without other workarounds - that I would consider as being very cumbersome or at least fragile. Note, that partial mocking does not work with ally versions of Mockito. You have use at least 1.8.0.
I would have just written a simple comment for the original question instead of posting this answer, but StackOverflow does not allow this.
Just one more thing: I really cannot understand that many times a question is being asked here gets comment with "Why you want to do this" without at least trying to understand the problem. Escpecially when it comes to then need for partial mocking there are really a lot of use cases that I could imagine where it would be useful. That's why the guys from Mockito provided that functionality. This feature should of course not be overused. But when we talk about test case setups that otherwise could not be established in a very complicated way, spying should be used.
You can use pandas it has some built in functions for comparison. So if you want to select values of "A" that are met by the conditions of "B" and "C" (assuming you want back a DataFrame pandas object)
df[['A']][df.B.gt(50) & df.C.ne(900)]
df[['A']]
will give you back column A in DataFrame format.
pandas 'gt' function will return the positions of column B that are greater than 50 and 'ne' will return the positions not equal to 900.
This is a common question -- especially in today's environment of virtual environments. Unfortunately, the answer is not as straight-forward as one might assume.
dd is the obvious first choice, but dd is essentially a copy and that forces you to write every block of data (thus, initializing the file contents)... And that initialization is what takes up so much I/O time. (Want to make it take even longer? Use /dev/random instead of /dev/zero! Then you'll use CPU as well as I/O time!) In the end though, dd is a poor choice (though essentially the default used by the VM "create" GUIs). E.g:
dd if=/dev/zero of=./gentoo_root.img bs=4k iflag=fullblock,count_bytes count=10G
truncate is another choice -- and is likely the fastest... But that is because it creates a "sparse file". Essentially, a sparse file is a section of disk that has a lot of the same data, and the underlying filesystem "cheats" by not really storing all of the data, but just "pretending" that it's all there. Thus, when you use truncate to create a 20 GB drive for your VM, the filesystem doesn't actually allocate 20 GB, but it cheats and says that there are 20 GB of zeros there, even though as little as one track on the disk may actually (really) be in use. E.g.:
truncate -s 10G gentoo_root.img
fallocate is the final -- and best -- choice for use with VM disk allocation, because it essentially "reserves" (or "allocates" all of the space you're seeking, but it doesn't bother to write anything. So, when you use fallocate to create a 20 GB virtual drive space, you really do get a 20 GB file (not a "sparse file", and you won't have bothered to write anything to it -- which means virtually anything could be in there -- kind of like a brand new disk!) E.g.:
fallocate -l 10G gentoo_root.img
$.browser
was removed from jQuery starting with version 1.9. It is now available as a plugin. It's generally recommended to avoid browser detection, which is why it was removed.
You can do it by hmset
(multiple keys can be set using hmset
).
hmset("RedisKey", dictionaryToSet)
import redis
conn = redis.Redis('localhost')
user = {"Name":"Pradeep", "Company":"SCTL", "Address":"Mumbai", "Location":"RCP"}
conn.hmset("pythonDict", user)
conn.hgetall("pythonDict")
{'Company': 'SCTL', 'Address': 'Mumbai', 'Location': 'RCP', 'Name': 'Pradeep'}
INSERT INTO Table
( Event_ID
, col2
...
)
SELECT "155"
, col2
...
FROM Table WHERE Event_ID = "120"
Here, the col2, ... represent the remaining columns (the ones other than Event_ID) in your table.
The foreign keys are there to ensure data integrity, so you can't drop a column as long as it's part of a foreign key. You need to drop the key first.
I would think the following query would do it:
ALTER TABLE assignmentStuff DROP FOREIGN KEY assignmentIDX;
For 3-D visualization pythreejs is the best way to go probably in the notebook. It leverages the interactive widget infrastructure of the notebook, so connection between the JS and python is seamless.
A more advanced library is bqplot which is a d3-based interactive viz library for the iPython notebook, but it only does 2D
Try moving the order by
after group by
:
var groupByReference = (from m in context.Measurements
group m by new { m.Reference } into g
order by g.Avg(i => i.CreationTime)
select g).Take(numOfEntries).ToList();
You use this signature: (in c#) static void Main(string[] args)
This article may help to explain the role of the main function in programming as well: http://en.wikipedia.org/wiki/Main_function_(programming)
Here is a little example for you:
class Program
{
static void Main(string[] args)
{
bool doSomething = false;
if (args.Length > 0 && args[0].Equals("doSomething"))
doSomething = true;
if (doSomething) Console.WriteLine("Commandline parameter called");
}
}
From IntelliJ Ultimate 2018.1.5, aka IntelliJ IDEA 2018.1.5, till 2019.3 , there are actually two options under File -> Preferences:
URL url=new URL("http://[any domain]");
URLConnection con=url.openConnection();
/*now errors WILL arise here, i hav tried myself and it always shows "connected" so we'll open an InputStream on the connection, this way we know for sure that we're connected to d internet */
/* Get input stream */
con.getInputStream();
Put the above statements in try catch blocks and if an exception in caught means that there's no internet connection established. :-)
milliseconds = x
total = 0
while (milliseconds >= 1000) {
milliseconds = (milliseconds - 1000)
total = total + 1
}
hr = 0
min = 0
while (total >= 60) {
total = total - 60
min = min + 1
if (min >= 60) hr = hr + 1
if (min == 60) min = 0
}
sec = total
This is on groovy, but I thing that this is not problem for you. Method work perfect.
All DDL statements in Oracle PL/SQL should use Execute Immediate before the statement. Hence you should use:
execute immediate 'truncate table schema.tablename';
I created a JSperf comparison of all suggested answers.
TL;DR - the best option for all current browsers is:
val | 0;
.
Update:
It seems like these days they are all pretty identical, except that the Number()
function is the slowest, while the best being val === true ? 1 : 0;
.
You need to add z-index
to the divs, with a positive number for the top div and negative for the div below
An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.
This is how it works for me:
#content {
display: block;
margin: 0 auto;
}
Gimpel Software's PC Lint can report on when an include file has been included more than once in a compilation unit, but it can't find include files which are not needed in the way you are looking for.
Edit: It can. See itsmatt's answer
This gets the timezone code (e.g., GMT
) in older javascript (I'm using google app script with old engine):
function getTimezoneName() {
return new Date().toString().get(/\((.+)\)/);
}
I'm just putting this here in case someone needs it.