to make UITableView sections header not sticky or sticky:
change the table view's style - make it grouped for not sticky & make it plain for sticky section headers - do not forget: you can do it from storyboard without writing code. (click on your table view and change it is style from the right Side/ component menu)
if you have extra components such as custom views or etc. please check the table view's margins to create appropriate design. (such as height of header for sections & height of cell at index path, sections)
var reader = cmd.ExecuteReader();
var columns = new List<string>();
for(int i=0;i<reader.FieldCount;i++)
{
columns.Add(reader.GetName(i));
}
or
var columns = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToList();
In case you have both python 2 and 3 in your path, you can move up the Python27 folder in your path, so it search and executes python 2 first.
You can do it as you do in vi, for example to yank lines from 3020 to the end, execute this command (write the block to a file):
:3020,$ w /tmp/yank
And to write this block in another line/file, go to the desired position and execute next command (insert file written before):
:r /tmp/yank
(Reminder: don't forget to remove file: /tmp/yank)
After many fruitful hours of exploring OCR libraries, bounding boxes and clustering algorithms - I found a solution so simple it makes you want to cry!
I hope you are using Linux;
pdftotext -layout NAME_OF_PDF.pdf
AMAZING!!
Now you have a nice text file with all the information lined up in nice columns, now it is trivial to format into a csv etc..
It is for times like this that I love Linux, these guys came up with AMAZING solutions to everything, and put it there for FREE!
Node.js is an open source command line tool built for the server side JavaScript code. You can download a tarball, compile and install the source. It lets you run JavaScript programs.
The JavaScript is executed by the V8, a JavaScript engine developed by Google which is used in Chrome browser. It uses a JavaScript API to access the network and file system.
It is popular for its performance and the ability to perform parallel operations.
Understanding node.js is the best explanation of node.js I have found so far.
Following are some good articles on the topic.
yeah, but as @supersan stated upper in a comment, if you delete() on a QueryBuilder, the model event will not be fired, because we are not loading the model itself, then calling delete() on that model.
The events are fired only if we use the delete function on a Model Instance.
So, this beeing said:
if user->hasMany(post)
and if post->hasMany(tags)
in order to delete the post tags when deleting the user, we would have to iterate over $user->posts
and calling $post->delete()
foreach($user->posts as $post) { $post->delete(); }
-> this will fire the deleting event on Post
VS
$user->posts()->delete()
-> this will not fire the deleting event on post because we do not actually load the Post Model (we only run a SQL like: DELETE * from posts where user_id = $user->id
and thus, the Post model is not even loaded)
To update the local list of remote branches:
git remote update origin --prune
To show all local and remote branches that (local) Git knows about
git branch -a
Without reading you can't do this. But you can use a work around like below.
You can use mark() and reset() methods to do this.
mark(int readlimit) method marks the current position in this input stream.
reset() method repositions this stream to the position at the time the mark method was last called on this input stream.
Before you can use the mark and reset, you need to test out whether these operations are supported on the inputstream you’re reading off. You can do that with markSupported.
The mark method accepts an limit (integer), which denotes the maximum number of bytes that are to be read ahead. If you read more than this limit, you cannot return to this mark.
To apply this functionalities for this use case, we need to mark the position as 0 and then read the input stream. There after we need to reset the input stream and the input stream will be reverted to the original one.
if (inputStream.markSupported()) {
inputStream.mark(0);
if (inputStream.read() != -1) {
inputStream.reset();
} else {
//Inputstream is empty
}
}
Here if the input stream is empty then read() method will return -1.
for angular 4, the working solution was to do inside the component
@HostListener('window:scroll', ['$event']) onScrollEvent($event){
console.log($event);
console.log("scrolling");
}
CryptoSwift Example
Updated to Swift 2
import Foundation
import CryptoSwift
extension String {
func aesEncrypt(key: String, iv: String) throws -> String{
let data = self.dataUsingEncoding(NSUTF8StringEncoding)
let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data!.arrayOfBytes(), padding: PKCS7())
let encData = NSData(bytes: enc, length: Int(enc.count))
let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let result = String(base64String)
return result
}
func aesDecrypt(key: String, iv: String) throws -> String {
let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())
let decData = NSData(bytes: dec, length: Int(dec.count))
let result = NSString(data: decData, encoding: NSUTF8StringEncoding)
return String(result!)
}
}
Usage:
let key = "bbC2H19lkVbQDfakxcrtNMQdd0FloLyw" // length == 32
let iv = "gqLOHUioQ0QjhuvI" // length == 16
let s = "string to encrypt"
let enc = try! s.aesEncrypt(key, iv: iv)
let dec = try! enc.aesDecrypt(key, iv: iv)
print(s) // string to encrypt
print("enc:\(enc)") // 2r0+KirTTegQfF4wI8rws0LuV8h82rHyyYz7xBpXIpM=
print("dec:\(dec)") // string to encrypt
print("\(s == dec)") // true
Make sure you have the right length of iv (16) and key (32) then you won't hit "Block size and Initialization Vector must be the same length!" error.
Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.
Use this, it works 100% _your_videocode?rel=0&vq=hd1080"
SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
and owner = 'Schema_name' order by object_name
here 'Schema_name' is a name of schema, example i have a schema named PMIS, so the example will be
SELECT * FROM all_procedures WHERE OBJECT_TYPE IN ('FUNCTION','PROCEDURE','PACKAGE')
and owner = 'PMIS' order by object_name
Ref: https://www.plsql.co/list-all-procedures-from-a-schema-of-oracle-database.html
How to design table like this in mongodb?
First, to clarify some naming conventions. MongoDB uses collections
instead of tables
.
I think there are no foreign keys!
Take the following model:
student
{
_id: ObjectId(...),
name: 'Jane',
courses: [
{ course: 'bio101', mark: 85 },
{ course: 'chem101', mark: 89 }
]
}
course
{
_id: 'bio101',
name: 'Biology 101',
description: 'Introduction to biology'
}
Clearly Jane's course list points to some specific courses. The database does not apply any constraints to the system (i.e.: foreign key constraints), so there are no "cascading deletes" or "cascading updates". However, the database does contain the correct information.
In addition, MongoDB has a DBRef standard that helps standardize the creation of these references. In fact, if you take a look at that link, it has a similar example.
How can I solve this task?
To be clear, MongoDB is not relational. There is no standard "normal form". You should model your database appropriate to the data you store and the queries you intend to run.
EDIT: This is no longer the right way to use refs with Typescript. Look at Jeff Bowen's answer and upvote it to increase its visibility.
Found the answer to the problem. Use refs as below inside the class.
refs: {
[key: string]: (Element);
stepInput: (HTMLInputElement);
}
Thanks @basarat for pointing in the right direction.
A solution without using the heap with std::vector
is to use boost::array
, though you can't initialize array members directly in the constructor.
#include <boost/array.hpp>
const boost::array<int, 2> aa={ { 2, 3} };
class A {
const boost::array<int, 2> b;
A():b(aa){};
};
You could use an asymmetrical border to make curves with CSS.
border-radius: 50%/100px 100px 0 0;
.box {_x000D_
width: 500px; _x000D_
height: 100px; _x000D_
border: solid 5px #000;_x000D_
border-color: #000 transparent transparent transparent;_x000D_
border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
Do you need to fake an anchor click? From the thickbox site:
ThickBox can be invoked from a link element, input element (typically a button), and the area element (image maps).
If that is acceptable it should be as easy as putting the thickbox class on the input itself:
<input id="thickboxButton" type="button" class="thickbox" value="Click me">
If not, I would recommend using Firebug and placing a breakpoint in the onclick method of the anchor element to see if it's only triggered on the first click.
Edit:
Okay, I had to try it for myself and for me pretty much exactly your code worked in both Chrome and Firefox:
<html>
<head>
<link rel="stylesheet" href="thickbox.css" type="text/css" media="screen" />
</head>
<body>
<script src="jquery-latest.pack.js" type="text/javascript"></script>
<script src="thickbox.js" type="text/javascript"></script>
<input onclick="$('#thickboxId').click();" type="button" value="Click me">
<a id="thickboxId" href="myScript.php" class="thickbox" title="">Link</a>
</body>
</html>
The window pop ups no matter if I click the input or the anchor element. If the above code works for you, I suggest your error lies elsewhere and that you try to isolate the problem.
Another possibly is that we are using different versions of jquery/thickbox. I am using what I got from the thickbox page - jquery 1.3.2 and thickbox 3.1.
This is a good one: apps-for-android
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
To add a little bit more information that confused me; I had always thought the same result could be achieved like so;
theDate.ToString("yyyy-MM-dd HH:mm:ss")
However, If your Current Culture doesn't use a colon(:) as the hour separator, and instead uses a full-stop(.) it could return as follow:
2009-06-15 13.45.30
Just wanted to add why the answer provided needs to be as it is;
theDate.ToString("yyyy-MM-dd HH':'mm':'ss")
:-)
First install pylint-django using following command
$ pip install pylint-django
Then run the second command as follows:
$ pylint test_file.py --load-plugins pylint_django
--load-plugins pylint_django is necessary for correctly review a code of django
Without using a formula you can do this with 'Text to columns'.
The 'side-effect' is that Excel has removed all trailing spaces in the original column.
Many of the above answers confused me but I suspect it may be due to older versions of Mockito. This answer is accomplished using
Using ArgumentCaptor I have done it this way:
@Mock
MyClientService myClientService;
@InjectMocks
MyService myService;
@Test
void myTest() {
ArgumentCaptor<String> captorParam1 = ArgumentCaptor.forClass(String.class);
ArgumentCaptor<String> captorParam2 = ArgumentCaptor.forClass(String.class);
Mockito.when(myClientService.doSomething(captorParam1.capture(), captorParam2.capture(), ArgumentMatchers.anyString()))
.thenReturn(expectedResponse);
assertDoesNotThrow(() -> myService.process(data));
assertEquals("param1", captorParam1.getValue());
assertEquals("param2", captorParam2.getValue());
verify(myClientService, times(1))
.doSomething(anyString(), anyString(), anyString());
}
Put into address line chrome://about
. You will see links to all possible dev pages.
SELECT create_date
FROM sys.tables
WHERE name='YourTableName'
You forgot to define the default value for left
so it doesn't know how to animate.
.test {
left: 0;
transition:left 1s linear;
}
See here: http://jsfiddle.net/shomz/yFy5n/5/
What you can do is select everything into a new instance of Course, and afterwards convert them to a List.
var qry = from a in obj.tbCourses
select new Course() {
Course.Property = a.Property
...
};
qry.toList<Course>();
If your count(distinct(x))
is significantly slower than count(x)
then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null)
, using triggers. But your write performance will suffer and if you update multiple x
values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.
import pickle
intArray = [i for i in range(1,100)]
output = open('data.pkl', 'wb')
pickle.dump(intArray, output)
output.close()
Test your pickle quickly. pickle is a part of standard python library and available by default.
meta-tags are part of the dom and can be accessed and -i guess- changed, but search-engines (the main consumers of meta-tags) won't see the change as the javascript won't be executed. so unless you're changing a meta-tag (refresh comes to mind) which has implications in the browser, this might be of little use?
What do you mean by a long date type?
You can cast a long to a double:
double d = (double) 15552451L;
You can use like this...
<div id="rot">hello</div>
#rot
{
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
width:100px;
}
Have a look at this fiddle:http://jsfiddle.net/anish/MAN4g/
Please take a look at the Android documentation.
Using the Bluetooth APIs, an Android application can perform the following:
Another way to escape quotes (though probably not preferable), which I've found used in certain places is to use multiple double-quotes. For the purpose of making other people's code legible, I'll explain.
Here's a set of basic rules:
program param1 param2 param 3
will pass four parameters to program.exe
:param1
, param2
, param
, and 3
.program one two "three and more"
will pass three parameters to program.exe
:one
, two
, and three and more
.hello"to the entire"world
acts as one parameter: helloto the entireworld
."Tim says, ""Hi!"""
will act as one parameter: Tim says, "Hi!"
Thus there are three different types of double-quotes: quotes that open, quotes that close, and quotes that act as plain-text.
Here's the breakdown of that last confusing line:
" open double-quote group T inside ""s i inside ""s m inside ""s inside ""s - space doesn't separate s inside ""s a inside ""s y inside ""s s inside ""s , inside ""s inside ""s - space doesn't separate " close double-quoted group " quote directly follows closer - acts as plain unwrapped text: " H outside ""s - gets joined to previous adjacent group i outside ""s - ... ! outside ""s - ... " open double-quote group " close double-quote group " quote directly follows closer - acts as plain unwrapped text: "
Thus, the text effectively joins four groups of characters (one with nothing, however):
Tim says,
is the first, wrapped to escape the spaces
"Hi!
is the second, not wrapped (there are no spaces)
is the third, a double-quote group wrapping nothing
"
is the fourth, the unwrapped close quote.
As you can see, the double-quote group wrapping nothing is still necessary since, without it, the following double-quote would open up a double-quoted group instead of acting as plain-text.
From this, it should be recognizable that therefore, inside and outside quotes, three double-quotes act as a plain-text unescaped double-quote:
"Tim said to him, """What's been happening lately?""""
will print Tim said to him, "What's been happening lately?"
as expected. Therefore, three quotes can always be reliably used as an escape.
However, in understanding it, you may note that the four quotes at the end can be reduced to a mere two since it technically is adding another unnecessary empty double-quoted group.
Here are a few examples to close it off:
program a b REM sends (a) and (b) program """a""" REM sends ("a") program """a b""" REM sends ("a) and (b") program """"Hello,""" Mike said." REM sends ("Hello," Mike said.) program ""a""b""c""d"" REM sends (abcd) since the "" groups wrap nothing program "hello to """quotes"" REM sends (hello to "quotes") program """"hello world"" REM sends ("hello world") program """hello" world"" REM sends ("hello world") program """hello "world"" REM sends ("hello) and (world") program "hello ""world""" REM sends (hello "world") program "hello """world"" REM sends (hello "world")
Final note: I did not read any of this from any tutorial - I came up with all of it by experimenting. Therefore, my explanation may not be true internally. Nonetheless all the examples above evaluate as given, thus validating (but not proving) my theory.
I tested this on Windows 7, 64bit using only *.exe calls with parameter passing (not *.bat, but I would suppose it works the same).
try this
FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener(OnSuccessListener<InstanceIdResult> { instanceIdResult ->
fcm_token = instanceIdResult.token}
The or
and and
python statements require truth
-values. For pandas
these are considered ambiguous so you should use "bitwise" |
(or) or &
(and) operations:
result = result[(result['var']>0.25) | (result['var']<-0.25)]
These are overloaded for these kind of datastructures to yield the element-wise or
(or and
).
Just to add some more explanation to this statement:
The exception is thrown when you want to get the bool
of a pandas.Series
:
>>> import pandas as pd
>>> x = pd.Series([1])
>>> bool(x)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
What you hit was a place where the operator implicitly converted the operands to bool
(you used or
but it also happens for and
, if
and while
):
>>> x or x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> x and x
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> if x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> while x:
... print('fun')
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
Besides these 4 statements there are several python functions that hide some bool
calls (like any
, all
, filter
, ...) these are normally not problematic with pandas.Series
but for completeness I wanted to mention these.
In your case the exception isn't really helpful, because it doesn't mention the right alternatives. For and
and or
you can use (if you want element-wise comparisons):
>>> import numpy as np
>>> np.logical_or(x, y)
or simply the |
operator:
>>> x | y
>>> np.logical_and(x, y)
or simply the &
operator:
>>> x & y
If you're using the operators then make sure you set your parenthesis correctly because of the operator precedence.
There are several logical numpy functions which should work on pandas.Series
.
The alternatives mentioned in the Exception are more suited if you encountered it when doing if
or while
. I'll shortly explain each of these:
If you want to check if your Series is empty:
>>> x = pd.Series([])
>>> x.empty
True
>>> x = pd.Series([1])
>>> x.empty
False
Python normally interprets the len
gth of containers (like list
, tuple
, ...) as truth-value if it has no explicit boolean interpretation. So if you want the python-like check, you could do: if x.size
or if not x.empty
instead of if x
.
If your Series
contains one and only one boolean value:
>>> x = pd.Series([100])
>>> (x > 50).bool()
True
>>> (x < 50).bool()
False
If you want to check the first and only item of your Series (like .bool()
but works even for not boolean contents):
>>> x = pd.Series([100])
>>> x.item()
100
If you want to check if all or any item is not-zero, not-empty or not-False:
>>> x = pd.Series([0, 1, 2])
>>> x.all() # because one element is zero
False
>>> x.any() # because one (or more) elements are non-zero
True
RawMaterialButton(
onPressed: () {},
constraints: BoxConstraints(),
elevation: 2.0,
fillColor: Colors.white,
child: Icon(
Icons.pause,
size: 35.0,
),
padding: EdgeInsets.all(15.0),
shape: CircleBorder(),
)
note down constraints: BoxConstraints()
, it's for not allowing padding in left.
Happy fluttering!!
changing:
collection.fetch({ data: { page: 1} });
to:
collection.fetch({ data: $.param({ page: 1}) });
So with out over doing it, this is called with your {data: {page:1}}
object as options
Backbone.sync = function(method, model, options) {
var type = methodMap[method];
// Default JSON-request options.
var params = _.extend({
type: type,
dataType: 'json',
processData: false
}, options);
// Ensure that we have a URL.
if (!params.url) {
params.url = getUrl(model) || urlError();
}
// Ensure that we have the appropriate request data.
if (!params.data && model && (method == 'create' || method == 'update')) {
params.contentType = 'application/json';
params.data = JSON.stringify(model.toJSON());
}
// For older servers, emulate JSON by encoding the request into an HTML-form.
if (Backbone.emulateJSON) {
params.contentType = 'application/x-www-form-urlencoded';
params.processData = true;
params.data = params.data ? {model : params.data} : {};
}
// For older servers, emulate HTTP by mimicking the HTTP method with `_method`
// And an `X-HTTP-Method-Override` header.
if (Backbone.emulateHTTP) {
if (type === 'PUT' || type === 'DELETE') {
if (Backbone.emulateJSON) params.data._method = type;
params.type = 'POST';
params.beforeSend = function(xhr) {
xhr.setRequestHeader('X-HTTP-Method-Override', type);
};
}
}
// Make the request.
return $.ajax(params);
};
So it sends the 'data' to jQuery.ajax which will do its best to append whatever params.data
is to the URL.
<td align="center" valign="center">textgoeshere</td>
Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.
When you return b
, it is just a reference to function b, but not being executed at this time.
When you return b()
, you're executing the function and returning its value.
Try alert
ing typeof(s)
in your examples. Snippet b will give you 'function'. What will snippet a give you?
Python doesn't have matrices. You can use a list of lists or NumPy
I think the difference is that there is a mousemove
between mousedown
and mouseup
in a drag, but not in a click.
You can do something like this:
const element = document.createElement('div')
element.innerHTML = 'test'
document.body.appendChild(element)
let moved
let downListener = () => {
moved = false
}
element.addEventListener('mousedown', downListener)
let moveListener = () => {
moved = true
}
element.addEventListener('mousemove', moveListener)
let upListener = () => {
if (moved) {
console.log('moved')
} else {
console.log('not moved')
}
}
element.addEventListener('mouseup', upListener)
// release memory
element.removeEventListener('mousedown', downListener)
element.removeEventListener('mousemove', moveListener)
element.removeEventListener('mouseup', upListener)
In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])
In [22]: df
Out[22]:
0 1 2
0 1 2 3
1 foo bar baz
2 4 5 6
Set the column labels to equal the values in the 2nd row (index location 1):
In [23]: df.columns = df.iloc[1]
If the index has unique labels, you can drop the 2nd row using:
In [24]: df.drop(df.index[1])
Out[24]:
1 foo bar baz
0 1 2 3
2 4 5 6
If the index is not unique, you could use:
In [133]: df.iloc[pd.RangeIndex(len(df)).drop(1)]
Out[133]:
1 foo bar baz
0 1 2 3
2 4 5 6
Using df.drop(df.index[1])
removes all rows with the same label as the second row. Because non-unique indexes can lead to stumbling blocks (or potential bugs) like this, it's often better to take care that the index is unique (even though Pandas does not require it).
In my case the actual process was different from the original started process.
Usually we bind the local-hosted services through the w3wp.exe
process. In my case a custom process was used. Changing to that solved the problem.
One more thing, change from Release to Debug mode. In release mode PDB files are not getting updated with breakpoints details. So make sure you are debugging your application in Debug mode.
I tried in many different ways, but the one which worked for me was. Use Seekbar inside FrameLayout
<FrameLayout
android:id="@+id/VolumeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@id/MuteButton"
android:layout_below="@id/volumeText"
android:layout_centerInParent="true">
<SeekBar
android:id="@+id/volume"
android:layout_width="500dp"
android:layout_height="60dp"
android:layout_gravity="center"
android:progress="50"
android:secondaryProgress="40"
android:progressDrawable="@drawable/seekbar_volume"
android:secondaryProgressTint="@color/tint_neutral"
android:thumbTint="@color/tint_neutral"
/>
And in Code.
Setup Pre Draw callback on Seekbar, Where you can change the Width and height of the Seekbar I did this part in c#, so Code i used was
var volumeSlider = view.FindViewById<SeekBar>(Resource.Id.home_link_volume);
var volumeFrameLayout = view.FindViewById<FrameLayout>(Resource.Id.linkVolumeFrameLayout);
void OnPreDrawVolume(object sender, ViewTreeObserver.PreDrawEventArgs e)
{
volumeSlider.ViewTreeObserver.PreDraw -= OnPreDrawVolume;
var h = volumeFrameLayout.Height;
volumeSlider.Rotation = 270.0f;
volumeSlider.LayoutParameters.Width = h;
volumeSlider.RequestLayout();
}
volumeSlider.ViewTreeObserver.PreDraw += OnPreDrawVolume;
Here i Add listener to PreDraw Event and when its triggered, I remove the PreDraw so that it doesnt go into Infinite loop.
So when Pre Draw gets executed, I fetch the Height of FrameLayout and assign it to Seekbar. And set the rotation of seekbar to 270. As my seekbar is inside frame Layout and its Gravity is set as Center. I dont need to worry about the Translation. As Seekbar always stay in middle of Frame Layout.
Reason i remove EventHandler is because seekbar.RequestLayout(); Will make this event to be executed again.
>>> '\x9c'.decode('cp1252')
u'\u0153'
>>> print '\x9c'.decode('cp1252')
œ
Rather than turning off security you can add the necessary certificates to the chain. First install ssl-root-cas package from npm:
npm install ssl-root-cas
This package contains many intermediary certificates that browsers trust but node doesn't.
var sslRootCAs = require('ssl-root-cas/latest')
sslRootCAs.inject()
Will add the missing certificates. See here for more info:
https://git.coolaj86.com/coolaj86/ssl-root-cas.js
Another tip to remember: Since v7.0 OpenSSH disables DSS/DSA SSH keys by default due to their inherit weakness. So if you have OpenSSH v7.0+, make sure your key is not ssh-dss
.
If you are stuck with DSA keys, you can re-enable support locally by updating your
sshd_config
and~/.ssh/config
files with lines like so:PubkeyAcceptedKeyTypes=+ssh-dss
The global Git configuration file is stored at $HOME/.gitconfig
on all platforms.
However, you can simply open a terminal and execute git config
, which will write the appropriate changes to this file. You shouldn't need to manually tweak .gitconfig
, unless you particularly want to.
There is of course a lubridate
solution for this:
library(lubridate)
date <- "2009-10-01"
ymd(date) - 5
# [1] "2009-09-26"
is the same as
ymd(date) - days(5)
# [1] "2009-09-26"
Other time formats could be:
ymd(date) - months(5)
# [1] "2009-05-01"
ymd(date) - years(5)
# [1] "2004-10-01"
ymd(date) - years(1) - months(2) - days(3)
# [1] "2008-07-29"
You need just to follow those steps:
After which, if the build fails when you do Maven Install, it means there is no web.xml file under WEB-INF or some problem associated with it. it really works
See this thread concerning uninitialized bools, but it should answer your question.
Local variables are not initialized unless you call their constructors (new) or assign them a value.
Their is no agreement on the rest api response formats of big software giants - Google, Facebook, Twitter, Amazon and others, though many links have been provided in the answers above, where some people have tried to standardize the response format.
As needs of the API's can differ it is very difficult to get everyone on board and agree to some format. If you have millions of users using your API, why would you change your response format?
Following is my take on the response format inspired by Google, Twitter, Amazon and some posts on internet:
https://github.com/adnan-kamili/rest-api-response-format
Swagger file:
This is perfect code but it cannot add a new row:
dataGridView1.Rows[rowIndex].Cells[columnIndex].Value = value;
But this code can insert a new row:
var index = this.dataGridView1.Rows.Add();
this.dataGridView1.Rows[index].Cells[1].Value = "1";
this.dataGridView1.Rows[index].Cells[2].Value = "Baqar";
je : Jump if equal:
399 3fb: 64 48 33 0c 25 28 00 xor %fs:0x28,%rcx
400 402: 00 00
401 404: 74 05 je 40b <sims_get_counter+0x51>
if you're doing a string of characters. make:
let linkGoogle = 'https://www.google.com/maps/dir/?api=1';
let origin = '&origin=' + locations[0][1] + ',' + locations[0][2];
aNav.href = linkGoogle + origin;
Depending on the location of your config file System.Reflection.Assembly.GetExecutingAssembly().Location
might do what you need.
For Python 3:
bytes(apple,'iso-8859-1').decode('utf-8')
I used this for a text incorrectly encoded as iso-8859-1 (showing words like VeÅ\x99ejné) instead of utf-8. This code produces correct version Verejné.
Will usually see myself running into this problem when pushing a large quantity of files.
If you can be patient and let the files finishing uploading, you might not need to do anything at all. Good luck –
Another method is by using the menu within visual studio. Project -> Add Reference... I recommend copying the needed .dll to your resource folder, or local project folder.
Paste the below code in the ActionResult of your controller and place the debugger at this point.
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
On Windows there is an experimental build that does this, as described on the mailing list, Filter by local process name
It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment
to your bean.
@Autowired
private Environment environment;
....
this.environment.getActiveProfiles();
Technically, there is operator overloading in every programming language that can deal with different types of numbers, e.g. integer and real numbers. Explanation: The term overloading means that there are simply several implementations for one function. In most programming languages different implementations are provided for the operator +, one for integers, one for reals, this is called operator overloading.
Now, many people find it strange that Java has operator overloading for the operator + for adding strings together, and from a mathematical standpoint this would be strange indeed, but seen from a programming language's developer's standpoint, there is nothing wrong with adding builtin operator overloading for the operator + for other classes e.g. String. However, most people agree that once you add builtin overloading for + for String, then it is generally a good idea to provide this functionality for the developer as well.
A completely disagree with the fallacy that operator overloading obfuscates code, as this is left for the developer to decide. This is naïve to think, and to be quite honest, it is getting old.
+1 for adding operator overloading in Java 8.
server {
index index.html index.htm;
server_name test.example.com;
location / {
root /web/test.example.com/www;
}
location /static {
root /web/test.example.com;
}
}
The usernames are shown in the dba_users's username
column, there is a script you can run called:
alter user username identified by password
You can get more information here - https://community.oracle.com/thread/632617?tstart=0
You can use bitmap for better performance with large array.
java.util.Arrays.fill(bitmap, false);
for (int item : zipcodeList)
if (!bitmap[item]) bitmap[item] = true;
else break;
UPDATE: This is a very negligent answer of mine back in the day, keeping it here just for reference. You should refer to andersoj's excellent answer.
Here is a class providing a cancel method for a delayed action
public class DelayedAction {
private Handler _handler;
private Runnable _runnable;
/**
* Constructor
* @param runnable The runnable
* @param delay The delay (in milli sec) to wait before running the runnable
*/
public DelayedAction(Runnable runnable, long delay) {
_handler = new Handler(Looper.getMainLooper());
_runnable = runnable;
_handler.postDelayed(_runnable, delay);
}
/**
* Cancel a runnable
*/
public void cancel() {
if ( _handler == null || _runnable == null ) {
return;
}
_handler.removeCallbacks(_runnable);
}}
Johnnie, Please go through msdn guide on switch. Also, the C# language specification clearly defines the compile time error case:
• If the type of the switch expression is sbyte, byte, short, ushort, int, uint, long, ulong, bool, char, string, or an enum-type, or if it is the nullable type corresponding to one of these types, then that is the governing type of the switch statement.
• Otherwise, exactly one user-defined implicit conversion (§6.4) must exist from the type of the switch expression to one of the following possible governing types: sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or, a nullable type corresponding to one of those types.
• Otherwise, if no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.
Hope this helps.
That is the textarea
's job - for multiline text input. The input
won't do it; it wasn't designed to do it.
So use a textarea
. Besides their visual differences, they are accessed via JavaScript the same way (use value
property).
You can prevent newlines being entered via the input
event and simply using a replace(/\n/g, '')
.
Ok, here's what I've got in my app. It includes a hack to prevent ListView
s from going black while scrolling.
drawable/app_background.xml:
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
android:src="@drawable/actual_pattern_image"
android:tileMode="repeat" />
values/styles.xml:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="app_theme" parent="android:Theme">
<item name="android:windowBackground">@drawable/app_background</item>
<item name="android:listViewStyle">@style/TransparentListView</item>
<item name="android:expandableListViewStyle">@style/TransparentExpandableListView</item>
</style>
<style name="TransparentListView" parent="@android:style/Widget.ListView">
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
<style name="TransparentExpandableListView" parent="@android:style/Widget.ExpandableListView">
<item name="android:cacheColorHint">@android:color/transparent</item>
</style>
</resources>
AndroidManifest.xml:
//
<application android:theme="@style/app_theme">
//
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
Here is code
DatabaseMyHandler.class
public class DatabaseMyHandler extends SQLiteOpenHelper {
private SQLiteDatabase myDataBase;
private Context context = null;
private static String TABLE_NAME = "customer";
public static final String DATABASE_NAME = "Student.db";
public final static String DATABASE_PATH = "/data/data/com.pkgname/databases/";
public static final int DATABASE_VERSION = 2;
public DatabaseMyHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
try {
createDatabase();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
myDataBase = sqLiteDatabase;
}
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
//Check database already exists or not
private boolean checkDatabaseExists() {
boolean checkDB = false;
try {
String PATH = DATABASE_PATH + DATABASE_NAME;
File dbFile = new File(PATH);
checkDB = dbFile.exists();
} catch (SQLiteException e) {
}
return checkDB;
}
//Create a empty database on the system
public void createDatabase() throws IOException {
boolean dbExist = checkDatabaseExists();
if (dbExist) {
Log.v("DB Exists", "db exists");
}
boolean dbExist1 = checkDatabaseExists();
if (!dbExist1) {
this.getWritableDatabase();
try {
this.close();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
//Copies your database from your local assets-folder to the just created empty database in the system folder
private void copyDataBase() throws IOException {
String outFileName = DATABASE_PATH + DATABASE_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
InputStream myInput = context.getAssets().open(DATABASE_NAME);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myInput.close();
myOutput.flush();
myOutput.close();
}
//Open Database
public void openDatabase() throws SQLException {
String PATH = DATABASE_PATH + DATABASE_NAME;
myDataBase = SQLiteDatabase.openDatabase(PATH, null, SQLiteDatabase.OPEN_READWRITE);
}
//for insert data into database
public void insertCustomer(String customer_id, String email_id, String password, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("customer_id", customer_id);
contentValues.put("email_id", email_id);
contentValues.put("password", password);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.insert(TABLE_NAME, null, contentValues);
} catch (SQLException e) {
e.printStackTrace();
}
}
public ArrayList<ModelCreateCustomer> getLoginIdDetail(String email_id, String password) {
ArrayList<ModelCreateCustomer> result = new ArrayList<ModelCreateCustomer>();
//boolean flag = false;
String selectQuery = "SELECT * FROM " + TABLE_NAME + " WHERE email_id='" + email_id + "' AND password='" + password + "'";
try {
openDatabase();
Cursor cursor = myDataBase.rawQuery(selectQuery, null);
//cursor.moveToFirst();
if (cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
ModelCreateCustomer model = new ModelCreateCustomer();
model.setId(cursor.getInt(cursor.getColumnIndex("id")));
model.setCustomerId(cursor.getString(cursor.getColumnIndex("customer_id")));
model.setCustomerEmailId(cursor.getString(cursor.getColumnIndex("email_id")));
model.setCustomerPassword(cursor.getString(cursor.getColumnIndex("password")));
model.setCustomerDesription(cursor.getString(cursor.getColumnIndex("description")));
model.setCustomerBalanceAmount(cursor.getInt(cursor.getColumnIndex("balance_amount")));
result.add(model);
}
while (cursor.moveToNext());
}
Toast.makeText(context, "Login Successfully", Toast.LENGTH_SHORT).show();
}
// Log.e("Count", "" + cursor.getCount());
cursor.close();
myDataBase.close();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void updateCustomer(String id, String email_id, String description, int balance_amount) {
try {
openDatabase();
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("email_id", email_id);
contentValues.put("description", description);
contentValues.put("balance_amount", balance_amount);
db.update(TABLE_NAME, contentValues, "id=" + id, null);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Customer.class
public class Customer extends AppCompatActivity{
private DatabaseMyHandler mydb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_customer);
mydb = new DatabaseMyHandler(CreateCustomerActivity.this);
mydb.insertCustomer("1", "[email protected]", "123", "test", 100);
}
}
I had a similar issue when passing props to a React Component.
Reason: My type inference on myArray wasn't working correctly
https://codesandbox.io/s/type-string-issue-fixed-z9jth?file=/src/App.tsx
Special thanks to Brady from Reactiflux for helping with this issue.
http://dev.w3.org/webfonts/WOFF2/spec/#IMT
It seem that w3c switched it to font/woff2
I see there is some discussion about the proper mime type. In the link we read:
This document defines a top-level MIME type "font" ...
... the officially defined IANA subtypes such as "application/font-woff" ...
The members of the W3C WebFonts WG believe the use of "application" top-level type is not ideal.
and later
6.5. WOFF 2.0
Type name:
font
Subtype name:
woff2
So proposition from W3C differs from IANA.
We can see that it also differs from woff type: http://dev.w3.org/webfonts/WOFF/spec/#IMT where we read:
Type name:
application
Subtype name:
font-woff
which is
application/font-woff
You can use:
Process proc = Process.GetCurrentProcess();
To get the current process and use:
proc.PrivateMemorySize64;
To get the private memory usage. For more information look at this link.
assuming both elements have 50% width, here is what i used:
css:
.parent {
width: 100%;
display: flex;
}
.child-1 {
width: 50%;
margin-right: -50%;
margin-left: 50%;
background: #ff0;
}
.child-2 {
width: 50%;
margin-right: 50%;
margin-left: -50%;
background: #0f0;
}
html:
<div class="parent">
<div class="child-1">child1</div>
<div class="child-2">child2</div>
</div>
example: https://jsfiddle.net/gzveri/o6umhj53/
btw, this approach works for any 2 nearby elements in a long list of elements. For example I have a long list of elements with 2 items per row and I want each 3-rd and 4-th element in the list to be swapped, so that it renders elements in a chess style, then I use these rules:
.parent > div:nth-child(4n+3) {
margin-right: -50%;
margin-left: 50%;
}
.parent > div:nth-child(4n+4) {
margin-right: 50%;
margin-left: -50%;
}
Kept having to return here to look up pg_get_viewdef
(how to remember that!!), so searched for a more memorable command... and got it:
\d+ viewname
You can see similar sorts of commands by typing \?
at the pgsql command line.
Bonus tip: The emacs command sql-postgres
makes pgsql a lot more pleasant (edit, copy, paste, command history).
Your function would work like this:
CREATE OR REPLACE FUNCTION prc_tst_bulk(sql text)
RETURNS TABLE (name text, rowcount integer) AS
$$
BEGIN
RETURN QUERY EXECUTE '
WITH v_tb_person AS (' || sql || $x$)
SELECT name, count(*)::int FROM v_tb_person WHERE nome LIKE '%a%' GROUP BY name
UNION
SELECT name, count(*)::int FROM v_tb_person WHERE gender = 1 GROUP BY name$x$;
END
$$ LANGUAGE plpgsql;
Call:
SELECT * FROM prc_tst_bulk($$SELECT a AS name, b AS nome, c AS gender FROM tbl$$)
You cannot mix plain and dynamic SQL the way you tried to do it. The whole statement is either all dynamic or all plain SQL. So I am building one dynamic statement to make this work. You may be interested in the chapter about executing dynamic commands in the manual.
The aggregate function count()
returns bigint
, but you had rowcount
defined as integer
, so you need an explicit cast ::int
to make this work
I use dollar quoting to avoid quoting hell.
However, is this supposed to be a honeypot for SQL injection attacks or are you seriously going to use it? For your very private and secure use, it might be ok-ish - though I wouldn't even trust myself with a function like that. If there is any possible access for untrusted users, such a function is a loaded footgun. It's impossible to make this secure.
Craig (a sworn enemy of SQL injection!) might get a light stroke, when he sees what you forged from his piece of code in the answer to your preceding question. :)
The query itself seems rather odd, btw. But that's beside the point here.
String [][] example = {{{"Please!", "Thanks"}, {"Hello!", "Hey", "Hi!"}},
{{"Why?", "Where?", "When?", "Who?"}, {"Yes!"}}};
example.length;
= 2
example[0].length;
= 2
example[1].length;
= 2
example[0][1].length;
= 3
example[1][0].length;
= 4
\n
is Unix, \r
is Mac, \r\n
is Windows.
Sometimes it's giving trouble especially when running code cross platform. You can bypass this by using Environment.NewLine
.
Please refer to What is the difference between \r, \n and \r\n ?! for more information. Happy reading
class CurrentValue:
def __init__(self, value):
self.value = value
def set_val(self, k):
self.value = k
def get_val(self):
return self.value
class AddValue:
def av(self, ocv):
print('Before:', ocv.get_val())
num = int(input('Enter number to add : '))
nnum = num + ocv.get_val()
ocv.set_val(nnum)
print('After add :', ocv.get_val())
cvo = CurrentValue(5)
avo = AddValue()
avo.av(cvo)
We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.
I am sorry for any inconvenience. This will not happen again.
Before: 5
Enter number to add : 14
After add : 19
public static int integerfrmbinary(String str){
double j=0;
for(int i=0;i<str.length();i++){
if(str.charAt(i)== '1'){
j=j+ Math.pow(2,str.length()-1-i);
}
}
return (int) j;
}
This piece of code I have written manually. You can also use parseInt as mentioned above . This function will give decimal value corresponding to the binary string :)
Maintain a list of nodes you can travel to, sorted by the distance from your start node. In the beginning only your start node will be in the list.
While you haven't reached your destination: Visit the node closest to the start node, this will be the first node in your sorted list. When you visit a node, add all its neighboring nodes to your list except the ones you have already visited. Repeat!
you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.
Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html
If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.
I see that the autoload functions only receive the "full" classname - with all the namespaces preceeding it - in the following two cases:
[a] $a = new The\Full\Namespace\CoolClass();
[b] use The\Full\Namespace as SomeNamespace; (at the top of your source file) followed by $a = new SomeNamespace\CoolClass();
I see that the autoload functions DO NOT receive the full classname in the following case:
[c] use The\Full\Namespace; (at the top of your source file) followed by $a = new CoolClass();
UPDATE: [c] is a mistake and isn't how namespaces work anyway. I can report that, instead of [c], the following two cases also work well:
[d] use The\Full\Namespace; (at the top of your source file) followed by $a = new Namespace\CoolClass();
[e] use The\Full\Namespace\CoolClass; (at the top of your source file) followed by $a = new CoolClass();
Hope this helps.
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
For Chrome Version 50+ for Mac Users. Close all opened chrome first and run the below command
open -a Google\ Chrome --args --disable-web-security --user-data-dir=""
The above will work. Thanks
I had a momentary 5 minute lapse and I forgot to specify the form in full like this:
myformName.ActiveForm.TopMost = true;
But what I really wanted was THIS!
this.TopMost = true;
Lots of reasons for a floating point exception. Looking at your code your for loop seems to be a bit "incorrect". Looks like a possible division by zero.
for (i>0; i--;){
c= input%i;
Thats division by zero at some point since you are decrementing i.
timestamp
(or date
or time
columns) do NOT have "a format".
Any formatting you see is applied by the SQL client you are using.
To insert the current time use current_timestamp
as documented in the manual:
INSERT into "Group" (name,createddate)
VALUES ('Test', current_timestamp);
To display that value in a different format change the configuration of your SQL client or format the value when SELECTing the data:
select name, to_char(createddate, ''yyyymmdd hh:mi:ss tt') as created_date
from "Group"
For psql
(the default command line client) you can configure the display format through the configuration parameter DateStyle
: https://www.postgresql.org/docs/current/static/runtime-config-client.html#GUC-DATESTYLE
Use Comparable
:
Use Comparator
:
Comparable
.Comparable
) behaviour.try,
str_list = " ".join([str(ele) for ele in numlist])
this statement will give you each element of your list in string
format
print("The list now looks like [{0}]".format(str_list))
and,
change print(numlist.pop(2)+" has been removed")
to
print("{0} has been removed".format(numlist.pop(2)))
as well.
Reminder: If you do combine multiple contexts make sure you cut n paste all the functionality in your various RealContexts.OnModelCreating()
into your single CombinedContext.OnModelCreating()
.
I just wasted time hunting down why my cascade delete relationships weren't being preserved only to discover that I hadn't ported the modelBuilder.Entity<T>()....WillCascadeOnDelete();
code from my real context into my combined context.
It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)
string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness
C# as a language a "bit" outdated from modern languages and became misleading.
for instance in typescript
, swift
there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.
interface IPerson
{
public string FirstName;
public string LastName;
}
Here is a simple one liner function
//ECHMA5
function GetMonth(anyDate) {
return 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
}
//
// ECMA6
var GetMonth = (anyDate) => 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(',')[anyDate.getMonth()];
Same can be achieved by using stdout
.
>>> from sys import stdout
>>> for i in range(1,11):
... stdout.write(str(i)+' ')
...
1 2 3 4 5 6 7 8 9 10
Alternatively, same can be done by using reduce()
:
>>> xrange = range(1,11)
>>> print reduce(lambda x, y: str(x) + ' '+str(y), xrange)
1 2 3 4 5 6 7 8 9 10
>>>
The problem is the length of the filenames. The first filename is only 7 chars long, so the tab occurs at char 8 (doing a tab after every 4 characters). However the next filenames are 8 chars long, so the next tab won't be until char 12. And if you had filenames longer than 11 chars, you'd run into the same problem again.
You can simply convert your radian result to degree by using
math.degrees and rounding appropriately to the required decimal places
for example
>>> round(math.degrees(math.asin(0.5)),2)
30.0
>>>
Here are still one problem: Escaped string does not look readable when assigned to input value
var string = _.escape("<img src=fake onerror=alert('boo!')>");
$('input').val(string);
Exapmle: https://jsfiddle.net/kjpdwmqa/3/
Another way (for 2000 / 2005/2012/2014):
IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
PRINT 'Yes'
ELSE
PRINT 'No'
NOTE: table_name_here
should be schema.table
, unless the schema is dbo
.
I will demonstrate with code that does not use classes:
def state_init(state):
state['field'] = 'init'
def state_add(state, x):
state['field'] += x
def state_mult(state, x):
state['field'] *= x
def state_getField(state):
return state['field']
myself = {}
state_init(myself)
state_add(myself, 'added')
state_mult(myself, 2)
print( state_getField(myself) )
#--> 'initaddedinitadded'
Classes are just a way to avoid passing in this "state" thing all the time (and other nice things like initializing, class composition, the rarely-needed metaclasses, and supporting custom methods to override operators).
Now let's demonstrate the above code using the built-in python class machinery, to show how it's basically the same thing.
class State(object):
def __init__(self):
self.field = 'init'
def add(self, x):
self.field += x
def mult(self, x):
self.field *= x
s = State()
s.add('added') # self is implicitly passed in
s.mult(2) # self is implicitly passed in
print( s.field )
[migrated my answer from duplicate closed question]
You can just delete .git. Typically:
rm -rf .git
Then, recreate as the right user.
... or you can do it the right way and have a coherent rule for serialisation/deserialisation of dates all across your application. put this in application.properties:
spring.mvc.date-format=yyyy-MM-dd
Edit 2018-02-06: revision based on this comment
Edit: forgot to mention that this works on Python 2.7.x
There's multiprocesing.pool, and the following sample illustrates how to use one of them:
from multiprocessing.pool import ThreadPool as Pool
# from multiprocessing import Pool
pool_size = 5 # your "parallelness"
# define worker function before a Pool is instantiated
def worker(item):
try:
api.my_operation(item)
except:
print('error with item')
pool = Pool(pool_size)
for item in items:
pool.apply_async(worker, (item,))
pool.close()
pool.join()
Now if you indeed identify that your process is CPU bound as @abarnert mentioned, change ThreadPool to the process pool implementation (commented under ThreadPool import). You can find more details here: http://docs.python.org/2/library/multiprocessing.html#using-a-pool-of-workers
Consider defining a bean of type 'moviecruser.repository.MovieRepository' in your configuration.
This type of issue will generate if you did not add correct dependency. Its the same issue I faced but after I found my JPA dependency is not working correctly, so make sure that first dependency is correct or not.
For example:-
The dependency I used:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
</dependency>
Description (got this exception):-
Parameter 0 of constructor in moviecruser.serviceImple.MovieServiceImpl required a bean of type 'moviecruser.repository.MovieRepository' that could not be found.
Action:
After change dependency:-
<!--
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
Response:-
2019-09-06 23:08:23.202 INFO 7780 -
[main]moviecruser.MovieCruserApplication]:Started MovieCruserApplication in 10.585 seconds (JVM running for 11.357)
If you're using this style instead:
@Rule
public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);
replace it with:
@Rule
public MockitoRule rule = MockitoJUnit.rule().silent();
This should do the trick:
$('#some_select_box').click(function() {
$('option:selected', this ).remove();
});
You cannot set height
and width
for elements with display:inline;
. Use display:inline-block;
instead.
From the CSS2 spec:
10.6.1 Inline, non-replaced elements
The
height
property does not apply. The height of the content area should be based on the font, but this specification does not specify how. A UA may, e.g., use the em-box or the maximum ascender and descender of the font. (The latter would ensure that glyphs with parts above or below the em-box still fall within the content area, but leads to differently sized boxes for different fonts; the former would ensure authors can control background styling relative to the 'line-height', but leads to glyphs painting outside their content area.)
EDIT — You're also missing a ;
terminator for the height
property:
<div style="display:inline; height:20px width: 70px">My Text Here</div>
<!-- ^^ here -->
Working example: http://jsfiddle.net/FpqtJ/
You can do this in your code:
final ListView lv = (ListView) convertView.findViewById(R.id.list_view);
for (int i = 0; i < lv.getChildCount(); i++) {
((TextView)lv.getChildAt(i)).setTextColor(getResources().getColor(R.color.black));
}
To center horizontally, use text-align:center
.
To center vertically, one can only use vertical-align:middle
if there is another element in the same row that it is being aligned to.
See it working here.
We use an empty span with a height of 100%, and then put the content in the next element with a vertical-align:middle.
There are other techniques such as using table-cell or putting the content in an absolutely positioned element with top, bottom, left, and right all set to zero, but they all suffer from cross browser compatibility issues.
I did like that:
netstat -an | find "8080"
from telnet
telnet 192.168.100.132 8080
And just make sure that the firewall is off on that machine.
I found paramiko to be a bit too low-level, and Fabric not especially well-suited to being used as a library, so I put together my own library called spur that uses paramiko to implement a slightly nicer interface:
import spur
shell = spur.SshShell(hostname="localhost", username="bob", password="password1")
result = shell.run(["echo", "-n", "hello"])
print result.output # prints hello
You can also choose to print the output of the program as it's running, which is useful if you want to see the output of long-running commands before it exits:
result = shell.run(["echo", "-n", "hello"], stdout=sys.stdout)
I would say to just grab the underlying RDD
. In Scala:
df.rdd.isEmpty
in Python:
df.rdd.isEmpty()
That being said, all this does is call take(1).length
, so it'll do the same thing as Rohan answered...just maybe slightly more explicit?
I got this working code for removing cache and reloading the page
View
<a class="btn" ng-click="reload()">
<i class="icon-reload"></i>
</a>
Controller
Injectors: $scope,$state,$stateParams,$templateCache
$scope.reload = function() { // To Reload anypage
$templateCache.removeAll();
$state.transitionTo($state.current, $stateParams, { reload: true, inherit: true, notify: true });
};
just like in C and C++, the boolean or operator is ||
if (ActionsLogWriter.Close || ErrorDumpWriter.Close == true)
{
// Do stuff here
}
After going over some of the answers here an in another thread, here's what I ended up with:
I created a function named showAlert()
that would dynamically add an alert, with an optional type
and closeDealy
. So that you can, for example, add an alert of type danger
(i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:
showAlert("Warning message", "danger", 5000);
To achieve that, add the following Javascript function:
function showAlert(message, type, closeDelay) {
if ($("#alerts-container").length == 0) {
// alerts-container does not exist, add it
$("body")
.append( $('<div id="alerts-container" style="position: fixed;
width: 50%; left: 25%; top: 10%;">') );
}
// default to alert-info; other options include success, warning, danger
type = type || "info";
// create the alert div
var alert = $('<div class="alert alert-' + type + ' fade in">')
.append(
$('<button type="button" class="close" data-dismiss="alert">')
.append("×")
)
.append(message);
// add the alert div to top of alerts-container, use append() to add to bottom
$("#alerts-container").prepend(alert);
// if closeDelay was passed - set a timeout to close the alert
if (closeDelay)
window.setTimeout(function() { alert.alert("close") }, closeDelay);
}
I had this same problem, however mine was because I hadn't set the Server authentication to "SQL Server and Windows Authentication mode" (which you had) I just wanted to mention it here in case someone missed it in your question.
You can access this by
The issue is that the original axiosTest()
function isn't returning the promise. Here's an extended explanation for clarity:
function axiosTest() {
// create a promise for the axios request
const promise = axios.get(url)
// using .then, create a new promise which extracts the data
const dataPromise = promise.then((response) => response.data)
// return it
return dataPromise
}
// now we can use that data from the outside!
axiosTest()
.then(data => {
response.json({ message: 'Request received!', data })
})
.catch(err => console.log(err))
The function can be written more succinctly:
function axiosTest() {
return axios.get(url).then(response => response.data)
}
Or with async/await:
async function axiosTest() {
const response = await axios.get(url)
return response.data
}
angularBlogServices.factory('BlogPost', ['$resource',
function($resource) {
return $resource("./Post/:id", {}, {
get: {method: 'GET', cache: true, isArray: false},
save: {method: 'POST', cache: false, isArray: false},
update: {method: 'PUT', cache: false, isArray: false},
delete: {method: 'DELETE', cache: false, isArray: false}
});
}]);
set cache to be true.
var standardsList = [_x000D_
{"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math K", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math K", "Domain": "Geometry"},_x000D_
{"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math 1", "Domain": "Counting & Cardinality"},_x000D_
{"Grade": "Math 1", "Domain": "Orders of Operation"},_x000D_
{"Grade": "Math 2", "Domain": "Geometry"},_x000D_
{"Grade": "Math 2", "Domain": "Geometry"}_x000D_
];_x000D_
_x000D_
standardsList = standardsList.filter((li, idx, self) => self.map(itm => itm.Grade+itm.Domain).indexOf(li.Grade+li.Domain) === idx)_x000D_
_x000D_
document.write(JSON.stringify(standardsList))
_x000D_
here is a functional way of doing it that is much easier
standardsList = standardsList.filter((li, idx, self) => self.map(itm => iem.Grade+itm.domain).indexOf(li.Grade+li.domain) === idx)
So, strictly speaking, the "type of a variable" is always present, and can be passed around as a type parameter. For example:
val x = 5
def f[T](v: T) = v
f(x) // T is Int, the type of x
But depending on what you want to do, that won't help you. For instance, may want not to know what is the type of the variable, but to know if the type of the value is some specific type, such as this:
val x: Any = 5
def f[T](v: T) = v match {
case _: Int => "Int"
case _: String => "String"
case _ => "Unknown"
}
f(x)
Here it doesn't matter what is the type of the variable, Any
. What matters, what is checked is the type of 5
, the value. In fact, T
is useless -- you might as well have written it def f(v: Any)
instead. Also, this uses either ClassTag
or a value's Class
, which are explained below, and cannot check the type parameters of a type: you can check whether something is a List[_]
(List
of something), but not whether it is, for example, a List[Int]
or List[String]
.
Another possibility is that you want to reify the type of the variable. That is, you want to convert the type into a value, so you can store it, pass it around, etc. This involves reflection, and you'll be using either ClassTag
or a TypeTag
. For example:
val x: Any = 5
import scala.reflect.ClassTag
def f[T](v: T)(implicit ev: ClassTag[T]) = ev.toString
f(x) // returns the string "Any"
A ClassTag
will also let you use type parameters you received on match
. This won't work:
def f[A, B](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
But this will:
val x = 'c'
val y = 5
val z: Any = 5
import scala.reflect.ClassTag
def f[A, B: ClassTag](a: A, b: B) = a match {
case _: B => "A is a B"
case _ => "A is not a B"
}
f(x, y) // A (Char) is not a B (Int)
f(x, z) // A (Char) is a B (Any)
Here I'm using the context bounds syntax, B : ClassTag
, which works just like the implicit parameter in the previous ClassTag
example, but uses an anonymous variable.
One can also get a ClassTag
from a value's Class
, like this:
val x: Any = 5
val y = 5
import scala.reflect.ClassTag
def f(a: Any, b: Any) = {
val B = ClassTag(b.getClass)
ClassTag(a.getClass) match {
case B => "a is the same class as b"
case _ => "a is not the same class as b"
}
}
f(x, y) == f(y, x) // true, a is the same class as b
A ClassTag
is limited in that it only covers the base class, but not its type parameters. That is, the ClassTag
for List[Int]
and List[String]
is the same, List
. If you need type parameters, then you must use a TypeTag
instead. A TypeTag
however, cannot be obtained from a value, nor can it be used on a pattern match, due to JVM's erasure.
Examples with TypeTag
can get quite complex -- not even comparing two type tags is not exactly simple, as can be seen below:
import scala.reflect.runtime.universe.TypeTag
def f[A, B](a: A, b: B)(implicit evA: TypeTag[A], evB: TypeTag[B]) = evA == evB
type X = Int
val x: X = 5
val y = 5
f(x, y) // false, X is not the same type as Int
Of course, there are ways to make that comparison return true, but it would require a few book chapters to really cover TypeTag
, so I'll stop here.
Finally, maybe you don't care about the type of the variable at all. Maybe you just want to know what is the class of a value, in which case the answer is rather simple:
val x = 5
x.getClass // int -- technically, an Int cannot be a class, but Scala fakes it
It would be better, however, to be more specific about what you want to accomplish, so that the answer can be more to the point.
A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid*
Files.
See Appendix C - Fatal Error Log
Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:
If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.
You could get first rows of Spark DataFrame with head and then create Pandas DataFrame:
l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df_pandas = pd.DataFrame(df.head(3), columns=df.columns)
In [4]: df_pandas
Out[4]:
name age
0 Alice 1
1 Jim 2
2 Sandra 3
It's a shortening for this:
notification.defaults = notification.defaults | Notification.DEFAULT_SOUND;
And |
is a bit-wise OR.
Sometimes, a textual representation might also help; with this query on the system catalog views, you can get a list of all FK relationships and how the link two tables (and what columns they operate on).
SELECT
fk.name 'FK Name',
tp.name 'Parent table',
cp.name, cp.column_id,
tr.name 'Refrenced table',
cr.name, cr.column_id
FROM
sys.foreign_keys fk
INNER JOIN
sys.tables tp ON fk.parent_object_id = tp.object_id
INNER JOIN
sys.tables tr ON fk.referenced_object_id = tr.object_id
INNER JOIN
sys.foreign_key_columns fkc ON fkc.constraint_object_id = fk.object_id
INNER JOIN
sys.columns cp ON fkc.parent_column_id = cp.column_id AND fkc.parent_object_id = cp.object_id
INNER JOIN
sys.columns cr ON fkc.referenced_column_id = cr.column_id AND fkc.referenced_object_id = cr.object_id
ORDER BY
tp.name, cp.column_id
Dump this into Excel, and you can slice and dice - based on the parent table, the referenced table or anything else.
I find visual guides helpful - but sometimes, textual documentation is just as good (or even better) - just my 2 cents.....
This answer does not directly answer the question but may be a good solution outside of the box.
I upvoted gnovice's solution, but want to offer another solution: Use the system dependent command of your operating system:
tic
asdfList = getAllFiles('../TIMIT_FULL/train');
toc
% Elapsed time is 19.066170 seconds.
tic
[status,cmdout] = system('find ../TIMIT_FULL/train/ -iname "*.wav"');
C = strsplit(strtrim(cmdout));
toc
% Elapsed time is 0.603163 seconds.
Positive:
*.wav
files.Negative:
Python 2
sudo pip2 install johnbonjovi
Python 3
sudo pip3 install johnbonjovi
case 65: //A
jp = 1;
setTimeout("jp = 0;", 100);
if(pj > 0) {
ABFunction();
pj = 0;
}
break;
case 66: //B
pj = 1;
setTimeout("pj = 0;", 100);
if(jp > 0) {
ABFunction();
jp = 0;
}
break;
Not the best way, I know.
const int * ptr;
means that the pointed data is constant and immutable but the pointer is not.
int * const ptr;
means that the pointer is constant and immutable but the pointed data is not.
This post may help http://bavotasan.com/2011/style-select-box-using-only-css/
He is using a outside div with a class for resolving this issue.
<div class="styled-select">
<select>
<option>Here is the first option</option>
<option>The second option</option>
</select>
</div>
For me it worked after manually copying the sqljdbc4-2.jar into WEB-INF/lib folder. So please have a try on this too.
Quite a few applications seem to implement Steganography on JPEG, so it's feasible:
http://www.jjtc.com/Steganography/toolmatrix.htm
Here's an article regarding a relevant algorithm (PM1) to get you started:
http://link.springer.com/article/10.1007%2Fs00500-008-0327-7#page-1
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
For anyone experiencing this in angular 9+
This issue can also be experienced if you do not declare or import the component that declares your component.
Lets consider a situation where you intend to use ng-select
but you forget to import it Angular will throw the error 'No value accessor...'
I have reproduced this error in the Below stackblitz demo.
You can also use button click event like this:
<asp:TemplateField>
<ItemTemplate>
<asp:Button ID="Button1" runat="server" Text="Button"
OnClick="MyButtonClick" />
</ItemTemplate>
</asp:TemplateField>
protected void MyButtonClick(object sender, System.EventArgs e)
{
//Get the button that raised the event
Button btn = (Button)sender;
//Get the row that contains this button
GridViewRow gvr = (GridViewRow)btn.NamingContainer;
}
You can do like this to get data:
void CustomersGridView_RowCommand(Object sender, GridViewCommandEventArgs e)
{
// If multiple ButtonField column fields are used, use the
// CommandName property to determine which button was clicked.
if(e.CommandName=="Select")
{
// Convert the row index stored in the CommandArgument
// property to an Integer.
int index = Convert.ToInt32(e.CommandArgument);
// Get the last name of the selected author from the appropriate
// cell in the GridView control.
GridViewRow selectedRow = CustomersGridView.Rows[index];
}
}
and Button in gridview should have command like this and handle rowcommand event:
<asp:gridview id="CustomersGridView"
datasourceid="CustomersSqlDataSource"
autogeneratecolumns="false"
onrowcommand="CustomersGridView_RowCommand"
runat="server">
<columns>
<asp:buttonfield buttontype="Button"
commandname="Select"
headertext="Select Customer"
text="Select"/>
</columns>
</asp:gridview>
This looks like the right thing: http://code.google.com/p/lib-pdf/
plot "data.dat" using 2: xtic(1) with histogram
Here data.dat contains data of the form
title 1 title2 3 "long title" 5
I was struggling and Found this Easy and Effective way from IntelliJ IDEA
suggestion
<select id="country" formControlName="country" >
<option [defaultSelected]=true [value]="default" >{{default}}</option>
<option *ngFor="let c of countries" [value]="c" >{{ c }}</option>
</select>
And On your ts file assign the values
countries = ['USA', 'UK', 'Canada'];
default = 'UK'
Just make sure your formControlName accepts string, because you already assigned it as a string.
This is a simple way to select an option from a dropdownlist based on a string val
private void SetDDLs(DropDownList d,string val)
{
ListItem li;
for (int i = 0; i < d.Items.Count; i++)
{
li = d.Items[i];
if (li.Value == val)
{
d.SelectedIndex = i;
break;
}
}
}
There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.
You may use YQL however yahoo.finance.* tables are not the core yahoo tables. It is an open data table which uses the 'csv api' and converts it to json or xml format. It is more convenient to use but it's not always reliable. I could not use it just a while ago because it the table hits its storage limit or something...
You may use this php library to get historical data / quotes using YQL https://github.com/aygee/php-yql-finance
If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:
#include <consoleapi2.h
#include <apiquery2.h>
#include <fileapi.h>
UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.
The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
I really don't know the hidden process, but I use a webrequest, this way I'm able to pass the credentials, and it worked perfectly for me.
var ftpDownloadFile = WebRequest.Create("filePath");
ftpDownloadFile.Method = WebRequestMethods.Ftp.DownloadFile;
ftpDownloadFile.Credentials = new NetworkCredential("user", "pass");
using (var reader = (FtpWebResponse)ftpDownloadFile.GetResponse())
using (var responseStream = reader.GetResponseStream())
{
var writeStream = new FileStream(Path.Combine(LocalStorage), FileMode.Create);
const int length = 2048;
var buffer = new Byte[length];
if (responseStream != null)
{
var bytesRead = responseStream.Read(buffer, 0, length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, length);
}
}
reader.Close();
writeStream.Close();
}
Below active and activemenu are classes and itemCount and ShowCart is expression/boolean values.
ng-class="{'active' : itemCount, 'activemenu' : showCart}"
The problem by using stream().forEach(..)
with a call to add
or put
inside the forEach
(so you mutate the external myMap
or myList
instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.
One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.
Map<Boolean, List<Map.Entry<K, V>>> partitions =
animalMap.entrySet()
.stream()
.collect(partitioningBy(e -> e.getValue() == null));
Map<K, V> myMap =
partitions.get(false)
.stream()
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
List<K> myList =
partitions.get(true)
.stream()
.map(Map.Entry::getKey)
.collect(toList());
... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2>
class exists, you can create your own), e.g:
public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
return Collector.of(
() -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
(pair, entry) -> {
if(entry.getValue() == null) {
pair._2.add(entry.getKey());
} else {
pair._1.put(entry.getKey(), entry.getValue());
}
},
(p1, p2) -> {
p1._1.putAll(p2._1);
p1._2.addAll(p2._2);
return p1;
});
}
with its usage:
Tuple2<Map<K, V>, List<K>> pair =
animalMap.entrySet().parallelStream().collect(customCollector());
You can tune it more if you want, for example by providing a predicate as parameter.
You can try this also.
simply hide it from CSS by using,
.dataTables_length {
display: none;
}
Both will work.
If you are using RESTful resources you can do the following:
redirect_to action_name_resource_path(resource_object, param_1: 'value_1', param_2: 'value_2')
or
#You can also use the object_id instead of the object
redirect_to action_name_resource_path(resource_object_id, param_1: 'value_1', param_2: 'value_2')
or
#if its a collection action like index, you can omit the id as follows
redirect_to action_name_resource_path(param_1: 'value_1', param_2: 'value_2')
#An example with nested resource is as follows:
redirect_to edit_user_project_path(@user, @project, param_1: 'value_1', param_2: 'value_2')
In your Spring @Configuration class which extends WebMvcConfigurerAdapter override the method configureMessageConverters, for instance:
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// http
HttpMessageConverter converter = new StringHttpMessageConverter();
converters.add(converter);
logger.info("HttpMessageConverter added");
// string
converter = new FormHttpMessageConverter();
converters.add(converter);
logger.info("FormHttpMessageConverter added");
// json
converter = new MappingJackson2HttpMessageConverter();
converters.add(converter);
logger.info("MappingJackson2HttpMessageConverter added");
}
And the error will be gone.
The problem may be that ssh is trying to connect to all the different IPs that www.google.com
resolves to. For example on my machine:
# ssh -v -o ConnectTimeout=1 -o ConnectionAttempts=1 www.google.com
OpenSSH_5.9p1, OpenSSL 0.9.8t 18 Jan 2012
debug1: Connecting to www.google.com [173.194.43.20] port 22.
debug1: connect to address 173.194.43.20 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.19] port 22.
debug1: connect to address 173.194.43.19 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.18] port 22.
debug1: connect to address 173.194.43.18 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.17] port 22.
debug1: connect to address 173.194.43.17 port 22: Connection timed out
debug1: Connecting to www.google.com [173.194.43.16] port 22.
debug1: connect to address 173.194.43.16 port 22: Connection timed out
ssh: connect to host www.google.com port 22: Connection timed out
If I run it with a specific IP, it returns much faster.
EDIT: I've timed it (with time
) and the results are:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.getJSON('people.json', function(data) {
$.each(data.person, function(i, f) {
var tblRow = "<tr>" + "<td>" + f.firstName + "</td>" +
"<td>" + f.lastName + "</td>" + "<td>" + f.job + "</td>" + "<td>" + f.roll + "</td>" + "</tr>"
$(tblRow).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" border="2">
<thead>
<th>First Name</th>
<th>Last Name</th>
<th>Email Address</th>
<th>City</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</body>
</html>
My JSON
file:
{
"person": [
{
"firstName": "Clark",
"lastName": "Kent",
"job": "Reporter",
"roll": 20
},
{
"firstName": "Bruce",
"lastName": "Wayne",
"job": "Playboy",
"roll": 30
},
{
"firstName": "Peter",
"lastName": "Parker",
"job": "Photographer",
"roll": 40
}
]
}
I succeeded in integrating a JSON
file to HTML
table after working a day on it!!!
Check out this list of lightbox plugins, depending on your exact requirements you can find the plugin of your choice from there easier than asking here. If you need a specific lightbox which can do just about anything and everything, try NyroModal.
On a high level, if you observe as to where normalization/standardization is mostly used, you will notice that, anytime there is a use of magnitude difference in model building process, it becomes necessary to standardize the inputs so as to ensure that important inputs with small magnitude don't loose their significance midway the model building process.
example:
v(3-1)^2+(1000-900)^2 ˜ v(1000-900)^2
Here, (3-1) contributes hardly a thing to the result and hence the input corresponding to these values is considered futile by the model.
Consider the following:
Both distance measure(Clustering) and cost function(NNs) use magnitude difference in some way and hence standardization ensures that magnitude difference doesn't command over important input parameters and the algorithm works as expected.
use this
@Temporal(TemporalType.TIMESTAMP)
@Column(name="create_date")
private Calendar createDate;
public Calendar getCreateDate() {
return createDate;
}
public void setCreateDate(Calendar createDate) {
this.createDate = createDate;
}
It labels whatever input is the parameter for the for
attribute.
<input id='myInput' type='radio'>_x000D_
<label for='myInput'>My 1st Radio Label</label>_x000D_
<br>_x000D_
<input id='input2' type='radio'>_x000D_
<label for='input2'>My 2nd Radio Label</label>_x000D_
<br>_x000D_
<input id='input3' type='radio'>_x000D_
<label for='input3'>My 3rd Radio Label</label>
_x000D_
Yes, there are negative effects from this:
If you script out a change blocked by this flag you get something like the script below (all i am turning the ID column in Contact into an autonumbered IDENTITY column, but the table has dependencies). Note potential errors that can occur while the following is running:
--
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_Contact_AddressType
GO
ALTER TABLE ref.ContactpointType SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Contact
DROP CONSTRAINT fk_contact_profile
GO
ALTER TABLE raw.Profile SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
CREATE TABLE raw.Tmp_Contact
(
ContactID int NOT NULL IDENTITY (1, 1),
ProfileID int NOT NULL,
AddressType char(2) NOT NULL,
ContactText varchar(250) NULL
) ON [PRIMARY]
GO
ALTER TABLE raw.Tmp_Contact SET (LOCK_ESCALATION = TABLE)
GO
SET IDENTITY_INSERT raw.Tmp_Contact ON
GO
IF EXISTS(SELECT * FROM raw.Contact)
EXEC('INSERT INTO raw.Tmp_Contact (ContactID, ProfileID, AddressType, ContactText)
SELECT ContactID, ProfileID, AddressType, ContactText FROM raw.Contact WITH (HOLDLOCK TABLOCKX)')
GO
SET IDENTITY_INSERT raw.Tmp_Contact OFF
GO
ALTER TABLE raw.PostalAddress
DROP CONSTRAINT fk_AddressProfile
GO
ALTER TABLE raw.MarketingFlag
DROP CONSTRAINT fk_marketingflag_contact
GO
ALTER TABLE raw.Phones
DROP CONSTRAINT fk_phones_contact
GO
DROP TABLE raw.Contact
GO
EXECUTE sp_rename N'raw.Tmp_Contact', N'Contact', 'OBJECT'
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact_1 PRIMARY KEY CLUSTERED
(
ProfileID,
ContactID
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
Idx_Contact UNIQUE NONCLUSTERED
(
ProfileID,
ContactID
)
GO
CREATE NONCLUSTERED INDEX idx_Contact_0 ON raw.Contact
(
AddressType
)
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_contact_profile FOREIGN KEY
(
ProfileID
) REFERENCES raw.Profile
(
ProfileID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Contact ADD CONSTRAINT
fk_Contact_AddressType FOREIGN KEY
(
AddressType
) REFERENCES ref.ContactpointType
(
ContactPointTypeCode
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.Phones ADD CONSTRAINT
fk_phones_contact FOREIGN KEY
(
ProfileID,
PhoneID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.Phones SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.MarketingFlag ADD CONSTRAINT
fk_marketingflag_contact FOREIGN KEY
(
ProfileID,
ContactID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.MarketingFlag SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE raw.PostalAddress ADD CONSTRAINT
fk_AddressProfile FOREIGN KEY
(
ProfileID,
AddressID
) REFERENCES raw.Contact
(
ProfileID,
ContactID
) ON UPDATE NO ACTION
ON DELETE NO ACTION
GO
ALTER TABLE raw.PostalAddress SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
start chrome https://www.google.com/
or start firefox https://www.google.com/
If using Anaconda, install with:
conda install PhantomJS
in your script:
from selenium import webdriver
driver=webdriver.PhantomJS()
works perfectly.
For Rails 4
The generator accepts column type as references (also available as belongs_to
).
This migration will create a user_id
column and appropriate index:
$ rails g migration AddUserRefToProducts user:references
generates:
class AddUserRefToProducts < ActiveRecord::Migration
def change
add_reference :products, :user, index: true
end
end
http://guides.rubyonrails.org/active_record_migrations.html#creating-a-standalone-migration
For Rails 3
Helper is called references (also available as belongs_to
).
This migration will create a category_id
column of the appropriate type. Note that you pass the model name, not the column name. Active Record adds the _id
for you.
change_table :products do |t|
t.references :category
end
If you have polymorphic belongs_to
associations then references will add both of the columns required:
change_table :products do |t|
t.references :attachment, :polymorphic => {:default => 'Photo'}
end
Will add an attachment_id column and a string attachment_type
column with a default value of Photo
.
http://guides.rubyonrails.org/v3.2.21/migrations.html#creating-a-standalone-migration
From all I have read you cannot do exactly what you want without javascript. If you float left before text
<div style="float:left;">widget</div> here is some CONTENT, etc.
Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content
here is some CONTENT, etc. <div style="float:left;">widget</div>
Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:
here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>
In your question you are using bootstrap which just adds row-fluid::after { content: ""}
which resolves the border/background issue.
Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/
<div class="container-fluid">
<div class="row-fluid">
<div class="offset1 span8 pull-right">
... Widget 1...
</div>
.... a lot of content ....
<div class="span8" style="margin-left: 0;">
... Widget 2...
</div>
</div>
</div><!--/.fluid-container-->
-> mysql -h host -u user -p database_name table_name < test_table.sql
Got a gotcha for those with their headspace in Pandas and moving to pyspark
from pyspark import SparkConf, SparkContext
from pyspark.sql import SQLContext
spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
sc = SparkContext(conf = spark_conf)
sqlContext = SQLContext(sc)
records = [
{"colour": "red"},
{"colour": "blue"},
{"colour": None},
]
pandas_df = pd.DataFrame.from_dict(records)
pyspark_df = sqlContext.createDataFrame(records)
So if we wanted the rows that are not red:
pandas_df[~pandas_df["colour"].isin(["red"])]
Looking good, and in our pyspark DataFrame
pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()
So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:
pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()
If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder.
If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using svnadmin dump
will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use svnadmin load
, which will essentially replay all the commits along with its metadata (author, timestamp, etc).
You can read more about the dump/load process here:
http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate
Also, if you do svnadmin load
, make sure you use the --force-uuid
option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository.
If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case.
I use this:
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
public class IconImageUtilities
{
public static void setIconImage(Window window)
{
try
{
InputStream imageInputStream = window.getClass().getResourceAsStream("/Icon.png");
BufferedImage bufferedImage = ImageIO.read(imageInputStream);
window.setIconImage(bufferedImage);
} catch (IOException exception)
{
exception.printStackTrace();
}
}
}
Just place your image called Icon.png
in the resources folder and call the above method with itself as parameter inside a class extending a class from the Window
family such as JFrame
or JDialog
:
IconImageUtilities.setIconImage(this);
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
You can use QString.arg like this
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", "Jane");
// You get "~/Tom-Jane.txt"
This method is preferred over sprintf because:
Changing the position of the string without having to change the ordering of substitution, e.g.
// To get "~/Jane-Tom.txt"
QString my_formatted_string = QString("%1/%3-%2.txt").arg("~", "Tom", "Jane");
Or, changing the type of the arguments doesn't require changing the format string, e.g.
// To get "~/Tom-1.txt"
QString my_formatted_string = QString("%1/%2-%3.txt").arg("~", "Tom", QString::number(1));
As you can see, the change is minimal. Of course, you generally do not need to care about the type that is passed into QString::arg() since most types are correctly overloaded.
One drawback though: QString::arg() doesn't handle std::string. You will need to call: QString::fromStdString() on your std::string to make it into a QString before passing it to QString::arg(). Try to separate the classes that use QString from the classes that use std::string. Or if you can, switch to QString altogether.
UPDATE: Examples are updated thanks to Frank Osterfeld.
UPDATE: Examples are updated thanks to alexisdm.
origin/master
is the remote master
branch
Usually after doing a git fetch origin
to bring all the changes from the server, you would do a git rebase origin/master
, to rebase your changes and move the branch to the latest index. Here, origin/master
is referring to the remote branch, because you are basically telling GIT to rebase the origin/master
branch onto the current branch.
You would use origin master
when pushing, for example. git push origin master
is simply telling GIT to push to the remote repository the local master
branch.
The basic principle of centering a page is to have a body CSS and main_container CSS. It should look something like this:
body {
margin: 0;
padding: 0;
text-align: center;
}
#main_container {
margin: 0 auto;
text-align: left;
}
The only way I know is by copying:
List<TestB> list = new ArrayList<TestB> (
Arrays.asList (
testAList.toArray(new TestB[0])
)
);
In JAVA, values like:
Is assumed as double and not float.
You can also perform a cast in order to solve the problem:
float b = (float) 3.5
;
Another solution:
float b = 3.5f
;
I understand that this error can occur because of many different reasons. In my case it was because I uninstalled WSUS service from Server Roles and the whole IIS went down. After doing a bit of research I found that uninstalling WSUS removes a few dlls which are used to do http compression. Since those dlls were missing and the IIS was still looking for them I did a reset using the following command in CMD:
appcmd set config -section:system.webServer/httpCompression /-[name='xpress']
Bingo! The problem is sorted now. Dont forget to run it as an administrator. You might also need to do "iisreset" as well. Just in case.
Hope it helps others. Cheers
Maybe the definition is at fault.
From my experience, I would separate the two as being hardware and software dependant.
If you have 200ms to service a hardware driven interrupt, that is what you've got. You stick 300ms of code in there and the system isn't broken, it hasn't been developed. You'll be switched out before you've finished. Your code doesn't work or is not fit for purpose. Many systems have hard defined processing periods. Video, telecoms etc.
If you're writing an application that's real-time, this could be considered soft. If you run out of time you could hope for less load next time, you could tune the OS, add some memory or even upgrade the hardware. You have options.
To look at it from a UX perspective is not helpful. A Skoda might not be broken if it glitches, but a BMW sure as hell will be.
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
try this
UIWindow *window = [[[UIApplication sharedApplication] windows] lastObject];
In my case even after following all of the above. I had to upgrade my project from .net 3.5 to .net 4 to authorize against our internal exchange 2010 mail server.
http://formatmysourcecode.blogspot.co.uk/ works fine, you just copy , format, paste back.
name() is literally the textual name in the java code of the enum. That means it is limited to strings that can actually appear in your java code, but not all desirable strings are expressible in code. For example, you may need a string that begins with a number. name() will never be able to obtain that string for you.
You can define pattern and check for it. Here I have taken both start and end pattern and looking for them in the filename. FILES contains the list of all the files in a directory.
import os
PATTERN_START = "145592"
PATTERN_END = ".jpg"
CURRENT_DIR = os.path.dirname(os.path.realpath(__file__))
for r,d,FILES in os.walk(CURRENT_DIR):
for FILE in FILES:
if PATTERN_START in FILE.startwith(PATTERN_START) and PATTERN_END in FILE.endswith(PATTERN_END):
print FILE
You could try my Beavertail ADSI browser - it should show you the current AD tree, and from it, you should be able to figure out the path and all.
Or if you're on .NET 3.5, using the System.DirectoryServices.AccountManagement
namespace, you could also do it programmatically:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
This would create a basic, default domain context and you should be able to peek at its properties and find a lot of stuff from it.
Or:
UserPrincipal myself = UserPrincipal.Current;
This will give you a UserPrincipal
object for yourself, again, with a ton of properties to inspect. I'm not 100% sure what you're looking for - but you most likely will be able to find it on the context or the user principal somewhere!
The data returned by the JSON is in json format : which is simply an arrays of values. Thats why you are seeing [object Object],[object Object],[object Object].
You have to iterate through that values to get actuall value. Like the following
jQuery provides $.each() for iterations, so you could also do this:
$.getJSON("url_with_json_here", function(data){
$.each(data, function (linktext, link) {
console.log(linktext);
console.log(link);
});
});
Now just create an Hyperlink using that info.
You don't say what language you're using, but looking at that output, it looks like PHP output (from print_r()
).
If so, just use unset()
:
unset($arr[1]);
DateTime.new(2012, 1, 15).to_time.to_i
You should do ex.StackTrace instead of ex.ToString()
def getUser(self, id, Email):
user_key = id and id or Email
assert user_key
Can be used to ensure parameters are passed in the function call.
No need for ajax. You can create a new image element, set its source attribute and place it somewhere in the document once it has finished loading:
var img = $("<img />").attr('src', 'http://somedomain.com/image.jpg')
.on('load', function() {
if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) {
alert('broken image!');
} else {
$("#something").append(img);
}
});
Visual studio is the most up to date and probably "best" free ide. Dev C++ is a little dated, and mingw doesn't compile most of boost, (except regex). Most of the other compilers are dated and fading, like mars and borland. But you can use whatever you like!
Here's a simple way using ngModel
(final Angular 2)
<!-- my.component.html -->
<div class="form-group">
<label for="options">Options:</label>
<div *ngFor="let option of options">
<label>
<input type="checkbox"
name="options"
value="{{option.value}}"
[(ngModel)]="option.checked"/>
{{option.name}}
</label>
</div>
</div>
// my.component.ts
@Component({ moduleId:module.id, templateUrl:'my.component.html'})
export class MyComponent {
options = [
{name:'OptionA', value:'1', checked:true},
{name:'OptionB', value:'2', checked:false},
{name:'OptionC', value:'3', checked:true}
]
get selectedOptions() { // right now: ['1','3']
return this.options
.filter(opt => opt.checked)
.map(opt => opt.value)
}
}
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
In order to get my modal to display when calling .modal('show')
I changed:
modal.on('loaded.bs.modal', function()
to:
modal.on('shown.bs.modal', function() {
you need length() function
select length(customer_name) from ar.ra_customers
Change to root build.gradle file
to
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.5.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
I guess you are using an old version of hibernate. You can download the latest version, 5.2, from here.
Yes, in your formula
, you can cbind
the numeric variables to be aggregated:
aggregate(cbind(x1, x2) ~ year + month, data = df1, sum, na.rm = TRUE)
year month x1 x2
1 2000 1 7.862002 -7.469298
2 2001 1 276.758209 474.384252
3 2000 2 13.122369 -128.122613
...
23 2000 12 63.436507 449.794454
24 2001 12 999.472226 922.726589
See ?aggregate
, the formula
argument and the examples.
Binding events from html is NOT recommended. This is recommended way:
document.getElementById('btn').addEventListener('click', function(){
pay();
cls();
});
One more addition: if you need to sync files by its extensions in one dir only (without of recursion) you should use a construction like this:
rsync -auzv --include './' --include '*.ext' --exclude '*' /source/dir/ /destination/dir/
Pay your attention to the dot in the first --include
. --no-r
does not work in this construction.
EDIT:
Thanks to gbyte.co for the valuable comment!