Very common problem in android
It can be broken down into 3 Pieces
1 ) start Activity B (Happens in Activity A)
2 ) Set requested data (Happens in activity B)
3 ) Receive requested data (Happens in activity A)
1) startActivity B
Intent i = new Intent(A.this, B.class);
startActivity(i);
2) Set requested data
In this part, you decide whether you want to send data back or not when a particular event occurs.
Eg: In activity B there is an EditText and two buttons b1, b2.
Clicking on Button b1 sends data back to activity A
Clicking on Button b2 does not send any data.
Sending data
b1......clickListener
{
Intent resultIntent = new Intent();
resultIntent.putExtra("Your_key","Your_value");
setResult(RES_CODE_A,resultIntent);
finish();
}
Not sending data
b2......clickListener
{
setResult(RES_CODE_B,new Intent());
finish();
}
user clicks back button
By default, the result is set with Activity.RESULT_CANCEL response code
3) Retrieve result
For that override onActivityResult method
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RES_CODE_A) {
// b1 was clicked
String x = data.getStringExtra("RES_CODE_A");
}
else if(resultCode == RES_CODE_B){
// b2 was clicked
}
else{
// back button clicked
}
}
Use the M0Rf30/android-udev-rules
GitHub community maintained udev-rules
https://github.com/M0Rf30/android-udev-rules/blob/master/51-android.rules
This is the most complete udev-rules list I've seen so far, even more than the currently recommended sudo apt-get install android-tools-adb
on the official documentation, and it solved that problem for me.
Everyone mentions zenity, there seem to be many others. A mixed up but interesting list is at http://alternativeto.net/software/zenity/
First, an example of zenity featuring text formatting markup, window title, button label.
zenity \
--info \
--text="<span size=\"xx-large\">Time is $(date +%Hh%M).</span>\n\nGet your <b>coffee</b>." \
--title="Coffee time" \
--ok-label="Sip"
gxmessage "my text"
xmessage
is very old so it is stable and probably available in all distributions that use X (since it's distributed with X). It is customizable through X resources, for those that have been using Linux or Unix for long enough to know what it means (.Xdefaults
, anyone ?).
xmessage -buttons Ok:0,"Not sure":1,Cancel:2 -default Ok -nearmouse "Is xmessage enough for the job ?" -timeout 10
(not tested)
YAD: Zenity On Steroids [Display Graphical Dialogs From Shell Scripts] ~ Web Upd8: Ubuntu / Linux blog. Does not seem to auto-size dialogs.
echo My text | yad \
--text-info \
--width=400 \
--height=200
An bigger example
yad \
--title="Desktop entry editor" \
--text="Simple desktop entry editor" \
--form \
--field="Type:CB" \
--field="Name" \
--field="Generic name" \
--field="Comment" \
--field="Command:FL" \
--field="Icon" \
--field="In terminal:CHK" \
--field="Startup notify:CHK" "Application" "Name" "Generic name" "This is the comment" "/usr/bin/yad" "yad" FALSE TRUE \
--button="WebUpd8:2" \
--button="gtk-ok:0" \
--button="gtk-cancel:1"
whiptail --msgbox "my text" 10 20
dialog --msgbox "my text" 10 20
Feel free to edit.
Run
gradlew -q app:dependencies
It will remove what is wrong.
function copyToClipboard(text) {
var dummy = document.createElement("textarea");
// to avoid breaking orgain page when copying more words
// cant copy when adding below this code
// dummy.style.display = 'none'
document.body.appendChild(dummy);
//Be careful if you use texarea. setAttribute('value', value), which works with "input" does not work with "textarea". – Eduard
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
copyToClipboard('hello world')
copyToClipboard('hello\nworld')
The usual way would be:
if (a instanceof A)
However, there are cases when you can't do this, such as when A
in a generic argument.
Due to Java's type erasure, the following won't compile:
<A> boolean someMethod(Object a) {
if (a instanceof A)
...
}
and the following won't work (and will produce an unchecked cast
warning):
<A> void someMethod(Object a) {
try {
A casted = (A)a;
} catch (ClassCastException e) {
...
}
}
You can't cast to A
at runtime, because at runtime, A
is essentially Object
.
The solutions to such cases is to use a Class
instead of the generic argument:
void someMethod(Object a, Class<A> aClass) {
if (aClass.isInstance(a)) {
A casted = aClass.cast(a);
...
}
}
You can then call the method as:
someMethod(myInstance, MyClass.class);
someMethod(myInstance, OtherClass.class);
The provided answer is absolutely correct, but I wanted to expand for any future visitors who may want to do it a bit more dynamically -
In the view -
<div ng-repeat="person in persons">
<div ng-click="changeView(person)">
Go to edit
<div>
<div>
In the controller -
$scope.changeView = function(person){
var earl = '/editperson/' + person.id;
$location.path(earl);
}
Same basic concept as the accepted answer, just adding some dynamic content to it to improve a bit. If the accepted answer wants to add this I will delete my answer.
Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().
std::string mystring;
mystring = "This is a test!"; // Assign C string to std:string directly
std::cout << mystring << '\n';
Login Page design using SwiftUI
import SwiftUI
struct ContentView: View {
@State var email: String = "[email protected]"
@State var password: String = ""
@State static var labelTitle: String = ""
var body: some View {
VStack(alignment: .center){
//Label
Text("Login").font(.largeTitle).foregroundColor(.yellow).bold()
//TextField
TextField("Email", text: $email)
.textContentType(.emailAddress)
.foregroundColor(.blue)
.frame(minHeight: 40)
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
TextField("Password", text: $password) //Placeholder
.textContentType(.newPassword)
.frame(minHeight: 40)
.foregroundColor(.blue) // Text color
.background(RoundedRectangle(cornerRadius: 10).foregroundColor(Color.green))
//Button
Button(action: {
}) {
HStack {
Image(uiImage: UIImage(named: "Login")!)
.renderingMode(.original)
.font(.title)
.foregroundColor(.blue)
Text("Login")
.font(.title)
.foregroundColor(.white)
}
.font(.headline)
.frame(minWidth: 0, maxWidth: .infinity)
.background(LinearGradient(gradient: Gradient(colors: [Color("DarkGreen"), Color("LightGreen")]), startPoint: .leading, endPoint: .trailing))
.cornerRadius(40)
.padding(.horizontal, 20)
.frame(width: 200, height: 50, alignment: .center)
}
Spacer()
}.padding(10)
.frame(minWidth: 0, idealWidth: .infinity, maxWidth: .infinity, minHeight: 0, idealHeight: .infinity, maxHeight: .infinity, alignment: .top)
.background(Color.gray)
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
I made a convenient underscore mixin for this.
_.isIE(); // Any version of IE?
_.isIE(9); // IE 9?
_.isIE([7,8,9]); // IE 7, 8 or 9?
_.mixin({_x000D_
isIE: function(mixed) {_x000D_
if (_.isUndefined(mixed)) {_x000D_
mixed = [7, 8, 9, 10, 11];_x000D_
} else if (_.isNumber(mixed)) {_x000D_
mixed = [mixed];_x000D_
}_x000D_
for (var j = 0; j < mixed.length; j++) {_x000D_
var re;_x000D_
switch (mixed[j]) {_x000D_
case 11:_x000D_
re = /Trident.*rv\:11\./g;_x000D_
break;_x000D_
case 10:_x000D_
re = /MSIE\s10\./g;_x000D_
break;_x000D_
case 9:_x000D_
re = /MSIE\s9\./g;_x000D_
break;_x000D_
case 8:_x000D_
re = /MSIE\s8\./g;_x000D_
break;_x000D_
case 7:_x000D_
re = /MSIE\s7\./g;_x000D_
break;_x000D_
}_x000D_
_x000D_
if (!!window.navigator.userAgent.match(re)) {_x000D_
return true;_x000D_
}_x000D_
}_x000D_
_x000D_
return false;_x000D_
}_x000D_
});_x000D_
_x000D_
console.log(_.isIE());_x000D_
console.log(_.isIE([7, 8, 9]));_x000D_
console.log(_.isIE(11));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
_x000D_
I had the same issue "Cannot create a connection to data source...Login failed for user.." on Windows 8.1, SQL Server 2014 Developer Edition and Visual Studio 2013 Pro. All solutions offered above by other Stackoverflow Community members did not work for me.
So, I did the next steps (running all Windows applications as Administrator):
VS2013 SSRS: I converted my Data Source to Shared Data Source (.rds) with Windows Authentication (Integrated Security) on the Right Pane "Solution Explorer".
Original (non-shared) Data Source (on the Left Pane "Report Data") got "Don't Use Credentials".
On the Project Properties, I set for "Deployment" "Overwrite DataSources" to "True" and redeployed the Project.
After that, I could run my report without further requirements to enter Credentials. All Shared DataSources were deployed in a separate Directory "DataSources".
You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):
void test(const std::vector<int>& in) {
// Iterate over vector and do whatever
}
becomes:
template <typename Iterator>
void test(Iterator begin, const Iterator end) {
// Iterate over range and do whatever
}
template <typename Container>
void test(const Container& in) {
test(std::begin(in), std::end(in));
}
Which lets you do:
int x[3]={1, 2, 3};
test(x); // Now correct
There is a built in method which would be the fastest method also, calling tolist
on the .values
np array:
df.values.tolist()
[[0.0, 3.61, 380.0, 3.0],
[1.0, 3.67, 660.0, 3.0],
[1.0, 3.19, 640.0, 4.0],
[0.0, 2.93, 520.0, 4.0]]
I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.
The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.
Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.
Yes, it is safe to simply delete anything that distutils installed. That goes for installed folders or .egg files. Naturally anything that depends on that code will no longer work.
If you want to make it work again, simply re-install.
By the way, if you are using distutils also consider using the multi-version feature. It allows you to have multiple versions of any single package installed. That means you do not need to delete an old version of a package if you simply want to install a newer version.
Perhaps you don't have to include the single quotes:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"
Update: Reading curl's manual, you could actually separate both fields with two --data:
curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"
You could also try --data-binary:
curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"
And --data-urlencode:
curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"
Using like might take longer time so use full_text_search:
SELECT * FROM items WHERE MATCH(items.xml) AGAINST ('your_search_word')
clear() will be much more efficient. It will simply remove each and every item. Using removeAll(arraylist) will take a lot more work because it will check every item in arraylist to see if it exists in arraylist before removing it.
After installing socket.io-client:
npm install socket.io-client
This is how the client code looks like:
var io = require('socket.io-client'),
socket = io.connect('localhost', {
port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });
Thanks alessioalex.
You are missing a field annotated with @Id
. Each @Entity
needs an @Id
- this is the primary key in the database.
If you don't want your entity to be persisted in a separate table, but rather be a part of other entities, you can use @Embeddable
instead of @Entity
.
If you want simply a data transfer object to hold some data from the hibernate entity, use no annotations on it whatsoever - leave it a simple pojo.
Update: In regards to SQL views, Hibernate docs write:
There is no difference between a view and a base table for a Hibernate mapping. This is transparent at the database level
I've had great success with wsdl2php. It will automatically create wrapper classes for all objects and methods used in your web service.
You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB
You can dowload the update here
I think you are near to a possible solution.
Execute mainloop
in a separate thread and extend it with the property shutdown_flag
. The signal can be caught with signal.signal(signal.SIGTERM, handler)
in the main thread (not in a separate thread). The signal handler should set shutdown_flag
to True and wait for the thread to end with thread.join()
I resolve the issue by restarting Docker.
Maybe you forgot the await before returning your collection
Using merge is risky and tricky, so it's a dirty workaround in your case. You need to remember at least that when you pass an entity object to merge, it stops being attached to the transaction and instead a new, now-attached entity is returned. This means that if anyone has the old entity object still in their possession, changes to it are silently ignored and thrown away on commit.
You are not showing the complete code here, so I cannot double-check your transaction pattern. One way to get to a situation like this is if you don't have a transaction active when executing the merge and persist. In that case persistence provider is expected to open a new transaction for every JPA operation you perform and immediately commit and close it before the call returns. If this is the case, the merge would be run in a first transaction and then after the merge method returns, the transaction is completed and closed and the returned entity is now detached. The persist below it would then open a second transaction, and trying to refer to an entity that is detached, giving an exception. Always wrap your code inside a transaction unless you know very well what you are doing.
Using container-managed transaction it would look something like this. Do note: this assumes the method is inside a session bean and called via Local or Remote interface.
@TransactionAttribute(TransactionAttributeType.REQUIRED)
public void storeAccount(Account account) {
...
if (account.getId()!=null) {
account = entityManager.merge(account);
}
Transaction transaction = new Transaction(account,"other stuff");
entityManager.persist(account);
}
How about this:
String filenameWithoutExtension = null;
String fullname = new File(
new URI("http://www.xyz.com/some/deep/path/to/abc.png").getPath()).getName();
int lastIndexOfDot = fullname.lastIndexOf('.');
filenameWithoutExtension = fullname.substring(0,
lastIndexOfDot == -1 ? fullname.length() : lastIndexOfDot);
The data still exists out in github, you can create a new branch from the old data:
git checkout origin/BranchName #get a readonly pointer to the old branch
git checkout –b BranchName #create a new branch from the old
git push origin BranchName #publish the new branch
Another way to get around this problem, if you are using some server side scripting language that allows you to manipulate the posted data, is to declare your html form like this :
<form>
<input name="a_name"/>
<input name="a_second_name"/>
<input name="subform[another_name]"/>
<input name="subform[another_second_name]"/>
</form>
If you print the posted data (I will use PHP here), you will get an array like this :
//print_r($_POST) will output :
array(
'a_name' => 'a_name_value',
'a_second_name' => 'a_second_name_value',
'subform' => array(
'another_name' => 'a_name_value',
'another_second_name' => 'another_second_name_value',
),
);
Then you can just do something like :
$my_sub_form_data = $_POST['subform'];
unset($_POST['subform']);
Your $_POST now has only your "main form" data, and your subform data is stored in another variable you can manipulate at will.
Hope this helps!
var json = {
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
};
$.each(json.people.person, function(i, v) {
if (v.name == "Peter") {
alert(v.age);
return;
}
});
Based on this answer, you could use something like:
$(function() {
var json = {
"people": {
"person": [{
"name": "Peter",
"age": 43,
"sex": "male"},
{
"name": "Zara",
"age": 65,
"sex": "female"}]
}
};
$.each(json.people.person, function(i, v) {
if (v.name.search(new RegExp(/peter/i)) != -1) {
alert(v.age);
return;
}
});
});
You can also see this error when selecting for a union where corresponding columns can be null.
select * from (select D.dept_no, D.nullable_comment
from dept D
union
select R.dept_no, NULL
from redundant_dept R
)
This apparently confuses the parser, a solution is to assign a column alias to the always null column.
select * from (select D.dept_no, D.comment
from dept D
union
select R.dept_no, NULL "nullable_comment"
from redundant_dept R
)
The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.
I think the best option for you is to enclose both divs by another div. Then you can make it by CSS in the following way:
<html>
<head>
<style>
div.both:hover .image { border: 1px solid blue }
div.both:hover .layer { border: 1px solid blue }
</style>
</head>
<body>
<div class="section">
<div class="both">
<div class="image"><img src="myImage.jpg" /></div>
<div class="layer">Lorem Ipsum</div>
</div>
</div>
</body>
</html>
You could try removing any alphanumeric characters and space. And then use -n
will give you the line number. Try following:
grep -vn "^[a-zA-Z0-9 ]*$" application.log
For me the following seemed to work.
git pull --tags
In Linux systems, you can use file command. It will give the correct encoding
Sample:
file blah.csv
Output:
blah.csv: ISO-8859 text, with very long lines
Another option is to repeat the rules in two prefix locations using an included file. Since prefix locations are position independent in the configuration, using them can save some confusion as you add other regex locations later on. Avoiding regex locations when you can will help your configuration scale smoothly.
server {
location /first/location/ {
include shared.conf;
}
location /second/location/ {
include shared.conf;
}
}
Here's a sample shared.conf:
default_type text/plain;
return 200 "http_user_agent: $http_user_agent
remote_addr: $remote_addr
remote_port: $remote_port
scheme: $scheme
nginx_version: $nginx_version
";
With AutoEventWireup
which is turned on by default on a page you can just add methods prepended with **Page_***event* and have ASP.NET connect to the events for you.
In the case of Unload the method signature is:
protected void Page_Unload(object sender, EventArgs e)
For details see the MSDN article.
Java, unlike languages like C and C++, treats boolean
as a completely separate data type which has 2 distinct values: true and false. The values 1 and 0 are of type int and are not implicitly convertible to boolean
.
Unless you have GNU awk 4.1.0 or later...
You won't have such an option as sed's -i
option so instead do:
$ awk '{print $0}' file > tmp && mv tmp file
Note: the -i
is not magic, it is also creating a temporary file sed
just handles it for you.
As of GNU awk 4.1.0...
GNU awk
added this functionality in version 4.1.0 (released 10/05/2013). It is not as straight forwards as just giving the -i
option as described in the released notes:
The new -i option (from xgawk) is used for loading awk library files. This differs from -f in that the first non-option argument is treated as a script.
You need to use the bundled inplace.awk
include file to invoke the extension properly like so:
$ cat file
123 abc
456 def
789 hij
$ gawk -i inplace '{print $1}' file
$ cat file
123
456
789
The variable INPLACE_SUFFIX
can be used to specify the extension for a backup file:
$ gawk -i inplace -v INPLACE_SUFFIX=.bak '{print $1}' file
$ cat file
123
456
789
$ cat file.bak
123 abc
456 def
789 hij
I am happy this feature has been added but to me, the implementation isn't very awkish as the power comes from the conciseness of the language and -i inplace
is 8 characters too long i.m.o.
Here is a link to the manual for the official word.
I know this is an old question, but I wanted to add ServiceCapture to the list, for those who may come across this.
I've been using ServiceCapture for about 4 years and love it. It's not free, but it is a great tool and not very expensive. If you debug a lot of Flash or AJAX apps it is invaluable.
That entity is converted to the char it represents when the browser renders the page. JS (jQuery) reads the rendered page, thus it will not encounter such a text sequence. The only way it could encounter such a thing is if you're double encoding entities.
For any situation where you have an unknown string and you need to figure out which of a bunch of other strings it matches up to, the only solution which doesn't get slower as you add more items is to use an array, but have all the possible strings as keys. So your switch can be replaced with the following:
// used for $current_home = 'current';
$group1 = array(
'home' => True,
);
// used for $current_users = 'current';
$group2 = array(
'users.online' => True,
'users.location' => True,
'users.featured' => True,
'users.new' => True,
'users.browse' => True,
'users.search' => True,
'users.staff' => True,
);
// used for $current_forum = 'current';
$group3 = array(
'forum' => True,
);
if(isset($group1[$p]))
$current_home = 'current';
else if(isset($group2[$p]))
$current_users = 'current';
else if(isset($group3[$p]))
$current_forum = 'current';
else
user_error("\$p is invalid", E_USER_ERROR);
This doesn't look as clean as a switch()
, but it is the only fast solution which doesn't include writing a small library of functions and classes to keep it tidy. It is still very easy to add items to the arrays.
bma answer is great! I have used it with ActiveRecords, here it is if anybody needs it in Rails:
Model.find_by_sql(
"SELECT TO_CHAR(created_at, 'Mon') AS month,
EXTRACT(year from created_at) as year,
SUM(desired_value) as desired_value
FROM desired_table
GROUP BY 1,2
ORDER BY 1,2"
)
You can use a subquery. The subquery will get the Max(CompletedDate)
. You then take this value and join on your table again to retrieve the note associate with that date:
select ET1.TrainingID,
ET1.CompletedDate,
ET1.Notes
from HR_EmployeeTrainings ET1
inner join
(
select Max(CompletedDate) CompletedDate, TrainingID
from HR_EmployeeTrainings
--where AvantiRecID IS NULL OR AvantiRecID = @avantiRecID
group by TrainingID
) ET2
on ET1.TrainingID = ET2.TrainingID
and ET1.CompletedDate = ET2.CompletedDate
where ET1.AvantiRecID IS NULL OR ET1.AvantiRecID = @avantiRecID
The setOnPageChangeListener() method is deprecated. Use addOnPageChangeListener(OnPageChangeListener) instead.
You can use OnPageChangeListener and getting the position inside onPageSelected()
method, this is an example:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
Log.d(TAG, "my position is : " + position);
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
Or just use getCurrentItem() to get the real position:
viewPager.getCurrentItem();
I'm not with computer,so I write a draft. You might be clear of what I say.
func main(){
const dir = "/etc/"
filesInfo, e := ioutil.ReadDir(dir)
var fileNames = make([]string, 0, 10)
for i,v:=range filesInfo{
if !v.IsDir() {
fileNames = append(fileNames, v.Name())
}
}
var fileNumber = len(fileNames)
var contents = make([]string, fileNumber, 10)
wg := sync.WaitGroup{}
wg.Add(fileNumber)
for i,_:=range content {
go func(i int){
defer wg.Done()
buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
defer file.Close()
content[i] = string(buf)
}(i)
}
wg.Wait()
}
function parseQueryString(queryString) {
if (!queryString) {
return false;
}
let queries = queryString.split("&"), params = {}, temp;
for (let i = 0, l = queries.length; i < l; i++) {
temp = queries[i].split('=');
if (temp[1] !== '') {
params[temp[0]] = temp[1];
}
}
return params;
}
I use this.
Edit Include path
Compiler path
JavaFX8
I'm adding new Item by a DialogBox. Here is my code.
ObservableList<Area> area = FXCollections.observableArrayList();
At initialize() or setApp()
this.areaTable.setItems(getAreaData());
getAreaData()
private ObservableList<Area> getAreaData() {
try {
area = AreaDAO.searchEmployees(); // To inform ObservableList
return area;
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error: " + e);
return null;
}
}
Add by dialog box.
@FXML
private void handleNewArea() {
Area tempArea = new Area();
boolean okClicked = showAreaDialog(tempArea);
if (okClicked) {
addNewArea(tempArea);
this.area.add(tempArea); // To inform ObservableList
}
}
Area
is an ordinary JavaFX POJO.
Hope this helps someone.
command in one line:
ftp -in -u ftp://username:password@servername/path/to/ localfile
To understand why xmlns:android=“http://schemas.android.com/apk/res/android”
must be the first in the layout xml file We shall understand the components using an example
Sample
::
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/container" >
</FrameLayout>
Uniform Resource Indicator(URI):
Ex:http://schemas.android.com/apk/res/android:id
is the URI here
xmlns:android
describes the android
namespace.textview
widget with different
features compared to android textview
, android namespace helps to
distinguish between our custom textview
widget and android
textview
widgetIt means litraly that, your trying to use the wrong http verb when accessing some http content. A lot of content on webservices you need to use a POST
to consume. I suspect your trying to access the facebook API using the wrong http verb.
SELECT * FROM `calendar` WHERE startTime like '2010-04-29%'
You can also use comparison operators on MySQL dates if you want to find something after or before. This is because they are written in such a way (largest value to smallest with leading zeros) that a simple string sort will sort them correctly.
there are two ways of doing it either you can use XML or Java for it. If it's static and requires no changes then you can initialize in XML.
android:drawableLeft="@drawable/cloud_up"
android:drawablePadding="5sp"
Now if you need to change the icons dynamically then you can do it by calling the icons based on the events
textViewContext.setText("File Uploaded");
textViewContext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uploaded, 0, 0, 0);
Use ls -s
to list file size, or if you prefer ls -sh
for human readable sizes.
For directories use du
, and again, du -h
for human readable sizes.
That's the way I did it with pure JS:
var files = document.getElementById('filePoster');_x000D_
var submit = document.getElementById('submitFiles');_x000D_
var warning = document.getElementById('warning');_x000D_
files.addEventListener("change", function () {_x000D_
if (files.files.length > 10) {_x000D_
submit.disabled = true;_x000D_
warning.classList += "warn"_x000D_
return;_x000D_
}_x000D_
submit.disabled = false;_x000D_
});
_x000D_
#warning {_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#warning.warn {_x000D_
color: red;_x000D_
transform: scale(1.5);_x000D_
transition: 1s all;_x000D_
}
_x000D_
<section id="shortcode-5" class="shortcode-5 pb-50">_x000D_
<p id="warning">Please do not upload more than 10 images at once.</p>_x000D_
<form class="imagePoster" enctype="multipart/form-data" action="/gallery/imagePoster" method="post">_x000D_
<div class="input-group">_x000D_
<input id="filePoster" type="file" class="form-control" name="photo" required="required" multiple="multiple" />_x000D_
<button id="submitFiles" class="btn btn-primary" type="submit" name="button">Submit</button>_x000D_
</div>_x000D_
</form>_x000D_
</section>
_x000D_
I also want to do the same thing: migrate a db from a standalone redis instance to a another redis instances(redis sentinel).
Because the data is not critical(session data), i will give https://github.com/yaauie/redis-copy a try.
Try:
gradle assemble
To list all available tasks for your project, try:
gradle tasks
UPDATE:
This may not seem the most correct answer at first, but read carefully gradle tasks
output or docs.
Build tasks
-----------
assemble - Assembles the outputs of this project.
build - Assembles and tests this project.
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
SessionFactory
vs. EntityManagerFactory
As I explained in the Hibernate User Guide, the Hibernate SessionFactory
extends the JPA EntityManagerFactory
, as illustrated by the following diagram:
So, the SessionFactory
is also a JPA EntityManagerFactory
.
Both the SessionFactory
and the EntityManagerFactory
contain the entity mapping metadata and allow you to create a Hibernate Session
or a EntityManager
.
Session
vs. EntityManager
Just like the SessionFactory
and EntityManagerFactory
, the Hibernate Session
extends the JPA EntityManager
. So, all methods defined by the EntityManager
are available in the Hibernate Session
.
The Session
and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.
When bootstrapping a JPA or Hibernate application, you have two choices:
SessionFactory
via the BootstrapServiceRegistryBuilder
. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean
, as illustrated by this GitHub example.EntityManagerFactory
via the Persistence
class or the EntityManagerFactoryBuilder
. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean
, as illustrated by this GitHub example.Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO
is a much better choice than the legacy FlushMode.AUTO
, which breaks read-your-writes consistency for native SQL queries.
Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory
via the @PersistenceUnit
annotation:
@PersistenceUnit
private EntityManagerFactory entityManagerFactory;
You can easily get access to the underlying Sessionfactory
using the unwrap
method:
SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);
The same can be done with the JPA EntityManager
. If you inject the EntityManager
via the @PersistenceContext
annotation:
@PersistenceContext
private EntityManager entityManager;
You can easily get access to the underlying Session
using the unwrap
method:
Session session = entityManager.unwrap(Session.class);
So, you should bootstrap via JPA, use the EntityManagerFactory
and EntityManager
, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
Another option is to make use of the $hidden
property on the model to hide the columns you don't want to display. You can define this property on the fly or set defaults on your model.
public static $hidden = array('password');
Now the users password will be hidden when you return the JSON response.
You can also set it on the fly in a similar manner.
User::$hidden = array('password');
I made this procedure for us to use at work.
cd ~
curl -s https://pypi.python.org/packages/source/p/pip/pip-1.3.1.tar.gz | tar xvz
cd pip-1.3.1
python setup.py install --user
cd ~
rm -rf pip-1.3.1
$HOME/.local/bin/pip install --user --upgrade pip distribute virtualenvwrapper
# Might want these three in your .bashrc
export PATH=$PATH:$HOME/.local/bin
export VIRTUALENVWRAPPER_VIRTUALENV_ARGS="--distribute"
source $HOME/.local/bin/virtualenvwrapper.sh
mkvirtualenv mypy
workon mypy
pip install --upgrade distribute
pip install pudb # Or whatever other nice package you might want.
Key points for the security minded:
You can pass GetDate()
function as an parameter to your insert query
e.g
Insert into table (col1,CreatedOn) values (value1,Getdate())
adding muted="muted"
property to HTML5 tag solved my issue
Adding something to the above correct answers. I am using netbeans IDE and it shows error while using url(#{$assetPath}/site/background.jpg)
this method. It was just netbeans error and no error in sass compiling. But this error break code formatting in netbeans and code become ugly. But when I use it inside quotes like below, it show wonder!
url("#{$assetPath}/site/background.jpg")
The following query will fetch all Stored Procedure names and the corresponding definition of those SP's
select
so.name,
text
from
sysobjects so,
syscomments sc
where
so.id = sc.id
and UPPER(text) like '%<TABLE NAME>%'
to check with the prefix as in the iPhone ContactApp
([string rangeOfString:prefixString options:NSCaseInsensitiveSearch].location == 0)
this blog was useful for me
For Ubuntu 20.04 users with php-fpm I fixed the issue by adding the full path in the php conf:
edit /etc/php/7.4/fpm/conf.d/20-mysqli.ini
and replace
extension=mysqli.so
with:
extension=/usr/lib/php/20190902/mysqli.so
ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.
I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.
Quick and working solution for me, was just simply double redirect. I created 2 files: fb-go.php
and fb-redirect.php
Where fb-go.php
looked like:
session_start();
$_SESSION['FBRLH_state'] = 'some_unique_string_for_each_call';
header('Location: fb-redirect.php');
and fb-redirect:
session_start();
header('Location: FULL_facebook_url_with_' . $_SESSION['FBRLH_state'] . '_value');
Also worth to mention is Android Chrome browser behavior. Where user can see something like that:
If user will chose Facebook app, then session is lost, because of opening in Facebook browser - not Chrome, which is storing user session data.
To determine the class of an object simply call:
someObject.getClass()
You can abbreviate this to someObject.class
in most cases. However, if you use this on a Map
it will try to retrieve the value with key 'class'. Because of this, I always use getClass()
even though it's a little longer.
If you want to check if an object implements a particular interface or extends a particular class (e.g. Date) use:
(somObject instanceof Date)
or to check if the class of an object is exactly a particular class (not a subclass of it), use:
(somObject.getClass() == Date)
In KOTLIN:- If you want to save Token into DB or shared preferences then override onNewToken in FirebaseMessagingService
override fun onNewToken(token: String) {
super.onNewToken(token)
}
Get token at run-time,use
FirebaseInstanceId.getInstance().instanceId
.addOnSuccessListener(this@SplashActivity) { instanceIdResult ->
val mToken = instanceIdResult.token
println("printing fcm token: $mToken")
}
If you really should use Double instead of double you even can get the int Value of Double by calling:
Double d = new Double(1.23);
int i = d.intValue();
Else its already described by Peter Lawreys answer.
Using {dplyr}:
library(dplyr)
# percentiles
infert %>%
mutate(PCT = ntile(age, 100))
# quartiles
infert %>%
mutate(PCT = ntile(age, 4))
# deciles
infert %>%
mutate(PCT = ntile(age, 10))
You can create your jar without Main-Class in its Manifest file. Then :
java -cp MyJar.jar com.mycomp.myproj.dir2.MainClass2 /home/myhome/datasource.properties /home/myhome/input.txt
This worked for me, in my case I had a button with a data-id attribute:
$("a").data("item-id");
Have you tried running npm config list
? And, if you want to see the defaults, run npm config ls -l
.
You can use Thread.getCurrentThread.getId(), but why would you want to do that when LogRecord objects managed by the logger already have the thread Id. I think you are missing a configuration somewhere that logs the thread Ids for your log messages.
Use media queries. Your CSS code would be:
@media screen and (max-width: 1024px) {
.yourClass {
display: none !important;
}
}
Docs: https://www.timkay.com/solo/
solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.
Example
* * * * * solo -port=3801 ./job.pl blah blah
After Python 3.4, you can also use pathlib
's class Path
to move file.
from pathlib import Path
Path("path/to/current/file.foo").rename("path/to/new/destination/for/file.foo")
https://docs.python.org/3.4/library/pathlib.html#pathlib.Path.rename
I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set
result = pandas.DataFrame(input).groupby(1).groups
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
^[0-9\-\+]{9,15}$
would match 0+0+0+0+0+0, or 000000000, etc.
(\-?[0-9]){7}
would match a specific number of digits with optional hyphens in any position among them.
What is this +077 format supposed to be?
It's not a valid format. No country codes begin with 0.
The digits after the + should usually be a country code, 1 to 3 digits long.
Allowing for "+" then country code CC, then optional hyphen, then "0" plus two digits, then hyphens and digits for next seven digits, try:
^\+CC\-?0[1-9][0-9](\-?[0-9]){7}$
Oh, and {3,3} is redundant, simplifes to {3}.
Swift 5 version of the solution
func myCriticalFunction() {
var value1: String?
var value2: String?
let group = DispatchGroup()
group.enter()
//async operation 1
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value1 = //out of async task
group.leave()
}
group.enter()
//async operation 2
DispatchQueue.global(qos: .default).async {
// Network calls or some other async task
value2 = //out of async task
group.leave()
}
group.wait()
print("Value1 \(value1) , Value2 \(value2)")
}
This will do the trick:
xargs -0 < /proc/<pid>/cmdline
Without the xargs, there will be no spaces between the arguments, because they have been converted to NULs.
it depends on what role this foreign key
plays in your relation.
foreign key
is also a key attribute
in your relation, then it can't be NULLforeign key
is a normal attribute in your relation, then it can be NULL.SQL Error: ORA-30926: unable to get a stable set of rows in the source tables
30926. 00000 - "unable to get a stable set of rows in the source tables"
*Cause: A stable set of rows could not be got because of large dml
activity or a non-deterministic where clause.
*Action: Remove any non-deterministic where clauses and reissue the dml.
This Error occurred for me because of duplicate records(16K)
I tried with unique it worked .
but again when I tried merge without unique same proble occurred Second time it was due to commit
after merge if commit is not done same Error will be shown.
Without unique, Query will work if commit is given after each merge operation.
I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:
We can enable TCP/IP protocol with WMI:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocol " _
& "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")
if tcpProtocols.Count = 1 then
' set tcpProtocol = tcpProtocols(0)
' I wish this worked, but unfortunately
' there's no int-indexed Item property in this type
' Doing this instead
for each tcpProtocol in tcpProtocols
dim setEnableResult
setEnableResult = tcpProtocol.SetEnable()
if setEnableResult <> 0 then
Wscript.Echo "Failed!"
end if
next
end if
I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)
We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456
:
set wmiComputer = GetObject( _
"winmgmts:" _
& "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
"select * from ServerNetworkProtocolProperty " _
& "where InstanceName='SQLEXPRESS' and " _
& "ProtocolName='Tcp' and IPAddressName='IPAll'")
for each tcpProperty in tcpProperties
dim setValueResult, requestedValue
if tcpProperty.PropertyName = "TcpPort" then
requestedValue = "3456"
elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
requestedValue = ""
end if
setValueResult = tcpProperty.SetStringValue(requestedValue)
if setValueResult = 0 then
Wscript.Echo "" & tcpProperty.PropertyName & " set."
else
Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
end if
next
Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.
Just a reminder that when working with WMI, WBEMTest.exe is your best friend!
I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:
Use LoginMode
property of Microsoft.SqlServer.Management.Smo.Server
class, as described here.
Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS
, so for my SQL Server 2008 R2 Express instance the right registry key was
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer
.
You got this one covered.
Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.
SQLCMD -U sa -P newPassword -S 192.168.0.120,3456
Please let me know if this works for you (fingers crossed!).
Is there a simple way to convert a LocalDate (introduced with Java 8) to java.util.Date object? By 'simple', I mean simpler than this
Nope. You did it properly, and as concisely as possible.
java.util.Date.from( // Convert from modern java.time class to troublesome old legacy class. DO NOT DO THIS unless you must, to inter operate with old code not yet updated for java.time.
myLocalDate // `LocalDate` class represents a date-only, without time-of-day and without time zone nor offset-from-UTC.
.atStartOfDay( // Let java.time determine the first moment of the day on that date in that zone. Never assume the day starts at 00:00:00.
ZoneId.of( "America/Montreal" ) // Specify time zone using proper name in `continent/region` format, never 3-4 letter pseudo-zones such as “PST”, “CST”, “IST”.
) // Produce a `ZonedDateTime` object.
.toInstant() // Extract an `Instant` object, a moment always in UTC.
)
Read below for issues, and then think about it. How could it be simpler? If you ask me what time does a date start, how else could I respond but ask you “Where?”?. A new day dawns earlier in Paris FR than in Montréal CA, and still earlier in Kolkata IN, and even earlier in Auckland NZ, all different moments.
So in converting a date-only (LocalDate
) to a date-time we must apply a time zone (ZoneId
) to get a zoned value (ZonedDateTime
), and then move into UTC (Instant
) to match the definition of a java.util.Date
.
Firstly, avoid the old legacy date-time classes such as java.util.Date
whenever possible. They are poorly designed, confusing, and troublesome. They were supplanted by the java.time classes for a reason, actually, for many reasons.
But if you must, you can convert to/from java.time types to the old. Look for new conversion methods added to the old classes.
java.util.Date
? java.time.LocalDate
Keep in mind that a java.util.Date
is a misnomer as it represents a date plus a time-of-day, in UTC. In contrast, the LocalDate
class represents a date-only value without time-of-day and without time zone.
Going from java.util.Date
to java.time means converting to the equivalent class of java.time.Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
The LocalDate
class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
So we need to move that Instant
into a time zone. We apply ZoneId
to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
From there, ask for a date-only, a LocalDate
.
LocalDate ld = zdt.toLocalDate();
java.time.LocalDate
? java.util.Date
To move the other direction, from a java.time.LocalDate
to a java.util.Date
means we are going from a date-only to a date-time. So we must specify a time-of-day. You probably want to go for the first moment of the day. Do not assume that is 00:00:00
. Anomalies such as Daylight Saving Time (DST) means the first moment may be another time such as 01:00:00
. Let java.time determine that value by calling atStartOfDay
on the LocalDate
.
ZonedDateTime zdt = myLocalDate.atStartOfDay( z );
Now extract an Instant
.
Instant instant = zdt.toInstant();
Convert that Instant
to java.util.Date
by calling from( Instant )
.
java.util.Date d = java.util.Date.from( instant );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes. Hibernate 5 & JPA 2.2 support java.time.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Something like this will do it. The for
loop may need to be modified depending on which filenames you wish to capture.
for fspec1 in DET01-ABC-5_50-*.dat ; do
fspec2=$(echo ${fspec1} | sed 's/-ABC-/-XYZ-/')
mv ${fspec1} ${fspec2}
done
You should always test these scripts on copies of your data, by the way, and in totally different directories.
You can also use this clone library to deep clone objects.
npm install --save clone
const clone = require('clone');
const clonedObject = clone(sourceObject);
The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.
In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.
Another approach to sort HTML table. (based on W3.JS HTML Sort)
let tid = "#usersTable";_x000D_
let headers = document.querySelectorAll(tid + " th");_x000D_
_x000D_
// Sort the table element when clicking on the table headers_x000D_
headers.forEach(function(element, i) {_x000D_
element.addEventListener("click", function() {_x000D_
w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")");_x000D_
});_x000D_
});
_x000D_
th {_x000D_
cursor: pointer;_x000D_
background-color: coral;_x000D_
}
_x000D_
<script src="https://www.w3schools.com/lib/w3.js"></script>_x000D_
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet" />_x000D_
<p>Click the <strong>table headers</strong> to sort the table accordingly:</p>_x000D_
_x000D_
<table id="usersTable" class="w3-table-all">_x000D_
<!-- _x000D_
<tr>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(1)')">Name</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(2)')">Address</th>_x000D_
<th onclick="w3.sortHTML('#usersTable', '.item', 'td:nth-child(3)')">Sales Person</th>_x000D_
</tr> _x000D_
-->_x000D_
<tr>_x000D_
<th>Name</th>_x000D_
<th>Address</th>_x000D_
<th>Sales Person</th>_x000D_
</tr>_x000D_
_x000D_
<tr class="item">_x000D_
<td>user:2911002</td>_x000D_
<td>UK</td>_x000D_
<td>Melissa</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2201002</td>_x000D_
<td>France</td>_x000D_
<td>Justin</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901092</td>_x000D_
<td>San Francisco</td>_x000D_
<td>Judy</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2801002</td>_x000D_
<td>Canada</td>_x000D_
<td>Skipper</td>_x000D_
</tr>_x000D_
<tr class="item">_x000D_
<td>user:2901009</td>_x000D_
<td>Christchurch</td>_x000D_
<td>Alex</td>_x000D_
</tr>_x000D_
_x000D_
</table>
_x000D_
You can easily call for a window called "Navigate To" with combination ctrl + ,
Or, go to Tools and then click Navigate To
Like others have mentioned, a functor is an object that acts like a function, i.e. it overloads the function call operator.
Functors are commonly used in STL algorithms. They are useful because they can hold state before and between function calls, like a closure in functional languages. For example, you could define a MultiplyBy
functor that multiplies its argument by a specified amount:
class MultiplyBy {
private:
int factor;
public:
MultiplyBy(int x) : factor(x) {
}
int operator () (int other) const {
return factor * other;
}
};
Then you could pass a MultiplyBy
object to an algorithm like std::transform:
int array[5] = {1, 2, 3, 4, 5};
std::transform(array, array + 5, array, MultiplyBy(3));
// Now, array is {3, 6, 9, 12, 15}
Another advantage of a functor over a pointer to a function is that the call can be inlined in more cases. If you passed a function pointer to transform
, unless that call got inlined and the compiler knows that you always pass the same function to it, it can't inline the call through the pointer.
Here is a plain and simple explanation:
// Include the public functions from 'helpers.js'
var helpers = require('./helpers');
// Let's assume this is the data which comes from the database or somewhere else
var databaseName = 'Walter';
var databaseSurname = 'Heisenberg';
// Use the function from 'helpers.js' in the main file, which is server.js
var fullname = helpers.concatenateNames(databaseName, databaseSurname);
// 'module.exports' is a node.JS specific feature, it does not work with regular JavaScript
module.exports =
{
// This is the function which will be called in the main file, which is server.js
// The parameters 'name' and 'surname' will be provided inside the function
// when the function is called in the main file.
// Example: concatenameNames('John,'Doe');
concatenateNames: function (name, surname)
{
var wholeName = name + " " + surname;
return wholeName;
},
sampleFunctionTwo: function ()
{
}
};
// Private variables and functions which will not be accessible outside this file
var privateFunction = function ()
{
};
If index
doesn't find the searched string, it throws the ValueError
you're seeing. Either
catch the ValueError:
try:
i = s.index("")
del s[i]
except ValueError:
print "new_tag_list has no empty string"
or use find
, which returns -1 in that case.
i = s.find("")
if i >= 0:
del s[i]
else:
print "new_tag_list has no empty string"
I solved this problem by searching "mvc". The System.Web.Mvc appeared in search results, despite it is not contained in the list.
If you are using mongoose, I have found the following plugin to be a useful implementation of the JSON Patch format
Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.
According to the Git documentation, the last argument of the git push
command can be the repository that you want to push to:
git push [--all | --mirror | --tags] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
[--repo=<repository>] [-f | --force] [--prune] [-v | --verbose] [-u | --set-upstream]
[<repository> [<refspec>…]]
And the repository
parameter can be either a URL or a remote name.
So you can specify username and password the same way as you do in your example of clone
command.
Do you mean the first N items, or the N largest items?
If you want the first:
top5 = sequence[:5]
This also works for the largest N items, assuming that your sequence is sorted in descending order. (Your LINQ example seems to assume this as well.)
If you want the largest, and it isn't sorted, the most obvious solution is to sort it first:
l = list(sequence)
l.sort(reverse=True)
top5 = l[:5]
For a more performant solution, use a min-heap (thanks Thijs):
import heapq
top5 = heapq.nlargest(5, sequence)
As suggested by @The Berga You can add android:layoutDirection="rtl"
but it's only available with API 17.
for dynamic implementation, here it goes
chkBox.setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
There are a few different ways you can achieve what you are asking for.
1.) Extend the application class and instantiate your controller and model objects there.
public class FavoriteColorsApplication extends Application {
private static FavoriteColorsApplication application;
private FavoriteColorsService service;
public FavoriteColorsApplication getInstance() {
return application;
}
@Override
public void onCreate() {
super.onCreate();
application = this;
application.initialize();
}
private void initialize() {
service = new FavoriteColorsService();
}
public FavoriteColorsService getService() {
return service;
}
}
Then you can call the your singleton from your custom Application object at any time:
public class FavoriteColorsActivity extends Activity {
private FavoriteColorsService service = null;
private ArrayAdapter<String> adapter;
private List<String> favoriteColors = new ArrayList<String>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favorite_colors);
service = ((FavoriteColorsApplication) getApplication()).getService();
favoriteColors = service.findAllColors();
ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);
adapter = new ArrayAdapter<String>(this, R.layout.favorite_colors_list_item,
favoriteColors);
lv.setAdapter(adapter);
}
2.) You can have your controller just create a singleton instance of itself:
public class Controller {
private static final String TAG = "Controller";
private static sController sController;
private Dao mDao;
private Controller() {
mDao = new Dao();
}
public static Controller create() {
if (sController == null) {
sController = new Controller();
}
return sController;
}
}
Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.
3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.
I hope I gave enough detail in regards to how you can do what you are hoping for.
Adding a solution for people with multiple Java versions installed
We have a large codebase, most of which is in Java. The majority of what I work on is written in either Java 1.7 or 1.8. Since JAVA_HOME
is static, I created aliases in my .bashrc
for running Maven with different values:
alias mvn5="JAVA_HOME=/usr/local/java5 && mvn"
alias mvn6="JAVA_HOME=/usr/local/java6 && mvn"
alias mvn7="JAVA_HOME=/usr/local/java7 && mvn"
alias mvn8="JAVA_HOME=/usr/local/java8 && mvn"
This lets me run Maven from the command line on my development machine regardless of the JDK version used on the project.
Edit: A better solution is presented by the answer from Ondrej, which obviates remembering aliases.
I did it by using the following options:
/njh /njs /ndl /nc /ns
Note that the file name still displays, but that's fine for me.
For more information on robocopy, go to http://technet.microsoft.com/en-us/library/cc733145%28WS.10%29.aspx
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
Well, this is a tricky one.
The answer is "not really".
CSS isn't a functional layer. It doesn't have any awareness of what happens or when. It's used simply to add a presentational layer to different "flags" (classes, ids, states).
By default, CSS/DOM does not provide any kind of "on load" state for CSS to use. If you wanted/were able to use JavaScript, you'd allocate a class to body
or something to activate some CSS.
That being said, you can create a hack for that. I'll give an example here, but it may or may not be applicable to your situation.
We're operating on the assumption that "close" is "good enough":
<html>
<head>
<!-- Reference your CSS here... -->
</head>
<body>
<!-- A whole bunch of HTML here... -->
<div class="onLoad">OMG, I've loaded !</div>
</body>
</html>
Here's an excerpt of our CSS stylesheet:
.onLoad
{
-webkit-animation:bounceIn 2s;
}
We're also on the assumption that modern browsers render progressively, so our last element will render last, and so this CSS will be activated last.
If you use Snap.svg, the following works:
var tPaper = Snap(300, 300);
var tLabelText = tPaper.text(100, 100, "label text");
var tWidth = tLabelText.getBBox().width; // the width of the text in pixels.
tLabelText.attr({ x : 150 - (tWidth/2)}); // now it's centered in x
just set the value of the model to the default you want like this:
selectedWorkout = 'back'
I created a fork of @Douglas' plnkr here to demonstrate the various ways to get the desired behavior in angular2.
There is no difference. From RDD.scala
.
/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def persist(): this.type = persist(StorageLevel.MEMORY_ONLY)
/** Persist this RDD with the default storage level (`MEMORY_ONLY`). */
def cache(): this.type = persist()
import org.apache.commons.lang.math.NumberUtils;
This will handle null
NumberUtils.createLong(String)
You can just use
datetime.date.today()
It's light and returns exactly what you want.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid
:
import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)
There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes
object instead of a Facet Grid
. These are different things, and the Axes.set_xticklabels()
method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes
. The lesson is that it's important to pay attention to what kind of objects you are working with.
If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.
>>> 0xffff
65535
from collections import OrderedDict
from operator import itemgetter
d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
print(OrderedDict(sorted(d.items(), key = itemgetter(1), reverse = True)))
prints
OrderedDict([('bb', 4), ('aa', 3), ('cc', 2), ('dd', 1)])
Though from your last sentence, it appears that a list of tuples would work just fine, e.g.
from operator import itemgetter
d = {"aa": 3, "bb": 4, "cc": 2, "dd": 1}
for key, value in sorted(d.items(), key = itemgetter(1), reverse = True):
print(key, value)
which prints
bb 4
aa 3
cc 2
dd 1
What is REST
REST stands for representational state transfer, it's actually an architectural style for creating Web API which treats everything(data or functionality) as recourse. It expects; exposing resources through URI and responding in multiple formats and representational transfer of state of the resources in stateless manner. Here I am talking about two things:
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
REST is not REST without HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
HATEOAS, an abbreviation for Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in some service-oriented architectures (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
In the vast majority of cases, the "stringification" of a SQLAlchemy statement or query is as simple as:
print(str(statement))
This applies both to an ORM Query
as well as any select()
or other statement.
Note: the following detailed answer is being maintained on the sqlalchemy documentation.
To get the statement as compiled to a specific dialect or engine, if the statement itself is not already bound to one you can pass this in to compile():
print(statement.compile(someengine))
or without an engine:
from sqlalchemy.dialects import postgresql
print(statement.compile(dialect=postgresql.dialect()))
When given an ORM Query
object, in order to get at the compile()
method we only need access the .statement accessor first:
statement = query.statement
print(statement.compile(someengine))
with regards to the original stipulation that bound parameters are to be "inlined" into the final string, the challenge here is that SQLAlchemy normally is not tasked with this, as this is handled appropriately by the Python DBAPI, not to mention bypassing bound parameters is probably the most widely exploited security holes in modern web applications. SQLAlchemy has limited ability to do this stringification in certain circumstances such as that of emitting DDL. In order to access this functionality one can use the 'literal_binds' flag, passed to compile_kwargs
:
from sqlalchemy.sql import table, column, select
t = table('t', column('x'))
s = select([t]).where(t.c.x == 5)
print(s.compile(compile_kwargs={"literal_binds": True}))
the above approach has the caveats that it is only supported for basic
types, such as ints and strings, and furthermore if a bindparam
without a pre-set value is used directly, it won't be able to
stringify that either.
To support inline literal rendering for types not supported, implement
a TypeDecorator
for the target type which includes a
TypeDecorator.process_literal_param
method:
from sqlalchemy import TypeDecorator, Integer
class MyFancyType(TypeDecorator):
impl = Integer
def process_literal_param(self, value, dialect):
return "my_fancy_formatting(%s)" % value
from sqlalchemy import Table, Column, MetaData
tab = Table('mytable', MetaData(), Column('x', MyFancyType()))
print(
tab.select().where(tab.c.x > 5).compile(
compile_kwargs={"literal_binds": True})
)
producing output like:
SELECT mytable.x
FROM mytable
WHERE mytable.x > my_fancy_formatting(5)
Check out the pack URI syntax. You want something like this:
<ResourceDictionary Source="pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml"/>
Note: This has been updated to reflect the release of API 21, Lollipop. Be sure to download the latest SDK.
In one of my modules I had the following in build.gradle:
dependencies {
compile 'com.android.support:support-v4:+'
}
Changing this to
dependencies {
// do not use dynamic updating.
compile 'com.android.support:support-v4:21.0.0'
}
fixed the issue.
Make sure you're not doing a general inclusion of com.android.support:support-v4:+
or any other support libraries (v7, v13, appcompat, etc), anywhere in your project.
I'd assume the problem is v4:+
picks up the release candidate (21.0.0-rc1) latest L release which obviously requires the L SDK.
Edit:
If you need to use the new views (CardView, RecyclerView, and Palette), the following should work:
compile "com.android.support:cardview-v7:21.0.0"
compile "com.android.support:recyclerview-v7:21.0.0"
compile "com.android.support:palette-v7:21.0.0"
(Credit to EddieRingle on /androiddev - http://www.reddit.com/r/androiddev/comments/297xli/howto_use_the_v21_support_libs_on_older_versions/)
Another Edit
Be sure to see @murtuza's answer below regarding appcompat-v7 and upvote if it helps!
Use of pseudo-element as suggested by Terry has one PRO and one CON:
Anyway is a great solution.
OTHER SOLUTIONS:
If you can accept compatibility since IE9 (IE8 does not have support for this), you can achieve desired result in other two possible ways:
outline
property combined with border
and a single inset box-shadow
box-shadow
combined with border
.Here a jsFiddle with Terry's modified code that shows, side by side, these other possible solutions. Main specific properties for each one are the following (others are shared in .double-border
class):
.left
{
outline: 4px solid #fff;
box-shadow:inset 0 0 0 4px #fff;
}
.right
{
box-shadow:0 0 0 4px #fff, inset 0 0 0 4px #fff;
}
LESS code:
You asked for possible advantages about using a pre-processor like LESS. I this specific case, utility is not so great, but anyway you could optimize something, declaring colors and border/ouline/shadow with @variable.
Here an example of my CSS code, declared in LESS (changing colors and border-width becomes very quick):
@double-border-size:4px;
@inset-border-color:#fff;
@content-color:#ccc;
.double-border
{
background-color: @content-color;
border: @double-border-size solid @content-color;
padding: 2em;
width: 16em;
height: 16em;
float:left;
margin-right:20px;
text-align:center;
}
.left
{
outline: @double-border-size solid @inset-border-color;
box-shadow:inset 0 0 0 @double-border-size @inset-border-color;
}
.right
{
box-shadow:0 0 0 @double-border-size @inset-border-color, inset 0 0 0 @double-border-size @inset-border-color;
}
This works well for specific articles where the text is all wrapped in <p>
tags. Since the web is an ugly place, it's not always the case.
Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span>
or a <div>
, or an <li>
).
To find all text nodes in the DOM, you can use soup.find_all(text=True)
.
This is going to return some undesired text, like the contents of <script>
and <style>
tags. You'll need to filter out the text contents of elements you don't want.
blacklist = [
'style',
'script',
# other elements,
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]
If you are working with a known set of tags, you can tag the opposite approach:
whitelist = [
'p'
]
text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]
Take a look here: https://reacttraining.com/react-router/core/api/Route/exact-bool
exact: bool
When true, will only match if the path matches the location.pathname
exactly.
**path** **location.pathname** **exact** **matches?**
/one /one/two true no
/one /one/two false yes
You can use template facility in C++ to do this. I did something like this :
template<typename T, size_t col>
T process(T a[][col], size_t row) {
...
}
the problem with this approach is that for every value of col which you provide, the a new function definition is instantiated using the template. so,
int some_mat[3][3], another_mat[4,5];
process(some_mat, 3);
process(another_mat, 4);
instantiates the template twice to produce 2 function definitions (one where col = 3 and one where col = 5).
curl is an extension that needs to be installed, it's got nothing to do with the PHP version.
Doing password checks on client side is unsafe especially when the password is hard coded.
The safest way is password checking on server side, but even then the password should not be transmitted plain text.
Checking the password client side is possible in a "secure way":
Say "abc" is your password so your md5 would be "900150983cd24fb0d6963f7d28e17f72" (consider salting!). Now build a url containing the hash (like http://yourdomain.com/90015...f72.html).
Evaluation of main answers with a performance benchmark which confirms concerns that the current chosen answer makes costly regex operations under the hood
To date the provided answers come in 3 main styles (ignoring the JavaScript answer ;) ):
In terms of code size clearly the String.replace is the most terse. The simple Java implementation is slightly smaller and cleaner (IMHO) than the Lambda (don't get me wrong - I use Lambdas often where they are appropriate)
Execution speed was, in order of fastest to slowest: simple Java implementation, Lambda and then String.replace() (that invokes regex).
By far the fastest implementation was the simple Java implementation tuned so that it preallocates the StringBuilder buffer to the max possible result length and then simply appends chars to the buffer that are not in the "chars to delete" string. This avoids any reallocates that would occur for Strings > 16 chars in length (the default allocation for StringBuilder) and it avoids the "slide left" performance hit of deleting characters from a copy of the string that occurs is the Lambda implementation.
The code below runs a simple benchmark test, running each implementation 1,000,000 times and logs the elapsed time.
The exact results vary with each run but the order of performance never changes:
Start simple Java implementation
Time: 157 ms
Start Lambda implementation
Time: 253 ms
Start String.replace implementation
Time: 634 ms
The Lambda implementation (as copied from Kaplan's answer) may be slower because it performs a "shift left by one" of all characters to the right of the character being deleted. This would obviously get worse for longer strings with lots of characters requiring deletion. Also there might be some overhead in the Lambda implementation itself.
The String.replace implementation, uses regex and does a regex "compile" at each call. An optimization of this would be to use regex directly and cache the compiled pattern to avoid the cost of compiling it each time.
package com.sample;
import java.util.function.BiFunction;
import java.util.stream.IntStream;
public class Main {
static public String deleteCharsSimple(String fromString, String charsToDelete)
{
StringBuilder buf = new StringBuilder(fromString.length()); // Preallocate to max possible result length
for(int i = 0; i < fromString.length(); i++)
if (charsToDelete.indexOf(fromString.charAt(i)) < 0)
buf.append(fromString.charAt(i)); // char not in chars to delete so add it
return buf.toString();
}
static public String deleteCharsLambda(String fromString1, String charsToDelete)
{
BiFunction<String, String, String> deleteChars = (fromString, chars) -> {
StringBuilder buf = new StringBuilder(fromString);
IntStream.range(0, buf.length()).forEach(i -> {
while (i < buf.length() && chars.indexOf(buf.charAt(i)) >= 0)
buf.deleteCharAt(i);
});
return (buf.toString());
};
return deleteChars.apply(fromString1, charsToDelete);
}
static public String deleteCharsReplace(String fromString, String charsToDelete)
{
return fromString.replace(charsToDelete, "");
}
public static void main(String[] args)
{
String str = "XXXTextX XXto modifyX";
String charsToDelete = "X"; // Should only be one char as per OP's requirement
long start, end;
System.out.println("Start simple");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsSimple(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start lambda");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsLambda(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
System.out.println("Start replace");
start = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++)
deleteCharsReplace(str, charsToDelete);
end = System.currentTimeMillis();
System.out.println("Time: " + (end - start));
}
}
The answers given so far are all OK.
However, one interesting difference is that Model.find
searches by id; if found, it returns a Model
object (just a single record) but throws an ActiveRecord::RecordNotFound
otherwise.
Model.find_by
is very similar to Model.find
and lets you search any column or group of columns in your database but it returns nil
if no record matches the search.
Model.where
on the other hand returns a Model::ActiveRecord_Relation
object which is just like an array containing all the records that match the search. If no record was found, it returns an empty Model::ActiveRecord_Relation
object.
I hope these would help you in deciding which to use at any point in time.
The fact that mongoDB is not relational have led some people to consider it useless. I think that you should know what you are doing before designing a DB. If you choose to use noSQL DB such as MongoDB, you better implement a schema. This will make your collections - more or less - resemble tables in SQL databases. Also, avoid denormalization (embedding), unless necessary for efficiency reasons.
If you want to design your own noSQL database, I suggest to have a look on Firebase documentation. If you understand how they organize the data for their service, you can easily design a similar pattern for yours.
As others pointed out, you will have to do the joins client-side, except with Meteor (a Javascript framework), you can do your joins server-side with this package (I don't know of other framework which enables you to do so). However, I suggest you read this article before deciding to go with this choice.
Edit 28.04.17: Recently Firebase published this excellent series on designing noSql Databases. They also highlighted in one of the episodes the reasons to avoid joins and how to get around such scenarios by denormalizing your database.
Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run
ip addr
This will give you a list of network adapters, one of which will look something like
3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
valid_lft forever preferred_lft forever
You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
The LLVM Compiler Infrastructure is particularly useful for performing optimizations and transformations on code. It also consists of a number of tools serving distinct usages. llvm-prof is a profiling tool that allows you to do profiling of execution in order to identify program hotspots. Opt is an optimization tool that offers various optimization passes (dead code elimination for instance).
Importantly LLVM provides you with the libraries, to write your own Passes. For instance if you require to add a range check on certain arguments that are passed into certain functions of a Program, writing a simple LLVM Pass would suffice.
For more information on writing your own Pass, check this http://llvm.org/docs/WritingAnLLVMPass.html
See our SD Thicket PHP Obfuscator for an obfuscator that works just fine with arbitrarily large sets of pages. It operates primarily by scrambling identifier names. With modest to large applications, this can make the code extremely difficult to understand, which is the entire purpose.
It doesn't waste any energy on "eval(decode(encodedprogramcode))" schemes, which a lot of PHP "obfuscators" do [these are "encoder"s, not "obfuscator"s], because any clod can find that call and execute the eval-decode himself and get the decoded code.
It uses a language-precise parser to process the PHP; it will tell you if your program is syntactically invalid. More importantly, it knows the whole language precisely; it won't get lost or confused, and it won't break your code (other that what happens if you obfuscate "incorrectly", e.g., fail to identify the public API of the code correctly).
Yes, it obfuscates identifiers identically across pages; if it didn't do that, the result wouldn't work.
This means you haven't generated the jquery files after you have installed the jquery-rails gem. So first you need to generate it.
rails generate devise:install
First Option:
This means either you have to change the following line on /config/initializers/devise.rb
config.sign_out_via = :delete to config.sign_out_via = :get
Second Option:
You only change this line <%= link_to "Sign out", destroy_user_session_path %>
to <%= link_to "Sign out", destroy_user_session_path, :method => :delete %>
on the view file.
Usually :method => :delete
is not written by default.
Just adding to the answers already given, the solution using the string "nunique"
seems much faster, tested here on ~21M rows dataframe, then grouped to ~2M
%time _=g.agg({"id": lambda x: x.nunique()})
CPU times: user 3min 3s, sys: 2.94 s, total: 3min 6s
Wall time: 3min 20s
%time _=g.agg({"id": pd.Series.nunique})
CPU times: user 3min 2s, sys: 2.44 s, total: 3min 4s
Wall time: 3min 18s
%time _=g.agg({"id": "nunique"})
CPU times: user 14 s, sys: 4.76 s, total: 18.8 s
Wall time: 24.4 s
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
In order to capture deadlock graphs without using a trace (you don't need profiler necessarily), you can enable trace flag 1222. This will write deadlock information to the error log. However, the error log is textual, so you won't get nice deadlock graph pictures - you'll have to read the text of the deadlocks to figure it out.
I would set this as a startup trace flag (in which case you'll need to restart the service). However, you can run it only for the current running instance of the service (which won't require a restart, but which won't resume upon the next restart) using the following global trace flag command:
DBCC TRACEON(1222, -1);
A quick search yielded this tutorial:
http://www.mssqltips.com/sqlservertip/2130/finding-sql-server-deadlocks-using-trace-flag-1222/
Also note that if your system experiences a lot of deadlocks, this can really hammer your error log, and can become quite a lot of noise, drowning out other, important errors.
Have you considered third party monitoring tools? SQL Sentry Performance Advisor, for example, has a much nicer deadlock graph, showing you object / index names as well as the order in which the locks were taken. As a bonus, these are captured for you automatically on monitored servers without having to configure trace flags, run your own traces, etc.:
Disclaimer: I work for SQL Sentry.
Bash allow u to use =~ to test if the substring is contained. Ergo, the use of negate will allow to test the opposite.
fullstring="123asdf123"
substringA=asdf
substringB=gdsaf
# test for contains asdf, gdsaf and for NOT CONTAINS gdsaf
[[ $fullstring =~ $substring ]] && echo "found substring $substring in $fullstring"
[[ $fullstring =~ $substringB ]] && echo "found substring $substringB in $fullstring" || echo "failed to find"
[[ ! $fullstring =~ $substringB ]] && echo "did not find substring $substringB in $fullstring"
Yes it is guaranteed in python 2.x:
If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeHere are two one-line macros that I use:
#define TICK NSDate *startTime = [NSDate date]
#define TOCK NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])
Use it like this:
TICK;
/* ... Do Some Work Here ... */
TOCK;
In TSQL, the modulo is done with a percent sign.
SELECT 38 % 5 would give you the modulo 3
I edited the method created by batbaatar above so it accepts the Configuration object as a parameter:
public static SessionFactory createSessionFactory(Configuration configuration) {
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(serviceRegistry);
return factory;
}
In the main class I did:
private static SessionFactory factory;
private static Configuration configuration
...
configuration = new Configuration();
configuration.configure().addAnnotatedClass(Employee.class);
// Other configurations, then
factory = createSessionFactory(configuration);
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
Use the svn move
command to move file/folder.
To obtain a stream of just the names:
$ jq '.[] | select(.location=="Stockholm") | .name' json
produces:
"Donald"
"Walt"
To obtain a stream of corresponding (key name, "name" attribute) pairs, consider:
$ jq -c 'to_entries[]
| select (.value.location == "Stockholm")
| [.key, .value.name]' json
Output:
["FOO","Donald"]
["BAR","Walt"]
SET myParam = IFNULL(myParam, 0);
Explanation: IFNULL(expression_1, expression_2)
The IFNULL
function returns expression_1
if expression_1
is not NULL
; otherwise it returns expression_2
. The IFNULL
function returns a string or a numeric based on the context where it is used.
Certify that your Manifest declaration includes android:theme="@style/AppTheme.NoActionBar" tag, like the following:
<activity
android:name=".PointsScreen"
android:theme="@style/AppTheme.NoActionBar">
</activity>
Remove javascript:
from onclick="..
, onsubmit="..
declarations
javascript:
prefix is used only in href=""
or similar attributes (not events related)
ActiveModel::Dirty
didn't work for me because the @model.update_attributes()
hid the changes. So this is how I detected changes it in an update
method in a controller:
def update
@model = Model.find(params[:id])
detect_changes
if @model.update_attributes(params[:model])
do_stuff if attr_changed?
end
end
private
def detect_changes
@changed = []
@changed << :attr if @model.attr != params[:model][:attr]
end
def attr_changed?
@changed.include :attr
end
If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.
Here's how do do it directly (without an explicit extra loop) by defining the appropriate Comparator
:
int keyOfMaxValue = Collections.max(
yourMap.entrySet(),
new Comparator<Entry<Double,Integer>>(){
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
return o1.getValue() > o2.getValue()? 1:-1;
}
}).getKey();
<div ng-controller="ExampleController">
<form name="myForm">
<label for="repeatSelect"> Repeat select: </label>
<select name="repeatSelect" id="repeatSelect" ng-model="data.model">
<option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
</select>
</form>
<hr>
<tt>model = {{data.model}}</tt><br/>
</div>
AngularJS:
angular.module('ngrepeatSelect', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.data = {
model: null,
availableOptions: [
{id: '1', name: 'Option A'},
{id: '2', name: 'Option B'},
{id: '3', name: 'Option C'}
]
};
}]);
taken from AngularJS docs
I had the same problem. This worked for me:
If you want to sum the digit of a number, one way to do it is using sum()
+ a generator expression:
sum(int(i) for i in str(155))
I modified a little your code using sum()
, maybe you want to take a look at it:
birthday = raw_input("When is your birthday(mm/dd/yyyy)? ")
summ = sum(int(i) for i in birthday[0:2])
sumd = sum(int(i) for i in birthday[3:5])
sumy = sum(int(i) for i in birthday[6:10])
sumall = summ + sumd + sumy
print "The sum of your numbers is", sumall
sumln = sum(int(c) for c in str(sumall)))
print "Your lucky number is", sumln
I think the best option is to use guide_legend
within guides
:
p + guides(fill=guide_legend(
keywidth=0.1,
keyheight=0.1,
default.unit="inch")
)
Note the use of default.unit
, no need to load grid
package.
int main () //start of main fcn
{
int values[ 20 ]; //delcares array and how many elements
int small,big; //declares integer
for ( int i = 0; i < 20; i++ ) //counts to 20 and prompts user for value and stores it
{
cout << "Enter value " << i << ": ";
cin >> values[i];
}
big=small=values[0]; //assigns element to be highest or lowest value
for (int i = 0; i < 20; i++) //works out bigggest number
{
if(values[i]>big) //compare biggest value with current element
{
big=values[i];
}
if(values[i]<small) //compares smallest value with current element
{
small=values[i];
}
}
cout << "The biggest number is " << big << endl; //prints outs biggest no
cout << "The smallest number is " << small << endl; //prints out smalles no
}
If you set <TextView>
in center in <Linearlayout>
then first put android:layout_width="fill_parent"
compulsory
No need of using any other gravity
<LinearLayout
android:layout_toRightOf="@+id/linear_profile"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
android:gravity="center_horizontal">
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="It's.hhhhhhhh...."
android:textColor="@color/Black"
/>
</LinearLayout>
I'm not aware of any particular convention for javascript files as they aren't really unique on the web versus css files or html files or any other type of file like that. There are some "safe" things you can do that make it less likely you will accidentally run into a cross platform issue:
various-scripts.js
, a hyphen is a safe and useful and commonly used separator.Greg is right-- you can use sys.stdout.write
Perhaps, though, you should consider refactoring your algorithm to accumulate a list of <whatevers> and then
lst = ['h', 'm']
print "".join(lst)
You may use os.stat()
function, which is a wrapper of system call stat()
:
import os
def getSize(filename):
st = os.stat(filename)
return st.st_size
Simply copy all icu****.dll files from
C:\xampp\php
to
C:\xampp\apache\bin
[or]
C:\wamp\bin\php\php5.5.12
to
C:\wamp\bin\apache\apache2.4.9
intl extension will start working!!!
For time as YYYY-MM-dd
String time = new DateTime( yourData ).toString("yyyy-MM-dd");
And the Library of DateTime is:
import org.joda.time.DateTime;
As Chris suggests, you can do it like this:
public string GetXMLAsString(XmlDocument myxml)
{
return myxml.OuterXml;
}
Or like this:
public string GetXMLAsString(XmlDocument myxml)
{
StringWriter sw = new StringWriter();
XmlTextWriter tx = new XmlTextWriter(sw);
myxml.WriteTo(tx);
string str = sw.ToString();//
return str;
}
and if you really want to create a new XmlDocument
then do this
XmlDocument newxmlDoc= myxml
Here is a more complex "not in" query, using a subquery in rails 4 using squeel. Of course very slow compared to the equivalent sql, but hey, it works.
scope :translations_not_in_english, ->(calmapp_version_id, language_iso_code){
join_to_cavs_tls_arr(calmapp_version_id).
joins_to_tl_arr.
where{ tl1.iso_code == 'en' }.
where{ cavtl1.calmapp_version_id == my{calmapp_version_id}}.
where{ dot_key_code << (Translation.
join_to_cavs_tls_arr(calmapp_version_id).
joins_to_tl_arr.
where{ tl1.iso_code == my{language_iso_code} }.
select{ "dot_key_code" }.all)}
}
The first 2 methods in the scope are other scopes which declare the aliases cavtl1 and tl1. << is the not in operator in squeel.
Hope this helps someone.
I added the vendor prefixes, and changed the animation to all
, so you have both opacity and width that are animated.
Is this what you're looking for ? http://jsfiddle.net/u2FKM/3/
For question 1:
SELECT DISTINCT a.*
FROM [Table] a
INNER JOIN
[Table] b
ON
a.C1 <> b.C1 AND a.C2 = b.C2 AND a.C3 = b.C3 AND a.C4 = b.C4
Using an inner join is much more efficient than a subquery because it requires fewer operations, and maintains the use of indexes when comparing the values, allowing the SQL server to better optimize the query before its run. Using appropriate indexes with this query can bring your query down to only n * log(n) rows to compare.
Using a subquery with your where clause or only doing a standard join where C1 does not equal C2 results in a table that has roughly 2 to the power of n rows to compare, where n is the number of rows in the table.
So by using proper indexing with an Inner Join, which only returns records which met the join criteria, we're able to drastically improve the performance. Also note that we return DISTINCT a.*, because this will only return the columns for table a where the join criteria was met. Returning * would return the columns for both a and b where the criteria was met, and not including DISTINCT would result in a duplicate of each row for each time that row row matched another row more than once.
A similar approach could also be performed using CROSS APPLY, which still uses a subquery, but makes use of indexes more efficiently.
An implementation with the keyword USING instead of ON could also work, but the syntax is more complicated to make work because your want to match on rows where C1 does not match, so you would need an additional where clause to filter out matching each row with itself. Also, USING is not compatible/allowed in conjunction with table values in all implementations of SQL, so it's best to stick with ON.
Similarly, for question 2:
SELECT DISTINCT a.*
FROM [Table] a
INNER JOIN
[Table] b
ON
a.C1 <> b.C1 AND a.C4 = b.C4
This is essentially the same query as for 1, but because it only wants to know which rows match for C4, we only compare on the rows for C4.
Try:
SELECT MEMBSHIP_ID
FROM user_payment
WHERE user_id=1
ORDER BY paym_date = (select MAX(paym_date) from user_payment and user_id=1);
Or:
SELECT MEMBSHIP_ID
FROM (
SELECT MEMBSHIP_ID, row_number() over (order by paym_date desc) rn
FROM user_payment
WHERE user_id=1 )
WHERE rn = 1
@jim mcnamara: try using parentheses for around NF
, i. e. $(NF-1)
and $(NF)
instead of $NF-1
and $NF
(works on Mac OS X 10.6.8 for FreeBSD awk
and gawk
).
echo '
1 2
2 3
one
one two three
' | gawk '{if (NF >= 2) print $(NF-1), $(NF);}'
# output:
# 1 2
# 2 3
# two three
We can do this using data() method. C++11 provides this method.
#include<bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
vector<int>v = {7, 8, 9, 10, 11};
int *arr = v.data();
for(int i=0; i<v.size(); i++)
{
cout<<arr[i]<<" ";
}
return 0;
}
UPDATE: Keep in mind, at the time the answer was initially written in 2010, the bellow function toFixed() worked slightly different. toFixed() seems to do some rounding now, but not in the strictly mathematical manner. So be careful with it. Do your tests... The method described bellow will do rounding well, as mathematician would expect.
toFixed()
- method converts a number into a string, keeping a specified number of decimals. It does not actually rounds up a number, it truncates the number.Math.round(n)
- rounds a number to the nearest integer. Thus turning:0.5 -> 1; 0.05 -> 0
so if you want to round, say number 0.55555, only to the second decimal place; you can do the following(this is step-by-step concept):
0.55555 * 100
= 55.555 Math.Round(55.555)
-> 56.00056.000 / 100
= 0.56000 (0.56000).toFixed(2)
-> 0.56and this is the code:
(Math.round(number * 100)/100).toFixed(2);
You can leave date_add function.
UPDATE `table`
SET `yourdatefield` = `yourdatefield` + INTERVAL 2 DAY
WHERE ...
a++ is known as postfix.
add 1 to a, returns the old value.
++a is known as prefix.
add 1 to a, returns the new value.
C#:
string[] items = {"a","b","c","d"};
int i = 0;
foreach (string item in items)
{
Console.WriteLine(++i);
}
Console.WriteLine("");
i = 0;
foreach (string item in items)
{
Console.WriteLine(i++);
}
Output:
1
2
3
4
0
1
2
3
foreach
and while
loops depend on which increment type you use. With for loops like below it makes no difference as you're not using the return value of i:
for (int i = 0; i < 5; i++) { Console.Write(i);}
Console.WriteLine("");
for (int i = 0; i < 5; ++i) { Console.Write(i); }
0 1 2 3 4
0 1 2 3 4
If the value as evaluated is used then the type of increment becomes significant:
int n = 0;
for (int i = 0; n < 5; n = i++) { }
You need to extract the initilization of time() out of the for loop.
Here is an example that will output in the windows console expected (ahah) random number.
#include <iostream>
#include <windows.h>
#include "time.h"
int main(int argc, char*argv[])
{
srand ( time(NULL) );
for (int t = 0; t < 10; t++)
{
int random_x;
random_x = rand() % 100;
std::cout << "\nRandom X = " << random_x << std::endl;
}
Sleep(50000);
return 0;
}
sed "s/^[ \t]*//" -i youfile
Warning: this will overwrite the original file.
If you want to return a format mm/dd/yyyy, then use 101 instead of 103: CONVERT(VARCHAR(10), [MyDate], 101)
The docs give a fair indicator of what's required., however requests
allow us to skip a few steps:
You only need to install the security
package extras (thanks @admdrew for pointing it out)
$ pip install requests[security]
or, install them directly:
$ pip install pyopenssl ndg-httpsclient pyasn1
Requests will then automatically inject pyopenssl
into urllib3
If you're on ubuntu, you may run into trouble installing pyopenssl
, you'll need these dependencies:
$ apt-get install libffi-dev libssl-dev
I had a similar problem . For this you can use a Hashmap which takes "string" and "object" as shown in code below:
/** stores the image database icons */
public static int[] imageIconDatabase = { R.drawable.ball,
R.drawable.catmouse, R.drawable.cube, R.drawable.fresh,
R.drawable.guitar, R.drawable.orange, R.drawable.teapot,
R.drawable.india, R.drawable.thailand, R.drawable.netherlands,
R.drawable.srilanka, R.drawable.pakistan,
};
private void initializeImageList() {
// TODO Auto-generated method stub
for (int i = 0; i < imageIconDatabase.length; i++) {
map = new HashMap<String, Object>();
map.put("Name", imageNameDatabase[i]);
map.put("Icon", imageIconDatabase[i]);
}
}
There are multiple ways to achieve this. I can explain you in brief about the 4 types which we use in our daily programming life cycle.
Please go through the below points.
1 Query String.
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + TextBox1.Text);
SecondForm.aspx.cs
TextBox1.Text = Request.QueryString["Parameter"].ToString();
This is the most reliable way when you are passing integer kind of value or other short parameters. More advance in this method if you are using any special characters in the value while passing it through query string, you must encode the value before passing it to next page. So our code snippet of will be something like this:
FirstForm.aspx.cs
Response.Redirect("SecondForm.aspx?Parameter=" + Server.UrlEncode(TextBox1.Text));
SecondForm.aspx.cs
TextBox1.Text = Server.UrlDecode(Request.QueryString["Parameter"].ToString());
URL Encoding
2. Passing value through context object
Passing value through context object is another widely used method.
FirstForm.aspx.cs
TextBox1.Text = this.Context.Items["Parameter"].ToString();
SecondForm.aspx.cs
this.Context.Items["Parameter"] = TextBox1.Text;
Server.Transfer("SecondForm.aspx", true);
Note that we are navigating to another page using Server.Transfer instead of Response.Redirect.Some of us also use Session object to pass values. In that method, value is store in Session object and then later pulled out from Session object in Second page.
3. Posting form to another page instead of PostBack
Third method of passing value by posting page to another form. Here is the example of that:
FirstForm.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
buttonSubmit.Attributes.Add("onclick", "return PostPage();");
}
And we create a javascript function to post the form.
SecondForm.aspx.cs
function PostPage()
{
document.Form1.action = "SecondForm.aspx";
document.Form1.method = "POST";
document.Form1.submit();
}
TextBox1.Text = Request.Form["TextBox1"].ToString();
Here we are posting the form to another page instead of itself. You might get viewstate invalid or error in second page using this method. To handle this error is to put EnableViewStateMac=false
4. Another method is by adding PostBackURL property of control for cross page post back
In ASP.NET 2.0, Microsoft has solved this problem by adding PostBackURL property of control for cross page post back. Implementation is a matter of setting one property of control and you are done.
FirstForm.aspx.cs
<asp:Button id=buttonPassValue style=”Z-INDEX: 102" runat=”server” Text=”Button” PostBackUrl=”~/SecondForm.aspx”></asp:Button>
SecondForm.aspx.cs
TextBox1.Text = Request.Form["TextBox1"].ToString();
In above example, we are assigning PostBackUrl property of the button we can determine the page to which it will post instead of itself. In next page, we can access all controls of the previous page using Request object.
You can also use PreviousPage class to access controls of previous page instead of using classic Request object.
SecondForm.aspx
TextBox textBoxTemp = (TextBox) PreviousPage.FindControl(“TextBox1");
TextBox1.Text = textBoxTemp.Text;
As you have noticed, this is also a simple and clean implementation of passing value between pages.
Reference: MICROSOFT MSDN WEBSITE
HAPPY CODING!
When I had this error, it went away after I my computer crashed and restarted. Try closing and reopening your IDE, if that doesn't work, try restarting your computer. I had just installed the libraries at that point without restarting pycharm when I got this error.
Never closed PyCharm first to test because my blasted computer keeps crashing randomly... working on that one, but it at least solved this problem.. little victories.. :).
if( char.toUpperCase() != char.toLowerCase() )
Will return true only in case of letter
As point out in below comment, if your character is non English, High Ascii or double byte range then you need to add check for code point.
if( char.toUpperCase() != char.toLowerCase() || char.codePointAt(0) > 127 )
Other solution:
def round_time(timestamp=None, lapse=0):
"""
Round a timestamp to a lapse according to specified minutes
Usage:
>>> import datetime, math
>>> round_time(datetime.datetime(2010, 6, 10, 3, 56, 23), 0)
datetime.datetime(2010, 6, 10, 3, 56)
>>> round_time(datetime.datetime(2010, 6, 10, 3, 56, 23), 1)
datetime.datetime(2010, 6, 10, 3, 57)
>>> round_time(datetime.datetime(2010, 6, 10, 3, 56, 23), -1)
datetime.datetime(2010, 6, 10, 3, 55)
>>> round_time(datetime.datetime(2019, 3, 11, 9, 22, 11), 3)
datetime.datetime(2019, 3, 11, 9, 24)
>>> round_time(datetime.datetime(2019, 3, 11, 9, 22, 11), 3*60)
datetime.datetime(2019, 3, 11, 12, 0)
>>> round_time(datetime.datetime(2019, 3, 11, 10, 0, 0), 3)
datetime.datetime(2019, 3, 11, 10, 0)
:param timestamp: Timestamp to round (default: now)
:param lapse: Lapse to round in minutes (default: 0)
"""
t = timestamp or datetime.datetime.now() # type: Union[datetime, Any]
surplus = datetime.timedelta(seconds=t.second, microseconds=t.microsecond)
t -= surplus
try:
mod = t.minute % lapse
except ZeroDivisionError:
return t
if mod: # minutes % lapse != 0
t += datetime.timedelta(minutes=math.ceil(t.minute / lapse) * lapse - t.minute)
elif surplus != datetime.timedelta() or lapse < 0:
t += datetime.timedelta(minutes=(t.minute / lapse + 1) * lapse - t.minute)
return t
Hope this helps!
OR you can use pandas
:
>>> import pandas as pd
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> df=pd.DataFrame(L)
>>> df[1]
0 2
1 3
2 5
3 4
4 7
5 7
6 8
Name: 1, dtype: int64
>>> df[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Or numpy
:
>>> import numpy as np
>>> L = [(1,2),(2,3),(4,5),(3,4),(6,7),(6,7),(3,8)]
>>> arr=np.array(L)
>>> arr.T[1]
array([2, 3, 5, 4, 7, 7, 8])
>>> arr.T[1].tolist()
[2, 3, 5, 4, 7, 7, 8]
>>>
Update: I've since created a downloadable REPL - see my other answer.
With the benefit of hindsight:
rlwrap
, which provides readline support to any command, you can combine it with a simple Perl command to create a usable REPL, and thus make do without third-party REPL solutions.
rlwrap
via Homebrew with brew install rlwrap
.rlwrap
via their respective package managers; e.g., on Ubuntu, use sudo apt-get install rlwrap
.rlwrap
and a Perl command.What you do NOT get with Ján's answer:
The only third-party solution that offers these (with non-trivial installation + additional, non-obvious steps), is psh, but:
it hasn't seen activity in around 2.5 years
its focus is different in that it aims to be a full-fledged shell replacement, and thus works like a traditional shell, which means that it doesn't automatically evaluate a command as a Perl statement, and requires an explicit output command such as print
to print the result of an expression.
Ján Sáreník's answer can be improved in one way:
If you install the Data::Printer
module with [sudo] cpan Data::Printer
as a one-time operation, you can load it into the REPL for use of the p()
function, to which you can pass lists/arrays/hashtables for enumeration.
Here's an alias named iperl
with readline and Data::Printer
support, which can you put in your POSIX-like shell's initialization file (e.g., ~/.bashrc
):
alias iperl='rlwrap -A -S "iperl> " perl -MData::Printer -wnE '\''BEGIN { say "# Use `p @<arrayOrList>` or `p %<hashTable>` to print arrays/lists/hashtables; e.g.: `p %ENV`"; } say eval()//$@'\'
E.g., you can then do the following to print all environment variables via hashtable %ENV
:
$ iperl # start the REPL
iperl> p %ENV # print key-value pairs in hashtable %ENV
As with Ján's answer, the scalar result of an expression is automatically printed; e.g.:
iperl> 22 / 7 # automatically print scalar result of expression: 3.14285714285714
Try running the following code:
List<String> listOfString = Arrays.asList("Hello", "World");
ArrayList<String> arrayListOfString = new ArrayList(listOfString);
System.out.println(listOfString.getClass());
System.out.println(arrayListOfString.getClass());
You'll get the following result:
class java.util.Arrays$ArrayList
class java.util.ArrayList
So, that means they're 2 different classes that aren't extending each other. java.util.Arrays$ArrayList signifies the private class named ArrayList (inner class of Arrays class) and java.util.ArrayList signifies the public class named ArrayList. Thus, casting from java.util.Arrays$ArrayList to java.util.ArrayList and vice versa are irrelevant/not available.
To remove duplicates from a single column
Sub removeDuplicate()
'removeDuplicate Macro
Columns("A:A").Select
ActiveSheet.Range("$A$1:$A$117").RemoveDuplicates Columns:=Array(1), _
Header:=xlNo
Range("A1").Select
End Sub
if you have header then use Header:=xlYes
Increase your range as per your requirement.
you can make it to 1000 like this :
ActiveSheet.Range("$A$1:$A$1000")
More info here here
In Swift 4.2 I would do something like that:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let yourVC = segue.destination as? YourViewController {
yourVC.yourData = self.someData
}
}
case 1 : if you are running project in your local system like 127.0.01:8000 ,
then
add SESSION_DOMAIN=
in your .env file
or in your config/session.php 'domain' => env('SESSION_DOMAIN', ''),
and then run php artisan cache:clear
case 2: if project is running on server and you have domain like "mydomain.com"
add SESSION_DOMAIN=mydomain.com
in your .env file
or in your config/session.php 'domain' => env('SESSION_DOMAIN', 'mydomain.com'),
and then run php artisan cache:clear
Here's an answer to a 2-year old question in case it helps anyone else with the same problem.
Based upon the information you've provided, a permissions issue on the file (or files) would be one cause of the same 500 Internal Server Error.
To check whether this is the problem (if you can't get more detailed information on the error), navigate to the directory in Terminal and run the following command:
ls -la
If you see limited permissions - e.g. -rw-------@
against your file, then that's your problem.
The solution then is to run chmod 644
on the problem file(s) or chmod 755
on the directories. See this answer - How do I set chmod for a folder and all of its subfolders and files? - for a detailed explanation of how to change permissions.
By way of background, I had precisely the same problem as you did on some files that I had copied over from another Mac via Google Drive, which transfer had stripped most of the permissions from the files.
The screenshot below illustrates. The index.php file with the -rw-------@
permissions generates a 500 Internal Server Error, while the index_finstuff.php (precisely the same content!) with -rw-r--r--@
permissions is fine. Changing the permissions on the index.php immediately resolves the problem.
In other words, your PHP code and the server may both be fine. However, the limited read permissions on the file may be forbidding the server from displaying the content, causing the 500 Internal Server Error message to be displayed instead.
I have struggled with this as well. In fact I got here with a google search of exactly the same question. Reading all these answers finally painted a picture in my head and I decided to try to get this down looking at the state of the 2 repositories and 1 sandbox and actions performed over time while watching the version of them. So here is what I came up with. Please correct me if I messed up anywhere.
The three repos with a fetch:
--------------------- ----------------------- -----------------------
- Remote Repo - - Remote Repo - - Remote Repo -
- - - gets pushed - - -
- @ R01 - - @ R02 - - @ R02 -
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
- Local Repo - - Local Repo - - Local Repo -
- pull - - - - fetch -
- @ R01 - - @ R01 - - @ R02 -
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
- Local Sandbox - - Local Sandbox - - Local Sandbox -
- Checkout - - new work done - - -
- @ R01 - - @ R01+ - - @R01+ -
--------------------- ----------------------- -----------------------
The three repos with a pull
--------------------- ----------------------- -----------------------
- Remote Repo - - Remote Repo - - Remote Repo -
- - - gets pushed - - -
- @ R01 - - @ R02 - - @ R02 -
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
- Local Repo - - Local Repo - - Local Repo -
- pull - - - - pull -
- @ R01 - - @ R01 - - @ R02 -
--------------------- ----------------------- -----------------------
--------------------- ----------------------- -----------------------
- Local Sandbox - - Local Sandbox - - Local Sandbox -
- Checkout - - new work done - - merged with R02 -
- @ R01 - - @ R01+ - - @R02+ -
--------------------- ----------------------- -----------------------
This helped me understand why a fetch is pretty important.
I had the same issue. My mistake was that I used @Service annotation on the Service Interface. The @Service annotation should be applied to the ServiceImpl class.
You are having a controlled component where input
value is determined by this.state.city
. So once you submit you have to clear your state which will clear your input automatically.
onHandleSubmit(e) {
e.preventDefault();
const city = this.state.city;
this.props.onSearchTermChange(city);
this.setState({
city: ''
});
}
I have experienced the same problem with Eclipse Indigo release - even though the project set up was correct. The main cause I suspect is that the workspace is defined in a separate folder from the actual source folders (as mentioned user748337). To fix the problem, I had to enable the project specific settings option (in the Porject preference) although it wasn't different from the workspace settings.
You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"
Get a key/value GET hset_key
equals to HGET hset key
Add a key/value SET hset_key value
equals to HSET hset key
Get all keys KEYS hset_*
equals to HGETALL hset
Get all vals should be done in 2 ops, first get all keys KEYS hset_*
then get the value for each key
Add a key/value with TTL or expire which is the topic of question:
SET hset_key value
EXPIRE hset_key
Note: KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.
Note:
KEYS
will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_*
might be better as long as it doesn't block the server but still performance is an issue in case of big database.
You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.
Thanks to @DanFarrell who highlighted the performance issue related to
KEYS
ImageMagick and GD can handle PNGs too; heck, you could even do stuff with nothing but gdk-pixbuf. Are you looking for a graphical editor, or scriptable/embeddable libraries?
You can change the display resolution graphically (without using Terminal) on Raspbian GNU/Linux 8 (jessie) using following window.
Application Menu > Preferences > Raspberry Pi Configuration > System > Set Resolution.