int num = 1;
num.ToString("0000");
I've faced such an issue and dig tones of material. So, to avoid ugly iteration you can simply tune your hql:
You need to frame your query like this
select entity from Entity as entity where ...
Also check such case, it perfectly works for me:
public List<User> findByRole(String role) {
Query query = sessionFactory.getCurrentSession().createQuery("select user from User user join user.userRoles where role_name=:role_name");
query.setString("role_name", role);
@SuppressWarnings("unchecked")
List<User> users = (List<User>) query.list();
return users;
}
So here we are extracting object from query, not a bunch of fields. Also it's looks much more pretty.
pointers(ex:char *arr,int *arr) -------> heap
Nope, they can be on the stack or in the data segment. They can point anywhere.
Basically, since Python 3.x you need to use print
with parenthesis.
Python 2.x: print "Lord of the Rings"
Python 3.x: print("Lord of the Rings")
print
was a statement in 2.x, but it's a function in 3.x. Now, there are a number of good reasons for this.
>>> items = ['foo', 'bar', 'baz'] >>> print(*items, sep='+') foo+bar+baz
add this code in .htaccess (as an alternative of php.ini / ini_set function):
<IfModule mod_php5.c>
php_flag log_errors on
php_value error_log ./path_to_MY_PHP_ERRORS.log
# php_flag display_errors on
</IfModule>
* as commented: this is for Apache-type servers, and not for Nginx or others.
According to MDN, the
split()
method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.
var str = 'Hello my friend'
var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]
var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]
console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else
Yet another way to use Rscript for *Unix systems is Process Substitution.
Rscript <(zcat a.r)
# [1] "hello"
Which obviously does the same as the accepted answer, but this allows you to manipulate and run your file without saving it the power of the command line, e.g.:
Rscript <(sed s/hello/bye/ a.r)
# [1] "bye"
Similar to Rscript -e "Rcode"
it also allows to run without saving into a file. So it could be used in conjunction with scripts that generate R-code, e.g.:
Rscript <(echo "head(iris,2)")
# Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1 5.1 3.5 1.4 0.2 setosa
# 2 4.9 3.0 1.4 0.2 setosa
Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.
good luck!
For some reason android studio doesn't like calling app icon from drawable folder. So in that case I created mipmap resource directory under res folder.
Right click res folder > new > android resource directory > resource type: mipmap and now drop any icon in there then reference that into manifest file. Sharing this since this method worked for me.
android:icon:@drawable/ic_launcher"
to
android:icon="@mipmap/ic_launcher"
You need to add a name
attribute to your dropdown list, then you need to add a required
attribute, and then you can reference the error using myForm.[input name].$error.required
:
HTML:
<form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
<input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
<select name="service_id" class="Sitedropdown" style="width: 220px;"
ng-model="ServiceID"
ng-options="service.ServiceID as service.ServiceName for service in services"
required>
<option value="">Select Service</option>
</select>
<span ng-show="myForm.service_id.$error.required">Select service</span>
</form>
Controller:
function Ctrl($scope) {
$scope.services = [
{ServiceID: 1, ServiceName: 'Service1'},
{ServiceID: 2, ServiceName: 'Service2'},
{ServiceID: 3, ServiceName: 'Service3'}
];
$scope.save = function(myForm) {
console.log('Selected Value: '+ myForm.service_id.$modelValue);
alert('Data Saved! without validate');
};
}
Here's a working plunker.
I solved it by editing styles.xml:
<style name="ToolbarColoredBackArrow" parent="AppTheme">
<item name="android:textColorSecondary">INSERT_COLOR_HERE</item>
</style>
...then referencing the style in the Toolbar definition in the activity:
<LinearLayout
android:id="@+id/main_parent_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
app:theme="@style/ToolbarColoredBackArrow"
app:popupTheme="@style/AppTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary"/>
This is a good overview:
http://reference.jumpingmonkey.org/programming_languages/objective-c/types.html
or run this code:
32 bit process:
NSLog(@"Primitive sizes:");
NSLog(@"The size of a char is: %d.", sizeof(char));
NSLog(@"The size of short is: %d.", sizeof(short));
NSLog(@"The size of int is: %d.", sizeof(int));
NSLog(@"The size of long is: %d.", sizeof(long));
NSLog(@"The size of long long is: %d.", sizeof(long long));
NSLog(@"The size of a unsigned char is: %d.", sizeof(unsigned char));
NSLog(@"The size of unsigned short is: %d.", sizeof(unsigned short));
NSLog(@"The size of unsigned int is: %d.", sizeof(unsigned int));
NSLog(@"The size of unsigned long is: %d.", sizeof(unsigned long));
NSLog(@"The size of unsigned long long is: %d.", sizeof(unsigned long long));
NSLog(@"The size of a float is: %d.", sizeof(float));
NSLog(@"The size of a double is %d.", sizeof(double));
NSLog(@"Ranges:");
NSLog(@"CHAR_MIN: %c", CHAR_MIN);
NSLog(@"CHAR_MAX: %c", CHAR_MAX);
NSLog(@"SHRT_MIN: %hi", SHRT_MIN); // signed short int
NSLog(@"SHRT_MAX: %hi", SHRT_MAX);
NSLog(@"INT_MIN: %i", INT_MIN);
NSLog(@"INT_MAX: %i", INT_MAX);
NSLog(@"LONG_MIN: %li", LONG_MIN); // signed long int
NSLog(@"LONG_MAX: %li", LONG_MAX);
NSLog(@"ULONG_MAX: %lu", ULONG_MAX); // unsigned long int
NSLog(@"LLONG_MIN: %lli", LLONG_MIN); // signed long long int
NSLog(@"LLONG_MAX: %lli", LLONG_MAX);
NSLog(@"ULLONG_MAX: %llu", ULLONG_MAX); // unsigned long long int
When run on an iPhone 3GS (iPod Touch and older iPhones should yield the same result) you get:
Primitive sizes:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 4.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 4.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -2147483648
LONG_MAX: 2147483647
ULONG_MAX: 4294967295
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
64 bit process:
The size of a char is: 1.
The size of short is: 2.
The size of int is: 4.
The size of long is: 8.
The size of long long is: 8.
The size of a unsigned char is: 1.
The size of unsigned short is: 2.
The size of unsigned int is: 4.
The size of unsigned long is: 8.
The size of unsigned long long is: 8.
The size of a float is: 4.
The size of a double is 8.
Ranges:
CHAR_MIN: -128
CHAR_MAX: 127
SHRT_MIN: -32768
SHRT_MAX: 32767
INT_MIN: -2147483648
INT_MAX: 2147483647
LONG_MIN: -9223372036854775808
LONG_MAX: 9223372036854775807
ULONG_MAX: 18446744073709551615
LLONG_MIN: -9223372036854775808
LLONG_MAX: 9223372036854775807
ULLONG_MAX: 18446744073709551615
Just add this function and call it, it will convert List to DataTable.
public static DataTable ToDataTable<T>(List<T> items)
{
DataTable dataTable = new DataTable(typeof(T).Name);
//Get all the properties
PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo prop in Props)
{
//Defining type of data column gives proper data table
var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
//Setting column names as Property names
dataTable.Columns.Add(prop.Name, type);
}
foreach (T item in items)
{
var values = new object[Props.Length];
for (int i = 0; i < Props.Length; i++)
{
//inserting property values to datatable rows
values[i] = Props[i].GetValue(item, null);
}
dataTable.Rows.Add(values);
}
//put a breakpoint here and check datatable
return dataTable;
}
To Remove element from the list
objectA.removeIf(x -> conditions);
eg:
objectA.removeIf(x -> blockedWorkerIds.contains(x));
List<String> str1 = new ArrayList<String>();
str1.add("A");
str1.add("B");
str1.add("C");
str1.add("D");
List<String> str2 = new ArrayList<String>();
str2.add("D");
str2.add("E");
str1.removeIf(x -> str2.contains(x));
str1.forEach(System.out::println);
OUTPUT: A B C
I do not know of a standalone PHP / Apache solution, as this would require a PHP library that can read and render SVG images. I'm not sure such a library exists - I don't know any.
ImageMagick is able to rasterize SVG files, either through the command line or the PHP binding, IMagick, but seems to have a number of quirks and external dependencies as shown e.g. in this forum thread. I think it's still the most promising way to go, it's the first thing I would look into if I were you.
All the symptoms you describe suggest that you never tell MySQL what time zone to use so it defaults to system's zone. Think about it: if all it has is '2011-03-13 02:49:10'
, how can it guess that it's a local Tanzanian date?
As far as I know, MySQL doesn't provide any syntax to specify time zone information in dates. You have to change it a per-connection basis; something like:
SET time_zone = 'EAT';
If this doesn't work (to use named zones you need that the server has been configured to do so and it's often not the case) you can use UTC offsets because Tanzania does not observe daylight saving time at the time of writing but of course it isn't the best option:
SET time_zone = '+03:00';
I was writing a program to check if a number was square and I encountered this issue, the code I used was:
import math
print ("this program will tell you if a number is square")
print ("enter an integer")
num = float(input())
if num > 0:
print ("ok!")
num = (math.sqrt(num))
inter = int(num)
if num == inter:
print ("It's a square number, and its root is")
print (num)
else:
print ("It's not a square number, but its root is")
print (num)
else:
print ("That's not a positive number!")
To tell if the number was an integer I converted the float number you get from square rooting the user input to a rounded integer (stored as the value ), if those two numbers were equal then the first number must have been an integer, allowing the program to respond. This may not be the shortest way of doing this but it worked for me.
Here's an example that let's you set the color of the background. If you don't want to use float, then you might need to set the width and height manually. But even that really depends on the surrounding CSS/HTML.
<style>
#color {
background-color: red;
float: left;
}#opacity {
opacity : 0.4;
filter: alpha(opacity=40);
}
</style>
<div id="color">
<div id="opacity">
<img src="image.jpg" />
</div>
</div>
Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:
library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")
# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()
# Start time
data %>%
xml_find_all("//start-valid-time") %>%
xml_text()
# Temperature
data %>%
xml_find_all("//temperature[@type='hourly']/value") %>%
xml_text() %>%
as.integer()
Here is a work around I found if you want to only shuffle a subset of the DataFrame:
shuffle_to_index = 20
df = pd.concat([df.iloc[np.random.permutation(range(shuffle_to_index))], df.iloc[shuffle_to_index:]])
Here's a more technical and thorough answer to an old question: Visual Basic for Applications (VBA) and Visual Basic (pre-.NET) are not just similar languages, they are the same language. Specifically:
In an old VB reference book I came across last year, the author (Paul Lomax) even asserted that 'VBA' has always been the name of the language itself, whether used in stand-alone applications or in embedded contexts (such as MS Office):
"Before we go any further, let's just clarify on fundamental point. Visual Basic for Applications (VBA) is the language used to program in Visual Basic (VB). VB itself is a development environment; the language element of that environment is VBA."
The minor differences
Hosted vs. stand-alone: In practical, terms, when most people say "VBA" they specifically mean "VBA when used in MS Office", and they say "VB6" to mean "VBA used in the last version of the standalone VBA compiler (i.e. Visual Studio 6)". The IDE and compiler bundled with MS Office is almost identical to Visual Studio 6, with the limitation that it does not allow compilation to stand-alone dll or exe files. This in turns means that classes defined in embedded VBA projects are not accessible from non-embedded COM consumers, because they cannot be registered.
Continued development: Microsoft stopped producing a stand-alone VBA compiler with Visual Studio 6, as they switched to the .NET runtime as the platform of choice. However, the MS Office team continues to maintain VBA, and even released a new version (VBA7) with a new VM (now just called VBA7.dll) starting with MS Office 2010. The only major difference is that VBA7 has both a 32- and 64-bit version and has a few enhancements to handle the differences between the two, specifically with regards to external API invocations.
Where is the file that you're running? If it is in your public html folder, you can do echo dirname(__FILE__);
In vue js :
self.$refs.inputFile.value = ''
_x000D_
I used JSONObject as shown below in Servlet.
JSONObject jsonReturn = new JSONObject();
NhAdminTree = AdminTasks.GetNeighborhoodTreeForNhAdministrator( connection, bwcon, userName);
map = new HashMap<String, String>();
map.put("Status", "Success");
map.put("FailureReason", "None");
map.put("DataElements", "2");
jsonReturn = new JSONObject();
jsonReturn.accumulate("Header", map);
List<String> list = new ArrayList<String>();
list.add(NhAdminTree);
list.add(userName);
jsonReturn.accumulate("Elements", list);
The Servlet returns this JSON object as shown below:
response.setContentType("application/json");
response.getWriter().write(jsonReturn.toString());
This Servlet is called from Browser using AngularJs as below
$scope.GetNeighborhoodTreeUsingPost = function(){
alert("Clicked GetNeighborhoodTreeUsingPost : " + $scope.userName );
$http({
method: 'POST',
url : 'http://localhost:8080/EPortal/xlEPortalService',
headers: {
'Content-Type': 'application/json'
},
data : {
'action': 64,
'userName' : $scope.userName
}
}).success(function(data, status, headers, config){
alert("DATA.header.status : " + data.Header.Status);
alert("DATA.header.FailureReason : " + data.Header.FailureReason);
alert("DATA.header.DataElements : " + data.Header.DataElements);
alert("DATA.elements : " + data.Elements);
}).error(function(data, status, headers, config) {
alert(data + " : " + status + " : " + headers + " : " + config);
});
};
This code worked and it is showing correct data in alert dialog box:
Data.header.status : Success
Data.header.FailureReason : None
Data.header.DetailElements : 2
Data.Elements : Coma seperated string values i.e. NhAdminTree, userName
<html>
<head>
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(function() {
//here you have the control over the body of the iframe document
var iBody = $("#iView").contents().find("body");
//here you have the control over any element (#myContent)
var myContent = iBody.find("#myContent");
});
</script>
</head>
<body>
<iframe src="mifile.html" id="iView" style="width:200px;height:70px;border:dotted 1px red" frameborder="0"></iframe>
</body>
</html>
$new_input = array('type' => 'text', 'label' => 'First name', 'show' => true, 'required' => true);
$options['inputs']['name'] = $new_input;
Oh my, C vs C++, a great way to start a flame war. :)
I think C is better for driver and embedded code.
C++ has some great features that C doesn't have, but many of the object oriented features of C++ can cause monumental coding messes when people write code with non-obvious side-effects that occur behinds the scenes. Crazy code can be hidden in constructors, destructors, virtual functions, ... The beauty of C code is the language does nothing non-obvious behind your back, thus you can read the code and not have to look up at every constructor and destructor and so on. A lot of the problem is bad coding practices by SOME people.
My perfect language would be a combination of C99 plus a minimal subset of safer C++ capabilities that adds ZERO (or near zero) compiler overhead to the binary output. Perfect additions would be class encapsulation and naming concepts of data and functions.
There were a lot of performance considerations, all in the vacuum.
The issue with this handlers is that you need to curry them in order to incorporate the argument that you can't name in the props.
This means that the component needs a handler for each and every clickable element. Let's agree that for a few buttons this is not an issue, right?
The problem arises when you are handling tabular data with dozens of columns and thousands of rows. There you notice the impact of creating that many handlers.
The fact is, I only need one.
I set the handler at the table level (or UL or OL...), and when the click happens I can tell which was the clicked cell using data available since ever in the event object:
nativeEvent.target.tagName
nativeEvent.target.parentElement.tagName
nativeEvent.target.parentElement.rowIndex
nativeEvent.target.cellIndex
nativeEvent.target.textContent
I use the tagname fields to check that the click happened in a valid element, for example ignore clicks in THs ot footers.
The rowIndex and cellIndex give the exact location of the clicked cell.
Textcontent is the text of the clicked cell.
This way I don't need to pass the cell's data to the handler, it can self-service it.
If I needed more data, data that is not to be displayed, I can use the dataset attribute, or hidden elements.
With some simple DOM navigation it's all at hand.
This has been used in HTML since ever, since PCs were much easier to bog.
Here is an example straight from PHP.net
$a = array(
"one" => 1,
"two" => 2,
"three" => 3,
"seventeen" => 17
);
foreach ($a as $k => $v) {
echo "\$a[$k] => $v.\n";
}
in the foreach you can do a comparison of each key to something that you are looking for
#!/bin/bash
read -p "Enter a directory: " BASEPATH
SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2
echo "I will create $SUBFOLD1 and $SUBFOLD2"
# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2
And if you want to use readline so you get completion and all that, add a -e
to the call to read
:
read -e -p "Enter a directory: " BASEPATH
About the nested properties discussion, you can avoid all the reflection stuff if you use the DataBinder.Eval Method (Object, String)
as below:
var value = DataBinder.Eval(DateTime.Now, "TimeOfDay.Hours");
Of course, you'll need to add a reference to the System.Web
assembly, but this probably isn't a big deal.
public ArrayAdapter (Context context, int resource, int textViewResourceId, T[] objects)
I am also new to Android , so i might be wrong. But as per my understanding while using this for listview creation 2nd argument is the layout of list items. A layout consists of many views (image view,text view etc). With 3rd argument you are specifying in which view or textview you want the text to be displayed.
You can use this command
$ git rev-list HEAD
You can also use the head
Unix command to show the latest n
HEAD
commits like
$ git rev-list HEAD | head - 2
My Problem:
docker run <IMAGE_NAME>
docker ps -a
I could see two containers. docker run <IMAGE_NAME>
command, new image was getting createdSolution: To work on the same container you created in the first place run follow these steps
docker ps
to get container of your containerdocker container start <CONTAINER_ID>
to start existing containerdocker exec -it <CONTAINER_ID> /bin/bash
select column1 || ' ' || column2 as whole_name FROM tablename;
Here ||
is the concat operator used for concatenating them to single column and (''
) inside ||
used for space between two columns.
Using nvidia-smi
should tell you that:
bwood@mybox:~$ nvidia-smi
Mon Oct 29 12:30:02 2012
+------------------------------------------------------+
| NVIDIA-SMI 3.295.41 Driver Version: 295.41 |
|-------------------------------+----------------------+----------------------+
| Nb. Name | Bus Id Disp. | Volatile ECC SB / DB |
| Fan Temp Power Usage /Cap | Memory Usage | GPU Util. Compute M. |
|===============================+======================+======================|
| 0. GeForce GTX 580 | 0000:25:00.0 N/A | N/A N/A |
| 54% 70 C N/A N/A / N/A | 25% 383MB / 1535MB | N/A Default |
|-------------------------------+----------------------+----------------------|
| Compute processes: GPU Memory |
| GPU PID Process name Usage |
|=============================================================================|
| 0. Not Supported |
+-----------------------------------------------------------------------------+
Given that a WHERE clause did not work, maybe this will:
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
Begin
Return
End
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
Have a look this:
use yii\helpers\ArrayHelper; // load classes
use app\models\Course;
.....
$dataList=ArrayHelper::map(Course::find()->asArray()->all(), 'id', 'name');
<?=$form->field($model, 'center_id')->dropDownList($dataList,
['prompt'=>'-Choose a Course-']) ?>
This is your safest way to do it:
$id =101;
//$user_id=25;
$criteria=new CDbCriteria;
$criteria->condition="email_id < :email_id";
//$criteria->addCondition("user_id=:user_id");
$criteria->params=array(
':email_id' => $id,
//':user_id' => $user_id,
);
$comments=EmailArchive::model()->findAll($criteria);
Note that if you comment out the commented lines you get a way to add more filtering to your search.
After this it is recommend to check if there is any data returned like:
if (isset($comments)) { // We found some comments, we can sleep well tonight
// do comments process or whatever
}
There is a way to remove the line.
1) Follow this tutorial: android-tabs-with-fragments
2) Then apply the RelativeLayout change that Leaudro suggested above (apply the layout props to all FrameLayouts).
You can also add an ImageView to the tab.xml in item #1 and get a very iPhone like look to the tabs.
Here is a screenshot of what I'm working on right now. I still have some work to do, mainly make a selector for the icons and ensure equal horizontal distribution, but you get the idea. In my case, I'm using fragments, but the same principals should apply to a standard tab view.
From my experience with GCC I know that static
and static inline
differs in a way how compiler issue warnings about unused functions. More precisely when you declare static
function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline
.
Thus I tend to think that static
should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline
should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.
Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline
inhibits unused function warnings. I'd appreciate if someone will share links to description of that.
-> it works like pointer u don't have to use *
for( list<student>::iterator iter= data.begin(); iter != data.end(); iter++ )
cout<<iter->name; //'iter' not 'it'
Yes.
In essence, as long as nothing is output, you can do whatever you want (kill a session, remove user cookies, calculate Pi to 'n' digits, etc.) prior to issuing a location header.
Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.
OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.
You can invoke onNewIntent always by putting it into onCreate method like
@Override
public void onCreate(Bundle savedState){
super.onCreate(savedState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//code
}
I know this is an old question but I stumbled upon this recently and it ended up misguiding me since the Subprocess API as changed since python 3.5.
The new way to execute external scripts is with the run
function, which runs the command described by args. Waits for command to complete, then returns a CompletedProcess instance.
import subprocess
subprocess.run(['./test.sh'])
how to validate the select "qualifica" it has 3 choose
$(document).ready(function(){
$('.validateForm').validate({
rules: {
fullname: 'required',
ragionesociale: 'required',
partitaiva: 'required',
recapitotelefonico: 'required',
qualifica: 'required',
email: {
required: true,
email: true
},
},
submitHandler: function(form) {
var fullname = $('#fullname').val(),
ragionesociale = $('#ragionesociale').val(),
partitaiva = $('#partitaiva').val(),
email = $('#email').val(),
recapitotelefonico = $('#recapitotelefonico').val(),
qualifica = $('#qualifica').val(),
dataString = 'fullname=' + fullname + '&ragionesociale=' + ragionesociale + '&partitaiva=' + partitaiva + '&email=' + email + '&recapitotelefonico=' + recapitotelefonico + '&qualifica=' + qualifica;
$.ajax({
type: "POST",
url: "util/sender.php",
data: dataString,
success: function() {
window.location.replace("./thank-you-page.php");
}
});
return false;
}
});
});
Using python-docx, as @Chinmoy Panda 's answer shows:
for para in doc.paragraphs:
fullText.append(para.text)
However, para.text
will lost the text in w:smarttag
(Corresponding github issue is here: https://github.com/python-openxml/python-docx/issues/328), you should use the following function instead:
def para2text(p):
rs = p._element.xpath('.//w:t')
return u" ".join([r.text for r in rs])
If you are not looking for Excel formula, Its easy from the Menu
Data Menu --> Remove Duplicates would alert, if there are no duplicates
Also, if you see the count and reduced after removing duplicates...
This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
You can use the DATE()
function to extract the date portion of the timestamp:
SELECT * FROM table
WHERE DATE(timestamp) = '2012-05-25'
Though, if you have an index on the timestamp column, this would be faster because it could utilize an index on the timestamp column if you have one:
SELECT * FROM table
WHERE timestamp BETWEEN '2012-05-25 00:00:00' AND '2012-05-25 23:59:59'
If you are getting such error, the only reason could be you using a Distribution profile rather than a development profile in Xcode or a missing Entitlement property. If you are not using the Entitlements.plist, then the only possible error could be the app is getting packaged with a distribution profile. You could verify this confirming the build logs. To change this, go to Build Setting of the project and verify Code Signing Entity setting. For debugging to work, this setting should be a developer profile for the configuration that you are currently using.
https://developer.apple.com/library/ios/#qa/qa1682/_index.html
For instant results, delete all mobile provisioning profiles from xcode and install the developer profile that you intend to use.
Use overrideLibrary
when the minSdk is declared in build.gradle
instead of in AndroidManifest.xml
If you are using Android Studio:
add <uses-sdk tools:overrideLibrary="android.support.v17.leanback"/>
to your manifest, don't forget to include xmlns:tools="http://schemas.android.com/tools"
too.
The "braces" are making an object literal, i.e. they create an object. It is one argument.
Example:
function someFunc(arg) {
alert(arg.foo);
alert(arg.bar);
}
someFunc({foo: "This", bar: "works!"});
the object can be created beforehand as well:
var someObject = {
foo: "This",
bar: "works!"
};
someFunc(someObject);
I recommend to read the MDN JavaScript Guide - Working with Objects.
Here's @Daniel Vérité's function with progress reporting functionality. It reports progress in three ways:
_
CREATE OR REPLACE FUNCTION search_columns(
needle text,
haystack_tables name[] default '{}',
haystack_schema name[] default '{public}',
progress_seq text default NULL
)
RETURNS table(schemaname text, tablename text, columnname text, rowctid text)
AS $$
DECLARE
currenttable text;
columnscount integer;
foundintables text[];
foundincolumns text[];
begin
currenttable='';
columnscount = (SELECT count(1)
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE')::integer;
PERFORM setval(progress_seq::regclass, columnscount);
FOR schemaname,tablename,columnname IN
SELECT c.table_schema,c.table_name,c.column_name
FROM information_schema.columns c
JOIN information_schema.tables t ON
(t.table_name=c.table_name AND t.table_schema=c.table_schema)
WHERE (c.table_name=ANY(haystack_tables) OR haystack_tables='{}')
AND c.table_schema=ANY(haystack_schema)
AND t.table_type='BASE TABLE'
LOOP
EXECUTE format('SELECT ctid FROM %I.%I WHERE cast(%I as text)=%L',
schemaname,
tablename,
columnname,
needle
) INTO rowctid;
IF rowctid is not null THEN
RETURN NEXT;
foundintables = foundintables || tablename;
foundincolumns = foundincolumns || columnname;
RAISE NOTICE 'FOUND! %, %, %, %', schemaname,tablename,columnname, rowctid;
END IF;
IF (progress_seq IS NOT NULL) THEN
PERFORM nextval(progress_seq::regclass);
END IF;
IF(currenttable<>tablename) THEN
currenttable=tablename;
IF (progress_seq IS NOT NULL) THEN
RAISE NOTICE 'Columns left to look in: %; looking in table: %', currval(progress_seq::regclass), tablename;
EXECUTE 'COPY (SELECT unnest(string_to_array(''Current table (column ' || columnscount-currval(progress_seq::regclass) || ' of ' || columnscount || '): ' || tablename || '\n\nFound in tables/columns:\n' || COALESCE(
(SELECT string_agg(c1 || '/' || c2, '\n') FROM (SELECT unnest(foundintables) AS c1,unnest(foundincolumns) AS c2) AS t1)
, '') || ''',''\n''))) TO ''c:\WINDOWS\temp\' || progress_seq || '.txt''';
END IF;
END IF;
END LOOP;
END;
$$ language plpgsql;
This question actually have more deep nature and good understanding of the multithreading concepts in general will provide you insight about this topic. In fact there is no any language or any operating system which provide you facilities for asynchronous abruptly thread termination without warning to not use them. And all these execution environments strongly advise developer or even require build multithreading applications on the base of cooperative or synchronous thread termination. The reason for this common decisions and advices is that all they are built on the base of the same general multithreading model.
Let's compare multiprocessing and multithreading concepts to better understand advantages and limitations of the second one.
Multiprocessing assumes splitting of the entire execution environment into set of completely isolated processes controlled by the operating system. Process incorporates and isolates execution environment state including local memory of the process and data inside it and all system resources like files, sockets, synchronization objects. Isolation is a critically important characteristic of the process, because it limits the faults propagation by the process borders. In other words, no one process can affects the consistency of any another process in the system. The same is true for the process behaviour but in the less restricted and more blur way. In such environment any process can be killed in any "arbitrary" moment, because firstly each process is isolated, secondly, operating system have full knowledges about all resources used by process and can release all of them without leaking, and finally process will be killed by OS not really in arbitrary moment, but in the number of well defined points where the state of the process is well known.
In contrast, multithreading assumes running multiple threads in the same process. But all this threads are share the same isolation box and there is no any operating system control of the internal state of the process. As a result any thread is able to change global process state as well as corrupt it. At the same moment the points in which the state of the thread is well known to be safe to kill a thread completely depends on the application logic and are not known neither for operating system nor for programming language runtime. As a result thread termination at the arbitrary moment means killing it at arbitrary point of its execution path and can easily lead to the process-wide data corruption, memory and handles leakage, threads leakage and spinlocks and other intra-process synchronization primitives leaved in the closed state preventing other threads in doing progress.
Due to this the common approach is to force developers to implement synchronous or cooperative thread termination, where the one thread can request other thread termination and other thread in well-defined point can check this request and start the shutdown procedure from the well-defined state with releasing of all global system-wide resources and local process-wide resources in the safe and consistent way.
Use these classes: navbar-brand mx-auto
All other solutions overcomplicate the matter.
My answer is "neither one".
I believe the most "Pythonic" way to do things is to NOT check beforehand if the key is in a dictionary and instead just write code that assumes it's there and catch any KeyErrors that get raised because it wasn't.
This is usually done with enclosing the code in a try...except
clause and is a well-known idiom usually expressed as "It's easier to ask forgiveness than permission" or with the acronym EAFP, which basically means it is better to try something and catch the errors instead for making sure everything's OK before doing anything. Why validate what doesn't need to be validated when you can handle exceptions gracefully instead of trying to avoid them? Because it's often more readable and the code tends to be faster if the probability is low that the key won't be there (or whatever preconditions there may be).
Of course, this isn't appropriate in all situations and not everyone agrees with the philosophy, so you'll need to decide for yourself on a case-by-case basis. Not surprisingly the opposite of this is called LBYL for "Look Before You Leap".
As a trivial example consider:
if 'name' in dct:
value = dct['name'] * 3
else:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
vs
try:
value = dct['name'] * 3
except KeyError:
logerror('"%s" not found in dictionary, using default' % name)
value = 42
Although in the case it's almost exactly the same amount of code, the second doesn't spend time checking first and is probably slightly faster because of it (try...except block isn't totally free though, so it probably doesn't make that much difference here).
Generally speaking, testing in advance can often be much more involved and the savings gain from not doing it can be significant. That said, if 'name' in dict:
is better for the reasons stated in the other answers.
If you're interested in the topic, this message titled "EAFP vs LBYL (was Re: A little disappointed so far)" from the Python mailing list archive probably explains the difference between the two approached better than I have here. There's also a good discussion about the two approaches in the book Python in a Nutshell, 2nd Ed by Alex Martelli in chapter 6 on Exceptions titled Error-Checking Strategies. (I see there's now a newer 3rd edition, publish in 2017, which covers both Python 2.7 and 3.x).
Script snip below creates a pause sub that displayes the pause text in a string and waits for the Enter key. z can be anything. Great if multilple user intervention required pauses are needed. I just keep it in my standard script template.
Pause("Press Enter to continue")
Sub Pause(strPause)
WScript.Echo (strPause)
z = WScript.StdIn.Read(1)
End Sub
Step 1. In your startup, register your exception handling route:
// It should be one of your very first registrations
app.UseExceptionHandler("/error"); // Add this
app.UseEndpoints(endpoints => endpoints.MapControllers());
Step 2. Create controller that will handle all exceptions and produce error response:
[ApiExplorerSettings(IgnoreApi = true)]
public class ErrorsController : ControllerBase
{
[Route("error")]
public MyErrorResponse Error()
{
var context = HttpContext.Features.Get<IExceptionHandlerFeature>();
var exception = context.Error; // Your exception
var code = 500; // Internal Server Error by default
if (exception is MyNotFoundException) code = 404; // Not Found
else if (exception is MyUnauthException) code = 401; // Unauthorized
else if (exception is MyException) code = 400; // Bad Request
Response.StatusCode = code; // You can use HttpStatusCode enum instead
return new MyErrorResponse(exception); // Your error model
}
}
A few important notes and observations:
[ApiExplorerSettings(IgnoreApi = true)]
is needed. Otherwise, it may break your Swashbuckle swaggerapp.UseExceptionHandler("/error");
has to be one of the very top registrations in your Startup Configure(...)
method. It's probably safe to place it at the top of the method.app.UseExceptionHandler("/error")
and in controller [Route("error")]
should be the same, to allow the controller handle exceptions redirected from exception handler middleware.Microsoft documentation for this subject is not that great but has some interesting ideas. I'll just leave the link here.
Implement your own response model and exceptions. This example is just a good starting point. Every service would need to handle exceptions in its own way. But with this code, you have full flexibility and control over handling exceptions and returning a proper result to the caller.
An example of error response model (just to give you some ideas):
public class MyErrorResponse
{
public string Type { get; set; }
public string Message { get; set; }
public string StackTrace { get; set; }
public MyErrorResponse(Exception ex)
{
Type = ex.GetType().Name;
Message = ex.Message;
StackTrace = ex.ToString();
}
}
For simpler services, you might want to implement http status code exception that would look like this:
public class HttpStatusException : Exception
{
public HttpStatusCode Status { get; private set; }
public HttpStatusException(HttpStatusCode status, string msg) : base(msg)
{
Status = status;
}
}
This can be thrown like that:
throw new HttpStatusCodeException(HttpStatusCode.NotFound, "User not found");
Then your handling code could be simplified to:
if (exception is HttpStatusException httpException)
{
code = (int) httpException.Status;
}
Why so un-obvious HttpContext.Features.Get<IExceptionHandlerFeature>()
?
ASP.NET Core developers embraced the concept of middlewares where different aspects of functionality such as Auth, Mvc, Swagger etc. are separated and executed sequentially by processing the request and returning the response or passing the execution to the next middleware. With this architecture, MVC itself, for instance, would not be able to handle errors happening in Auth. So, they came up with exception handling middleware that catches all the exceptions happening in middlewares registered down in the pipeline, pushes exception data into HttpContext.Features
, and re-runs the pipeline for specified route (/error
), allowing any middleware to handle this exception, and the best way to handle it is by our Controllers to maintain proper content negotiation.
I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.
window.setTimeout(function() { // hide alert message
$("#alert_message").removeClass('in');
}, 5000);
When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)
$('#Some_Button_Or_Event_Here').click(function () { // Show alert message
$('#alert_message').addClass('in');
});
If you're using @ConfigurationProperties
with Spring Boot 2 to inject maps with keys that contain colons then you need an additional level of escaping using square brackets inside the quotes because spring only allows alphanumeric and '-' characters, stripping out the rest. Your new key would look like this:
"[8.11.32.120:8000]": GoogleMapsKeyforThisDomain
See this github issue for reference.
it's easy to export mylib.so
to env:
$ export LD_PRELOAD=/path/mylib.so
$ ./mybin
to disable :
$ export LD_PRELOAD=
use HASHBYTES
declare @first_value nvarchar(1) = 'a'
declare @second_value navarchar(1) = 'A'
if HASHBYTES('SHA1',@first_value) = HASHBYTES('SHA1',@second_value) begin
print 'equal'
end else begin
print 'not equal'
end
-- output:
-- not equal
...in where clause
declare @example table (ValueA nvarchar(1), ValueB nvarchar(1))
insert into @example (ValueA, ValueB)
values ('a', 'A'),
('a', 'a'),
('a', 'b')
select ValueA + ' = ' + ValueB
from @example
where hashbytes('SHA1', ValueA) = hashbytes('SHA1', ValueB)
-- output:
-- a = a
select ValueA + ' <> ' + ValueB
from @example
where hashbytes('SHA1', ValueA) <> hashbytes('SHA1', ValueB)
-- output:
-- a <> A
-- a <> b
or to find a value
declare @value_b nvarchar(1) = 'A'
select ValueB + ' = ' + @value_b
from @example
where hashbytes('SHA1', ValueB) = hasbytes('SHA1', @value_b)
-- output:
-- A = A
You can do this with the hex codec. ie:
>>> s='000000000000484240FA063DE5D0B744ADBED63A81FAEA390000C8428640A43D5005BD44'
>>> s.decode('hex')
'\x00\x00\x00\x00\x00\x00HB@\xfa\x06=\xe5\xd0\xb7D\xad\xbe\xd6:\x81\xfa\xea9\x00\x00\xc8B\x86@\xa4=P\x05\xbdD'
This answer is not the answer for the above mentioned question but it is related to same topic and might be useful for people searching for same error.
I faced the same error when I executed below mentioned query.
select OR.* from ORDER_REL_STAT OR
problem with above query was OR is keyword so it was expecting other values when I replaced with some other alias it worked fine.
Use the before
and after
methods: Javadoc
if (mytime.after(fromtime) && mytime.before(totime))
If the initial order of elements isn't really important, you could just sort the array, then binarySearch it:
import java.util.Arrays;
class masi {
public static void main( String[] args ) {
char[] list = {'m', 'e', 'y'};
Arrays.sort(list);
// should print 0, as e is now sorted to the beginning
// returns negative number if the result isn't found
System.out.println( Arrays.binarySearch(list, 'e') );
}
}
From the @Tgr's comment, there is an online tool : https://codetabs.com/count-loc/count-loc-online.html
I export lists into YAML format with CPAN YAML package.
l <- list(a="1", b=1, c=list(a="1", b=1))
yaml::write_yaml(l, "list.yaml")
Bonus of YAML that it's a human readable text format so it's easy to read/share/import/etc
$ cat list.yaml
a: '1'
b: 1.0
c:
a: '1'
b: 1.0
When you import lib
, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py
in the lib directory.
If you want access to your function, you can do something like this from lib.mod1 import mod1
and then run the mod12
function like so mod1.mod12()
.
If you want to be able to access mod1
when you import lib
, you need to put an import mod1
inside the __init__.py
file inside the lib
directory.
array=("word" "two words") # let's look for "two words"
grep
and printf
:(printf '%s\n' "${array[@]}" | grep -x -q "two words") && <run_your_if_found_command_here>
for
:(for e in "${array[@]}"; do [[ "$e" == "two words" ]] && exit 0; done; exit 1) && <run_your_if_found_command_here>
For not_found results add || <run_your_if_notfound_command_here>
If it is simply to disable a group policy that is enforced every 30 minutes you can uncheck the box then change the permissions to Read Only.
This link might help you out: http://pastebin.com/f10584951.
Pasted below for posterity:
/*
* Slightly modified version of the com.ibatis.common.jdbc.ScriptRunner class
* from the iBATIS Apache project. Only removed dependency on Resource class
* and a constructor
*/
/*
* Copyright 2004 Clinton Begin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.PrintWriter;
import java.io.Reader;
import java.sql.*;
/**
* Tool to run database scripts
*/
public class ScriptRunner {
private static final String DEFAULT_DELIMITER = ";";
private Connection connection;
private boolean stopOnError;
private boolean autoCommit;
private PrintWriter logWriter = new PrintWriter(System.out);
private PrintWriter errorLogWriter = new PrintWriter(System.err);
private String delimiter = DEFAULT_DELIMITER;
private boolean fullLineDelimiter = false;
/**
* Default constructor
*/
public ScriptRunner(Connection connection, boolean autoCommit,
boolean stopOnError) {
this.connection = connection;
this.autoCommit = autoCommit;
this.stopOnError = stopOnError;
}
public void setDelimiter(String delimiter, boolean fullLineDelimiter) {
this.delimiter = delimiter;
this.fullLineDelimiter = fullLineDelimiter;
}
/**
* Setter for logWriter property
*
* @param logWriter
* - the new value of the logWriter property
*/
public void setLogWriter(PrintWriter logWriter) {
this.logWriter = logWriter;
}
/**
* Setter for errorLogWriter property
*
* @param errorLogWriter
* - the new value of the errorLogWriter property
*/
public void setErrorLogWriter(PrintWriter errorLogWriter) {
this.errorLogWriter = errorLogWriter;
}
/**
* Runs an SQL script (read in using the Reader parameter)
*
* @param reader
* - the source of the script
*/
public void runScript(Reader reader) throws IOException, SQLException {
try {
boolean originalAutoCommit = connection.getAutoCommit();
try {
if (originalAutoCommit != this.autoCommit) {
connection.setAutoCommit(this.autoCommit);
}
runScript(connection, reader);
} finally {
connection.setAutoCommit(originalAutoCommit);
}
} catch (IOException e) {
throw e;
} catch (SQLException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error running script. Cause: " + e, e);
}
}
/**
* Runs an SQL script (read in using the Reader parameter) using the
* connection passed in
*
* @param conn
* - the connection to use for the script
* @param reader
* - the source of the script
* @throws SQLException
* if any SQL errors occur
* @throws IOException
* if there is an error reading from the Reader
*/
private void runScript(Connection conn, Reader reader) throws IOException,
SQLException {
StringBuffer command = null;
try {
LineNumberReader lineReader = new LineNumberReader(reader);
String line = null;
while ((line = lineReader.readLine()) != null) {
if (command == null) {
command = new StringBuffer();
}
String trimmedLine = line.trim();
if (trimmedLine.startsWith("--")) {
println(trimmedLine);
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("//")) {
// Do nothing
} else if (trimmedLine.length() < 1
|| trimmedLine.startsWith("--")) {
// Do nothing
} else if (!fullLineDelimiter
&& trimmedLine.endsWith(getDelimiter())
|| fullLineDelimiter
&& trimmedLine.equals(getDelimiter())) {
command.append(line.substring(0, line
.lastIndexOf(getDelimiter())));
command.append(" ");
Statement statement = conn.createStatement();
println(command);
boolean hasResults = false;
if (stopOnError) {
hasResults = statement.execute(command.toString());
} else {
try {
statement.execute(command.toString());
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
}
}
if (autoCommit && !conn.getAutoCommit()) {
conn.commit();
}
ResultSet rs = statement.getResultSet();
if (hasResults && rs != null) {
ResultSetMetaData md = rs.getMetaData();
int cols = md.getColumnCount();
for (int i = 0; i < cols; i++) {
String name = md.getColumnLabel(i);
print(name + "\t");
}
println("");
while (rs.next()) {
for (int i = 0; i < cols; i++) {
String value = rs.getString(i);
print(value + "\t");
}
println("");
}
}
command = null;
try {
statement.close();
} catch (Exception e) {
// Ignore to workaround a bug in Jakarta DBCP
}
Thread.yield();
} else {
command.append(line);
command.append(" ");
}
}
if (!autoCommit) {
conn.commit();
}
} catch (SQLException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} catch (IOException e) {
e.fillInStackTrace();
printlnError("Error executing: " + command);
printlnError(e);
throw e;
} finally {
conn.rollback();
flush();
}
}
private String getDelimiter() {
return delimiter;
}
private void print(Object o) {
if (logWriter != null) {
System.out.print(o);
}
}
private void println(Object o) {
if (logWriter != null) {
logWriter.println(o);
}
}
private void printlnError(Object o) {
if (errorLogWriter != null) {
errorLogWriter.println(o);
}
}
private void flush() {
if (logWriter != null) {
logWriter.flush();
}
if (errorLogWriter != null) {
errorLogWriter.flush();
}
}
}
JButton b3 = new JButton("CLOSE");
b3.setBounds(50, 375, 250, 50);
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
});
try using this in your properties file:
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
Structure types should, whenever practical, either have all of their state encapsulated in public fields which may independently be set to any values which are valid for their respective type, or else behave as a single unified value which can only bet set via constructor, factory, method, or else by passing an instance of the struct as an explicit ref
parameter to one of its public methods. Contrary to what some people claim, that there's nothing wrong with a struct having public fields, if it is supposed to represent a set of values which may sensibly be either manipulated individually or passed around as a group (e.g. the coordinates of a point). Historically, there have been problems with structures that had public property setters, and a desire to avoid public fields (implying that setters should be used instead) has led some people to suggest that mutable structures should be avoided altogether, but fields do not have the problems that properties had. Indeed, an exposed-field struct is the ideal representation for a loose collection of independent variables, since it is just a loose collection of variables.
In your particular example, however, it appears that the two fields of your struct are probably not supposed to be independent. There are three ways your struct could sensibly be designed:
You could have the only public field be the string, and then have a read-only "helper" property called length
which would report its length if the string is non-null, or return zero if the string is null.
You could have the struct not expose any public fields, property setters, or mutating methods, and have the contents of the only field--a private string--be specified in the object's constructor. As above, length
would be a property that would report the length of the stored string.
You could have the struct not expose any public fields, property setters, or mutating methods, and have two private fields: one for the string and one for the length, both of which would be set in a constructor that takes a string, stores it, measures its length, and stores that. Determining the length of a string is sufficiently fast that it probably wouldn't be worthwhile to compute and cache it, but it might be useful to have a structure that combined a string and its GetHashCode
value.
It's important to be aware of a detail with regard to the third design, however: if non-threadsafe code causes one instance of the structure to be read while another thread is writing to it, that may cause the accidental creation of a struct instance whose field values are inconsistent. The resulting behaviors may be a little different from those that occur when classes are used in non-threadsafe fashion. Any code having anything to do with security must be careful not to assume that structure fields will be in a consistent state, since malicious code--even in a "full trust" enviroment--can easily generate structs whose state is inconsistent if that's what it wants to do.
PS -- If you wish to allow your structure to be initialized using an assignment from a string, I would suggest using an implicit conversion operator and making Length
be a read-only property that returns the length of the underlying string if non-null, or zero if the string is null.
I know this is a really old question, but in case someone is looking for the newer way to do this, use the spring util namespace:
<util:constant static-field="my.pkg.types.MyEnumType.TYPE1" />
As described in the spring documentation.
This if an Info message that could pop in your LogCat on many situations.
In my case, it happened when I was inflating several views from XML layout files programmatically. The message is harmless by itself, but could be the sign of a later problem that would use all the RAM your App is allowed to use and cause the mega-evil Force Close to happen. I have grown to be the kind of Developer that likes to see his Log WARN/INFO/ERROR Free. ;)
So, this is my own experience:
I got the message:
10-09 01:25:08.373: I/Choreographer(11134): Skipped XXX frames! The application may be doing too much work on its main thread.
... when I was creating my own custom "super-complex multi-section list" by inflating a view from XML and populating its fields (images, text, etc...) with the data coming from the response of a REST/JSON web service (without paging capabilities) this views would act as rows, sub-section headers and section headers by adding all of them in the correct order to a LinearLayout (with vertical orientation inside a ScrollView). All of that to simulate a listView with clickable elements... but well, that's for another question.
As a responsible Developer you want to make the App really efficient with the system resources, so the best practice for lists (when your lists are not so complex) is to use a ListActivity or ListFragment with a Loader and fill the ListView with an Adapter, this is supposedly more efficient, in fact it is and you should do it all the time, again... if your list is not so complex.
Solution: I implemented paging on my REST/JSON web service to prevent "big response sizes" and I wrapped the code that added the "rows", "section headers" and "sub-section headers" views on an AsyncTask to keep the Main Thread cool.
So... I hope my experience helps someone else that is cracking their heads open with this Info message.
Happy hacking!
UPDATE table_name
SET column_name=CASE
WHEN column_name in ('value1', 'value2',.....)
THEN 'update_value'
WHEN column_name in ('value1', 'value2',.....)
THEN 'update_value'
END
table_name
= The name of table on which you want to perform operation.
column_name
= The name of Column/Field of which value you want to set.
update_value
= The value you want to set of column_name
alert("I will get back to you soon\nThanks and Regards\nSaurav Kumar");
or %0D%0A in a url
Also worth noting that WinFlexBison has been packaged for the Chocolatey package manager. Install that and then go:
choco install winflexbison
...which at the time of writing contains Bison 2.7 & Flex 2.6.3.
There is also winflexbison3
which (at the time of writing) has Bison 3.0.4 & Flex 2.6.3.
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.
#include <stdio.h>
void func(int row, int col, int* matrix){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
}
printf("\n");
}
}
int main(){
int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
func(2, 3, matrix[0]);
return 0;
}
Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.
Other type of format :
$headers[] = 'Accept: application/json';
$headers[] = 'Content-Type: application/json';
$headers[] = 'Content-length: 0';
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);
You can do it by listening to phone call events . You do it by having a BroadcastReceiver to PHONE_STATE and to NEW_OUTGOING_CALL. You find there what is the phone number.
Then when you decide to end the call, this is a bit tricky, because only from Android P it's guaranteed to work. Check here.
This may be what you are looking for:
for ($i=1; $i -le $ActiveCampaigns; $i++)
{
$PQCampaign = Get-Variable -Name "PQCampaign$i" -ValueOnly
$PQCampaignPath = Get-Variable -Name "PQCampaignPath$i" -ValueOnly
# Do stuff with $PQCampaign and $PQCampaignPath
}
$_SERVER['QUERY_STRING']
contains the data that you are looking for.
DOCUMENTATION
In case someone wanted an example using variables...
#!/bin/bash
# Only continue for 'develop' or 'release/*' branches
BRANCH_REGEX="^(develop$|release//*)"
if [[ $BRANCH =~ $BRANCH_REGEX ]];
then
echo "BRANCH '$BRANCH' matches BRANCH_REGEX '$BRANCH_REGEX'"
else
echo "BRANCH '$BRANCH' DOES NOT MATCH BRANCH_REGEX '$BRANCH_REGEX'"
fi
Below code will fix root = tk.Tk()
to its size before it was called:
root.resizable(False, False)
For Windows 10 x64
and Python
:
Open a Visual Studio x64 command prompt, and use dumpbin:
dumpbin /dependents [Python Module DLL or PYD file]
If you do not have Visual Studio installed, it is possible to download dumpbin elsewhere, or use another utility such as Dependency Walker.
Note that all other answers (to date) are simply random stabs in the dark, whereas this method is closer to a sniper rifle with night vision.
I switched on Address Sanitizer for a Python module that I wrote using C++ using MSVC and CMake.
It was giving this error: ImportError: DLL load failed: The specified module could not be found
Opened a Visual Studio x64 command prompt.
Under Windows, a .pyd
file is a .dll
file in disguise, so we want to run dumpbin on this file.
cd MyLibrary\build\lib.win-amd64-3.7\Debug
dumpbin /dependents MyLibrary.cp37-win_amd64.pyd
which prints this:
Microsoft (R) COFF/PE Dumper Version 14.27.29112.0
Copyright (C) Microsoft Corporation. All rights reserved.
Dump of file MyLibrary.cp37-win_amd64.pyd
File Type: DLL
Image has the following dependencies:
clang_rt.asan_dbg_dynamic-x86_64.dll
gtestd.dll
tbb_debug.dll
python37.dll
KERNEL32.dll
MSVCP140D.dll
VCOMP140D.DLL
VCRUNTIME140D.dll
VCRUNTIME140_1D.dll
ucrtbased.dll
Summary
1000 .00cfg
D6000 .data
7000 .idata
46000 .pdata
341000 .rdata
23000 .reloc
1000 .rsrc
856000 .text
Searched for clang_rt.asan_dbg_dynamic-x86_64.dll
, copied it into the same directory, problem solved.
Alternatively, could update the environment variable PATH to point to the directory with the missing .dll.
Please feel free to add your own case studies here! I've made it a community wiki answer.
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
There is no standardized way to do that. For windows the functionality is provided in the DbgHelp library
Alternatively,
1) Without touching System.Reflection
namespace,
GETNAME(new { myInput });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return myInput.ToString().TrimStart('{').TrimEnd('}').Split('=')[0].Trim();
}
2) The below one can be faster though (from my tests)
GETNAME(new { variable });
public static string GETNAME<T>(T myInput) where T : class
{
if (myInput == null)
return string.Empty;
return typeof(T).GetProperties()[0].Name;
}
You can also extend this for properties of objects (may be with extension methods):
new { myClass.MyProperty1 }.GETNAME();
You can cache property values to improve performance further as property names don't change during runtime.
The Expression approach is going to be slower for my taste. To get parameter name and value together in one go see this answer of mine
You can use an alert dialog
AlertDialog.Builder b = new Builder(this);
b.setTitle("Example");
String[] types = {"By Zip", "By Category"};
b.setItems(types, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
switch(which){
case 0:
onZipRequested();
break;
case 1:
onCategoryRequested();
break;
}
}
});
b.show();
This will close the dialog when one of them is pressed like you are wanting. Hope this helps!
I'm using THUNDERBIRD as MUA and I have same issues. I solved adding the IP address of my home PC on mynetworks parameter on main.cf
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128 MyIpAddress
P.S. I don't have a static ip for my home PC so when my ISP change it I ave to adjust every time.
I faced the same issue. I updated my Android studio and used API 25 target as Android 7.1.1 and X86 and everything worked fine. I use Google play services and firebase for my project
From ios 10.0 we need set { self.orientations = newValue }
for setting up the orientation, Make sure landscape property is enabled in your project.
private var orientations = UIInterfaceOrientationMask.landscapeLeft
override var supportedInterfaceOrientations : UIInterfaceOrientationMask {
get { return self.orientations }
set { self.orientations = newValue }
}
&&
means "and if successful"; by placing your if
statement on the right-hand side of it, you ensure that it will only run if grep
returns 0
. To fix it, use ;
instead:
ps aux | grep some_proces[s] > /tmp/test.txt ; if [ $? -eq 0 ]; then echo 1; else echo 0; fi
(or just use a line-break).
Function GetSearchArray(strSearch)
Dim strResults As String
Dim SHT As Worksheet
Dim rFND As Range
Dim sFirstAddress
For Each SHT In ThisWorkbook.Worksheets
Set rFND = Nothing
With SHT.UsedRange
Set rFND = .Cells.Find(What:=strSearch, LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlRows, SearchDirection:=xlNext, MatchCase:=False)
If Not rFND Is Nothing Then
sFirstAddress = rFND.Address
Do
If strResults = vbNullString Then
strResults = "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
Else
strResults = strResults & "|" & "Worksheet(" & SHT.Index & ").Range(" & Chr(34) & rFND.Address & Chr(34) & ")"
End If
Set rFND = .FindNext(rFND)
Loop While Not rFND Is Nothing And rFND.Address <> sFirstAddress
End If
End With
Next
If strResults = vbNullString Then
GetSearchArray = Null
ElseIf InStr(1, strResults, "|", 1) = 0 Then
GetSearchArray = Array(strResults)
Else
GetSearchArray = Split(strResults, "|")
End If
End Function
Sub test2()
For Each X In GetSearchArray("1")
Debug.Print X
Next
End Sub
Careful when doing a Find Loop that you don't get yourself into an infinite loop... Reference the first found cell address and compare after each "FindNext" statement to make sure it hasn't returned back to the first initially found cell.
In my case clicking the checkbox for 'import project into workspace' fixed the error, even though the project was already in the workspace folder and didn't actually get moved their by eclipse.
Look, the sed script that prints the 100 last lines you can find in the documentation for sed (https://www.gnu.org/software/sed/manual/sed.html#tail):
$ cat sed.cmd
1! {; H; g; }
1,100 !s/[^\n]*\n//
$p
$ sed -nf sed.cmd logfilename
For me it is way more difficult than your script so
tail -n 100 logfilename
is much much simpler. And it is quite efficient, it will not read all file if it is not necessary. See my answer with strace report for tail ./huge-file
: https://unix.stackexchange.com/questions/102905/does-tail-read-the-whole-file/102910#102910
You have two options.
Make the menu bar temporarily visible.
Make the menu bar permanently visible.
Steps:
str
is text representation in bytes, unicode
is text representation in characters.
You decode text from bytes to unicode and encode a unicode into bytes with some encoding.
That is:
>>> 'abc'.decode('utf-8') # str to unicode
u'abc'
>>> u'abc'.encode('utf-8') # unicode to str
'abc'
UPD Sep 2020: The answer was written when Python 2 was mostly used. In Python 3, str
was renamed to bytes
, and unicode
was renamed to str
.
>>> b'abc'.decode('utf-8') # bytes to str
'abc'
>>> 'abc'.encode('utf-8'). # str to bytes
b'abc'
Here are the outputs of isset()
and empty()
for the 4 possibilities: undeclared, null, false and true.
$a=null;
$b=false;
$c=true;
var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared
//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) }
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) }
You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset
and false when tested by 'empty'.
So use isset()
when you're concerned about the existence of a variable. And use empty
when you're testing for true or false. If the actual type of emptiness matters, use is_null
and ===0
, ===false
, ===''
.
How about the latest version of jQuery Fileuploader: http://pixelcone.com/fileuploader/
Its a powerful file upload plugin, very easy to setup compared to other plugin, and its now support html5 api.
This can be a nice way to do it that does not involve long constructors
class Person {
firstName?: string = 'Bob';
lastName?: string = 'Smith';
// Pass in this class as the required params
constructor(params: Person) {
// object.assign will overwrite defaults if params exist
Object.assign(this, params)
}
}
// you can still use the typing
function sayName(params: Person){
let name = params.firstName + params.lastName
alert(name)
}
// you do have to call new but for my use case this felt better
sayName(new Person({firstName: 'Gordon'}))
sayName(new Person({lastName: 'Thomas'}))
I think this is very nice and short
<img src="imagenotfound.gif" alt="Image not found" onerror="this.src='imagefound.gif';" />
But, be careful. The user's browser will be stuck in an endless loop if the onerror image itself generates an error.
EDIT
To avoid endless loop, remove the onerror
from it at once.
<img src="imagenotfound.gif" alt="Image not found" onerror="this.onerror=null;this.src='imagefound.gif';" />
By calling this.onerror=null
it will remove the onerror then try to get the alternate image.
NEW I would like to add a jQuery way, if this can help anyone.
<script>
$(document).ready(function()
{
$(".backup_picture").on("error", function(){
$(this).attr('src', './images/nopicture.png');
});
});
</script>
<img class='backup_picture' src='./images/nonexistent_image_file.png' />
You simply need to add class='backup_picture' to any img tag that you want a backup picture to load if it tries to show a bad image.
You can do this
[self performSelector:@selector(MethodToExecute) withObject:nil afterDelay:1.0 ];
$().ready(function(){_x000D_
_x000D_
$('div.alert').delay(1500);_x000D_
$('div.alert').hide(1000);_x000D_
});
_x000D_
div.alert{_x000D_
color: green;_x000D_
background-color: rgb(50,200,50, .5);_x000D_
padding: 10px;_x000D_
text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="alert"><p>Inserted Successfully . . .</p></div>
_x000D_
For just elements this can be used to find the index of an element amongst it's sibling elements:
function getElIndex(el) {
for (var i = 0; el = el.previousElementSibling; i++);
return i;
}
Note that previousElementSibling
isn't supported in IE<9.
Wouldn't it be easier to test the cube roots? Start with 20 (20**3 = 8000) and go up to 30 (30**3 = 27000). Then you have to test fewer than 10 integers.
for i in range(20, 30):
print("Trying {0}".format(i))
if i ** 3 > 12000:
print("Maximum integral cube root less than 12000: {0}".format(i - 1))
break
I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i)
but to return x[length(x) - i + 1]
and not the whole tail.
Following commentaries I benchmarked two solutions:
accessRevTail <- function(x, n) {
tail(x,n)[1]
}
accessRevLen <- function(x, n) {
x[length(x) - n + 1]
}
microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
expr min lq mean median uq max neval
accessRevLen(1:100, 87) 1.860 2.3775 2.84976 2.803 3.2740 6.755 100
accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833 100
So it appears in this case that even for small vectors, tail
is very slow comparing to direct access
The file you give is a shell script, not an awk program. So, try sh my.awk
.
If you want to use awk -f my.awk life.csv > life_out.cs
, then remove awk -F , '
and the last line from the file and add FS=","
in BEGIN
.
Uh you guys...
C:\>findstr /n . c:\boot.ini | findstr ^1:
1:[boot loader]
C:\>findstr /n . c:\boot.ini | findstr ^3:
3:default=multi(0)disk(0)rdisk(0)partition(1)\WINNT
C:\>
In python, integers and strings are immutable and are passed by value. You cannot pass a string, or integer, to a function and expect the argument to be modified.
So to convert string limit="100"
to a number, you need to do
limit = int(limit) # will return new object (integer) and assign to "limit"
If you really want to go around it, you can use a list. Lists are mutable in python; when you pass a list, you pass it's reference, not copy. So you could do:
def int_in_place(mutable):
mutable[0] = int(mutable[0])
mutable = ["1000"]
int_in_place(mutable)
# now mutable is a list with a single integer
But you should not need it really. (maybe sometimes when you work with recursions and need to pass some mutable state).
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
or (e.g. with sqlite3 from the Python standard library):
cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))
or others yet (after VALUES
you could have (:1, :2, :3)
, or "named styles" (:fee, :fie, :fo)
or (%(fee)s, %(fie)s, %(fo)s)
where you pass a dict instead of a map as the second argument to execute
). Check the paramstyle
string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!
Check your server config file /etc/mysql/my.cnf
- verify bind_address
is not set to 127.0.0.1
. Set it to 0.0.0.0
or comment it out then restart server with:
sudo service mysql restart
For nodemon users: Just use the --ignore flag to solve the problem.
Example:
nodemon app.js --ignore node_modules/ --ignore data/
Upgrade pip as follows:
curl https://bootstrap.pypa.io/get-pip.py | python
Note: You may need to use sudo python
above if not in a virtual environment.
Python.org sites are stopping support for TLS versions 1.0 and 1.1. This means that Mac OS X version 10.12 (Sierra) or older will not be able to use pip unless they upgrade pip as above.
(Note that upgrading pip via pip install --upgrade pip
will also not upgrade it correctly. It is a chicken-and-egg issue)
This thread explains it (thanks to this Twitter post):
Mac users who use pip and PyPI:
If you are running macOS/OS X version 10.12 or older, then you ought to upgrade to the latest pip (9.0.3) to connect to the Python Package Index securely:
curl https://bootstrap.pypa.io/get-pip.py | python
and we recommend you do that by April 8th.
Pip 9.0.3 supports TLSv1.2 when running under system Python on macOS < 10.13. Official release notes: https://pip.pypa.io/en/stable/news/
Also, the Python status page:
Completed - The rolling brownouts are finished, and TLSv1.0 and TLSv1.1 have been disabled. Apr 11, 15:37 UTC
Update - The rolling brownouts have been upgraded to a blackout, TLSv1.0 and TLSv1.1 will be rejected with a HTTP 403 at all times. Apr 8, 15:49 UTC
Lastly, to avoid other install errors, make sure you also upgrade setuptools after doing the above:
pip install --upgrade setuptools
If the content is a variable, it will be necessary to concatenate it with quotation marks. It worked for me. Like this:
itemSelected(id: number){ console.log('label contains', document.querySelector("label[for='" + id + "']")); }
yum install glibc.i686
install this.
Had a hard time finding the logs because the IDE was crashing on launch, if you are on Mac and use Android Studio 4.1 then the logs location may be found at /Users/{user}/Library/Logs/Google/AndroidStudio4.1/
And to be specific for me it is on macOS Big Sur
The easiest thing to do is to set the content type of your ajax request to "application/json; charset=utf-8"
and then let your API method consume JSON. Like this:
var basicInfo = JSON.stringify({
firstName: playerProfile.firstName(),
lastName: playerProfile.lastName(),
gender: playerProfile.gender(),
address: playerProfile.address(),
country: playerProfile.country(),
bio: playerProfile.bio()
});
$.ajax({
url: "http://localhost:8080/social/profile/update",
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: basicInfo,
success: function(data) {
// ...
}
});
@RequestMapping(
value = "/profile/update",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE,
consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<ResponseModel> UpdateUserProfile(
@RequestBody User usersNewDetails,
HttpServletRequest request,
HttpServletResponse response
) {
// ...
}
I guess the problem is that Spring Boot has issues submitting form data which is not JSON via ajax request.
Note: the default content type for ajax is "application/x-www-form-urlencoded"
.
ld
is trying to find libcrypto.so
which is not present as seen in your locate
output.
You can make a copy of the libcrypto.so.0.9.8
and name it as libcrypto.so
. Put this is your ld path. ( If you do not have root access then you can put it in a local path and specify the path manually )
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
This seems weird, but you can try setting vertical-align: top
in the CSS
for the inputs. That fixes it in IE8, at least.
ARIA stands for Accessible Rich Internet Applications.
WAI-ARIA is an incredibly powerful technology that allows developers to easily describe the purpose, state and other functionality of visually rich user interfaces - in a way that can be understood by Assistive Technology. WAI-ARIA has finally been integrated into the current working draft of the HTML 5 specification.
And if you are wondering what WAI-ARIA is, its the same thing.
Please note the terms WAI-ARIA and ARIA refer to the same thing. However, it is more correct to use WAI-ARIA to acknowledge its origins in WAI.
WAI = Web Accessibility Initiative
From the looks of it, ARIA is used for assistive technologies and mostly screen reading.
Most of your doubts will be cleared if you read this article
Since WP 2.6.0 you can use plugins_url()
method.
The first things popping up
EXTRACT(EPOCH FROM current_timestamp-somedate)/3600
May not be pretty, but unblocks the road. Could be prettier if division of interval by interval was defined.
Edit: if you want it greater than zero either use abs or greatest(...,0). Whichever suits your intention.
Edit++: the reason why I didn't use age
is that age
with a single argument, to quote the documentation: Subtract from current_date (at midnight). Meaning you don't get an accurate "age" unless running at midnight. Right now it's almost 1am here:
select age(current_timestamp);
age
------------------
-00:52:40.826309
(1 row)
Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example
Another way -
Add these lines to your application config file configuration section:
<system.net>
<settings>
<servicePointManager expect100Continue="false" />
</settings>
</system.net>
Try this,
body.modal-open {
overflow: hidden;
position:fixed;
width: 100%;
}
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
You'll have to pop everything off the first stack to get the bottom element. Then put them all back onto the second stack for every "dequeue" operation.
The above solutions suggesting the use of regex aren't ideal because this is such a small task and regex requires more resource overhead than the simplicity of the task justifies.
Here's what I do:
myString = myString.replace(' ', '').replace('\t', '').replace('\n', '')
or if you had a bunch of things to remove such that a single line solution would be gratuitously long:
removal_list = [' ', '\t', '\n']
for s in removal_list:
myString = myString.replace(s, '')
I guess you looking for CURDATE()
or NOW()
.
SELECT name, datum
FROM tasks
WHERE datum >= CURDATE()
LooK the rsult of NOW and CURDATE
NOW() CURDATE()
2008-11-11 12:45:34 2008-11-11
android:drawablePadding
will only create a padding gap between the text and the drawable if the button is small enough to squish the 2 together. If your button is wider than the combined width (for drawableLeft/drawableRight) or height (for drawableTop/drawableBottom) then drawablePadding doesn't do anything.
I'm struggling with this right now as well. My buttons are quite wide, and the icon is hanging on the left edge of the button and the text is centered in the middle. My only way to get around this for now has been to bake in a margin on the drawable by adding blank pixels to the left edge of the canvas with photoshop. Not ideal, and not really recommended either. But thats my stop-gap solution for now, short of rebuilding TextView/Button.
You can also simply add the font tag inside the p tag.
CSS sheet:
<style type="text/css">
p { font:15px Arial; color:white; }
</style>
and in HTML page:
<p> Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua.
<font color="red">
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
</font>
Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>
It works for me. But, in case you need modification, see w3schools for more usage :)
Long.valueOf(String s) - obviously due care must be taken to protect against non-numbers if that is possible in your code.
Synchronized keyword in Java has to do with thread-safety, that is, when multiple threads read or write the same variable.
This can happen directly (by accessing the same variable) or indirectly (by using a class that uses another class that accesses the same variable).
The synchronized keyword is used to define a block of code where multiple threads can access the same variable in a safe way.
Syntax-wise the synchronized
keyword takes an Object
as it's parameter (called a lock object), which is then followed by a { block of code }
.
When execution encounters this keyword, the current thread tries to "lock/acquire/own" (take your pick) the lock object and execute the associated block of code after the lock has been acquired.
Any writes to variables inside the synchronized code block are guaranteed to be visible to every other thread that similarly executes code inside a synchronized code block using the same lock object.
Only one thread at a time can hold the lock, during which time all other threads trying to acquire the same lock object will wait (pause their execution). The lock will be released when execution exits the synchronized code block.
Adding synchronized
keyword to a method definition is equal to the entire method body being wrapped in a synchronized code block with the lock object being this
(for instance methods) and ClassInQuestion.getClass()
(for class methods).
- Instance method is a method which does not have static
keyword.
- Class method is a method which has static
keyword.
Without synchronization, it is not guaranteed in which order the reads and writes happen, possibly leaving the variable with garbage.
(For example a variable could end up with half of the bits written by one thread and half of the bits written by another thread, leaving the variable in a state that neither of the threads tried to write, but a combined mess of both.)
It is not enough to complete a write operation in a thread before (wall-clock time) another thread reads it, because hardware could have cached the value of the variable, and the reading thread would see the cached value instead of what was written to it.
Thus in Java's case, you have to follow the Java Memory Model to ensure that threading errors do not happen.
In other words: Use synchronization, atomic operations or classes that use them for you under the hoods.
Sources
http://docs.oracle.com/javase/specs/jls/se8/html/index.html
Java® Language Specification, 2015-02-13
There are a couple of ways to address your problem, however this is probably the most straightforward:
Your main
method is static, so it does not have access to instance members (isLeapYear
field and isLeapYear
method. One approach to rectify this is to make both the field and the method static as well:
static boolean isLeapYear;
/* (snip) */
public static boolean isLeapYear(int year)
{
/* (snip) */
}
Lastly, you're not actually calling your isLeapYear
method (which is why you're not seeing any results). Add this line after int year = kboard.nextInt();
:
isLeapYear(year);
That should be a start. There are some other best practices you could follow but for now just focus on getting your code to work; you can refactor later.
I would just like to share the recent predicament I encounter with the RecyclerView. I hope that anyone experiencing the same problem will benefit.
My Project Requirement: So I have a RecyclerView that list some clickable items in my Main Activity (Activity-A). When the Item is clicked a new Activity is shown with the Item Details (Activity-B).
I implemented in the Manifest file the that the Activity-A is the parent of Activity-B, that way, I have a back or home button on the ActionBar of the Activity-B
Problem: Every time I pressed the Back or Home button in the Activity-B ActionBar, the Activity-A goes into the full Activity Life Cycle starting from onCreate()
Even though I implemented an onSaveInstanceState() saving the List of the RecyclerView's Adapter, when Activity-A starts it's lifecycle, the saveInstanceState is always null in the onCreate() method.
Further digging in the internet, I came across the same problem but the person noticed that the Back or Home button below the Anroid device (Default Back/Home button), the Activity-A does not goes into the Activity Life-Cycle.
Solution:
I enabled the home or back button on Activity-B
Under onCreate() method add this line supportActionBar?.setDisplayHomeAsUpEnabled(true)
In the overide fun onOptionsItemSelected() method, I checked for the item.ItemId on which item is clicked based on the id. The Id for the back button is
android.R.id.home
Then implement a finish() function call inside the android.R.id.home
This will end the Activity-B and bring Acitivy-A without going through the entire life-cycle.
For my requirement this is the best solution so far.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_project)
supportActionBar?.title = projectName
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId){
android.R.id.home -> {
finish()
}
}
return super.onOptionsItemSelected(item)
}
std::less<>
when using custom classes with operator<
If you are dealing with a set of your custom class that has operator<
defined, then you can just use std::less<>
.
As mentioned at http://en.cppreference.com/w/cpp/container/set/find C++14 has added two new find
APIs:
template< class K > iterator find( const K& x );
template< class K > const_iterator find( const K& x ) const;
which allow you to do:
main.cpp
#include <cassert>
#include <set>
class Point {
public:
// Note that there is _no_ conversion constructor,
// everything is done at the template level without
// intermediate object creation.
//Point(int x) : x(x) {}
Point(int x, int y) : x(x), y(y) {}
int x;
int y;
};
bool operator<(const Point& c, int x) { return c.x < x; }
bool operator<(int x, const Point& c) { return x < c.x; }
bool operator<(const Point& c, const Point& d) {
return c.x < d;
}
int main() {
std::set<Point, std::less<>> s;
s.insert(Point(1, -1));
s.insert(Point(2, -2));
s.insert(Point(0, 0));
s.insert(Point(3, -3));
assert(s.find(0)->y == 0);
assert(s.find(1)->y == -1);
assert(s.find(2)->y == -2);
assert(s.find(3)->y == -3);
// Ignore 1234, find 1.
assert(s.find(Point(1, 1234))->y == -1);
}
Compile and run:
g++ -std=c++14 -Wall -Wextra -pedantic -o main.out main.cpp
./main.out
More info about std::less<>
can be found at: What are transparent comparators?
Tested on Ubuntu 16.10, g++
6.2.0.
Your syntax is incorrect. The var
keyword in your for
loop must be followed by a variable name, in this case its propName
var propValue;
for(var propName in nyc) {
propValue = nyc[propName]
console.log(propName,propValue);
}
I suggest you have a look here for some basics:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
Here is another approach, up to the OP to choose which one he prefers.
When including the code below in the __init__
.py file before any other code, messages printed with print
and any errors will no longer be logged to Ableton's Log.txt but to separate files on your disk:
import sys
path = "/Users/#username#"
errorLog = open(path + "/stderr.txt", "w", 1)
errorLog.write("---Starting Error Log---\n")
sys.stderr = errorLog
stdoutLog = open(path + "/stdout.txt", "w", 1)
stdoutLog.write("---Starting Standard Out Log---\n")
sys.stdout = stdoutLog
(for Mac, change #username#
to the name of your user folder. On Windows the path to your user folder will have a different format)
When you open the files in a text editor that refreshes its content when the file on disk is changed (example for Mac: TextEdit does not but TextWrangler does), you will see the logs being updated in real-time.
Credits: this code was copied mostly from the liveAPI control surface scripts by Nathan Ramella
This is a classic case of rebase --onto
:
# let's go to current master (X, where quickfix2 should begin)
git checkout master
# replay every commit *after* quickfix1 up to quickfix2 HEAD.
git rebase --onto master quickfix1 quickfix2
So you should go from
o-o-X (master HEAD)
\
q1a--q1b (quickfix1 HEAD)
\
q2a--q2b (quickfix2 HEAD)
to:
q2a'--q2b' (new quickfix2 HEAD)
/
o-o-X (master HEAD)
\
q1a--q1b (quickfix1 HEAD)
This is best done on a clean working tree.
See git config --global rebase.autostash true
, especially after Git 2.10.
If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.
Also a empty check using
listName.size() != 0
Is discouraged because all collection implementations have the
listName.isEmpty()
function that does exactly the same.
So all in all, if you have the Apache common utils in your classpath anyway, use
if (CollectionUtils.isNotEmpty(listName))
in any other case use
if(listName != null && listName.isEmpty())
You will not notice any performance difference. Both lines do exactly the same.
Here is simple way to access parent id
document.getElementById("child1").parentNode;
will do the magic for you to access the parent div.
<html>
<head>
</head>
<body id="body">
<script>
function alertAncestorsUntilID() {
var a = document.getElementById("child").parentNode;
alert(a.id);
}
</script>
<div id="master">
Master
<div id="child">Child</div>
</div>
<script>
alertAncestorsUntilID();
</script>
</body>
</html>
var top = window?.rootViewController
while ((top?.presentedViewController) != nil) {
top = top?.presentedViewController
}
if !(type(of: top!) === CallingVC.self) {
top?.performSegue(withIdentifier: "CallingVC", sender: call)
}
"apstring"
is not standard C++, in C++, you'd want to #include
the <string>
header.
Example:
\Large\begin{verbatim}
<how to set font size here to 10 px ? />
\end{verbatim}
\normalsize
\Large
can be obviously substituted by one of:
\tiny
\scriptsize
\footnotesize
\small
\normalsize
\large
\Large
\LARGE
\huge
\Huge
If you need arbitrary font sizes:
You can try also:
echo -n > /my/file
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
// data for manipulation
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
},
},
},
Change key in Project > Build Setting "typecheck calls to printf/scanf : NO"
Explanation : [How it works]
Check calls to printf and scanf, etc., to make sure that the arguments supplied have types appropriate to the format string specified, and that the conversions specified in the format string make sense.
Hope it work
Other warning
objective c implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int
Change key "implicit conversion to 32Bits Type > Debug > *64 architecture : No"
[caution: It may void other warning of 64 Bits architecture conversion].
On Ubuntu:
sudo apt install chromium-chromedriver
On Debian:
sudo apt install chromium-driver
On macOS install https://brew.sh/ then do
brew cask install chromedriver
passing the xml content as string.
table1
ID int
XML CLOB
import oracle.jdbc.OraclePreparedStatement;
/*
Your Code
*/
void insert(int id, String xml){
try {
String sql = "INSERT INTO table1(ID,XML) VALUES ("
+ id
+ "', ? )";
PreparedStatement ps = conn.prepareStatement(sql);
((OraclePreparedStatement) ps).setStringForClob(1, xml);
ps.execute();
result = true;
} catch (Exception e) {
e.printStackTrace();
}
}
In vim
:%s/<option value='.\{1,}' >//
or
:%s/<option value='.\+' >//
In vim regular expressions you have to escape the one-or-more symbol, capturing parentheses, the bounded number curly braces and some others.
See :help /magic
to see which special characters need to be escaped (and how to change that).
My solution is based on the TechNet article Fun Things You Can Do With the Get-ChildItem Cmdlet.
Get-ChildItem C:\foo | Where-Object {$_.mode -match "d"}
I used it in my script, and it works well.
here is with one line
try (BufferedReader br = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream(
"F:/gawiki-20090614-stub-meta-history.xml.gz")))))
{br.readLine();}
You need to set with only C:\Program Files\Java\jdk1.8.0_12.
And check with using new cmd. It will be updated
"UPDATE TableName SET TableField = TableField + 1 WHERE SomeFilterField = @ParameterID"
string s = "ABCDEFG";
string t = "st";
s = s.Remove(4, t.Length);
s = s.Insert(4, t);
Sorry, this might be a bit late. But I think I found a better implementation on the go docs.
buf := new(bytes.Buffer)
var num uint16 = 1234
err := binary.Write(buf, binary.LittleEndian, num)
if err != nil {
fmt.Println("binary.Write failed:", err)
}
fmt.Printf("% x", buf.Bytes())
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
I was facing following error with code (nodejs 0.10.13), provided by ampersand:
origin is not allowed by access-control-allow-origin
Issue was resolved changing
response.writeHead(200, {"Content-Type": "text/plain"});
to
response.writeHead(200, {
'Content-Type': 'text/html',
'Access-Control-Allow-Origin' : '*'});
On your solution explorer window, right click to References, select Add Reference, go to .NET tab, find and add Microsoft.CSharp.
Alternatively add the Microsoft.CSharp NuGet package.
Install-Package Microsoft.CSharp
This will tell if you're connected to a network:
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
connected = true;
}
else
connected = false;
Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected
will still be true.
You will need this permission in your manifest:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
The solution consists in a regex pattern matching open and closing parenthesis
String str = "Your(String)";
// parameter inside split method is the pattern that matches opened and closed parenthesis,
// that means all characters inside "[ ]" escaping parenthesis with "\\" -> "[\\(\\)]"
String[] parts = str.split("[\\(\\)]");
for (String part : parts) {
// I print first "Your", in the second round trip "String"
System.out.println(part);
}
Writing in Java 8's style, this can be solved in this way:
Arrays.asList("Your(String)".split("[\\(\\)]"))
.forEach(System.out::println);
I hope it is clear.
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
You could subtract the current time stamp from 12 AM of the same day.
Using current timestamp:
moment().valueOf() - moment().startOf('day').valueOf()
Using arbitrary day:
moment(someDate).valueOf() - moment(someDate).startOf('day').valueOf()
Here is a good procedure for resetting any sequence to 0 from Oracle guru Tom Kyte. Great discussion on the pros and cons in the links below too.
[email protected]>
create or replace
procedure reset_seq( p_seq_name in varchar2 )
is
l_val number;
begin
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by -' || l_val ||
' minvalue 0';
execute immediate
'select ' || p_seq_name || '.nextval from dual' INTO l_val;
execute immediate
'alter sequence ' || p_seq_name || ' increment by 1 minvalue 0';
end;
/
From this page: Dynamic SQL to reset sequence value
Another good discussion is also here: How to reset sequences?
PS> $a = "-----start-------Hello World------end-------" PS> $a.substring(17, 11) or PS> $a.Substring($a.IndexOf('H'), 11)
$a.Substring(argument1, argument2)
--> Here argument1
= Starting position of the desired alphabet and argument2
= Length of the substring you want as output.
Here 17 is the index of the alphabet 'H'
and since we want to Print till Hello World, we provide 11 as the second argument
length = 4
string = "abcdefgh"
str_dict = [ o for o in string ]
parts = [ ''.join( str_dict[ (j * length) : ( ( j + 1 ) * length ) ] ) for j in xrange(len(string)/length )]
PHP has no explicit byte
type, but its string
is already the equivalent of Java's byte array. You can safely write fputs($connection, "The quick brown fox …")
. The only thing you must be aware of is character encoding, they must be the same on both sides. Use mb_convert_encoding() when in doubt.
For iOS7 and before you should indeed use enabledRemoteNotificationTypes
and check if it equals (or doesn't equal depending on what you want) to UIRemoteNotificationTypeNone
.
However for iOS8 it is not always enough to only check with isRegisteredForRemoteNotifications
as many state above. You should also check if application.currentUserNotificationSettings.types
equals (or doesn't equal depending on what you want) UIUserNotificationTypeNone
!
isRegisteredForRemoteNotifications
might return true even though currentUserNotificationSettings.types
returns UIUserNotificationTypeNone
.
JIT stands for Just-in-Time which means that code gets compiled when it is needed, not before runtime.
This is beneficial because the compiler can generate code that is optimised for your particular machine. A static compiler, like your average C compiler, will compile all of the code on to executable code on the developer's machine. Hence the compiler will perform optimisations based on some assumptions. It can compile more slowly and do more optimisations because it is not slowing execution of the program for the user.
Make sure that mWakeLock
isn't accidentally cleaned up before you're ready to release it. If it's finalized, the lock is released. This can happen, for example, if you set it to null and the garbage collector subsequently runs. It can also happen if you accidentally set a local variable of the same name instead of the method-level variable.
I'd also recommend checking LogCat for entries that have the PowerManagerService tag or the tag that you pass to newWakeLock
.
Try this:
$array = array_values($array);
Using array_values()
Your comment to cletus' (correct) answer implies that there are multiple Maven settings files involved.
Maven always uses either one or two settings files. The global settings defined in (${M2_HOME}/conf/settings.xml) is always required. The user settings file (defined in ${user.home}/.m2/settings.xml) is optional. Any settings defined in the user settings take precedence over the corresponding global settings.
You can override the location of the global and user settings from the command line, the following example will set the global settings to c:\global\settings.xml and the user settings to c:\user\settings.xml:
mvn install --settings c:\user\settings.xml
--global-settings c:\global\settings.xml
Currently there is no property or means to establish what user and global settings files were used from with Maven. To access these values, you would have to modify MavenCli and/or DefaultMavenSettingsBuilder to inject the file locations into the resolved Settings object.
Try
SELECT to_char(p1.PA_VALUE,'DD/MM/YYYY') as StartDate,
to_char(p2.PA_VALUE,'DD/MM/YYYY') as EndDate
...
You should watch this: Node Tuts episode 19 - Asynchronous Iteration Patterns
It should answers your questions.
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.
class a:
def func1(self):
a.var1 = "Stack "
class b:
def func2(self):
b.var2 = "Overflow"
class c(a,b):
def func3(self):
c.var3 = a.var1 + b.var2
print(c.var3)
a().func1()
b().func2()
c().func3()
This is a modification of nate_weldon's answer with a few improvements:
application.DisplayAlerts = false;
before attempting to save to hide promptsAlso note that the application.Workbooks.Open
and ws.SaveAs
methods expect sourceFilePath
and targetFilePath
to be full paths (ie. directory path + filename)
private static void SaveAs(string sourceFilePath, string targetFilePath)
{
Application application = null;
Workbook wb = null;
Worksheet ws = null;
try
{
application = new Application();
application.DisplayAlerts = false;
wb = application.Workbooks.Open(sourceFilePath);
ws = (Worksheet)wb.Sheets[1];
ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
}
catch (Exception e)
{
// Handle exception
}
finally
{
if (application != null) application.Quit();
if (ws != null) Marshal.ReleaseComObject(ws);
if (wb != null) Marshal.ReleaseComObject(wb);
if (application != null) Marshal.ReleaseComObject(application);
}
}
To add a foreign key (grade_id) to an existing table (users), follow the following steps:
ALTER TABLE users ADD grade_id SMALLINT UNSIGNED NOT NULL DEFAULT 0;
ALTER TABLE users ADD CONSTRAINT fk_grade_id FOREIGN KEY (grade_id) REFERENCES grades(id);
localStorage
is something that is kept on the client side. There is no data transmitted to the server side.
You can only get the data with JavaScript and you can send it to the server side with Ajax.
If you are only looking for a refresh rate for the GOOGLEFINANCE
function, keep in mind that data delays can be up to 20 minutes (per Google Finance Disclaimer).
GoogleClock
)Here is a modified version of the refresh action, taking the data delay into consideration, to save on unproductive refresh cycles.
=GoogleClock(GOOGLEFINANCE(symbol,"datadelay"))
For example, with:
then
=GoogleClock(GOOGLEFINANCE("GOOG","datadelay"))
Results in a dynamic data-based refresh rate of:
=GoogleClock(15)
GoogleClock
)If your sheet contains a number of rows of symbols, you could add a datadelay
column for each symbol and use the lowest value, for example:
=GoogleClock(MIN(dataDelayValuesNamedRange))
Where dataDelayValuesNamedRange
is the absolute reference or named reference of the range of cells that contain the data delay values for each symbol (assuming these values are different).
GoogleClock()
The GoogleClock()
function was removed in 2014 and replaced with settings setup for refreshing sheets. At present, I have confirmed that replacement settings is only on available in Sheets from when accessed from a desktop browser, not the mobile app (I'm using Google's mobile Sheets app updated 2016-03-14).
(This part of the answer is based on, and portions copied from, Google Docs Help)
To change how often "some" Google Sheets functions update:
NOTE External data functions recalculate at the following intervals:
The references in earlier sections to the display and use of the datadelay
attribute still apply, as well as the concepts for more efficient coding of sheets.
On a positive note, the new refresh option continues to be refreshed by Google servers regardless of whether you have the sheet loaded or not. That's a positive for shared sheets for sure; even more so for Google Apps Scripts (GAS), where GAS is used in workflow code or referenced data is used as a trigger for an event.
[*] in my understanding so far (I am currently testing this)
C# in .NET 3.5 using System.DirectoryServices.AccountManagement.
bool valid = false;
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
valid = context.ValidateCredentials( username, password );
}
This will validate against the current domain. Check out the parameterized PrincipalContext constructor for other options.
I don't think we had this class back when you asked the question, but today there is an easy answer.
What you want to do is use the DataFormatter class. You pass this a cell, and it does its best to return you a string containing what Excel would show you for that cell. If you pass it a string cell, you'll get the string back. If you pass it a numeric cell with formatting rules applied, it will format the number based on them and give you the string back.
For your case, I'd assume that the numeric cells have an integer formatting rule applied to them. If you ask DataFormatter to format those cells, it'll give you back a string with the integer string in it.
Also, note that lots of people suggest doing cell.setCellType(Cell.CELL_TYPE_STRING)
, but the Apache POI JavaDocs quite clearly state that you shouldn't do this! Doing the setCellType
call will loose formatting, as the javadocs explain the only way to convert to a String with formatting remaining is to use the DataFormatter class.
If you are using Atlassian SourceTree app, you could use the reset option in the context menu.
Just Keep pressing ESC
key. It will stop the VBA. This methods works when you get infinite MsgBox
s
My Scenario: I had to scroll down on page to open dialog on a button click, due to window scroll the dialog was not opening vertically center to window, it was going out of view-port.
As Ken has mentioned above , after you have set your modal content execute below statement.
$("selector").dialog('option', 'position', 'center');
If content is pre-loaded before modal opens just execute this in open event, else manipulate DOM in open event and then execute statement.
$( ".selector" ).dialog({
open: function( event, ui ) {
//Do DOM manipulation if needed before executing below statement
$(this).dialog('option', 'position', 'center');
}
});
It worked well for me and the best thing is that you don't include any other plugin or library for it to work.
You can use a converter or create new property in your ViewModel like that:
public bool CanDoIt
{
get
{
return !string.IsNullOrEmpty(SomeField);
}
}
and use it:
<DataTrigger Binding="{Binding SomeField}" Value="{Binding CanDoIt}">
I setup an ssh alias using a custom IdentityFile
and rewrote the origin to use my custom me-github
hostname.
#when prompted enter `id_rsa_user1` as filename
ssh-keygen -t rsa
# ~/.ssh/config
Host user1-github
HostName github.com
Port 22
User git
IdentityFile ~/.ssh/id_rsa_user1
#check original remote origin url
git remote -v
origin [email protected]:user1/my-repo.git
#change it to use your custom `user1-github` hostname
git remote rm origin
git remote add origin git@user1-github:user1/my-repo.git
I just had to do this myself, so I thought I would post another answer here.
Here is another way to create a rounded corner border and clip its inner content. This is the straightforward way by using the Clip property. It's nice if you want to avoid a VisualBrush.
The xaml:
<Border
Width="200"
Height="25"
CornerRadius="11"
Background="#FF919194"
>
<Border.Clip>
<RectangleGeometry
RadiusX="{Binding CornerRadius.TopLeft, RelativeSource={RelativeSource AncestorType={x:Type Border}}}"
RadiusY="{Binding RadiusX, RelativeSource={RelativeSource Self}}"
>
<RectangleGeometry.Rect>
<MultiBinding
Converter="{StaticResource widthAndHeightToRectConverter}"
>
<Binding
Path="ActualWidth"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
<Binding
Path="ActualHeight"
RelativeSource="{RelativeSource AncestorType={x:Type Border}}"
/>
</MultiBinding>
</RectangleGeometry.Rect>
</RectangleGeometry>
</Border.Clip>
<Rectangle
Width="100"
Height="100"
Fill="Blue"
HorizontalAlignment="Left"
VerticalAlignment="Center"
/>
</Border>
The code for the converter:
public class WidthAndHeightToRectConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)values[0];
double height = (double)values[1];
return new Rect(0, 0, width, height);
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}
One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).
As mentioned earlier, CASCADE will delete the record that has a foreign key and references another object that was deleted. So for example if you have a real estate website and have a Property that references a City
class City(models.Model):
# define model fields for a city
class Property(models.Model):
city = models.ForeignKey(City, on_delete = models.CASCADE)
# define model fields for a property
and now when the City is deleted from the database, all associated Properties (eg. real estate located in that city) will also be deleted from the database
Now I also want to mention the merit of other options, such as SET_NULL or SET_DEFAULT or even DO_NOTHING. Basically, from the administration perspective, you want to "delete" those records. But you don't really want them to disappear. For many reasons. Someone might have deleted it accidentally, or for auditing and monitoring. And plain reporting. So it can be a way to "disconnect" the property from a City. Again, it will depend on how your application is written.
For example, some applications have a field "deleted" which is 0 or 1. And all their searches and list views etc, anything that can appear in reports or anywhere the user can access it from the front end, exclude anything that is deleted == 1
. However, if you create a custom report or a custom query to pull down a list of records that were deleted and even more so to see when it was last modified (another field) and by whom (i.e. who deleted it and when)..that is very advantageous from the executive standpoint.
And don't forget that you can revert accidental deletions as simple as deleted = 0
for those records.
My point is, if there is a functionality, there is always a reason behind it. Not always a good reason. But a reason. And often a good one too.
You were in the correct folder if you got the ./mongod working! You now need to open another terminal, go to the same folder and type ./mongo the first terminal window serves as your server, the second is where you enter your commands!