Try this out.
int day = 0;
int hh = 0;
int mm = 0;
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy 'at' hh:mm aa");
Date oldDate = dateFormat.parse(oldTime);
Date cDate = new Date();
Long timeDiff = cDate.getTime() - oldDate.getTime();
day = (int) TimeUnit.MILLISECONDS.toDays(timeDiff);
hh = (int) (TimeUnit.MILLISECONDS.toHours(timeDiff) - TimeUnit.DAYS.toHours(day));
mm = (int) (TimeUnit.MILLISECONDS.toMinutes(timeDiff) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(timeDiff)));
} catch (ParseException e) {
e.printStackTrace();
}
if (mm <= 60 && hh!= 0) {
if (hh <= 60 && day != 0) {
return day + " DAYS AGO";
} else {
return hh + " HOUR AGO";
}
} else {
return mm + " MIN AGO";
}
fun Fragment?.runOnUiThread(action: () -> Unit) {
this ?: return
if (!isAdded) return // Fragment not attached to an Activity
activity?.runOnUiThread(action)
}
Then, in any Fragment
you can just call runOnUiThread
. This keeps calls consistent across activities and fragments.
runOnUiThread {
// Call your code here
}
NOTE: If
Fragment
is no longer attached to anActivity
, callback will not be called and no exception will be thrown
If you want to access this style from anywhere, you can add a common object and import the method:
object ThreadUtil {
private val handler = Handler(Looper.getMainLooper())
fun runOnUiThread(action: () -> Unit) {
if (Looper.myLooper() != Looper.getMainLooper()) {
handler.post(action)
} else {
action.invoke()
}
}
}
==
is the correct operator to compare strings in Go. However, the strings that you read from STDIN with reader.ReadString
do not contain "a"
, but "a\n"
(if you look closely, you'll see the extra line break in your example output).
You can use the strings.TrimRight
function to remove trailing whitespaces from your input:
if strings.TrimRight(input, "\n") == "a" {
// ...
}
I have no idea why Enums are not support natively by Python. The best way I've found to emulate them is by overridding _ str _ and _ eq _ so you can compare them and when you use print() you get the string instead of the numerical value.
class enumSeason():
Spring = 0
Summer = 1
Fall = 2
Winter = 3
def __init__(self, Type):
self.value = Type
def __str__(self):
if self.value == enumSeason.Spring:
return 'Spring'
if self.value == enumSeason.Summer:
return 'Summer'
if self.value == enumSeason.Fall:
return 'Fall'
if self.value == enumSeason.Winter:
return 'Winter'
def __eq__(self,y):
return self.value==y.value
Usage:
>>> s = enumSeason(enumSeason.Spring)
>>> print(s)
Spring
This was extremely helpful for me when trying to automate Cisco SIP phone configuration using an Excel spreadsheet as the source. My only issue was when I tried to make an array and populate it using $array | Add-Member ...
as I needed to use it later on to generate the config file. Just defining an array and making it the for loop allowed it to store correctly.
$lastCell = 11
$startRow, $model, $mac, $nOF, $ext = 1, 1, 5, 6, 7
$excel = New-Object -ComObject excel.application
$wb = $excel.workbooks.open("H:\Strike Network\Phones\phones.xlsx")
$sh = $wb.Sheets.Item(1)
$endRow = $sh.UsedRange.SpecialCells($lastCell).Row
$phoneData = for ($i=1; $i -le $endRow; $i++)
{
$pModel = $sh.Cells.Item($startRow,$model).Value2
$pMAC = $sh.Cells.Item($startRow,$mac).Value2
$nameOnPhone = $sh.Cells.Item($startRow,$nOF).Value2
$extension = $sh.Cells.Item($startRow,$ext).Value2
New-Object PSObject -Property @{ Model = $pModel; MAC = $pMAC; NameOnPhone = $nameOnPhone; Extension = $extension }
$startRow++
}
I used to have no issues adding information to an array with Add-Member but that was back in PSv2/3, and I've been away from it a while. Though the simple solution saved me manually configuring 100+ phones and extensions - which nobody wants to do.
DateTimeFormatter
has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and
NOV wont work:
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
try {
LocalDate datetime = LocalDate.parse(oldDate, pattern);
System.out.println(datetime);
} catch (DateTimeParseException e) {
// DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
// Exception handling message/mechanism/logging as per company standard
}
DateTimeFormatterBuilder
provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.
DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
.append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
LocalDate datetime = LocalDate.parse(oldDate, f);
System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
// Exception handling message/mechanism/logging as per company standard
}
I had this same notice appear after making some changes. It turned out to be because I had changed between a single $http
request to multiple requests using angularjs $q
service.
I hadn't wrapped them in an array. e.g.
$q.all(request1, request2).then(...)
rather than
$q.all([request1, request2]).then(...)
I hope this might save somebody some time.
This is the error that is returned when the Windows Firewall blocks the port (out-going). We have a strict web server so the outgoing ports are blocked by default. All I had to do was to create a rule to allow the TCP port number in wf.msc.
You need to find reference of existing Fragment and remove that fragment using below code. You need add/commit fragment using one tag ex. "TAG_FRAGMENT".
Fragment fragment = getSupportFragmentManager().findFragmentByTag(TAG_FRAGMENT);
if(fragment != null)
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
That is it.
I think the problem you're running into is that, even though you can set your own umask values in the system, this does not allow you to explicitly control the default permissions set on a new file by gedit (or whatever editor you use).
I believe this detail is hard-coded into gedit and most other editors. Your options for changing it are (a) hacking up your own mod of gedit or (b) finding a text editor that allows you to set a preference for default permissions on new files. (Sorry, I know of none.)
In light of this, it's really not so bad to have to chmod your files, right?
By far the most simplest way I can think of -
If your dialog is made out of a vertical LinearLayout, just add a "height filling" dummy view, that will occupy the entire height of the screen.
For example -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/editSearch" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/listView"/>
<!-- this is a dummy view that will make sure the dialog is highest -->
<View
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"/>
</LinearLayout>
Notice the android:weightSum="1"
in the LinearLayout's attributes and the android:layout_weight="1"
in the dummy View's attributes
Code:
$rows = array();
while($r = mysqli_fetch_array($result,MYSQL_ASSOC)) {
$row_array['result'] = $r;
array_push($rows,$row_array); // here we push every iteration to an array otherwise you will get only last iteration value
}
echo json_encode($rows);
Another option is using eval
. This is only suitable if the strings are trusted. The first script can echo the variable assignments:
echo "VAR=myvalue"
Then:
eval $(./first.sh) ./second.sh
This approach is of particular interest when the second script you want to set environment variables for is not in bash and you also don't want to export
the variables, perhaps because they are sensitive and you don't want them to persist.
(Firstly read the other answers which has explained the for
in the <label></label>
tags.
Well, both the tops answers are correct, but for my challenge, it was when you have several radio boxes, you should select for them a common name like name="r1"
but with different ids id="r1_1" ... id="r1_2"
So this way the answer is more clear and removes the conflicts between name and ids as well.
You need different ids for different options of the radio box.
<input type="radio" name="r1" id="r1_1" />_x000D_
_x000D_
<label for="r1_1">button text one</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_2" />_x000D_
_x000D_
<label for="r1_2">button text two</label>_x000D_
<br/>_x000D_
<input type="radio" name="r1" id="r1_3" />_x000D_
_x000D_
<label for="r1_3">button text three</label>
_x000D_
I think using xdg-open http://example.com
is probably the best choice.
In case they don't have it installed I suppose they might have just kde-open
or gnome-open
(both of which take a single file/url) or some other workaround such as looping over common browser executable names until you find one which can be executed(using which). If you want a full list of workarounds/fallbacks I suggest reading xdg-open(it's a shell script which calls out to kde-open/gnome-open/etc. or some other fallback).
But since xdg-open and xdg-mime(used for one of the fallbacks,) are shell scripts I'd recommend including them in your application and if calling which xdg-open
fails add them to temporary PATH variable in your subprograms environment and call out to them. If xdg-open fails, I'd recommend throwing an Exception with an error message from what it output on stderr and catching the exception and printing/displaying the error message.
I would ignore the java awt Desktop solution as the bug seems to indicate they don't plan on supporting non-gnome desktops anytime soon.
Default behaviour of PowerShell is just to dump everything that falls out of a pipeline without being picked up by another pipeline element or being assigned to a variable (or redirected) into Out-Host
. What Out-Host
does is obviously host-dependent.
Just letting things fall out of the pipeline is not a substitute for Write-Host
which exists for the sole reason of outputting text in the host application.
If you want output, then use the Write-*
cmdlets. If you want return values from a function, then just dump the objects there without any cmdlet.
try to clean the eclipse project
swift 5 just two lines is enough. Add into your viewDidLoad
should work.
let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
view.addGestureRecognizer(tapGesture)
If your tap gesture blocked some other touches, then add this line:
tapGesture.cancelsTouchesInView = false
You probably shouldn't do this; you're breaking the basic pattern of how Make works. But here it is:
action:
@echo action $(filter-out $@,$(MAKECMDGOALS))
%: # thanks to chakrit
@: # thanks to William Pursell
EDIT:
To explain the first command,
$(MAKECMDGOALS)
is the list of "targets" spelled out on the command line, e.g. "action value1 value2".
$@
is an automatic variable for the name of the target of the rule, in this case "action".
filter-out
is a function that removes some elements from a list. So $(filter-out bar, foo bar baz)
returns foo baz
(it can be more subtle, but we don't need subtlety here).
Put these together and $(filter-out $@,$(MAKECMDGOALS))
returns the list of targets specified on the command line other than "action", which might be "value1 value2".
If you don't need to retrieve the user's location every time it changes (I have no idea why nearly every solution does that by using a location listener), it's just wasteful to do so. The asker was clearly interested in retrieving the location just once. Now FusedLocationApi is deprecated, so as a replacement for @Andrey's post, you can do:
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
// I suppressed the missing-permission warning because this wouldn't be executed in my
// case without location services being enabled
@SuppressLint("MissingPermission") android.location.Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
double userLat = lastKnownLocation.getLatitude();
double userLong = lastKnownLocation.getLongitude();
This just puts together some scattered information in the docs, this being the most important source.
If you have
@Transactional // Spring Transactional
class MyDao extends Dao {
}
and super-class
class Dao {
public void save(Entity entity) { getEntityManager().merge(entity); }
}
and you call
@Autowired MyDao myDao;
myDao.save(entity);
you won't get a Spring TransactionInterceptor (that gives you a transaction).
This is what you need to do:
@Transactional
class MyDao extends Dao {
public void save(Entity entity) { super.save(entity); }
}
Unbelievable but true.
This may read like your grandpa givin advice, but all answers here did not mention the best way: go nd install ActivePython instead of python.org windows binaries. I was really wondering for a long time why Python development on windows was such a pita - until I installed activestate python. I am not affiliated with them. It is just the plain truth. Write it on every wall: Python development on Windows = ActiveState!
you then just pypm install mysql-python
and everything works smoothly. no compile orgy. no strange errors. no terror. Just start coding and doing real work after five minutes.
This is the only way to go on windows. Really.
I encountered just the same problem when I wanted to store the dates in the DB as UTC and avoid using varchar
and explicit String <-> java.util.Date
conversions, or setting my whole Java app in the UTC time zone (because this could lead to another unexpected issues, if the JVM is shared across many applications).
So, there is an open source project DbAssist
, which allows you to easily fix the read/write as UTC date from the database. Since you are using JPA Annotations to map the fields in the entity, all you have to do is to include the following dependency to your Maven pom
file:
<dependency>
<groupId>com.montrosesoftware</groupId>
<artifactId>DbAssist-5.2.2</artifactId>
<version>1.0-RELEASE</version>
</dependency>
Then you apply the fix (for Hibernate + Spring Boot example) by adding @EnableAutoConfiguration
annotation before the Spring application class. For other setups installation instructions and more use examples, just refer to the project's github.
The good thing is that you don't have to modify the entities at all; you can leave their java.util.Date
fields as they are.
5.2.2
has to correspond to the Hibernate version you are using. I am not sure, which version you are using in your project, but the full list of provided fixes is available on the wiki page of the project's github. The reason why the fix is different for various Hibernate versions is because Hibernate creators changed the API a couple of times between the releases.
Internally, the fix uses hints from divestoclimb, Shane and a few other sources in order to create a custom UtcDateType
. Then it maps the standard java.util.Date
with the custom UtcDateType
which handles all the necessary time zone handling.
The mapping of the types is achieved using @Typedef
annotation in the provided package-info.java
file.
@TypeDef(name = "UtcDateType", defaultForType = Date.class, typeClass = UtcDateType.class),
package com.montrosesoftware.dbassist.types;
You can find an article here which explains why such a time shift occurs at all and what are the approaches to solve it.
This work for me
$('#mySelect option:contains(' + value + ')').attr('selected', 'selected');
The command is date
To customise the output there are a myriad of options available, see date --help
for a list.
For example, date '+%A %W %Y %X'
gives Tuesday 34 2013 08:04:22
which is the name of the day of the week, the week number, the year and the time.
Explicitly Target IE versions without hacks using HTML and CSS
Use this approach if you don't want hacks in your CSS. Add a browser-unique class to the <html>
element so you can select based on browser later.
Example
<!doctype html>
<!--[if IE]><![endif]-->
<!--[if lt IE 7 ]> <html lang="en" class="ie6"> <![endif]-->
<!--[if IE 7 ]> <html lang="en" class="ie7"> <![endif]-->
<!--[if IE 8 ]> <html lang="en" class="ie8"> <![endif]-->
<!--[if IE 9 ]> <html lang="en" class="ie9"> <![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html lang="en"><!--<![endif]-->
<head></head>
<body></body>
</html>
Then in your CSS you can very strictly access your target browser.
Example
.ie6 body {
border:1px solid red;
}
.ie7 body {
border:1px solid blue;
}
For more information check out http://html5boilerplate.com/
Target IE versions with CSS "Hacks"
More to your point, here are the hacks that let you target IE versions.
Use "\9" to target IE8 and below.
Use "*" to target IE7 and below.
Use "_" to target IE6.
Example:
body {
border:1px solid red; /* standard */
border:1px solid blue\9; /* IE8 and below */
*border:1px solid orange; /* IE7 and below */
_border:1px solid blue; /* IE6 */
}
Update: Target IE10
IE10 does not recognize the conditional statements so you can use this to apply an "ie10" class to the <html>
element
<!doctype html>
<html lang="en">
<!--[if !IE]><!--><script>if (/*@cc_on!@*/false) {document.documentElement.className+=' ie10';}</script><!--<![endif]-->
<head></head>
<body></body>
</html>
1. About onCreate() and onUpgrade()
onCreate(..)
is called whenever the app is freshly installed. onUpgrade
is called whenever the app is upgraded and launched and the database version is not the same.
2. Incrementing the db version
You need a constructor like:
MyOpenHelper(Context context) {
super(context, "dbname", null, 2); // 2 is the database version
}
IMPORTANT: Incrementing the app version alone is not enough for onUpgrade
to be called!
3. Don't forget your new users!
Don't forget to add
database.execSQL(DATABASE_CREATE_color);
to your onCreate() method as well or newly installed apps will lack the table.
4. How to deal with multiple database changes over time
When you have successive app upgrades, several of which have database upgrades, you want to be sure to check oldVersion
:
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch(oldVersion) {
case 1:
db.execSQL(DATABASE_CREATE_color);
// we want both updates, so no break statement here...
case 2:
db.execSQL(DATABASE_CREATE_someothertable);
}
}
This way when a user upgrades from version 1 to version 3, they get both updates. When a user upgrades from version 2 to 3, they just get the revision 3 update... After all, you can't count on 100% of your user base to upgrade each time you release an update. Sometimes they skip an update or 12 :)
5. Keeping your revision numbers under control while developing
And finally... calling
adb uninstall <yourpackagename>
totally uninstalls the app. When you install again, you are guaranteed to hit onCreate
which keeps you from having to keep incrementing the database version into the stratosphere as you develop...
ngModel
and ngChecked
are not meant to be used together.
ngChecked
is expecting an expression, so by saying ng-checked="true"
, you're basically saying that the checkbox will always be checked by default.
You should be able to just use ngModel
, tied to a boolean property on your model. If you want something else, then you either need to use ngTrueValue
and ngFalseValue
(which only support strings right now), or write your own directive.
What is it exactly that you're trying to do? If you just want the first checkbox to be checked by default, you should change your model -- item1: true,
.
Edit: You don't have to submit your form to debug the current state of the model, btw, you can just dump {{testModel}}
into your HTML (or <pre>{{testModel|json}}</pre>
). Also your ngModel
attributes can be simplified to ng-model="testModel.item1"
.
Here is my one-liner:
console.log('time: ', new Date(new Date().valueOf() + 60000))
_x000D_
Sometimes the columns will have commas within themselves, such as:
"Some item", "Another Item", "Also, One more item"
In these cases, splitting on "," will break some columns. Maybe an easier way, but I just made my own method (as a bonus, handles spaces after commas and returns an IList):
private IList<string> GetColumns(string columns)
{
IList<string> list = new List<string>();
if (!string.IsNullOrWhiteSpace(columns))
{
if (columns[0] != '\"')
{
// treat as just one item
list.Add(columns);
}
else
{
bool gettingItemName = true;
bool justChanged = false;
string itemName = string.Empty;
for (int index = 1; index < columns.Length; index++)
{
justChanged = false;
if (subIndustries[index] == '\"')
{
gettingItemName = !gettingItemName;
justChanged = true;
}
if ((gettingItemName == false) &&
(justChanged == true))
{
list.Add(itemName);
itemName = string.Empty;
justChanged = false;
}
if ((gettingItemName == true) && (justChanged == false))
{
itemName += columns[index];
}
}
}
}
return list;
}
If you need good, easy GIT server than you must try GitBlit. Also i use gitolite but it only server, with GitBlit you get all in one, server, admin, repos. manager ... URL: http://gitblit.com/
With the new C++ standard (may need special flags to be enabled on your compiler) you can simply do:
std::vector<int> v { 34,23 };
// or
// std::vector<int> v = { 34,23 };
Or even:
std::vector<int> v(2);
v = { 34,23 };
On compilers that don't support this feature (initializer lists) yet you can emulate this with an array:
int vv[2] = { 12,43 };
std::vector<int> v(&vv[0], &vv[0]+2);
Or, for the case of assignment to an existing vector:
int vv[2] = { 12,43 };
v.assign(&vv[0], &vv[0]+2);
Like James Kanze suggested, it's more robust to have functions that give you the beginning and end of an array:
template <typename T, size_t N>
T* begin(T(&arr)[N]) { return &arr[0]; }
template <typename T, size_t N>
T* end(T(&arr)[N]) { return &arr[0]+N; }
And then you can do this without having to repeat the size all over:
int vv[] = { 12,43 };
std::vector<int> v(begin(vv), end(vv));
It does not exactly answer your question, but to get around the problem,
you can either create a .cmd file with following content:
start netbeans --jdkhome c:\path\to\jdk
or in the shortcut of Netbeans set the above option.
Try this one for CLOB sizes bigger than VARCHAR2:
We have to split the CLOB in parts of "VARCHAR2 compatible" sizes, run lengthb through every part of the CLOB data, and summarize all results.
declare
my_sum int;
begin
for x in ( select COLUMN, ceil(DBMS_LOB.getlength(COLUMN) / 2000) steps from TABLE )
loop
my_sum := 0;
for y in 1 .. x.steps
loop
my_sum := my_sum + lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 ));
-- some additional output
dbms_output.put_line('step:' || y );
dbms_output.put_line('char length:' || DBMS_LOB.getlength(dbms_lob.substr( x.COLUMN, 2000 , (y-1)*2000+1 )));
dbms_output.put_line('byte length:' || lengthb(dbms_lob.substr( x.COLUMN, 2000, (y-1)*2000+1 )));
continue;
end loop;
dbms_output.put_line('char summary:' || DBMS_LOB.getlength(x.COLUMN));
dbms_output.put_line('byte summary:' || my_sum);
continue;
end loop;
end;
/
To increase security even more, You can have md5 encryption along with two different salt strings, one static salt defined in php file and then one more randomly generated unique salt for each password record.
Here is how you can generate salt, md5 string and store:
$unique_salt_string = hash('md5', microtime());
$password = hash('md5', $_POST['password'].'static_salt'.$unique_salt_string);
$query = "INSERT INTO users (username,password,salt) VALUES('bob','".$password."', '".$unique_salt_string."');
Now you have a static salt, which is valid for all your passwords, that is stored in the .php file. Then, at registration execution, you generate a unique hash for that specific password.
This all ends up with: two passwords that are spelled exactly the same, will have two different hashes. The unique hash is stored in the database along with the current id. If someone grab the database, they will have every single unique salt for every specific password. But what they don't have is your static salt, which make things a lot harder for every "hacker" out there.
This is how you check the validity of your password on login.php for example:
$user = //username input;
$db_query = mysql_query("SELECT salt FROM users WHERE username='$user'");
while($salt = mysql_fetch_array($db_query)) {
$password = hash('md5',$_POST['userpassword'].'static_salt'.$salt[salt]);
}
This method is very powerful and secure. If you want to use sha512 encryption, just to put that inside the hash function instead of md5 in above code.
A class is a blueprint that is needed to make an object(= instance).
The difference between an object and an instance is, an object is a thing and an instance is a relation.
In other words, instance describes the relation of an object to the class that the object was made from.
You could use scipy.interpolate.spline
to smooth out your data yourself:
from scipy.interpolate import spline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
power_smooth = spline(T, power, xnew)
plt.plot(xnew,power_smooth)
plt.show()
spline is deprecated in scipy 0.19.0, use BSpline class instead.
Switching from spline
to BSpline
isn't a straightforward copy/paste and requires a little tweaking:
from scipy.interpolate import make_interp_spline, BSpline
# 300 represents number of points to make between T.min and T.max
xnew = np.linspace(T.min(), T.max(), 300)
spl = make_interp_spline(T, power, k=3) # type: BSpline
power_smooth = spl(xnew)
plt.plot(xnew, power_smooth)
plt.show()
As one of the possible codes
echo off
for /f "usebackq tokens=* delims= " %%x in (`chdir`) do set var=%var% %%x
echo The current directory is: "%var:~1%"
For me it works a deleting "C:\ProgramData\Oracle\Java\javapath" in my system enviroment PATH variable
Edit: If you don't have that variable or it does not work you can directly delete or rename the directory "C:\ProgramData\Oracle\Java\javapath"
The new Database projects in Visual Studio provide source control and change scripts.
They have a nice tool that compares databases and can generate a script that converts the schema of one into the other, or updates the data in one to match the other.
The db schema is "shredded" to create many, many small .sql files, one per DDL command that describes the DB.
+tom
Additional info 2008-11-30
I have been using it as a developer for the past year and really like it. It makes it easy to compare my dev work to production and generate a script to use for the release. I don't know if it is missing features that DBAs need for "enterprise-type" projects.
Because the schema is "shredded" into sql files the source control works fine.
One gotcha is that you need to have a different mindset when you use a db project. The tool has a "db project" in VS, which is just the sql, plus an automatically generated local database which has the schema and some other admin data -- but none of your application data, plus your local dev db that you use for app data dev work. You rarely are aware of the automatically generated db, but you have to know its there so you can leave it alone :). This special db is clearly recognizable because it has a Guid in its name,
The VS DB Project does a nice job of integrating db changes that other team members have made into your local project/associated db. but you need to take the extra step to compare the project schema with your local dev db schema and apply the mods. It makes sense, but it seems awkward at first.
DB Projects are a very powerful tool. They not only generate scripts but can apply them immediately. Be sure not to destroy your production db with it. ;)
I really like the VS DB projects and I expect to use this tool for all my db projects going forward.
+tom
There isn't really a formal manual, because there's no single style or standard.
So long as you understand the rules of identifier naming you can use whatever you like.
In practice, I find it easier to use lower_case_underscore_separated_identifiers
because it isn't necessary to "Double Quote"
them everywhere to preserve case, spaces, etc.
If you wanted to name your tables and functions "@MyA??! ""betty"" Shard$42"
you'd be free to do that, though it'd be pain to type everywhere.
The main things to understand are:
Unless double-quoted, identifiers are case-folded to lower-case, so MyTable
, MYTABLE
and mytable
are all the same thing, but "MYTABLE"
and "MyTable"
are different;
Unless double-quoted:
SQL identifiers and key words must begin with a letter (a-z, but also letters with diacritical marks and non-Latin letters) or an underscore (_). Subsequent characters in an identifier or key word can be letters, underscores, digits (0-9), or dollar signs ($).
You must double-quote keywords if you wish to use them as identifiers.
In practice I strongly recommend that you do not use keywords as identifiers. At least avoid reserved words. Just because you can name a table "with"
doesn't mean you should.
I don't think "blueprint" is a good word to use. A blueprint tells you how to build something. An interface specifically avoids telling you how to build something.
An interface defines how you can interact with a class, i.e. what methods it supports.
AQTime is reasonable, but has a bit of a learning curve and isn't as easy to use as the built in one in Team Suite
In case anybody is looking at this old question, a handy command to see the changes since your last update:
svn log -r $(svn info | grep Revision | cut -f 2 -d ' '):HEAD -v
LE (thanks Gary for the comment)
same thing, but much shorter and more logical:
svn log -r BASE:HEAD -v
On top of your lastest jsfiddle, you just missed one thing:
#sidebar_wrap {
width:40%;
height:200px;
background:green;
float:right;
}
#sidebar {
width:inherit;
margin-top:10px;
background-color:limegreen;
position:fixed;
max-width: 240px; /*This is you missed*/
}
But, how this will solve your problem? Simple, lets explain why is bigger than expect first.
Fixed element #sidebar
will use window width size as base to get its own size, like every other fixed element, once in this element is defined width:inherit
and #sidebar_wrap
has 40% as value in width, then will calculate window.width * 40%
, then when if your window width is bigger than your .container
width, #sidebar
will be bigger than #sidebar_wrap
.
This is way, you must set a max-width in your #sidebar_wrap
, to prevent to be bigger than #sidebar_wrap
.
Check this jsfiddle that shows a working code and explain better how this works.
I have some documents where …
was showing as …
and ê
was showing as ê
. This is how it got there (python code):
# Adam edits original file using windows-1252
windows = '\x85\xea'
# that is HORIZONTAL ELLIPSIS, LATIN SMALL LETTER E WITH CIRCUMFLEX
# Beth reads it correctly as windows-1252 and writes it as utf-8
utf8 = windows.decode("windows-1252").encode("utf-8")
print(utf8)
# Charlie reads it *incorrectly* as windows-1252 writes a twingled utf-8 version
twingled = utf8.decode("windows-1252").encode("utf-8")
print(twingled)
# detwingle by reading as utf-8 and writing as windows-1252 (it's really utf-8)
detwingled = twingled.decode("utf-8").encode("windows-1252")
assert utf8==detwingled
To fix the problem, I used python code like this:
with open("dirty.html","rb") as f:
dt = f.read()
ct = dt.decode("utf8").encode("windows-1252")
with open("clean.html","wb") as g:
g.write(ct)
(Because someone had inserted the twingled version into a correct UTF-8 document, I actually had to extract only the twingled part, detwingle it and insert it back in. I used BeautifulSoup for this.)
It is far more likely that you have a Charlie in content creation than that the web server configuration is wrong. You can also force your web browser to twingle the page by selecting windows-1252 encoding for a utf-8 document. Your web browser cannot detwingle the document that Charlie saved.
Note: the same problem can happen with any other single-byte code page (e.g. latin-1) instead of windows-1252.
Within Nano use Ctrl+O to save and Ctrl+X to exit if you were wondering
<ul>
<li ng-repeat=interface in interfaces>
<img src='green-checkmark.png' ng-show="interface=='UP'" />
<img src='big-black-X.png' ng-show="interface=='DOWN'" />
</li>
</ul>
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
If you're ok with POSIX, you can also use popen()
/pclose()
#include <stdio.h>
#include <stdlib.h>
int main(void) {
/* ls -al | grep '^d' */
FILE *pp;
pp = popen("ls -al", "r");
if (pp != NULL) {
while (1) {
char *line;
char buf[1000];
line = fgets(buf, sizeof buf, pp);
if (line == NULL) break;
if (line[0] == 'd') printf("%s", line); /* line includes '\n' */
}
pclose(pp);
}
return 0;
}
You should use the exit
keyword.
I prefer tools with some friendly gui!
I used npm-gui
which gives you list of local and global packages
The package is at https://www.npmjs.com/package/npm-gui and https://github.com/q-nick/npm-gui
//Once
npm install -g npm-gui
cd c:\your-prject-folder
npm-gui localhost:9000
At your browser http:\\localhost:9000
This work crossbrowser for me (IE11, EDGE, CHROME, FIREFOX, OPERA), use https://www.icoconverter.com/ to create .ico file
<link data-senna-track="temporary" href="${favicon_url}" rel="Shortcut Icon" />
<link rel="icon" href="${favicon_url}" type="image/x-icon" />
<link rel="shortcut icon" href="${favicon_url}" type="image/x-icon" />
In HTML5 better use this:
{
//...
canvas.width = img.naturalWidth; //img.width;
canvas.height = img.naturalHeight; //img.height;
//...
}
I presume that this question is a continuation of this one.
What are you trying to do? Do you really want to dynamically change the text in your TextView objects when the user clicks a button? You can certainly do that, if you have a reason, but, if the text is static, it is usually set in the main.xml file, like this:
<TextView
android:id="@+id/rate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/rate"
/>
The string "@string/rate" refers to an entry in your strings.xml file that looks like this:
<string name="rate">Rate</string>
If you really want to change this text later, you can do so by using Nikolay's example - you'd get a reference to the TextView by utilizing the id defined for it within main.xml, like this:
final TextView textViewToChange = (TextView) findViewById(R.id.rate);
textViewToChange.setText(
"The new text that I'd like to display now that the user has pushed a button.");
You have several options if you use BufferedReader
. This buffered reader is faster than Reader so you can wrap it.
BufferedReader reader = new BufferedReader(new FileReader(path));
reader.read(char[] buffer);
this reads line into char array. You have similar options. Look at documentation.
You can collect or set the content of a selected tag.
As a Pseudo idea, its similar to having many boxes within a room and imply the idea 'everything within that box'
map
can be much faster than replace
If your dictionary has more than a couple of keys, using map
can be much faster than replace
. There are two versions of this approach, depending on whether your dictionary exhaustively maps all possible values (and also whether you want non-matches to keep their values or be converted to NaNs):
In this case, the form is very simple:
df['col1'].map(di) # note: if the dictionary does not exhaustively map all
# entries then non-matched entries are changed to NaNs
Although map
most commonly takes a function as its argument, it can alternatively take a dictionary or series: Documentation for Pandas.series.map
If you have a non-exhaustive mapping and wish to retain the existing variables for non-matches, you can add fillna
:
df['col1'].map(di).fillna(df['col1'])
as in @jpp's answer here: Replace values in a pandas series via dictionary efficiently
Using the following data with pandas version 0.23.1:
di = {1: "A", 2: "B", 3: "C", 4: "D", 5: "E", 6: "F", 7: "G", 8: "H" }
df = pd.DataFrame({ 'col1': np.random.choice( range(1,9), 100000 ) })
and testing with %timeit
, it appears that map
is approximately 10x faster than replace
.
Note that your speedup with map
will vary with your data. The largest speedup appears to be with large dictionaries and exhaustive replaces. See @jpp answer (linked above) for more extensive benchmarks and discussion.
Although almost all web sites still place Jquery and other javascript on header :D , even check stackoverflow.com .
I also suggest you to put on before end tag of body. You can check loading time after placing on either places. Script tag will pause your webpage to load further.
and after placing javascript on footer, you may get unusual looks of your webpage until it loads javascript, so place css on your header section.
Use Func<T>
rather than Action<T>
.
Action<T>
acts like a void method with parameter of type T, while Func<T>
works like a function with no parameters and which returns an object of type T.
If you wish to give parameters to your function, use Func<TParameter1, TParameter2, ..., TReturn>
.
Consider the applications that you are pulling - are they Windows based? If not, you need to run a Linux container.
Without using the experimental mode, you can only use Docker in one style of container vs the other. If you activate the experimental mode as mentioned above, you can use Windows and Linux containers as required by the applications you are pulling in the compose file.
Key note: Experimental - still in development by Docker.
Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.
curl: (3) [globbing] nested braces not supported at pos X
This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.
As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing:
curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'
<ul class="names" id="names_list">
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
<a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>
</ul>
$(document).ready(function(){
var a=0;
var ac;
var ac2;
$(".names li").click(function(){
var b=0;
if(a==0)
{
var accc="#"+ac2;
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
$(this).css({
"background":"#d3b730",
"color":"#000",
});
ac=$(this).attr('class');
ac2=$(this).attr('id');
a=1;
}
else{
var accc="#"+ac2;
//alert(accc);
if(ac=='part2')
{
$(accc).css({
"background": "#322f28",
"color":"#fff",
});
}
if(ac=='part1')
{
$(accc).css({
"background": "#3e3b34",
"color":"#fff",
});
}
a=0;
ac=$(this).attr('class');
ac2=$(this).attr('id');
$(this).css({
"background":"#d3b730",
"color":"#000",
});
}
});
Max heap Usage for the application is is 1024 MB
Obviously some of your lines don't have valid float data, specifically some line have text id
which can't be converted to float.
When you try it in interactive prompt you are trying only first line, so best way is to print the line where you are getting this error and you will know the wrong line e.g.
#!/usr/bin/python
import os,sys
from scipy import stats
import numpy as np
f=open('data2.txt', 'r').readlines()
N=len(f)-1
for i in range(0,N):
w=f[i].split()
l1=w[1:8]
l2=w[8:15]
try:
list1=[float(x) for x in l1]
list2=[float(x) for x in l2]
except ValueError,e:
print "error",e,"on line",i
result=stats.ttest_ind(list1,list2)
print result[1]
The signature:
bool operator<<(const obj&, const obj&);
Seems rather suspect, this does not fit the stream
convention nor the bitwise convention so it looks like a case of operator overloading abuse, operator <
should return bool
but operator <<
should probably return something else.
If you meant so say:
ostream& operator<<(ostream&, const obj&);
Then since you can't add functions to ostream
by necessity the function must be a free function, whether it a friend
or not depends on what it has to access (if it doesn't need to access private or protected members there's no need to make it friend).
Well, I assume you like to copy data to the Sd-card from the developers computer? You might have rooted the devise and made the area you address available?) I had about the same problem to upload data files for my application(Android Studio 1.3.2 in Win7), but.
So for instance the the adb command can look like this:
adb push C:\testdata\t.txt /sdcard/download/t.txt
The proper way to do this is like this:
LIBS += -L/path/to -lpsapi
This way it will work on all platforms supported by Qt. The idea is that you have to separate the directory from the library name (without the extension and without any 'lib' prefix). Of course, if you are including a Windows specific lib, this really doesn't matter.
In case you want to store your lib files in the project directory, you can reference them with the $$_PRO_FILE_PWD_
variable, e.g.:
LIBS += -L"$$_PRO_FILE_PWD_/3rdparty/libs/" -lpsapi
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
I try to explain it more understandably than the referred PostgreSQL documentation.
Neither TIMESTAMP
variants store a time zone (or an offset), despite what the names suggest. The difference is in the interpretation of the stored data (and in the intended application), not in the storage format itself:
TIMESTAMP WITHOUT TIME ZONE
stores local date-time (aka. wall calendar date and wall clock time). Its time zone is unspecified as far as PostgreSQL can tell (though your application may knows what it is). Hence, PostgreSQL does no time zone related conversion on input or output. If the value was entered into the database as '2011-07-01 06:30:30'
, then no mater in what time zone you display it later, it will still say year 2011, month 07, day 01, 06 hours, 30 minutes, and 30 seconds (in some format). Also, any offset or time zone you specify in the input is ignored by PostgreSQL, so '2011-07-01 06:30:30+00'
and '2011-07-01 06:30:30+05'
are the same as just '2011-07-01 06:30:30'
.
For Java developers: it's analogous to java.time.LocalDateTime
.
TIMESTAMP WITH TIME ZONE
stores a point on the UTC time line. How it looks (how many hours, minutes, etc.) depends on your time zone, but it always refers to the same "physical" instant (like the moment of an actual physical event). The
input is internally converted to UTC, and that's how it's stored. For that, the offset of the input must be known, so when the input contains no explicit offset or time zone (like '2011-07-01 06:30:30'
) it's assumed to be in the current time zone of the PostgreSQL session, otherwise the explicitly specified offset or time zone is used (as in '2011-07-01 06:30:30+05'
). The output is displayed converted to the current time zone of the PostgreSQL session.
For Java developers: It's analogous to java.time.Instant
(with lower resolution though), but with JDBC and JPA 2.2 you are supposed to map it to java.time.OffsetDateTime
(or to java.util.Date
or java.sql.Timestamp
of course).
Some say that both TIMESTAMP
variations store UTC date-time. Kind of, but it's confusing to put it that way in my opinion. TIMESTAMP WITHOUT TIME ZONE
is stored like a TIMESTAMP WITH TIME ZONE
, which rendered with UTC time zone happens to give the same year, month, day, hours, minutes, seconds, and microseconds as they are in the local date-time. But it's not meant to represent the point on the time line that the UTC interpretation says, it's just the way the local date-time fields are encoded. (It's some cluster of dots on the time line, as the real time zone is not UTC; we don't know what it is.)
If you have any access to the server at all, convert its processing to UTF-8. The art of submitting non-UTF-8 forms is a long and sorry story; this document about forms and i18n may be of interest. I understand you do not seem to care about international support; you can always convert the UTF-8 data to html entities to make sure it stays Latin-1.
SOLVED: That's it!!!! For me was compiling with JDK6 but running Tomcat with JDK7, WST uses the system properties and not the eclipse settings. I also configure the same JDK Version in eclipse and in System (check it with java -version in cmd line)
Details: I try to configure eclipse like describe here, but it didn´t solve the problem, then I notice in eclipse´s error log that tomcat was started with jre 1.7. in spite of my configurations.
I also try, in cmd line, 'java -version' and obtained '1.7' instead of expected '1.6'.
I also decide to configure java 1.6 (like in eclipse) in system panel but it didn´t solve the problem. I also desinstall jre 1.7 restart eclipse AND IT SUCCESS!.. It was a very usefull clue, thank you.
Here's my step in Ubuntu 16.04 and Tomcat 8.
Copy folder /var/lib/tomcat8/webapps/ROOT to your folder.
cp -r /var/lib/tomcat8/webapps/ROOT /var/lib/tomcat8/webapps/{yourfolder}
Add your html, css, js, to your folder.
Open "http://localhost:8080/{yourfolder}" in browser
Notes:
If you using chrome web browser and did wrong folder before, then clean web browser's cache(or change another name) otherwise (sometimes) it always 404.
The folder META-INF with context.xml is needed.
manage_pages
permission (you may need the user_events
permission too, not sure)me/accounts
connection and copy your page's access_token
access_token
to the GET fieldsPAGE_ID/events
)See,
There are two ways to convert an RDD to DF in Spark.
toDF()
and createDataFrame(rdd, schema)
I will show you how you can do that dynamically.
The toDF()
command gives you the way to convert an RDD[Row]
to a Dataframe. The point is, the object Row()
can receive a **kwargs
argument. So, there is an easy way to do that.
from pyspark.sql.types import Row
#here you are going to create a function
def f(x):
d = {}
for i in range(len(x)):
d[str(i)] = x[i]
return d
#Now populate that
df = rdd.map(lambda x: Row(**f(x))).toDF()
This way you are going to be able to create a dataframe dynamically.
Other way to do that is creating a dynamic schema. How?
This way:
from pyspark.sql.types import StructType
from pyspark.sql.types import StructField
from pyspark.sql.types import StringType
schema = StructType([StructField(str(i), StringType(), True) for i in range(32)])
df = sqlContext.createDataFrame(rdd, schema)
This second way is cleaner to do that...
So this is how you can create dataframes dynamically.
It looks like whichever program or process you're trying to initialize either isn't installed on your machine, has a damaged installation or needs to be registered.
Either install it, repair it (via Add/Remove Programs) or register it (via Regsvr32.exe).
You haven't provided enough information for us to help you any more than this.
// This code was tested by me (Helio Barbosa)
// this directory (../backup) is for try only.
// it is necessary create it and put files into him.
$hDir = '../backup';
if ($handle = opendir( $hDir )) {
echo "Manipulador de diretório: $handle\n";
echo "Arquivos:\n";
/* Esta é a forma correta de varrer o diretório */
/* Here is the correct form to do find files into the directory */
while (false !== ($file = readdir($handle))) {
// echo($file . "</br>");
$filepath = $hDir . "/" . $file ;
// echo( $filepath . "</br>" );
if(is_file($filepath))
{
echo("Deleting:" . $file . "</br>");
unlink($filepath);
}
}
closedir($handle);
}
String s=pwd;
int n=0;
for(int i=0;i<s.length();i++)
{
if((Character.isDigit(s.charAt(i))))
{
n=5;
break;
}
else
{
}
}
for(int i=0;i<s.length();i++)
{
if((Character.isLetter(s.charAt(i))))
{
n+=5;
break;
}
else
{
}
}
if(n==10)
{
out.print("Password format correct <b>Accepted</b><br>");
}
else
{
out.print("Password must be alphanumeric <b>Declined</b><br>");
}
Explanation:
Try
yum list installed | grep reponame
On one of my servers:
yum list installed | grep remi ImageMagick2.x86_64 6.6.5.10-1.el5.remi installed memcache.x86_64 1.4.5-2.el5.remi installed mysql.x86_64 5.1.54-1.el5.remi installed mysql-devel.x86_64 5.1.54-1.el5.remi installed mysql-libs.x86_64 5.1.54-1.el5.remi installed mysql-server.x86_64 5.1.54-1.el5.remi installed mysqlclient15.x86_64 5.0.67-1.el5.remi installed php.x86_64 5.3.5-1.el5.remi installed php-cli.x86_64 5.3.5-1.el5.remi installed php-common.x86_64 5.3.5-1.el5.remi installed php-domxml-php4-php5.noarch 1.21.2-1.el5.remi installed php-fpm.x86_64 5.3.5-1.el5.remi installed php-gd.x86_64 5.3.5-1.el5.remi installed php-mbstring.x86_64 5.3.5-1.el5.remi installed php-mcrypt.x86_64 5.3.5-1.el5.remi installed php-mysql.x86_64 5.3.5-1.el5.remi installed php-pdo.x86_64 5.3.5-1.el5.remi installed php-pear.noarch 1:1.9.1-6.el5.remi installed php-pecl-apc.x86_64 3.1.6-1.el5.remi installed php-pecl-imagick.x86_64 3.0.1-1.el5.remi.1 installed php-pecl-memcache.x86_64 3.0.5-1.el5.remi installed php-pecl-xdebug.x86_64 2.1.0-1.el5.remi installed php-soap.x86_64 5.3.5-1.el5.remi installed php-xml.x86_64 5.3.5-1.el5.remi installed remi-release.noarch 5-8.el5.remi installed
It works.
For Example Object variable; hastaId
Object hastaId = session.getAttribute("hastaID");
For Example Cast an Object to an int,hastaID
int hastaID=Integer.parseInt(String.valueOf(hastaId));
New updated MatInput Module import is:
import {MatInputModule} from '@angular/material/input';
As per Angular Materials API
Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...
list = [1,2,3,4,5]
deleteList = []
processNo = 0
for item in list:
if condition:
print item
deleteList.insert(0, processNo)
processNo += 1
if len(deleteList) > 0:
for item in deleteList:
del list[item]
It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.
I didn't understand how the accepted answer answers the actual question of how to run any commands on the server after sshpass is given from within the bash script file. For that reason, I'm providing an answer.
After your provided script commands, execute additional commands like below:
sshpass -p 'password' ssh user@host "ls; whois google.com;" #or whichever commands you would like to use, for multiple commands provide a semicolon ; after the command
In your script:
#! /bin/bash
sshpass -p 'password' ssh user@host "ls; whois google.com;"
The accepted answer above is correct. If, however, you only want to reload the cache periodically, and you are using Firefox, the Web Developer tools (under the Tools menu item as of November 2015) provides a Network option. This includes a Reload button. Select the Reload for a once off cache reset.
With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"
Parameters
{
"web": {
"title" : "Le titre de ma Page",
"cssFile" : "20200608_1018.css"
}
}
Application
var express = require('express');
var appli = express();
var serveur = require('http').Server(appli);
var myParams = require('./include/my_params.json');
var myFonctions = require('./include/my_fonctions.js');
appli.locals = myParams;
EJS Page
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title><%= web.title %></title>
<link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
</head>
</body>
</html>
Hoping it will help
Maximum number of elements of an array
is (2^31)-1
or 2 147 483 647
Generate a different random number each time, not the same one six times in a row.
Use case scenario
I likened Predictability's problem to a bag of six bits of paper, each with a value from 0 to 5 written on it. A piece of paper is drawn from the bag each time a new value is required. If the bag is empty, then the numbers are put back into the bag.
...from this, I can create an algorithm of sorts.
Algorithm
A bag is usually a Collection
. I chose a bool[]
(otherwise known as a boolean array, bit plane or bit map) to take the role of the bag.
The reason I chose a bool[]
is because the index of each item is already the value of each piece of paper. If the papers required anything else written on them then I would have used a Dictionary<string, bool>
in its place. The boolean value is used to keep track of whether the number has been drawn yet or not.
A counter called RemainingNumberCount
is initialised to 5
that counts down as a random number is chosen. This saves us from having to count how many pieces of paper are left each time we wish to draw a new number.
To select the next random value I'm using a for..loop
to scan through the bag of indexes, and a counter to count off when an index
is false
called NumberOfMoves
.
NumberOfMoves
is used to choose the next available number. NumberOfMoves
is first set to be a random value between 0
and 5
, because there are 0..5 available steps we can make through the bag. On the next iteration NumberOfMoves
is set to be a random value between 0
and 4
, because there are now 0..4 steps we can make through the bag. As the numbers are used, the available numbers reduce so we instead use rand() % (RemainingNumberCount + 1)
to calculate the next value for NumberOfMoves
.
When the NumberOfMoves
counter reaches zero, the for..loop
should as follows:
for..loop
's index.false
.for..loop
.Code
The code for the above solution is as follows:
(put the following three blocks into the main .cpp file one after the other)
#include "stdafx.h"
#include <ctime>
#include <iostream>
#include <string>
class RandomBag {
public:
int Value = -1;
RandomBag() {
ResetBag();
}
void NextValue() {
int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);
int NumberOfMoves = rand() % (RemainingNumberCount + 1);
for (int i = 0; i < BagOfNumbersLength; i++)
if (BagOfNumbers[i] == 0) {
NumberOfMoves--;
if (NumberOfMoves == -1)
{
Value = i;
BagOfNumbers[i] = 1;
break;
}
}
if (RemainingNumberCount == 0) {
RemainingNumberCount = 5;
ResetBag();
}
else
RemainingNumberCount--;
}
std::string ToString() {
return std::to_string(Value);
}
private:
bool BagOfNumbers[6];
int RemainingNumberCount;
int NumberOfMoves;
void ResetBag() {
RemainingNumberCount = 5;
NumberOfMoves = rand() % 6;
int BagOfNumbersLength = sizeof(BagOfNumbers) / sizeof(*BagOfNumbers);
for (int i = 0; i < BagOfNumbersLength; i++)
BagOfNumbers[i] = 0;
}
};
A Console class
I create this Console class because it makes it easy to redirect output.
Below in the code...
Console::WriteLine("The next value is " + randomBag.ToString());
...can be replaced by...
std::cout << "The next value is " + randomBag.ToString() << std::endl;
...and then this Console
class can be deleted if desired.
class Console {
public:
static void WriteLine(std::string s) {
std::cout << s << std::endl;
}
};
Main method
Example usage as follows:
int main() {
srand((unsigned)time(0)); // Initialise random seed based on current time
RandomBag randomBag;
Console::WriteLine("First set of six...\n");
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
Console::WriteLine("\nSecond set of six...\n");
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
Console::WriteLine("\nThird set of six...\n");
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
randomBag.NextValue();
Console::WriteLine("The next value is " + randomBag.ToString());
Console::WriteLine("\nProcess complete.\n");
system("pause");
}
Example output
When I ran the program, I got the following output:
First set of six...
The next value is 2
The next value is 3
The next value is 4
The next value is 5
The next value is 0
The next value is 1
Second set of six...
The next value is 3
The next value is 4
The next value is 2
The next value is 0
The next value is 1
The next value is 5
Third set of six...
The next value is 4
The next value is 5
The next value is 2
The next value is 0
The next value is 3
The next value is 1
Process complete.
Press any key to continue . . .
Closing statement
This program was written using Visual Studio 2017, and I chose to make it a Visual C++ Windows Console Application
project using .Net 4.6.1
.
I'm not doing anything particularly special here, so the code should work on earlier versions of Visual Studio too.
You can use this BASH script:
#!/bin/bash
USER="YOUR_DATABASE_USER"
PASSWORD="YOUR_USER_PASSWORD"
DB_NAME="DATABASE_NAME"
CHARACTER_SET="utf8" # your default character set
COLLATE="utf8_general_ci" # your default collation
tables=`mysql -u $USER -p$PASSWORD -e "SELECT tbl.TABLE_NAME FROM information_schema.TABLES tbl WHERE tbl.TABLE_SCHEMA = '$DB_NAME' AND tbl.TABLE_TYPE='BASE TABLE'"`
for tableName in $tables; do
if [[ "$tableName" != "TABLE_NAME" ]] ; then
mysql -u $USER -p$PASSWORD -e "ALTER TABLE $DB_NAME.$tableName DEFAULT CHARACTER SET $CHARACTER_SET COLLATE $COLLATE;"
echo "$tableName - done"
fi
done
If anyone cares, for NTEXT
, use the following format:
SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT)
FROM [DataTable]
Not only does it not get executed, it doesn't even get compiled.
#if
is a preprocessor command, which gets evaluated before the actual compilation step. The code inside that block doesn't appear in the compiled binary.
It's often used for temporarily removing segments of code with the intention of turning them back on later.
Firts as mentioned by David, we need to set up public/private key.
Then using below command had worked for me, means it didn't prompt me for password as we are passing private key in the command using -i option
scp -i path/to/private_key path/to/local/file remoteUserId@remoteHost:/path/to/remote/folder
Here path/to/private_key is private key file which we generated while setting up public/private key.
$Location_Category_array = array(5,50,7,6,1,7,7,30,50,50,50,40,50,9,9,11,2,2,2,2,2,11,21,21,1,12,1,5);
asort($Location_Category_array);
$count=array_count_values($Location_Category_array);//Counts the values in the array, returns associatve array
print_r($count);
$maxsize = 0;
$maxvalue = 0;
foreach($count as $a=>$y){
echo "<br/>".$a."=".$y;
if($y>=$maxvalue){
$maxvalue = $y;
if($a>$maxsize){
$maxsize = $a;
}
}
}
echo "<br/>max = ".$maxsize;
This code should do the trick:
var array = ["ab", "abcdefgh", "abcd"];
array.sort(function(a, b){return b.length - a.length});
console.log(JSON.stringify(array, null, '\t'));
The 51Degrees beta, 1.0.1.6 and the latest stable release 1.0.2.2 (4/28/2011) now have the ability to sniff for tablet. Basically along the lines of:
string capability = Request.Browser["is_tablet"];
Hope this helps you.
You may have moved on by now, but... as far as I know there's no way to delete a history entry (or state).
One option I've been looking into is to handle the history yourself in JavaScript and use the window.history
object as a carrier of sorts.
Basically, when the page first loads you create your custom history object (we'll go with an array here, but use whatever makes sense for your situation), then do your initial pushState
. I would pass your custom history object as the state object, as it may come in handy if you also need to handle users navigating away from your app and coming back later.
var myHistory = [];
function pageLoad() {
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data.
}
Now when you navigate, you add to your own history object (or don't - the history is now in your hands!) and use replaceState
to keep the browser out of the loop.
function nav_to_details() {
myHistory.push("page_im_on_now");
window.history.replaceState(myHistory, "<name>", "<url>");
//Load page data.
}
When the user navigates backwards, they'll be hitting your "base" state (your state object will be null) and you can handle the navigation according to your custom history object. Afterward, you do another pushState.
function on_popState() {
// Note that some browsers fire popState on initial load,
// so you should check your state object and handle things accordingly.
// (I did not do that in these examples!)
if (myHistory.length > 0) {
var pg = myHistory.pop();
window.history.pushState(myHistory, "<name>", "<url>");
//Load page data for "pg".
} else {
//No "history" - let them exit or keep them in the app.
}
}
The user will never be able to navigate forward using their browser buttons because they are always on the newest page.
From the browser's perspective, every time they go "back", they've immediately pushed forward again.
From the user's perspective, they're able to navigate backwards through the pages but not forward (basically simulating the smartphone "page stack" model).
From the developer's perspective, you now have a high level of control over how the user navigates through your application, while still allowing them to use the familiar navigation buttons on their browser. You can add/remove items from anywhere in the history chain as you please. If you use objects in your history array, you can track extra information about the pages as well (like field contents and whatnot).
If you need to handle user-initiated navigation (like the user changing the URL in a hash-based navigation scheme), then you might use a slightly different approach like...
var myHistory = [];
function pageLoad() {
// When the user first hits your page...
// Check the state to see what's going on.
if (window.history.state === null) {
// If the state is null, this is a NEW navigation,
// the user has navigated to your page directly (not using back/forward).
// First we establish a "back" page to catch backward navigation.
window.history.replaceState(
{ isBackPage: true },
"<back>",
"<back>"
);
// Then push an "app" page on top of that - this is where the user will sit.
// (As browsers vary, it might be safer to put this in a short setTimeout).
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
// We also need to start our history tracking.
myHistory.push("<whatever>");
return;
}
// If the state is NOT null, then the user is returning to our app via history navigation.
// (Load up the page based on the last entry of myHistory here)
if (window.history.state.isBackPage) {
// If the user came into our app via the back page,
// you can either push them forward one more step or just use pushState as above.
window.history.go(1);
// or window.history.pushState({ isBackPage: false }, "<name>", "<url>");
}
setTimeout(function() {
// Add our popstate event listener - doing it here should remove
// the issue of dealing with the browser firing it on initial page load.
window.addEventListener("popstate", on_popstate);
}, 100);
}
function on_popstate(e) {
if (e.state === null) {
// If there's no state at all, then the user must have navigated to a new hash.
// <Look at what they've done, maybe by reading the hash from the URL>
// <Change/load the new page and push it onto the myHistory stack>
// <Alternatively, ignore their navigation attempt by NOT loading anything new or adding to myHistory>
// Undo what they've done (as far as navigation) by kicking them backwards to the "app" page
window.history.go(-1);
// Optionally, you can throw another replaceState in here, e.g. if you want to change the visible URL.
// This would also prevent them from using the "forward" button to return to the new hash.
window.history.replaceState(
{ isBackPage: false },
"<new name>",
"<new url>"
);
} else {
if (e.state.isBackPage) {
// If there is state and it's the 'back' page...
if (myHistory.length > 0) {
// Pull/load the page from our custom history...
var pg = myHistory.pop();
// <load/render/whatever>
// And push them to our "app" page again
window.history.pushState(
{ isBackPage: false },
"<name>",
"<url>"
);
} else {
// No more history - let them exit or keep them in the app.
}
}
// Implied 'else' here - if there is state and it's NOT the 'back' page
// then we can ignore it since we're already on the page we want.
// (This is the case when we push the user back with window.history.go(-1) above)
}
}
String fileContents = new File('/path/to/file').text
If you need to specify the character encoding, use the following instead:
String fileContents = new File('/path/to/file').getText('UTF-8')
In Java create the pattern with Pattern p = Pattern.compile("^\\w{14}$");
for further information see the javadoc
I sometimes find a variation of this useful.
Example in JavaScript:
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges
One important note, the solution mentioned above will not work on local host, you have to upload your code to server and then it will work. I was getting no error, than bad request, the problem was I was using localhost (test.dev,myproject.git). Both solution above work, the solution that uses SSL cert is recommended.
Go to https://curl.haxx.se/docs/caextract.html, download the latest cacert.pem. Store is somewhere (not in public folder - but will work regardless)
Use this code
".$result; //echo "
Path:".$_SERVER['DOCUMENT_ROOT'] . "/ssl/cacert.pem"; // this is for troubleshooting only ?>
Use the following to check if text box is empty or have more than 1 white spaces
var name = jQuery.trim($("#ContactUsName").val());
if ((name.length == 0))
{
Your code
}
else
{
Your code
}
Unless the role was made dbo, db_owner or db_datawriter, it won't have permission to edit any data. If you want to grant full edit permissions to a single table, do this:
GRANT ALL ON table1 TO doctor
Users in that role will have no permissions whatsoever to other tables (not even read).
In addition to setting Cache-control: no-cache, you should also set the Expires header to -1 if you would like the local copy to be refreshed each time (some versions of IE seem to require this).
See HTTP Cache - check with the server, always sending If-Modified-Since
ok , i've solved it by creating a handler on the onCreate of the service , and calling the gps functions through there .
The code is as simple as this:
final handler=new Handler(Looper.getMainLooper());
And then to force running things on the UI, I call post
on it.
if you have error in Sqlite built in python you can use Conda to solve this conflict
conda install sqlite
This is all you need.
rsync -e ssh file host:/directory/.
From what I've been able to piece together, you have to add the view using LayoutParams.
LinearLayout linearLayout = new LinearLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
relativeParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
parentView.addView(linearLayout, relativeParams);
All credit to sechastain, to relatively position your items programmatically you have to assign ids to them.
TextView tv1 = new TextView(this);
tv1.setId(1);
TextView tv2 = new TextView(this);
tv2.setId(2);
Then addRule(RelativeLayout.RIGHT_OF, tv1.getId());
Regular expressions with character classes (e.g. [[:digit:]]
) are not supported in the default regular expression syntax used by find
. You need to specify a different regex type such as posix-extended
in order to use them.
Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.
Following are the steps that will definitely work:
netstat -aon | find ":8080" | find "LISTENING"
Ctrl+Shift+Esc
)end process
NOTE : If you are running your program for the first time in Netbeans, it takes some time. So don't worry if it takes time.
You can use imshow() method from matplotlib
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')
plt.imshow(X.corr(), cmap=plt.cm.Reds, interpolation='nearest')
plt.colorbar()
tick_marks = [i for i in range(len(X.columns))]
plt.xticks(tick_marks, X.columns, rotation='vertical')
plt.yticks(tick_marks, X.columns)
plt.show()
Add this to you applicationContext:
<bean id="userService" class="com.example.my.services.user.UserServiceImpl ">
To access the tomcat manager from different machine you have to follow bellow steps:
1. Update conf/tomcat-users.xml file with user and some roles:
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<user username="admin" password="admin" roles="manager-gui,manager-script,manager-jmx,manager-status"/>
Here admin user is assigning roles="manager-gui,manager-script,manager-jmx,manager-status".
Here tomcat user and password is : admin
2. Update webapps/manager/META-INF/context.xml file (Allowing IP address):
Default configuration:
<Context antiResourceLocking="false" privileged="true" >
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" />
<Manager sessionAttributeValueClassNameFilter="java\.lang\.(?:Boolean|Integer|Long|Number|String)|org\.apache\.catalina\.filters\.CsrfPreventionFilter\$LruCache(?:\$1)?|java\.util\.(?:Linked)?HashMap"/>
</Context>
Here in Valve it is allowing only local machine IP start with 127.\d+.\d+.\d+ .
2.a : Allow specefic IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1|YOUR.IP.ADDRESS.HERE" />
Here you just replace |YOUR.IP.ADDRESS.HERE with your IP address
2.b : Allow all IP:
<Valve className="org.apache.catalina.valves.RemoteAddrValve"
allow=".*" />
Here using allow=".*" you are allowing all IP.
Thanks :)
To check Version of Your Running Kibana,Try this:
Step1. Start your Kibana Service.
Step2. Open Browser and Type below line,
localhost:5601
Step3. Go to settings->About
You can See Version of Your Running kibana.
If you want to use it in testing/TDD context, I'd say this is a standard way:
from nose.tools import assert_almost_equals
assert_almost_equals(x, y, places=7) #default is 7
String g = "line";
//string to char
char c = g.charAt(0);
char[] c_arr = g.toCharArray();
//char to string
char[] charArray = {'a', 'b', 'c'};
String str = String.valueOf(charArray);
//(or iterate the charArray and append each character to str -> str+=charArray[i])
//or String s= new String(chararray);
I think for finding the second Highest no we require these lines,if we can use inbuilt function
int[] randomIntegers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
Arrays.sort(randomIntegers);
System.out.println(randomIntegers[randomIntegers.length-2]);
maybe this helps:
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
//iterate through
if (frm.Name == "YourFormName")
{
bFormNameOpen = true;
}
}
Some code in the foreach to detect the specific form and it could be done. Untested though.
Found on http://bytes.com/topic/c-sharp/answers/591308-iterating-all-open-forms
If you want a generic way, you can define an error page in web.xml:
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/500</location>
</error-page>
And add mapping in Spring MVC:
@Controller
public class ErrorController {
@RequestMapping(value="/500")
public @ResponseBody String handleException(HttpServletRequest req) {
// you can get the exception thrown
Throwable t = (Throwable)req.getAttribute("javax.servlet.error.exception");
// customize response to what you want
return "Internal server error.";
}
}
I guess you want to do this:
$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
$avg = round($total_rating_points / $total_rating_count, 1);
You can get the values of two or more variables by setting them by reference:
function t(&$a, &$b) {
$a = 1;
$b = 2;
}
t($a, $b);
echo $a . ' ' . $b;
Output:
1 2
For those have to calculate Circle/Rectangle collision in Geographic Coordinates with SQL,
this is my implementation in oracle 11 of e.James suggested algorithm.
In input it requires circle coordinates, circle radius in km and two vertices coordinates of the rectangle:
CREATE OR REPLACE FUNCTION "DETECT_CIRC_RECT_COLLISION"
(
circleCenterLat IN NUMBER, -- circle Center Latitude
circleCenterLon IN NUMBER, -- circle Center Longitude
circleRadius IN NUMBER, -- circle Radius in KM
rectSWLat IN NUMBER, -- rectangle South West Latitude
rectSWLon IN NUMBER, -- rectangle South West Longitude
rectNELat IN NUMBER, -- rectangle North Est Latitude
rectNELon IN NUMBER -- rectangle North Est Longitude
)
RETURN NUMBER
AS
-- converts km to degrees (use 69 if miles)
kmToDegreeConst NUMBER := 111.045;
-- Remaining rectangle vertices
rectNWLat NUMBER;
rectNWLon NUMBER;
rectSELat NUMBER;
rectSELon NUMBER;
rectHeight NUMBER;
rectWIdth NUMBER;
circleDistanceLat NUMBER;
circleDistanceLon NUMBER;
cornerDistanceSQ NUMBER;
BEGIN
-- Initialization of remaining rectangle vertices
rectNWLat := rectNELat;
rectNWLon := rectSWLon;
rectSELat := rectSWLat;
rectSELon := rectNELon;
-- Rectangle sides length calculation
rectHeight := calc_distance(rectSWLat, rectSWLon, rectNWLat, rectNWLon);
rectWidth := calc_distance(rectSWLat, rectSWLon, rectSELat, rectSELon);
circleDistanceLat := abs( (circleCenterLat * kmToDegreeConst) - ((rectSWLat * kmToDegreeConst) + (rectHeight/2)) );
circleDistanceLon := abs( (circleCenterLon * kmToDegreeConst) - ((rectSWLon * kmToDegreeConst) + (rectWidth/2)) );
IF circleDistanceLon > ((rectWidth/2) + circleRadius) THEN
RETURN -1; -- -1 => NO Collision ; 0 => Collision Detected
END IF;
IF circleDistanceLat > ((rectHeight/2) + circleRadius) THEN
RETURN -1; -- -1 => NO Collision ; 0 => Collision Detected
END IF;
IF circleDistanceLon <= (rectWidth/2) THEN
RETURN 0; -- -1 => NO Collision ; 0 => Collision Detected
END IF;
IF circleDistanceLat <= (rectHeight/2) THEN
RETURN 0; -- -1 => NO Collision ; 0 => Collision Detected
END IF;
cornerDistanceSQ := POWER(circleDistanceLon - (rectWidth/2), 2) + POWER(circleDistanceLat - (rectHeight/2), 2);
IF cornerDistanceSQ <= POWER(circleRadius, 2) THEN
RETURN 0; -- -1 => NO Collision ; 0 => Collision Detected
ELSE
RETURN -1; -- -1 => NO Collision ; 0 => Collision Detected
END IF;
RETURN -1; -- -1 => NO Collision ; 0 => Collision Detected
END;
The answer to this question is saying to use display:none and display:block, but this does not help for someone who is trying to use css transitions to show and hide content using the visibility property.
This also drove me crazy, because using display kills any css transitions.
One solution is to add this to the class that's using visibility:
overflow:hidden
For this to work is does depend on the layout, but it should keep the empty content within the div it resides in.
I faced the same problem with JBoss 4.2.3 GA when deploying my web application. I solved the issue by copying my commons-codec 1.6 jar into C:\jboss-4.2.3.GA\server\default\lib
Short answer:
We can't live without onStart because that is the state when the activity becomes "visible" to the user, but the user cant "interact" with it yet may be cause it's overlapped with some other small dialog. This ability to interact with the user is the one that differentiates onStart and onResume. Think of it as a person behind a glass door. You can see the person but you can't interact (talk/listen/shake hands) with him. OnResume is like the door opener after which you can begin the interaction.
Additionally onRestart() is the least understood one. We can ask the question as to why not directly go to onStart() or onResume() after onStop() instead of onRestart(). It becomes easier to understand if we note that onRestart() is partially equivalent to onCreate() if the creation part is omitted. Basically both states lead to onStart() (i.e the Activity becomes visible). So both the states have to "prepare" the stuff to be displayed. OnCreate has the additional responsibility to "create" the stuff to be displayed
So their code structures might fit to something like:
onCreate()
{
createNecessaryObjects();
prepareObjectsForDisplay();
}
onRestart()
{
prepareObjectsForDisplay();
}
The entire confusion is caused since Google chose non-intuitive names instead of something as follows:
onCreateAndPrepareToDisplay() [instead of onCreate() ]
onPrepareToDisplay() [instead of onRestart() ]
onVisible() [instead of onStart() ]
onBeginInteraction() [instead of onResume() ]
onPauseInteraction() [instead of onPause() ]
onInvisible() [instead of onStop]
onDestroy() [no change]
The Activity Diagram might be interpreted as:
I would suggest you don't use symlinks within the repo'. Store the actual content inside the repo' and then place symlinks out side the repo' that point to the content.
So lets say you are using a repo' to compare hosting your site on *nix with hosting on win. Store the content in your repo', lets say /httpRepoContent
and c:\httpRepoContent
with this being the folder that is synced via GIT, SVN etc.
Then, replace the content folder of you web server (/var/www
and c:\program files\web server\www
{names don't really matter, edit if you must}) with a symbolic link to the content in your repo'. The web servers will see the content as actually in the 'right' place, but you get to use your source control.
However, if you need to use symlinks with in the repo', you will need to look into something like some sort of pre/post commit scripts. I know you can use them to do things, such as parse code files through a formatter for example, so it should be possible to convert the symlinks between platforms.
if any one knows a good place to learn how to do these scripts for the common source controls, SVN GIT MG, then please do add a comment.
Instead of using string interpolation you could simply format the DateTime using the ToString("u")
method and concatenate that with the rest of the string:
$startTime = Get-Date
Write-Host "The script was started " + $startTime.ToString("u")
In addition to installing the repository and the SDK packages one should be aware that the version number changes periodically. A simple solution at this point is to replace the specific version number with a plus (+) symbol.
compile 'com.google.android.gms:play-services:+'
Google instructions indicate that one should be sure to upgrade the version numbers, however adding the plus deals with the changes in versioning. Also note that when building in Android Studio a message will appear in the status line when a new version is available.
One can view the available versions of play services by drilling down on the correct repository path:
References
This site also has instructions for Eclipse, and other IDE's.
Change your markup slightly:
$(function() {_x000D_
enable_cb();_x000D_
$("#group1").click(enable_cb);_x000D_
});_x000D_
_x000D_
function enable_cb() {_x000D_
if (this.checked) {_x000D_
$("input.group1").removeAttr("disabled");_x000D_
} else {_x000D_
$("input.group1").attr("disabled", true);_x000D_
}_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form name="frmChkForm" id="frmChkForm">_x000D_
<input type="checkbox" name="chkcc9" id="group1">Check Me <br>_x000D_
<input type="checkbox" name="chk9[120]" class="group1"><br>_x000D_
<input type="checkbox" name="chk9[140]" class="group1"><br>_x000D_
<input type="checkbox" name="chk9[150]" class="group1"><br>_x000D_
</form>
_x000D_
You can do this using attribute selectors without introducing the ID and classes but it's slower and (imho) harder to read.
Some explanation ignore a condition about the retain cycle [If a group of objects is connected by a circle of strong relationships, they keep each other alive even if there are no strong references from outside the group.] For more information, read the document
None of the current answers helped me here. We were getting something like:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
#.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar
This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib
in the path. Our tools.jar
is in $JAVA_HOME/lib/tools.jar
not in $JAVA_HOME/../lib/tools.jar
.
Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- not sure if this is also needed -->
<executable>${JAVA_HOME}/bin/javac</executable>
<!-- ^^^^^^^^^^^^^^^^^^^^^^ -->
</configuration>
</plugin>
By pointing the executable to the right place this at least got past our compilation failures.
To supplement what everyone else has said above, your js file is being read on the client side when you have a path to it in your HTML file. At least that was the problem for me. I had it as a script in my tag in my index.html Hope this helps!
ftplib now supports context managers so I guess it can be made even easier
from ftplib import FTP
from pathlib import Path
file_path = Path('kitten.jpg')
with FTP('server.address.com', 'USER', 'PWD') as ftp, open(file_path, 'rb') as file:
ftp.storbinary(f'STOR {file_path.name}', file)
No need to close the file or the session
Make sure you have your email set properly.
git config --global user.email "[email protected]"
Those like me who understand character encoding principles, also read Joel's article which is funny as it contains wrong characters anyway and still can't figure out what the heck (spoiler alert, I'm Mac user) then your solution can be as simple as removing your local repo and clone it again.
My code base did not change since the last time it was running OK so it made no sense to have UTF errors given the fact that our build system never complained about it....till I remembered that I accidentally unplugged my computer few days ago with IntelliJ Idea and the whole thing running (Java/Tomcat/Hibernate)
My Mac did a brilliant job as pretending nothing happened and I carried on business as usual but the underlying file system was left corrupted somehow. Wasted the whole day trying to figure this one out. I hope it helps somebody.
code for a simple copy.
cp -r ./SourceFolder ./DestFolder
code for a copy with success result
cp -rv ./SourceFolder ./DestFolder
code for Forcefully if source contains any readonly file it will also copy
cp -rf ./SourceFolder ./DestFolder
for details help
cp --help
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
While you can do OO in C (e.g. by adding a theType *this
first parameter to methods, and manually handling something like vtables for polymorphism) this is never particularly satisfactory as a design, and will look ugly (even with some pre-processor hacks).
I would suggest at least looking at a re-design to compare how this would work out.
Overall a lot depends on the answer to the key question: if you have working C++ code, why do you want C instead?
Since mysql -u yourusername -p yourpassword yourdatabase < text_file
did not work on a remote server (Amazon's EC2)...
Make sure that the Database is created first.
Then:
mysql --host=localhost --user=your_username --password=your_password your_database_name < pathTofilename.sql
If you want to do remote debugging (for CGI or if you don't want to mess output with debug command line), use this:
Given test:
use v5.14;
say 1;
say 2;
say 3;
Start a listener on whatever host and port on terminal 1 (here localhost:12345
):
$ nc -v -l localhost -p 12345
For readline support use rlwrap (you can use on perl -d
too):
$ rlwrap nc -v -l localhost -p 12345
And start the test on another terminal (say terminal 2):
$ PERLDB_OPTS="RemotePort=localhost:12345" perl -d test
Input/Output on terminal 1:
Connection from 127.0.0.1:42994
Loading DB routines from perl5db.pl version 1.49
Editor support available.
Enter h or 'h h' for help, or 'man perldebug' for more help.
main::(test:2): say 1;
DB<1> n
main::(test:3): say 2;
DB<1> select $DB::OUT
DB<2> n
2
main::(test:4): say 3;
DB<2> n
3
Debugged program terminated. Use q to quit or R to restart,
use o inhibit_exit to avoid stopping after program termination,
h q, h R or h o to get additional info.
DB<2>
Output on terminal 2:
1
Note the sentence if you want output on debug terminal
select $DB::OUT
If you are Vim user, install this plugin: dbg.vim which provides basic support for Perl.
you have to set the tableName you want to your dtimage that is for instance
dtImage.TableName="mydtimage";
if(!ds.Tables.Contains(dtImage.TableName))
ds.Tables.Add(dtImage);
it will be reflected in dataset because dataset is a container of your datatable dtimage and you have a reference on your dtimage
There are hardware and software watchpoints. They are for reading and for writing a variable. You need to consult a tutorial:
http://www.unknownroad.com/rtfm/gdbtut/gdbwatch.html
To set a watchpoint, first you need to break the code into a place where the varianle i is present in the environment, and set the watchpoint.
watch
command is used to set a watchpoit for writing, while rwatch
for reading, and awatch
for reading/writing.
This can not be done easily. There's no way to make an NVARCHAR
parameter take "more than one value". What I've done before is - as you do already - make the parameter value like a list with comma-separated values. Then, split this string up into its parts in the stored procedure.
Splitting up can be done using string functions. Add every part to a temporary table. Pseudo-code for this could be:
CREATE TABLE #TempTable (ID INT)
WHILE LEN(@PortfolioID) > 0
BEGIN
IF NOT <@PortfolioID contains Comma>
BEGIN
INSERT INTO #TempTable VALUES CAST(@PortfolioID as INT)
SET @PortfolioID = ''
END ELSE
BEGIN
INSERT INTO #Temptable VALUES CAST(<Part until next comma> AS INT)
SET @PortfolioID = <Everything after the next comma>
END
END
Then, change your condition to
WHERE PortfolioId IN (SELECT ID FROM #TempTable)
EDIT
You may be interested in the documentation for multi value parameters in SSRS, which states:
You can define a multivalue parameter for any report parameter that you create. However, if you want to pass multiple parameter values back to a data source by using the query, the following requirements must be satisfied:
The data source must be SQL Server, Oracle, Analysis Services, SAP BI NetWeaver, or Hyperion Essbase.
The data source cannot be a stored procedure. Reporting Services does not support passing a multivalue parameter array to a stored procedure.
The query must use an IN clause to specify the parameter.
Just note to anyone trying the REGEXP to use "LIKE IN" functionality.
IN allows you to do:
field IN (
'val1',
'val2',
'val3'
)
In REGEXP this won't work
REGEXP '
val1$|
val2$|
val3$
'
It has to be in one line like this:
REGEXP 'val1$|val2$|val3$'
Overwrite the brand class, either in the bootstrap.css or a new CSS file, as below -
.brand
{
background: url(images/logo.png) no-repeat left center;
height: 20px;
width: 100px;
}
and your html should look like -
<div class="container-fluid">
<a class="brand" href="index.html"></a>
</div>
You can't manipulate :after
, because it's not technically part of the DOM and therefore is inaccessible by any JavaScript. But you can add a new class with a new :after
specified.
CSS:
.pageMenu .active.changed:after {
/* this selector is more specific, so it takes precedence over the other :after */
border-top-width: 22px;
border-left-width: 22px;
border-right-width: 22px;
}
JS:
$('.pageMenu .active').toggleClass('changed');
UPDATE: while it's impossible to directly modify the :after
content, there are ways to read and/or override it using JavaScript. See "Manipulating CSS pseudo-elements using jQuery (e.g. :before and :after)" for a comprehensive list of techniques.
You can also install simplejson.
If you have pip (see https://pypi.python.org/pypi/pip) as your Python package manager you can install simplejson with:
pip install simplejson
This is similar to the comment of installing with easy_install, but I prefer pip to easy_install as you can easily uninstall in pip with "pip uninstall package".
The other answers assume that your compiler is C++11 compliant. That is fine if it is. But what if you are using an older compiler?
I picked up the following hack somewhere on the net. It works well enough for me:
#if defined __UINT32_MAX__ or UINT32_MAX
#include <inttypes.h>
#else
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned long uint32_t;
typedef unsigned long long uint64_t;
#endif
It is not portable, of course. But it might work for your compiler.
A shorter version of the accepted answer using Guava:
.getMap(Iterables.toArray(locations, WorldLocation.class));
can be shortened further by statically importing toArray:
import static com.google.common.collect.toArray;
// ...
.getMap(toArray(locations, WorldLocation.class));
No, not exactly. But it can inherit from a class and implement one or more interfaces.
Clear terminology is important when discussing concepts like this. One of the things that you'll see mark out Jon Skeet's writing, for example, both here and in print, is that he is always precise in the way he decribes things.
For attached properties you can either call SetValue on the object for which you want to assign the value:
tblock.SetValue(Grid.RowProperty, 4);
Or call the static Set method (not as an instance method like you tried) for the property on the owner type, in this case SetRow:
Grid.SetRow(tblock, 4);
very simple find port 5900:
sudo lsof -i :5900
then considering 59553 as PID
sudo kill 59553
In windows:
I tried to delete sklearn from the shell: pip uninstall sklearn, and re install it but doesn't work ..
the solution:
1- open the cmd shell.
2- cd c:\pythonVERSION\scripts
3- pip uninstall sklearn
4- open in the explorer: C:\pythonVERSION\Lib\site-packages
5- look for the folders that contains sklearn and delete them ..
6- back to cmd: pip install sklearn
mybytestring.encode(somecodec) is meaningful for these values of somecodec
:
I am not sure what decoding an already decoded unicode text is good for. Trying that with any encoding seems to always try to encode with the system's default encoding first.
Since there's no default method of setting the value to today's date, I would say this should be dependent upon it's application. If you're looking to maximize your audience's exposure to the date picker, then use a server-side script (PHP, ASP, etc.) to set the default value.
However, if it's for the administration console of the CMS, and you know that the user will always have JS on or your site trusted, then you can safely use JS to fill the default value, as per jlbruno.
This one worked for me too
msiexec /i "msi path" INSTALLDIR="D:\myfolder" /q
I had tried two other iterations and both installed in the default C:\Program Files
INSTALLDIR="D:\myfolder" /q got it installed on the other drive.
<table width="400px">
<tr>
<td width="100px"></td>
<td width="100px"></td>
<td width="100px"></td>
<td width="100px"></td>
</tr>
</table>
For variable number of columns use %
<table width="100%">
<tr>
<td width="(100/x)%"></td>
</tr>
</table>
where 'x' is number of columns
Use the beginning and end anchors.
Regex regex = new Regex(@"^\d$");
Use "^\d+$"
if you need to match more than one digit.
Note that "\d"
will match [0-9]
and other digit characters like the Eastern Arabic numerals ??????????
. Use "^[0-9]+$"
to restrict matches to just the Arabic numerals 0 - 9.
If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.
Using scala:
import xml._
val xml = XML.loadString("<tag><nested>hello</nested></tag>")
val formatted = new PrettyPrinter(150, 2).format(xml)
println(formatted)
You can do this in Java too, if you depend on the scala-library.jar. It looks like this:
import scala.xml.*;
public class FormatXML {
public static void main(String[] args) {
String unformattedXml = "<tag><nested>hello</nested></tag>";
PrettyPrinter pp = new PrettyPrinter(150, 3);
String formatted = pp.format(XML.loadString(unformattedXml), TopScope$.MODULE$);
System.out.println(formatted);
}
}
The PrettyPrinter
object is constructed with two ints, the first being max line length and the second being the indentation step.
Try this: (even [1] will be removed)
> cat(noquote("love"))
love
else just use noquote
> noquote("love")
[1] love
Use GNU Parallel:
(echo command1; echo command2) | parallel
parallel ::: command1 command2
To kill:
parallel ::: command1 command2 &
PID=$!
kill -TERM $PID
kill -TERM $PID
Along with jerjer answer(top), sometimes in your parent window and child window are not both external or both internal you will see a problem of opener undefined, and you cannot access parent page properties, see window.opener is undefined on Internet Explorer
In jQuery you can use Ajax to call a server-side script. The server-side script will find all the files in the folder and return them to your html file where you will need to process the returned information.
Two things which can be done more efficiently:
StringBuilder
instead of StringBuffer
since it's the faster and younger brother.BufferedReader#readLine()
to read it line by line instead of reading it char by char.HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
StringBuilder builder = new StringBuilder();
for (String line = null; (line = reader.readLine()) != null;) {
builder.append(line).append("\n");
}
JSONTokener tokener = new JSONTokener(builder.toString());
JSONArray finalResult = new JSONArray(tokener);
If the JSON is actually a single line, then you can also remove the loop and builder.
HttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
JSONTokener tokener = new JSONTokener(json);
JSONArray finalResult = new JSONArray(tokener);
blog_development doesn't exist
You can see this in sql by the 0 rows affected
message
create it in mysql with
mysql> create database blog_development
However as you are using rails you should get used to using
$ rake db:create
to do the same task. It will use your database.yml file settings, which should include something like:
development:
adapter: mysql2
database: blog_development
pool: 5
Also become familiar with:
$ rake db:migrate # Run the database migration
$ rake db:seed # Run thew seeds file create statements
$ rake db:drop # Drop the database
Create a random string
Here's a MySQL function to create a random string of a given length.
DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `RandString`(length SMALLINT(3)) RETURNS varchar(100) CHARSET utf8
begin
SET @returnStr = '';
SET @allowedChars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
SET @i = 0;
WHILE (@i < length) DO
SET @returnStr = CONCAT(@returnStr, substring(@allowedChars, FLOOR(RAND() * LENGTH(@allowedChars) + 1), 1));
SET @i = @i + 1;
END WHILE;
RETURN @returnStr;
END
Usage SELECT RANDSTRING(8)
to return an 8 character string.
You can customize the @allowedChars
.
Uniqueness isn't guaranteed - as you'll see in the comments to other solutions, this just isn't possible. Instead you'll need to generate a string, check if it's already in use, and try again if it is.
Check if the random string is already in use
If we want to keep the collision checking code out of the app, we can create a trigger:
DELIMITER $$
CREATE TRIGGER Vehicle_beforeInsert
BEFORE INSERT ON `Vehicle`
FOR EACH ROW
BEGIN
SET @vehicleId = 1;
WHILE (@vehicleId IS NOT NULL) DO
SET NEW.plate = RANDSTRING(8);
SET @vehicleId = (SELECT id FROM `Vehicle` WHERE `plate` = NEW.plate);
END WHILE;
END;$$
DELIMITER ;
If you are using MySql
function daysSince($date, $date2){
$q = "SELECT DATEDIFF('$date','$date2') AS days;";
$result = execQ($q);
$row = mysql_fetch_array($result,MYSQL_BOTH);
return ($row[0]);
}
function execQ($q){
$result = mysql_query( $q);
if(!$result){echo ('Database error execQ' . mysql_error());echo $q;}
return $result;
}
I wanted a splash screen that would display until the main program form was ready to be displayed, so timers etc were no use to me. I also wanted to keep it as simple as possible. My application starts with (abbreviated):
static void Main()
{
Splash frmSplash = new Splash();
frmSplash.Show();
Application.Run(new ReportExplorer(frmSplash));
}
Then, ReportExplorer has the following:
public ReportExplorer(Splash frmSplash)
{
this.frmSplash = frmSplash;
InitializeComponent();
}
Finally, after all the initialisation is complete:
if (frmSplash != null)
{
frmSplash.Close();
frmSplash = null;
}
Maybe I'm missing something, but this seems a lot easier than mucking about with threads and timers.
In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.
What did the trick was:
bfg -b 100M # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive
Then, you need to push force on your branch:
git push origin <your_branch_name> --force
Note: bfg is a tool that can be installed on Linux and macOS using brew:
brew install bfg
Pure JavaScript with properly set reset time and bindings via addEventListener
(function() {
var t,
timeout = 5000;
function resetTimer() {
console.log("reset: " + new Date().toLocaleString());
if (t) {
window.clearTimeout(t);
}
t = window.setTimeout(logout, timeout);
}
function logout() {
console.log("done: " + new Date().toLocaleString());
}
resetTimer();
//And bind the events to call `resetTimer()`
["click", "mousemove", "keypress"].forEach(function(name) {
console.log(name);
document.addEventListener(name, resetTimer);
});
}());
This is a complete example loading image from URL, creating with PIL, printing the size and resizing...
import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)
from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))
width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)
try to use the array_unique()
this elminates duplicated data inside the list of your arrays..
There is no Gacutil included in the .net 4.0 standard installation. They have moved the GAC too, from %Windir%\assembly to %Windir%\Microsoft.NET\Assembly.
They havent' even bothered adding a "special view" for the folder in Windows explorer, as they have for the .net 1.0/2.0 GAC.
Gacutil is part of the Windows SDK, so if you want to use it on your developement machine, just install the Windows SDK for your current platform. Then you will find it somewhere like this (depending on your SDK version):
C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools
There is a discussion on the new GAC here: .NET 4.0 has a new GAC, why?
If you want to install something in GAC on a production machine, you need to do it the "proper" way (gacutil was never meant as a tool for installing stuff on production servers, only as a development tool), with a Windows Installer, or with other tools. You can e.g. do it with PowerShell and the System.EnterpriseServices dll.
On a general note, and coming from several years of experience, I would personally strongly recommend against using GAC at all. Your application will always work if you deploy the DLL with each application in its bin folder as well. Yes, you will get multiple copies of the DLL on your server if you have e.g. multiple web apps on one server, but it's definitely worth the flexibility of being able to upgrade one application without breaking the others (by introducing an incompatible version of the shared DLL in the GAC).
Mutable objects can have their fields changed after construction. Immutable objects cannot.
public class MutableClass {
private int value;
public MutableClass(int aValue) {
value = aValue;
}
public void setValue(int aValue) {
value = aValue;
}
public getValue() {
return value;
}
}
public class ImmutableClass {
private final int value;
// changed the constructor to say Immutable instead of mutable
public ImmutableClass (final int aValue) {
//The value is set. Now, and forever.
value = aValue;
}
public final getValue() {
return value;
}
}
Then just modify the previous answers to:
Console.Write(strToProcess.Replace("@", "@" + Environment.NewLine));
If you don't want the newlines in the text file, then don't preserve it.
This is a little more lightweight than Arrays.copyOfRange - no range or negative
public static final byte[] copy(byte[] data, int pos, int length )
{
byte[] transplant = new byte[length];
System.arraycopy(data, pos, transplant, 0, length);
return transplant;
}
The other solutions should work, but here is a solution for docker-compose
.
To fix that error, you need to pass $DISPLAY and .X11-unix to docker, as well as grant the user who started docker access to xhost.
Within docker-compose.yml
file:
version: '2'
services:
node:
build: .
container_name: node
environment:
- DISPLAY
volumes:
- /tmp/.X11-unix:/tmp/.X11-unix
In terminal or script:
xhost +si:localuser:$USER
xhost +local:docker
export DISPLAY=$DISPLAY
docker-compose up
void 0
returns undefined and can not be overwritten while undefined
can be overwritten.
var undefined = "HAHA";
Looks like your Vim is launched in easy mode. See :help easy
.
This happens when Vim is invoked with the -y
argument or as evim
, or maybe you have a :set insertmode
somewhere in your .vimrc
configuration. Find the source and disable it; temporarily this can be also done via Ctrl + O :set noim
Enter.
I would guess that it is a way to make apps which don't use it at all perform slightly better. Here's my thinking on this.
x86 OSes (and I imagine others) need to store FPU state on context switch. However, most OSes only bother to save/restore this state after the app attempts to use the FPU for the first time.
In addition to this, there is probably some basic code in the math library which will set the FPU to a sane base state when the library is loaded.
So, if you don't link in any math code at all, none of this will happen, therefore the OS doesn't have to save/restore any FPU state at all, making context switches slightly more efficient.
Just a guess though.
EDIT: in response to some of the comments, the same base premise still applies to non-FPU cases (the premise being that it was to make apps which didn't make use libm perform slightly better).
For example, if there is a soft-FPU which was likley in the early days of C. Then having libm separate could prevent a lot of large (and slow if it was used) code from unnecessarily being linked in.
In addition, if there is only static linking available, then a similar argument applies that it would keep executable sizes and compile times down.
...In short:
string[] arr = "This is a sentence".Split(new string[] { "is" }, StringSplitOptions.None);
You can activate JVM's debugging capability when starting up the java
command with a special option:
java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar
Starting up jar.jar
like that on the command line will:
server=y
) listening on port 8000 (address=8000
)Listening for transport dt_socket at address: 8000
to stdout
andsuspend=y
) until some debugger connects. The debugger acts as the client in this scenario.Common options for selecting a debugger are:
jar.jar
should begin executing.jdb -connect com.sun.jdi.SocketAttach:port=8000
You maybe not asking the UWP api.
But in UWP, file.DisplayName
is the name without extensions. Hope useful for others.
incoming = 'arbit'
result = '%(s)s hello world %(s)s hello world %(s)s' % {'s': incoming}
You may like to have a read of this to get an understanding: String Formatting Operations.
The syntax (<<<
) and the command used (echo
) is wrong.
Correct would be:
#!/bin/bash
kernel="2.6.39"
distro="xyz"
cat >/etc/myconfig.conf <<EOL
line 1, ${kernel}
line 2,
line 3, ${distro}
line 4 line
...
EOL
cat /etc/myconfig.conf
This construction is referred to as a Here Document and can be found in the Bash man pages under man --pager='less -p "\s*Here Documents"' bash
.
If you are using custom cell as header, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView = UIView()
let headerCell = tableView.dequeueReusableCell(withIdentifier: "customTableCell") as! CustomTableCell
headerView.addSubview(headerCell)
return headerView
}
If you want to have simple view, add the following.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let headerView:UIView = UIView()
return headerView
}
You're almost there. Although I agree with @Alex Young answer about using props for that, you simply need a reference to the instance
before trying to spy on the method.
describe('my sweet test', () => {
it('clicks it', () => {
const app = shallow(<App />)
const instance = app.instance()
const spy = jest.spyOn(instance, 'myClickFunc')
instance.forceUpdate();
const p = app.find('.App-intro')
p.simulate('click')
expect(spy).toHaveBeenCalled()
})
})
Docs: http://airbnb.io/enzyme/docs/api/ShallowWrapper/instance.html
I've just removed the tags "portrait" from the non full-screen elements and everything went fine.
android:screenOrientation="portrait"
If you are passing (like me) all the parameters like port, username, password through a system and you are not allow to modify the code, then you can do that easy change on the web.config
:
<system.net>
<mailSettings>
<smtp>
<network enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
Use OpenFileDialog.SafeFileName
OpenFileDialog.SafeFileName
Gets the file name and extension for the file selected in the dialog box. The file name does not include the path.
vector.clear()
should work for you. In case you want to shrink the capacity of the vector
along with clear then
std::vector<T>(v).swap(v);
Following https://docs.microsoft.com/en-gb/visualstudio/ide/reference/how-to-manage-word-wrap-in-the-editor
When viewing a document: Edit / Advanced / Word Wrap (Ctrl+E, Ctrl+W)
General settings: Tools / Options / Text Editor / All Languages / Word wrap
Or search for 'word wrap' in the Quick Launch box.
If you're familiar with word wrap in Notepad++, Sublime Text, or Visual Studio Code, be aware of the following issues where Visual Studio behaves differently to other editors:
Unfortunately these bugs have been closed "lower priority". If you'd like these bugs fixed, please vote for the feature request Fix known issues with word wrap.
Debian appears to include the following:
I'll test symlinks of each for mpic, etc., and see if that helps the likes of HDF5-openmpi enabled find mpi.h.
Take that back Debian includes symlinks via their alternatives system and it still cannot find the proper paths between HDF5 openmpi packages and mpi.h referenced in the H5public.h header.
I found a bug in MySQL 5.1.72 when using the nested if() functions .... the value of column variables (e.g. qty_1) is blank inside the second if(), rendering it useless. Use the following construct instead:
case
when qty_1<='23' then price
when '23'>qty_1 && qty_2<='23' then price_2
when '23'>qty_2 && qty_3<='23' then price_3
when '23'>qty_3 then price_4
else 1
end
$(HTMLelement)
can success it. If you want an epmty div use it as $('<div></div>');
. Also you can set the other elements by the same method. If you want to change inner HTML after created you can use html()
method. For get outerHTML as string you can use is like this :
var element = $('<div/>');
var innerHTML = element.html(); // if you want set new HTML use it like this element.html('<b>new HTML</b>');
var outerHTML = element[0].outerHTML;
If I remember correctly the XmlDocument.Load(string) method always assumes UTF-8, regardless of the XML encoding. You would have to create a StreamReader with the correct encoding and use that as the parameter.
xmlDoc.Load(new StreamReader(
File.Open("file.xml"),
Encoding.GetEncoding("iso-8859-15")));
I just stumbled across KB308061 from Microsoft. There's an interesting passage: Specify the encoding declaration in the XML declaration section of the XML document. For example, the following declaration indicates that the document is in UTF-16 Unicode encoding format:
<?xml version="1.0" encoding="UTF-16"?>
Note that this declaration only specifies the encoding format of an XML document and does not modify or control the actual encoding format of the data.
Link Source:
Correct me if I'm mistaken, but the previous example, I believe, is just slightly out of sync with the latest version of James Newton's Json.NET library.
var o = JObject.Parse(stringFullOfJson);
var page = (int)o["page"];
var totalPages = (int)o["total_pages"];