just use mCheckedPosition
save status
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.checkBox.setChecked(position == mCheckedPostion);
holder.checkBox.setOnClickListener(v -> {
if (position == mCheckedPostion) {
holder.checkBox.setChecked(false);
mCheckedPostion = -1;
} else {
mCheckedPostion = position;
notifyDataSetChanged();
}
});
}
Tested and working. Check this
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
public class MyAndroidAppActivity extends Activity {
private RadioGroup radioGroup;
private RadioButton radioButton;
private Button btnDisplay;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
}
public void addListenerOnButton() {
radioGroup = (RadioGroup) findViewById(R.id.radio);
btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// get selected radio button from radioGroup
int selectedId = radioGroup.getCheckedRadioButtonId();
// find the radiobutton by returned id
radioButton = (RadioButton) findViewById(selectedId);
Toast.makeText(MyAndroidAppActivity.this,
radioButton.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
xml
<RadioGroup
android:id="@+id/radio"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<RadioButton
android:id="@+id/radioMale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_male"
android:checked="true" />
<RadioButton
android:id="@+id/radioFemale"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/radio_female" />
</RadioGroup>
Use in XML:
android:src="@drawable/image"
Source use:
imageView.setImageDrawable(ContextCompat.getDrawable(activity, R.drawable.your_image));
you may also go for a simple View.OnClickListener
:
satView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(((CompoundButton) view).isChecked()){
System.out.println("Checked");
} else {
System.out.println("Un-Checked");
}
}
});
That looks like it should stop the service when you uncheck the checkbox. Are there any exceptions in the log? stopService returns a boolean indicating whether or not it was able to stop the service.
If you are starting your service by Intents, then you may want to extend IntentService instead of Service. That class will stop the service on its own when it has no more work to do.
AutoService
class AutoService extends IntentService {
private static final String TAG = "AutoService";
private Timer timer;
private TimerTask task;
public onCreate() {
timer = new Timer();
timer = new TimerTask() {
public void run()
{
System.out.println("done");
}
}
}
protected void onHandleIntent(Intent i) {
Log.d(TAG, "onHandleIntent");
int delay = 5000; // delay for 5 sec.
int period = 5000; // repeat every sec.
timer.scheduleAtFixedRate(timerTask, delay, period);
}
public boolean stopService(Intent name) {
// TODO Auto-generated method stub
timer.cancel();
task.cancel();
return super.stopService(name);
}
}
Example fetch with authorization header:
fetch('URL_GOES_HERE', {
method: 'post',
headers: new Headers({
'Authorization': 'Basic '+btoa('username:password'),
'Content-Type': 'application/x-www-form-urlencoded'
}),
body: 'A=1&B=2'
});
Don't use functions from ato...
group. These are broken and virtually useless. A moderately better solution would be to use sscanf
, although it is not perfect either.
To convert string to integer, functions from strto...
group should be used. In your specific case it would be strtol
function.
Hit Ctrl+Alt+Del to open the Windows Task manager and switch to the processes tab.
32-bit programs should be marked with *32
.
WCHAR path[MAX_PATH] = {0};
GetModuleFileName(NULL, path, MAX_PATH);
PathRemoveFileSpec(path);
I'll assume you mean the URI:
class BankController < ActionController::Base
before_filter :pre_process
def index
# do something
end
private
def pre_process
logger.debug("The URL" + request.url)
end
end
As per your comment below, if you need the name of the controller, you can simply do this:
private
def pre_process
self.controller_name # Will return "order"
self.controller_class_name # Will return "OrderController"
end
the best way: $('#myTextBox').val('new value').trim();
Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.
As you know this is UK format issue. You can do date conversion indirectly by using function.
CREATE FUNCTION ChangeDateFormatFromUK
(
@DateColumn varchar(10)
)
RETURNS VARCHAR(10)
AS
BEGIN
DECLARE @Year varchar(4), @Month varchar(2), @Day varchar(2), @Result varchar(10)
SET @Year = (SELECT substring(@DateColumn,7,10))
SET @Month = (SELECT substring(@DateColumn,4,5))
SET @Day = (SELECT substring(@DateColumn,1,2))
SET @Result = @Year + '/' @Month + '/' + @Day
RETURN @Result
END
To call this function
SELECT dbo.ChangeDateFormatFromUK([dates]) from table
Convert it normally to datetime
SELECT CONVERT(DATETIME,dbo.ChangeDateFormatFromUK([dates])) from table
In your Case, you can do
SELECT [dates] from table where CONVERT(DATETIME,dbo.ChangeDateFormatFromUK([dates])) > GetDate() -- or any date
You can use something like following:
Matrix matrix = new Matrix();
matrix.setRotate(mRotation,source.getWidth()/2,source.getHeight()/2);
RectF rectF = new RectF(0, 0, source.getWidth(), source.getHeight());
matrix.mapRect(rectF);
Bitmap targetBitmap = Bitmap.createBitmap(rectF.width(), rectF.height(), config);
Canvas canvas = new Canvas(targetBitmap);
canvas.drawBitmap(source, matrix, new Paint());
Are you running on Linux? Perhaps the management agent is binding to localhost:
http://java.sun.com/j2se/1.5.0/docs/guide/management/faq.html#linux1
This works like a clock for me:
methods: {
hasHistory () { return window.history.length > 2 }
}
Then, in the template:
<button
type="button"
@click="hasHistory()
? $router.go(-1)
: $router.push('/')" class="my-5 btn btn-outline-success">«
Back
</button>
I'm surprised nobody suggest this simple approach to creating a list of empty lists. This is an old thread, but just adding this for completeness. This will create a list of 10 empty lists
x = [[] for i in range(10)]
I am a fan of
params[:one].present?
Just because it keeps the params[sym]
form so it's easier to read.
You can float your column divs using float: left; and give them widths.
And to make sure none of your other content gets messed up, you can wrap the floated divs within a parent div and give it some clear float styling.
Hope this helps.
Better use $_SERVER['REQUEST_METHOD']
:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// …
}
I got it work by overriding annotation with XML file for Postgres. Annotation is kept for Oracle. In my opinion, in this case it would be best we override the mapping of this trouble-some enity with xml mapping. We can override single / multiple entities with xml mapping. So we would use annotation for our mainly-supported database, and a xml file for each other database.
Note: we just need to override one single class , so it is not a big deal. Read more from my example Example to override annotation with XML
A ListIterator
allows you to add or remove items in the list. Suppose you have a list of Car
objects:
List<Car> cars = ArrayList<>();
// add cars here...
for (ListIterator<Car> carIterator = cars.listIterator(); carIterator.hasNext(); )
{
if (<some-condition>)
{
carIterator().remove()
}
else if (<some-other-condition>)
{
carIterator().add(aNewCar);
}
}
SWIFT 3: Don't know if this is what you're looking for. But I compare a string to a current timestamp to see if my string is older that now.
func checkTimeStamp(date: String!) -> Bool {
let dateFormatter: DateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
dateFormatter.locale = Locale(identifier:"en_US_POSIX")
let datecomponents = dateFormatter.date(from: date)
let now = Date()
if (datecomponents! >= now) {
return true
} else {
return false
}
}
To use it:
if (checkTimeStamp(date:"2016-11-21 12:00:00") == false) {
// Do something
}
export default
is used to create local registration for Vue component.
Here is a great article that explain more about components https://frontendsociety.com/why-you-shouldnt-use-vue-component-ff019fbcac2e
You may also change inheritance from ActionBarActivity to Activity as written here.
UPDATE
A good solution is here:
@Override
protected void onCreate(Bundle savedInstanceState) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
}
Yes, views can have a clustered index assigned and, when they do, they'll store temporary results that can speed up resulting queries.
Update: At least three people have voted me down on this one. With all due respect, I think that they are just wrong; Microsoft's own documentation makes it very clear that Views can improve performance.
First, simple views are expanded in place and so do not directly contribute to performance improvements - that much is true. However, indexed views can dramatically improve performance.
Let me go directly to the documentation:
After a unique clustered index is created on the view, the view's result set is materialized immediately and persisted in physical storage in the database, saving the overhead of performing this costly operation at execution time.
Second, these indexed views can work even when they are not directly referenced by another query as the optimizer will use them in place of a table reference when appropriate.
Again, the documentation:
The indexed view can be used in a query execution in two ways. The query can reference the indexed view directly, or, more importantly, the query optimizer can select the view if it determines that the view can be substituted for some or all of the query in the lowest-cost query plan. In the second case, the indexed view is used instead of the underlying tables and their ordinary indexes. The view does not need to be referenced in the query for the query optimizer to use it during query execution. This allows existing applications to benefit from the newly created indexed views without changing those applications.
This documentation, as well as charts demonstrating performance improvements, can be found here.
Update 2: the answer has been criticized on the basis that it is the "index" that provides the performance advantage, not the "View." However, this is easily refuted.
Let us say that we are a software company in a small country; I'll use Lithuania as an example. We sell software worldwide and keep our records in a SQL Server database. We're very successful and so, in a few years, we have 1,000,000+ records. However, we often need to report sales for tax purposes and we find that we've only sold 100 copies of our software in our home country. By creating an indexed view of just the Lithuanian records, we get to keep the records we need in an indexed cache as described in the MS documentation. When we run our reports for Lithuanian sales in 2008, our query will search through an index with a depth of just 7 (Log2(100) with some unused leaves). If we were to do the same without the VIEW and just relying on an index into the table, we'd have to traverse an index tree with a search depth of 21!
Clearly, the View itself would provide us with a performance advantage (3x) over the simple use of the index alone. I've tried to use a real-world example but you'll note that a simple list of Lithuanian sales would give us an even greater advantage.
Note that I'm just using a straight b-tree for my example. While I'm fairly certain that SQL Server uses some variant of a b-tree, I don't know the details. Nonetheless, the point holds.
Update 3: The question has come up about whether an Indexed View just uses an index placed on the underlying table. That is, to paraphrase: "an indexed view is just the equivalent of a standard index and it offers nothing new or unique to a view." If this was true, of course, then the above analysis would be incorrect! Let me provide a quote from the Microsoft documentation that demonstrate why I think this criticism is not valid or true:
Using indexes to improve query performance is not a new concept; however, indexed views provide additional performance benefits that cannot be achieved using standard indexes.
Together with the above quote regarding the persistence of data in physical storage and other information in the documentation about how indices are created on Views, I think it is safe to say that an Indexed View is not just a cached SQL Select that happens to use an index defined on the main table. Thus, I continue to stand by this answer.
You first need to understand Call Stack. Understanding Call stack will also give you clarity to how "function hierarchy and execution order" works in JavaScript Engine.
The call stack is primarily used for function invocation (call). Since there is only one call stack. Hence, all function(s) execution get pushed and popped one at a time, from top to bottom.
It means the call stack is synchronous. When you enter a function, an entry for that function is pushed onto the Call stack and when you exit from the function, that same entry is popped from the Call Stack. So, basically if everything is running smooth, then at the very beginning and at the end, Call Stack will be found empty.
Here is the illustration of Call Stack:
Now, if you provide too many arguments or caught inside any unhandled recursive call. You will encounter
RangeError: Maximum call stack size exceeded
which is quite obvious as explained by others.
Hope this helps !
Kotlin
stateListAnimator = null
Java
setStateListAnimator(null);
XML
android:stateListAnimator="@null"
Use the below css to solve your issue
#footer{ text-align:center; height:58px;}
#footer ul { font-size:11px;}
#footer ul li {display:inline-block;}
Note: Don't use float:left
in li. it will make your li to align left.
How about when you do the
totalCost.setText(tot);
You just do
totalCost.setText( "" + total );
Where the "" + < variable > will convert it to string automaticly
If you need to format the result to a specific number of decimal places, for example to represent currency, you need something like the toFixed()
method.
number.toFixed( [digits] )
digits
is the number of digits to display after the decimal place.
By dictionary comprehension
d = { line.split()[0] : line.split()[1] for line in open("file.txt") }
Or By pandas
import pandas as pd
d = pd.read_csv("file.txt", delimiter=" ", header = None).to_dict()[0]
How about this one?
We simply use a try-catch block.
$dateTime = 'an invalid datetime';
try {
$dateTimeObject = new DateTime($dateTime);
} catch (Exception $exc) {
echo 'Do something with an invalid DateTime';
}
This approach is not limited to only one date/time format, and you don't need to define any function.
The easiest way to achieve this, without changing the HTML table
-based structure, is to use a class-name on the tr
elements containing a header, such as .header
, to give:
<table border="0">
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr class="header">
<td colspan="2">Header</td>
</tr>
<tr>
<td>date</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
<tr>
<td>data</td>
<td>data</td>
</tr>
</table>
And the jQuery:
// bind a click-handler to the 'tr' elements with the 'header' class-name:
$('tr.header').click(function(){
/* get all the subsequent 'tr' elements until the next 'tr.header',
set the 'display' property to 'none' (if they're visible), to 'table-row'
if they're not: */
$(this).nextUntil('tr.header').css('display', function(i,v){
return this.style.display === 'table-row' ? 'none' : 'table-row';
});
});
In the linked demo I've used CSS to hide the tr
elements that don't have the header
class-name; in practice though (despite the relative rarity of users with JavaScript disabled) I'd suggest using JavaScript to add the relevant class-names, hiding and showing as appropriate:
// hide all 'tr' elements, then filter them to find...
$('tr').hide().filter(function () {
// only those 'tr' elements that have 'td' elements with a 'colspan' attribute:
return $(this).find('td[colspan]').length;
// add the 'header' class to those found 'tr' elements
}).addClass('header')
// set the display of those elements to 'table-row':
.css('display', 'table-row')
// bind the click-handler (as above)
.click(function () {
$(this).nextUntil('tr.header').css('display', function (i, v) {
return this.style.display === 'table-row' ? 'none' : 'table-row';
});
});
References:
Actually - Patrick's code sort of worked for me as well. The correct way to do it would be along the lines of this:
Note: there's a bit of jquery ahead:
if ($.browser.msie == false) {
var h = (document.getElementById("iframeID").contentDocument.body.offsetHeight);
} else {
var h = (document.getElementById("iframeID").Document.body.scrollHeight);
}
android:focusableInTouchMode="true"
android:focusable="true"
android:clickable="true"
Add them to your ViewGroup that includes your EditTextView. It works properly to my Constraint Layout. Hope this help
Amit-
I don't believe you can add a column anywhere but at the end of the table once the table is created. One solution might be to try this:
CREATE TABLE MY_TEMP_TABLE AS
SELECT *
FROM TABLE_TO_CHANGE;
Drop the table you want to add columns to:
DROP TABLE TABLE_TO_CHANGE;
It's at the point you could rebuild the existing table from scratch adding in the columns where you wish. Let's assume for this exercise you want to add the columns named "COL2 and COL3".
Now insert the data back into the new table:
INSERT INTO TABLE_TO_CHANGE (COL1, COL2, COL3, COL4)
SELECT COL1, 'Foo', 'Bar', COL4
FROM MY_TEMP_TABLE;
When the data is inserted into your "new-old" table, you can drop the temp table.
DROP TABLE MY_TEMP_TABLE;
This is often what I do when I want to add columns in a specific location. Obviously if this is a production on-line system, then it's probably not practical, but just one potential idea.
-CJ
Objects in python store their atributes (including functions) in a dict called __dict__
. You can (but generally shouldn't) use this to access the attributes directly. If you just want a list, you can also call dir(obj)
, which returns an iterable with all the attribute names, which you could then pass to getattr
.
However, needing to do anything with the names of the variables is usually bad design. Why not keep them in a collection?
class Foo(object):
def __init__(self, **values):
self.special_values = values
You can then iterate over the keys with for key in obj.special_values:
Change
$data[$parts[0]] = $parts[1];
to
if ( ! isset($parts[1])) {
$parts[1] = null;
}
$data[$parts[0]] = $parts[1];
or simply:
$data[$parts[0]] = isset($parts[1]) ? $parts[1] : null;
Not every line of your file has a colon in it and therefore explode on it returns an array of size 1.
According to php.net possible return values from explode:
Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.
If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.
I prefer to destruct object values into array:
[...Object.values(dataObject)]
var dataObject = {
object1: {id: 1, name: "Fred"},
object2: {id: 2, name: "Wilma"},
object3: {id: 3, name: "Pebbles"}
};
var dataArray = [...Object.values(dataObject)];
<a href="/fruits/index.html">Back to Fruits List</a>
One thing that really hung me up, was when I inspected this html in the browser, instead of seeing it expanded to something like:
<button ng-click="removeTask(1234)">remove</button>
I saw:
<button ng-click="removeTask(task.id)">remove</button>
However, the latter works!
This is because you are in the "Angular World", when inside ng-click="" Angular all ready knows about task.id as you are inside it's model. There is no need to use Data binding, as in {{}}.
Further, if you wanted to pass the task object itself, you can like:
<button ng-click="removeTask(task)">remove</button>
I find this process much safer and easier to understand by creating another branch from the SHA1 of A and cherry-picking the desired changes so I can make sure I'm satisfied with how this new branch looks. After that, it is easy to remove the old branch and rename the new one.
git checkout <SHA1 of A>
git log #verify looks good
git checkout -b rework
git cherry-pick <SHA1 of D>
....
git log #verify looks good
git branch -D <oldbranch>
git branch -m rework <oldbranch>
I did a benchmark test to try and answer this question, then found this post so here are my findings (which differ slightly from the other answers)
Here is the benchmark code:
require 'benchmark'
h = { abc: 'hello', 'another_key' => 123, 4567 => 'third' }
a = 1..10
many = 500_000
Benchmark.bm do |b|
GC.start
b.report("hash keys collect") do
many.times do
h.keys.collect(&:to_s)
end
end
GC.start
b.report("hash keys map") do
many.times do
h.keys.map(&:to_s)
end
end
GC.start
b.report("array collect") do
many.times do
a.collect(&:to_s)
end
end
GC.start
b.report("array map") do
many.times do
a.map(&:to_s)
end
end
end
And the results I got were:
user system total real
hash keys collect 0.540000 0.000000 0.540000 ( 0.570994)
hash keys map 0.500000 0.010000 0.510000 ( 0.517126)
array collect 1.670000 0.020000 1.690000 ( 1.731233)
array map 1.680000 0.020000 1.700000 ( 1.744398)
Perhaps an alias isn't free?
While the accepted answer solved the OP's original problem, most people finding this question through a Google search are likely having an entirely different problem which just happens to throw the same no suitable HttpMessageConverter found exception.
What happens under the covers is that MappingJackson2HttpMessageConverter
swallows any exceptions that occur in its canRead()
method, which is supposed to auto-detect whether the payload is suitable for json decoding. The exception is replaced by a simple boolean return that basically communicates sorry, I don't know how to decode this message to the higher level APIs (RestClient
). Only after all other converters' canRead() methods return false, the no suitable HttpMessageConverter found exception is thrown by the higher-level API, totally obscuring the true problem.
For people who have not found the root cause (like you and me, but not the OP), the way to troubleshoot this problem is to place a debugger breakpoint on onMappingJackson2HttpMessageConverter.canRead()
, then enable a general breakpoint on any exception, and hit Continue. The next exception is the true root cause.
My specific error happened to be that one of the beans referenced an interface that was missing the proper deserialization annotations.
UPDATE FROM THE FUTURE
This has proven to be such a recurring issue across so many of my projects, that I've developed a more proactive solution. Whenever I have a need to process JSON exclusively (no XML or other formats), I now replace my RestTemplate
bean with an instance of the following:
public class JsonRestTemplate extends RestTemplate {
public JsonRestTemplate(
ClientHttpRequestFactory clientHttpRequestFactory) {
super(clientHttpRequestFactory);
// Force a sensible JSON mapper.
// Customize as needed for your project's definition of "sensible":
ObjectMapper objectMapper = new ObjectMapper()
.registerModule(new Jdk8Module())
.registerModule(new JavaTimeModule())
.configure(
SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
List<HttpMessageConverter<?>> messageConverters = new ArrayList<>();
MappingJackson2HttpMessageConverter jsonMessageConverter = new MappingJackson2HttpMessageConverter() {
public boolean canRead(java.lang.Class<?> clazz,
org.springframework.http.MediaType mediaType) {
return true;
}
public boolean canRead(java.lang.reflect.Type type,
java.lang.Class<?> contextClass,
org.springframework.http.MediaType mediaType) {
return true;
}
protected boolean canRead(
org.springframework.http.MediaType mediaType) {
return true;
}
};
jsonMessageConverter.setObjectMapper(objectMapper);
messageConverters.add(jsonMessageConverter);
super.setMessageConverters(messageConverters);
}
}
This customization makes the RestClient
incapable of understanding anything other than JSON. The upside is that any error messages that may occur will be much more explicit about what's wrong.
I think you should change that like so:
<input value={this.state.value} onChange={(e) => {this.handleChange(e)}}/>
That is in principle the same as onClick={this.handleClick.bind(this)}
as you did on the button.
So if you want to call handleChange()
when the button is clicked, than:
<button onClick={this.handleChange.bind(this)}>Change Input</button>
or
handleClick () {
this.setState({value: 'another random text'});
this.handleChange();
}
That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.
Example. Suppose I write:
(function() {
var x = 2;
// do stuff with x
})();
Now other libraries cannot access the variable x
I created to use in my library.
Here's an ES6 version of the answer provided by 7stud.
const sel = document.createElement('select');
sel.name = 'drop1';
sel.id = 'Select1';
const cars = [
"Volvo",
"Saab",
"Mercedes",
"Audi",
];
const options = cars.map(car => {
const value = car.toLowerCase();
return `<option value="${value}">${car}</option>`;
});
sel.innerHTML = options;
window.onload = () => document.body.appendChild(sel);
You can use the jQuery ajax method link if you want to pass data from client to server.
In this case you can use $_SERVER['HTTP_USER_AGENT']
variable to found browser user agent.
You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString()
on each object in the list. You could think that given it is a list of SelectListItem
it should be smart enough to detect this... but it is not.
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text", 1);
BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.
I think it is better to do it like this:
u.UserTypeOptions = new SelectList(
new List<SelectListItem>
{
new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
}, "Value" , "Text");
I removed the -1 item, and the setting of each items selected true/false.
Then, in your view:
@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")
This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType
will be null (the UserType
need to be int?
).
If you need to set one of the SelectList items as selected, you can use:
u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);
It's a linker error. ld
is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.
The error message tells you that none of the object files you're linking against contains a definition for avergecolumns
. The reason for that is that the function you've defined is called averagecolumns
(in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
If you are logged in into psql on the Linux shell the command is:
\i fileName.sql
for an absolute path and
\ir filename.sql
for the relative path from where you have called psql.
There is no way to gracefully kill a thread.
You can try to interrupt the thread, one commons strategy is to use a poison pill to message the thread to stop itself
public class CancelSupport {
public static class CommandExecutor implements Runnable {
private BlockingQueue<String> queue;
public static final String POISON_PILL = “stopnow”;
public CommandExecutor(BlockingQueue<String> queue) {
this.queue=queue;
}
@Override
public void run() {
boolean stop=false;
while(!stop) {
try {
String command=queue.take();
if(POISON_PILL.equals(command)) {
stop=true;
} else {
// do command
System.out.println(command);
}
} catch (InterruptedException e) {
stop=true;
}
}
System.out.println(“Stopping execution”);
}
}
}
BlockingQueue<String> queue=new LinkedBlockingQueue<String>();
Thread t=new Thread(new CommandExecutor(queue));
queue.put(“hello”);
queue.put(“world”);
t.start();
Thread.sleep(1000);
queue.put(“stopnow”);
You could create many tasks like:
List<Task> TaskList = new List<Task>();
foreach(...)
{
var LastTask = new Task(SomeFunction);
LastTask.Start();
TaskList.Add(LastTask);
}
Task.WaitAll(TaskList.ToArray());
man your container is 40% of the width of the parent element
but when you use position:fixed, the width is based on viewport(document) width...
thinking about, i realized your parent element have 10% padding(left and right), it means your element have 80% of the total page width. so your fixed element must have 40% based on 80% of total width
so you just need to change your #fixed class to
#fixed{
position:fixed;
width: calc(80% * 0.4);
height:10px;
background-color:#333;
}
if you use sass, postcss or another css compiler, you can use variables to avoid breaking the layout when you change the padding value of parent element.
here is the updated fiddle http://jsfiddle.net/C93mk/2343/
i hope it helps, regards
Assume scenario where swimmers swim in swimming pool in the areas reserved for them.what happens if swimmers swim other than the areas reserved for them,the whole thing would become mess.similarly iis uses application pools to seperate one process from another.
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
You can't view the hashed password; the only thing you can do is reset it!
Stop MySQL:
sudo service mysql stop
or
$ sudo /usr/local/mysql/support-files/mysql.server stop
Start it in safe mode:
$ sudo mysqld_safe --skip-grant-tables
(above line is the whole command)
This will be an ongoing command until the process is finished so open another shell/terminal window, log in without a password:
$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
MySQL 5.7 and over:
mysql> use mysql;
mysql> update user set authentication_string=password('password') where user='root';
Start MySQL:
sudo mysql start
or
sudo /usr/local/mysql/support-files/mysql.server start
Your new password is 'password'.
Demo
public static void main(String[] args) {
outer:
while (true) {
while (true) {
break outer;
}
}
}
Regarding your second question about properties, you can use self.myView
only if you declared it as a property in class. Since myView
is a local variable, you can not use it that way. For more details on this, I would recommend you to go through the apple documentation on Declared Properties,
You can compare class tokens to each other, so you could use value.getClass() == Integer.class
. However, the simpler and more canonical way is to use instanceof
:
if (value instanceof Integer) {
System.out.println("This is an Integer");
} else if(value instanceof String) {
System.out.println("This is a String");
} else if(value instanceof Float) {
System.out.println("This is a Float");
}
Notes:
instanceof C
matches for subclasses of C
too. However, in this case all the classes listed are final
, so they have no subclasses. Thus instanceof
is probably fine here.as JB Nizet stated, such checks are not OO design. You may be able to solve this problem in a more OO way, e.g.
System.out.println("This is a(n) " + value.getClass().getSimpleName());
As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.
In my case:
antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip pip2 pip2.7 pip3 pip3.5
And then just uninstall with the specific pip version.
Here's one approach which automates creating labels above each column of a listbox (on a worksheet).
It will work (though not super-pretty!) as long as there's no horizontal scrollbar on your listbox.
Sub Tester()
Dim i As Long
With Me.lbTest
.Clear
.ColumnCount = 5
'must do this next step!
.ColumnWidths = "70;60;100;60;60"
.ListStyle = fmListStylePlain
Debug.Print .ColumnWidths
For i = 0 To 10
.AddItem
.List(i, 0) = "blah" & i
.List(i, 1) = "blah"
.List(i, 2) = "blah"
.List(i, 3) = "blah"
.List(i, 4) = "blah"
Next i
End With
LabelHeaders Me.lbTest, Array("Header1", "Header2", _
"Header3", "Header4", "Header5")
End Sub
Sub LabelHeaders(lb, arrHeaders)
Const LBL_HT As Long = 15
Dim T, L, shp As Shape, cw As String, arr
Dim i As Long, w
'delete any previous headers for this listbox
For i = lb.Parent.Shapes.Count To 1 Step -1
If lb.Parent.Shapes(i).Name Like lb.Name & "_*" Then
lb.Parent.Shapes(i).Delete
End If
Next i
'get an array of column widths
cw = lb.ColumnWidths
If Len(cw) = 0 Then Exit Sub
cw = Replace(cw, " pt", "")
arr = Split(cw, ";")
'start points for labels
T = lb.Top - LBL_HT
L = lb.Left
For i = LBound(arr) To UBound(arr)
w = CLng(arr(i))
If i = UBound(arr) And (L + w) < lb.Width Then w = lb.Width - L
Set shp = ActiveSheet.Shapes.AddShape(msoShapeRectangle, _
L, T, w, LBL_HT)
With shp
.Name = lb.Name & "_" & i
'do some formatting
.Line.ForeColor.RGB = vbBlack
.Line.Weight = 1
.Fill.ForeColor.RGB = RGB(220, 220, 220)
.TextFrame2.TextRange.Characters.Text = arrHeaders(i)
.TextFrame2.TextRange.Font.Size = 9
.TextFrame2.TextRange.Font.Fill.ForeColor.RGB = vbBlack
End With
L = L + w
Next i
End Sub
In case you need to convert the returned date of a select statement to a specific format you may use the following:
select to_char(DATE (*date_you_want_to_select*)::date, 'DD/MM/YYYY') as "Formated Date"
The angular way is shown in the angular docs :)
https://docs.angularjs.org/api/ng/directive/ngReadonly
Here is the example they use:
<body>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>
Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).
So basically in your case you would want to do something like below or check out this working example.
<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>
Download the file and from the same directory run docker build -t nodebb .
This will give you an image on your local machine that's named nodebb that you can launch an container from with docker run -d nodebb
(you can change nodebb to your own name).
You have to specify what encoding the data is. Either in meta or in headers
header('Content-Type: text/plain; charset=utf-8');
I just incorporated the SELECT with a CASE statement (For my situation Monday marked the first day of the week, and didn't want to deal with the SET DATEFIRST command:
CASE DATEPART(dw,<YourDateTimeField>)
WHEN 1 THEN CONVERT(char(10), DATEADD(DD, -6, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), <YourDateTimeField>,126)
WHEN 2 THEN CONVERT(char(10), <YourDateTimeField>,126) + ' to ' + CONVERT(char(10), DATEADD(DD, 6, <YourDateTimeField>),126)
WHEN 3 THEN CONVERT(char(10), DATEADD(DD, -1, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), DATEADD(DD, 5, <YourDateTimeField>),126)
WHEN 4 THEN CONVERT(char(10), DATEADD(DD, -2, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), DATEADD(DD, 4, <YourDateTimeField>),126)
WHEN 5 THEN CONVERT(char(10), DATEADD(DD, -3, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), DATEADD(DD, 3, <YourDateTimeField>),126)
WHEN 6 THEN CONVERT(char(10), DATEADD(DD, -4, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), DATEADD(DD, 2, <YourDateTimeField>),126)
WHEN 7 THEN CONVERT(char(10), DATEADD(DD, -5, <YourDateTimeField>),126) + ' to ' + CONVERT(char(10), DATEADD(DD, 1, <YourDateTimeField>),126)
ELSE 'UNK'
END AS Week_Range
if [ -d "$DIRECTORY" ]; then
# Will enter here if $DIRECTORY exists
fi
This is not completely true...
If you want to go to that directory, you also need to have the execute rights on the directory. Maybe you need to have write rights as well.
Therefore:
if [ -d "$DIRECTORY" ] && [ -x "$DIRECTORY" ] ; then
# ... to go to that directory (even if DIRECTORY is a link)
cd $DIRECTORY
pwd
fi
if [ -d "$DIRECTORY" ] && [ -w "$DIRECTORY" ] ; then
# ... to go to that directory and write something there (even if DIRECTORY is a link)
cd $DIRECTORY
touch foobar
fi
I have Archlinux with php 7.2, which has Curl integrated, so no amount of configuration voodoo would make Composer see ext-curl, that PHP could see and work with happily. Work around is to use Composer with --ignore-platform-reqs.
eg composer update --ignore-platform-reqs
Reference = https://github.com/composer/composer/issues/1426
I've already encountered this error and this is the best solution I've found:
In your root folder (probably called public_html)please add this code to your .htaccess file...
REPLACE the 00.00.00.000 with YOUR IP address. If you don't know your IP address buzz over to What Is My IP - The IP Address Experts Since 1999
#By Marky WP Root Directory to deny entry for WP-Login & xmlrpc
<Files wp-login.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
<Files xmlrpc.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
In your wp-admin folder please add this code to your .htaccess file...
#By Marky WP Admin Folder to deny entry for entire admin folder
order deny,allow
deny from all
allow from 00.00.00.000
<Files index.php>
order deny,allow
deny from all
allow from 00.00.00.000
</Files>
MultiCell($w, $h, 'text<br />', $border=0, $align='L', $fill=1, $ln=0,
$x='', $y='', $reseth=true, $reseth=0, $ishtml=true, $autopadding=true,
$maxh=0);
You can configure the MultiCell
to read html on a basic level.
Here is a method that is supported by nearly all browsers:
if (sessionStorage.getItem('reloaded') != null) {
console.log('page was reloaded');
} else {
console.log('page was not reloaded');
}
sessionStorage.setItem('reloaded', 'yes'); // could be anything
It uses SessionStorage to check if the page is opened the first time or if it is refreshed.
I took a slightly different approach than others
static float NextFloat(Random random)
{
double val = random.NextDouble(); // range 0.0 to 1.0
val -= 0.5; // expected range now -0.5 to +0.5
val *= 2; // expected range now -1.0 to +1.0
return float.MaxValue * (float)val;
}
The comments explain what I'm doing. Get the next double, convert that number to a value between -1 and 1 and then multiply that with float.MaxValue
.
This is a hairy one to answer, because you didn't give the full context of what you're doing. The accepted answer will work, but in some cases will cause poor performance. That, and it's going to be harder to test.
If you're doing this as part of a static form, fine. The accepted answer will work, even if it isn't easy to test, and it's hinky.
You'll want to keep any "business logic" (i.e. logic that alters data to be displayed) out of your views. This is so you can unit test your logic, and so you don't end up tightly coupling your controller and your view. Theoretically, you should be able to point your controller at another view and use the same values from the scopes. (if that makes sense).
You'll also want to consider that any function calls inside of a binding (such as {{}}
or ng-bind
or ng-bind-html
) will have to be evaluated on every digest, because angular has no way of knowing if the value has changed or not like it would with a property on the scope.
The "angular" way to do this would be to cache the value in a property on the scope on change using an ng-change event or even a $watch.
For example with a static form:
angular.controller('MainCtrl', function($scope, $window) {
$scope.count = 0;
$scope.total = 1;
$scope.updatePercentage = function () {
$scope.percentage = $window.Math.round((100 * $scope.count) / $scope.total);
};
});
<form name="calcForm">
<label>Count <input name="count" ng-model="count"
ng-change="updatePercentage()"
type="number" min="0" required/></label><br/>
<label>Total <input name="total" ng-model="total"
ng-change="updatePercentage()"
type="number" min="1" required/></label><br/>
<hr/>
Percentage: {{percentage}}
</form>
describe('Testing percentage controller', function() {
var $scope = null;
var ctrl = null;
//you need to indicate your module in a test
beforeEach(module('plunker'));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {
$scope: $scope
});
}));
it('should calculate percentages properly', function() {
$scope.count = 1;
$scope.total = 1;
$scope.updatePercentage();
expect($scope.percentage).toEqual(100);
$scope.count = 1;
$scope.total = 2;
$scope.updatePercentage();
expect($scope.percentage).toEqual(50);
$scope.count = 497;
$scope.total = 10000;
$scope.updatePercentage();
expect($scope.percentage).toEqual(5); //4.97% rounded up.
$scope.count = 231;
$scope.total = 10000;
$scope.updatePercentage();
expect($scope.percentage).toEqual(2); //2.31% rounded down.
});
});
I suggest also checking how much memory is currently being used.
It turns out that the inability to find these DLL files was the first symptom exhibited when trying to run a program (either run or debug) in Visual Studio.
After over a half hour with much head scratching, searching the web, running Process Monitor, and Task Manager, and depends, a completely different program that had been running since the beginning of time reported that "memory is low; try stopping some programs" or some such. After killing Firefox, Thunderbird, Process Monitor, and depends, everything worked again.
In chrome, you can apply this css if you need to apply ellipsis on multiple lines.
You can also add width in your css to specify element of certain width:
.multi-line-ellipsis {_x000D_
overflow: hidden;_x000D_
display: -webkit-box;_x000D_
-webkit-line-clamp: 3;_x000D_
-webkit-box-orient: vertical;_x000D_
}
_x000D_
<p class="multi-line-ellipsis">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
_x000D_
You can pass input as ["apple","orange"]
if you want to leave the method as it is.
It worked for me with a similar method signature.
Have a look at the example in this link :
http://docs.angularjs.org/api/ngSanitize.$sanitize
Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :
If you already have done all this :
// My magic HTML string function.
function htmlString (str) {
return "<h1>" + str + "</h1>";
}
function Ctrl ($scope) {
var str = "HELLO!";
$scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];
Then in your html within the scope of that controller, you could
<div ng-bind-html="htmlString"></div>
The if
statement takes a command as an argument (as do &&
, ||
, etc.). The integer result code of the command is interpreted as a boolean (0/null=true, 1/else=false).
The test
statement takes operators and operands as arguments and returns a result code in the same format as if
. An alias of the test
statement is [
, which is often used with if
to perform more complex comparisons.
The true
and false
statements do nothing and return a result code (0 and 1, respectively). So they can be used as boolean literals in Bash. But if you put the statements in a place where they're interpreted as strings, you'll run into issues. In your case:
if [ foo ]; then ... # "if the string 'foo' is non-empty, return true"
if foo; then ... # "if the command foo succeeds, return true"
So:
if [ true ] ; then echo "This text will always appear." ; fi;
if [ false ] ; then echo "This text will always appear." ; fi;
if true ; then echo "This text will always appear." ; fi;
if false ; then echo "This text will never appear." ; fi;
This is similar to doing something like echo '$foo'
vs. echo "$foo"
.
When using the test
statement, the result depends on the operators used.
if [ "$foo" = "$bar" ] # true if the string values of $foo and $bar are equal
if [ "$foo" -eq "$bar" ] # true if the integer values of $foo and $bar are equal
if [ -f "$foo" ] # true if $foo is a file that exists (by path)
if [ "$foo" ] # true if $foo evaluates to a non-empty string
if foo # true if foo, as a command/subroutine,
# evaluates to true/success (returns 0 or null)
In short, if you just want to test something as pass/fail (aka "true"/"false"), then pass a command to your if
or &&
etc. statement, without brackets. For complex comparisons, use brackets with the proper operators.
And yes, I'm aware there's no such thing as a native boolean type in Bash, and that if
and [
and true
are technically "commands" and not "statements"; this is just a very basic, functional explanation.
An actual JSON request would look like this:
data: '{"command":"on"}',
Where you're sending an actual JSON string. For a more general solution, use JSON.stringify()
to serialize an object to JSON, like this:
data: JSON.stringify({ "command": "on" }),
To support older browsers that don't have the JSON
object, use json2.js which will add it in.
What's currently happening is since you have processData: false
, it's basically sending this: ({"command":"on"}).toString()
which is [object Object]
...what you see in your request.
I'm showing that a combination of lines.pop(0)
l.remove()
and del l
does the trick.
from matplotlib import pyplot
import numpy, weakref
a = numpy.arange(int(1e3))
fig = pyplot.Figure()
ax = fig.add_subplot(1, 1, 1)
lines = ax.plot(a)
l = lines.pop(0)
wl = weakref.ref(l) # create a weak reference to see if references still exist
# to this object
print wl # not dead
l.remove()
print wl # not dead
del l
print wl # dead (remove either of the steps above and this is still live)
I checked your large dataset and the release of the memory is confirmed on the system monitor as well.
Of course the simpler way (when not trouble-shooting) would be to pop it from the list and call remove
on the line object without creating a hard reference to it:
lines.pop(0).remove()
A simple client-side pagination example where data is fetched only once at page loading.
// dummy data_x000D_
const myarr = [{ "req_no": 1, "title": "test1" },_x000D_
{ "req_no": 2, "title": "test2" },_x000D_
{ "req_no": 3, "title": "test3" },_x000D_
{ "req_no": 4, "title": "test4" },_x000D_
{ "req_no": 5, "title": "test5" },_x000D_
{ "req_no": 6, "title": "test6" },_x000D_
{ "req_no": 7, "title": "test7" },_x000D_
{ "req_no": 8, "title": "test8" },_x000D_
{ "req_no": 9, "title": "test9" },_x000D_
{ "req_no": 10, "title": "test10" },_x000D_
{ "req_no": 11, "title": "test11" },_x000D_
{ "req_no": 12, "title": "test12" },_x000D_
{ "req_no": 13, "title": "test13" },_x000D_
{ "req_no": 14, "title": "test14" },_x000D_
{ "req_no": 15, "title": "test15" },_x000D_
{ "req_no": 16, "title": "test16" },_x000D_
{ "req_no": 17, "title": "test17" },_x000D_
{ "req_no": 18, "title": "test18" },_x000D_
{ "req_no": 19, "title": "test19" },_x000D_
{ "req_no": 20, "title": "test20" },_x000D_
{ "req_no": 21, "title": "test21" },_x000D_
{ "req_no": 22, "title": "test22" },_x000D_
{ "req_no": 23, "title": "test23" },_x000D_
{ "req_no": 24, "title": "test24" },_x000D_
{ "req_no": 25, "title": "test25" },_x000D_
{ "req_no": 26, "title": "test26" }];_x000D_
_x000D_
// on page load collect data to load pagination as well as table_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
_x000D_
// At a time maximum allowed pages to be shown in pagination div_x000D_
const pagination_visible_pages = 4;_x000D_
_x000D_
_x000D_
// hide pages from pagination from beginning if more than pagination_visible_pages_x000D_
function hide_from_beginning(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.nextSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// hide pages from pagination ending if more than pagination_visible_pages_x000D_
function hide_from_end(element) {_x000D_
if (element.style.display === "" || element.style.display === "block") {_x000D_
element.style.display = "none";_x000D_
} else {_x000D_
hide_from_beginning(element.previousSibling);_x000D_
}_x000D_
}_x000D_
_x000D_
// load data and style for active page_x000D_
function active_page(element, rows, req_per_page) {_x000D_
var current_page = document.getElementsByClassName('active');_x000D_
var next_link = document.getElementById('next_link');_x000D_
var prev_link = document.getElementById('prev_link');_x000D_
var next_tab = current_page[0].nextSibling; _x000D_
var prev_tab = current_page[0].previousSibling;_x000D_
current_page[0].className = current_page[0].className.replace("active", "");_x000D_
if (element === "next") {_x000D_
if (parseInt(next_tab.text).toString() === 'NaN') {_x000D_
next_tab.previousSibling.className += " active";_x000D_
next_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
next_tab.className += " active"_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(next_tab.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_tab.style.display === "none") {_x000D_
next_tab.style.display = "block";_x000D_
hide_from_beginning(prev_link.nextSibling)_x000D_
}_x000D_
}_x000D_
} else if (element === "prev") {_x000D_
if (parseInt(prev_tab.text).toString() === 'NaN') {_x000D_
prev_tab.nextSibling.className += " active";_x000D_
prev_tab.setAttribute("onclick", "return false");_x000D_
} else {_x000D_
prev_tab.className += " active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(prev_tab.text));_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (prev_tab.style.display === "none") {_x000D_
prev_tab.style.display = "block";_x000D_
hide_from_end(next_link.previousSibling)_x000D_
}_x000D_
}_x000D_
} else {_x000D_
element.className += "active";_x000D_
render_table_rows(rows, parseInt(req_per_page), parseInt(element.text));_x000D_
if (prev_link.getAttribute("onclick") === "return false") {_x000D_
prev_link.setAttribute("onclick", `active_page('prev',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
if (next_link.getAttribute("onclick") === "return false") {_x000D_
next_link.setAttribute("onclick", `active_page('next',\"${rows}\",${req_per_page})`);_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
// Render the table's row in table request-table_x000D_
function render_table_rows(rows, req_per_page, page_no) {_x000D_
const response = JSON.parse(window.atob(rows));_x000D_
const resp = response.slice(req_per_page * (page_no - 1), req_per_page * page_no)_x000D_
$('#request-table').empty()_x000D_
$('#request-table').append('<tr><th>Index</th><th>Request No</th><th>Title</th></tr>');_x000D_
resp.forEach(function (element, index) {_x000D_
if (Object.keys(element).length > 0) {_x000D_
const { req_no, title } = element;_x000D_
const td = `<tr><td>${++index}</td><td>${req_no}</td><td>${title}</td></tr>`;_x000D_
$('#request-table').append(td)_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
// Pagination logic implementation_x000D_
function pagination(data, myarr) {_x000D_
const all_data = window.btoa(JSON.stringify(myarr));_x000D_
$(".pagination").empty();_x000D_
if (data.req_per_page !== 'ALL') {_x000D_
let pager = `<a href="#" id="prev_link" onclick=active_page('prev',\"${all_data}\",${data.req_per_page})>«</a>` +_x000D_
`<a href="#" class="active" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>1</a>`;_x000D_
const total_page = Math.ceil(parseInt(myarr.length) / parseInt(data.req_per_page));_x000D_
if (total_page < pagination_visible_pages) {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= total_page; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
} else {_x000D_
render_table_rows(all_data, data.req_per_page, data.page_no);_x000D_
for (let num = 2; num <= pagination_visible_pages; num++) {_x000D_
pager += `<a href="#" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
for (let num = pagination_visible_pages + 1; num <= total_page; num++) {_x000D_
pager += `<a href="#" style="display:none;" onclick=active_page(this,\"${all_data}\",${data.req_per_page})>${num}</a>`;_x000D_
}_x000D_
}_x000D_
pager += `<a href="#" id="next_link" onclick=active_page('next',\"${all_data}\",${data.req_per_page})>»</a>`;_x000D_
$(".pagination").append(pager);_x000D_
} else {_x000D_
render_table_rows(all_data, myarr.length, 1);_x000D_
}_x000D_
}_x000D_
_x000D_
//calling pagination function_x000D_
pagination(data, myarr);_x000D_
_x000D_
_x000D_
// trigger when requests per page dropdown changes_x000D_
function filter_requests() {_x000D_
const data = { "req_per_page": document.getElementById("req_per_page").value, "page_no": 1 };_x000D_
pagination(data, myarr);_x000D_
}
_x000D_
.box {_x000D_
float: left;_x000D_
padding: 50px 0px;_x000D_
}_x000D_
_x000D_
.clearfix::after {_x000D_
clear: both;_x000D_
display: table;_x000D_
}_x000D_
_x000D_
.options {_x000D_
margin: 5px 0px 0px 0px;_x000D_
float: left;_x000D_
}_x000D_
_x000D_
.pagination {_x000D_
float: right;_x000D_
}_x000D_
_x000D_
.pagination a {_x000D_
color: black;_x000D_
float: left;_x000D_
padding: 8px 16px;_x000D_
text-decoration: none;_x000D_
transition: background-color .3s;_x000D_
border: 1px solid #ddd;_x000D_
margin: 0 4px;_x000D_
}_x000D_
_x000D_
.pagination a.active {_x000D_
background-color: #4CAF50;_x000D_
color: white;_x000D_
border: 1px solid #4CAF50;_x000D_
}_x000D_
_x000D_
.pagination a:hover:not(.active) {_x000D_
background-color: #ddd;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div>_x000D_
<table id="request-table">_x000D_
</table>_x000D_
</div>_x000D_
_x000D_
<div class="clearfix">_x000D_
<div class="box options">_x000D_
<label>Requests Per Page: </label>_x000D_
<select id="req_per_page" onchange="filter_requests()">_x000D_
<option>5</option>_x000D_
<option>10</option>_x000D_
<option>ALL</option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="box pagination">_x000D_
</div>_x000D_
</div>
_x000D_
By using cursor you can easily iterate through records individually and print records separately or as a single message including all the records.
DECLARE @CustomerID as INT;
declare @msg varchar(max)
DECLARE @BusinessCursor as CURSOR;
SET @BusinessCursor = CURSOR FOR
SELECT CustomerID FROM Customer WHERE CustomerID IN ('3908745','3911122','3911128','3911421')
OPEN @BusinessCursor;
FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
WHILE @@FETCH_STATUS = 0
BEGIN
SET @msg = '{
"CustomerID": "'+CONVERT(varchar(10), @CustomerID)+'",
"Customer": {
"LastName": "LastName-'+CONVERT(varchar(10), @CustomerID) +'",
"FirstName": "FirstName-'+CONVERT(varchar(10), @CustomerID)+'",
}
}|'
print @msg
FETCH NEXT FROM @BusinessCursor INTO @CustomerID;
END
Sounds like myversioncontrol.com have added a pre-commit hook, or have one that is now failing. If it's a free account, it might be you've exceeded some sort of monthly commit or bandwidth limit. Check their terms of service and/or contact them to see what's up.
UPDATE:
I've just checked their website, and it looks like the free account is only valid for 30 days, so you might've exceeded that. You may need to pony up the £3.50pcm or find somewhere else (Google Code is one suggestion, though there are others).
Simon Groenewolt makes a good point that you may have changed something in the control panel on their website that has turned on a pre-commit hook but where it's configured incorrectly.
//String to Date Convert
var dateString = "2014-01-12"
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
let s = dateFormatter.dateFromString(dateString)
println(s)
//CONVERT FROM NSDate to String
let date = NSDate()
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
var dateString = dateFormatter.stringFromDate(date)
println(dateString)
You can do it like this
$(function(){_x000D_
$("tr").find("td:eq(0)").css("color","red");_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
<tr>_x000D_
<td>col_1</td>_x000D_
<td>col_2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>col_1</td>_x000D_
<td>col_2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>col_1</td>_x000D_
<td>col_2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>col_1</td>_x000D_
<td>col_2</td>_x000D_
</tr>_x000D_
</table>
_x000D_
go to...
C:\wamp\alias
Inside alias folder you will see some files like phpmyadmin,phpsysinfo,etc...
open each file, and you can see inside file some commented instruction are give to access from outside ,like to give access to phpmyadmin from outside replace the lines
Require local
by
Require all granted
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
$(document).on('change','#multiid',function(){
// you desired code
});
reference on
If you want them gone by default, you can set:
Chart.defaults.scale.gridLines.display = false;
I use this class for Audio play. If your audio location is raw folder.
Call method for play:
new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
.getDetail().get(0).getAudio(),"raw", getPackageName()));
AudioPlayer.java class:
public class AudioPlayer {
private MediaPlayer mMediaPlayer;
public void stop() {
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
}
// mothod for raw folder (R.raw.fileName)
public void play(Context context, int rid){
stop();
mMediaPlayer = MediaPlayer.create(context, rid);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
// mothod for other folder
public void play(Context context, String name) {
stop();
//mMediaPlayer = MediaPlayer.create(c, rid);
mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mediaPlayer) {
stop();
}
});
mMediaPlayer.start();
}
}
Microsoft says here
Table variables does not have distribution statistics, they will not trigger recompiles. Therefore, in many cases, the optimizer will build a query plan on the assumption that the table variable has no rows. For this reason, you should be cautious about using a table variable if you expect a larger number of rows (greater than 100). Temp tables may be a better solution in this case.
Background:
Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.
Custom Validation Attributes
public class EmployeeModel
{
[Required]
[UniqueEmailAddress]
public string EmailAddress {get;set;}
public string FirstName {get;set;}
public string LastName {get;set;}
public int OrganizationId {get;set;}
}
To create a custom validation attribute, you will have to derive this class from ValidationAttribute.
public class UniqueEmailAddress : ValidationAttribute
{
private IEmployeeRepository _employeeRepository;
[Inject]
public IEmployeeRepository EmployeeRepository
{
get { return _employeeRepository; }
set
{
_employeeRepository = value;
}
}
protected override ValidationResult IsValid(object value,
ValidationContext validationContext)
{
var model = (EmployeeModel)validationContext.ObjectInstance;
if(model.Field1 == null){
return new ValidationResult("Field1 is null");
}
if(model.Field2 == null){
return new ValidationResult("Field2 is null");
}
if(model.Field3 == null){
return new ValidationResult("Field3 is null");
}
return ValidationResult.Success;
}
}
Hope this helps. Cheers !
References
A generic version that works for any X and Y value, and is the same as the window.scrollTo api, just with the addition of scrollDuration.
*A generic version matching the window.scrollTo browser api**
function smoothScrollTo(x, y, scrollDuration) {
x = Math.abs(x || 0);
y = Math.abs(y || 0);
scrollDuration = scrollDuration || 1500;
var currentScrollY = window.scrollY,
currentScrollX = window.scrollX,
dirY = y > currentScrollY ? 1 : -1,
dirX = x > currentScrollX ? 1 : -1,
tick = 16.6667, // 1000 / 60
scrollStep = Math.PI / ( scrollDuration / tick ),
cosParameterY = currentScrollY / 2,
cosParameterX = currentScrollX / 2,
scrollCount = 0,
scrollMargin;
function step() {
scrollCount = scrollCount + 1;
if ( window.scrollX !== x ) {
scrollMargin = cosParameterX + dirX * cosParameterX * Math.cos( scrollCount * scrollStep );
window.scrollTo( 0, ( currentScrollX - scrollMargin ) );
}
if ( window.scrollY !== y ) {
scrollMargin = cosParameterY + dirY * cosParameterY * Math.cos( scrollCount * scrollStep );
window.scrollTo( 0, ( currentScrollY - scrollMargin ) );
}
if (window.scrollX !== x || window.scrollY !== y) {
requestAnimationFrame(step);
}
}
step();
}
Swift 3: another solution (tested in playground)
extension String {
func substr(_ start:Int, length:Int=0) -> String? {
guard start > -1 else {
return nil
}
let count = self.characters.count - 1
guard start <= count else {
return nil
}
let startOffset = max(0, start)
let endOffset = length > 0 ? min(count, startOffset + length - 1) : count
return self[self.index(self.startIndex, offsetBy: startOffset)...self.index(self.startIndex, offsetBy: endOffset)]
}
}
Usage:
let txt = "12345"
txt.substr(-1) //nil
txt.substr(0) //"12345"
txt.substr(0, length: 0) //"12345"
txt.substr(1) //"2345"
txt.substr(2) //"345"
txt.substr(3) //"45"
txt.substr(4) //"5"
txt.substr(6) //nil
txt.substr(0, length: 1) //"1"
txt.substr(1, length: 1) //"2"
txt.substr(2, length: 1) //"3"
txt.substr(3, length: 1) //"4"
txt.substr(3, length: 2) //"45"
txt.substr(3, length: 3) //"45"
txt.substr(4, length: 1) //"5"
txt.substr(4, length: 2) //"5"
txt.substr(5, length: 1) //nil
txt.substr(5, length: -1) //nil
txt.substr(-1, length: -1) //nil
On windows platform, you have 2 choices:
In a command line terminal, type
c:\python23\python xxxx.py
Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.
For your posted code, the error is at this line:
def main(url, out_folder="C:\asdf\"):
It should be:
def main(url, out_folder="C:\\asdf\\"):
GNU parallel
and xargs
These two tools that can make scripts simpler, and also control the maximum number of threads (thread pool). E.g.:
seq 10 | xargs -P4 -I'{}' echo '{}'
or:
seq 10 | parallel -j4 echo '{}'
See also: how to write a process-pool bash shell
To make a translation in the controller you could use $translate
service:
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
That statement only does the translation on controller activation but it doesn't detect the runtime change in language. In order to achieve that behavior, you could listen the $rootScope
event: $translateChangeSuccess
and do the same translation there:
$rootScope.$on('$translateChangeSuccess', function () {
$translate(['COMMON.SI', 'COMMON.NO']).then(function (translations) {
vm.si = translations['COMMON.SI'];
vm.no = translations['COMMON.NO'];
});
});
Of course, you could encapsulate the $translate
service in a method and call it in the controller and in the $translateChangeSucess
listener.
#include <iostrema>
int main(){
int32_t maxSigned = -1U >> 1;
cout << maxSigned << '\n';
return 0;
}
It might be architecture dependent but it does work at least in my setup.
Since he was asking to do it all in the same line using split so i suggest this:
lastone = one.split("-")[(one.split("-")).length -1]
I always avoid defining new variables as far as I can, and I find it a very good practice
If you have a large data frame and need to divide into a variable number of sub data frames rows, like for example each sub dataframe has a max of 4500 rows, this script could help:
max_rows = 4500
dataframes = []
while len(df) > max_rows:
top = df[:max_rows]
dataframes.append(top)
df = df[max_rows:]
else:
dataframes.append(df)
You could then save out these data frames:
for _, frame in enumerate(dataframes):
frame.to_csv(str(_)+'.csv', index=False)
Hope this helps someone!
A SELECT INTO
statement creates the table for you. There is no need for the CREATE TABLE
statement before hand.
What is happening is that you create #ivmy_cash_temp1
in your CREATE
statement, then the DB tries to create it for you when you do a SELECT INTO
. This causes an error as it is trying to create a table that you have already created.
Either eliminate the CREATE TABLE
statement or alter your query that fills it to use INSERT INTO SELECT
format.
If you need a unique ID added to your new row then it's best to use SELECT INTO
... since IDENTITY()
only works with this syntax.
As of Git v2.23.0 (August 2019), git switch
is preferred over git checkout
when you’re simply switching branches/tags. I’m guessing they did this since git checkout
had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch
, and git restore
, to separate those concerns. I would predict at some point in the future, git checkout
will be deprecated.
To switch to a normal branch, use git switch <branch-name>
. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>
, where <commitish>
is the tag name or commit number.
The --detach
option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>
.
I would suggest this:
e.pageX - this.getBoundingClientRect().left
If you really want to dive into it and even need to distinguish between -0
and 0
, here's a way to do it.
function negative(number) {
return !Object.is(Math.abs(number), +number);
}
console.log(negative(-1)); // true
console.log(negative(1)); // false
console.log(negative(0)); // false
console.log(negative(-0)); // true
Thinking in terms of C++,
val x: T
is analogous to constant pointer to non-constant data
T* const x;
while
var x: T
is analogous to non-constant pointer to non-constant data
T* x;
Favoring val
over var
increases immutability of the codebase which can facilitate its correctness, concurrency and understandability.
To understand the meaning of having a constant pointer to non-constant data consider the following Scala snippet:
val m = scala.collection.mutable.Map(1 -> "picard")
m // res0: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard)
Here the "pointer" val m
is constant so we cannot re-assign it to point to something else like so
m = n // error: reassignment to val
however we can indeed change the non-constant data itself that m
points to like so
m.put(2, "worf")
m // res1: scala.collection.mutable.Map[Int,String] = HashMap(1 -> picard, 2 -> worf)
I got the same error in android studio. I was able to resolve it by running Build->Clean Project in the IDE.
A Primary key is a special kind of index in that:
there can be only one;
it cannot be nullable
it must be unique.
Candidate keys are selected from the set of super keys, the only thing we take care while selecting the candidate key is: It should not have any redundant attribute.
Example of an Employee table: Employee ( Employee ID, FullName, SSN, DeptID )
Candidate Key: are individual columns in a table that qualifies for the uniqueness of all the rows. Here in Employee table EmployeeID & SSN are Candidate keys.
Primary Key: are the columns you choose to maintain uniqueness in a table. Here in Employee table, you can choose either EmployeeID or SSN columns, EmployeeID is a preferable choice, as SSN is a secure value.
Alternate Key: Candidate column other the Primary column, like if EmployeeID is PK then SSN would be the Alternate key.
Super Key: If you add any other column/attribute to a Primary Key then it becomes a super key, like EmployeeID + FullName, is a Super Key.
Composite Key: If a table does not have a single column that qualifies for a Candidate key, then you have to select 2 or more columns to make a row unique. Like if there is no EmployeeID or SSN columns, then you can make FullName + DateOfBirth as Composite primary Key. But still, there can be a narrow chance of duplicate row.
You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:
select @StartChequeNumber = 3446;
SELECT
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable
will give the correct cheque number for each row.
1st is more efficient (and the best possible option) because val.ToLowerCase()
creates a new object since Strings are immutable.
Use With in the code.
Try this way :
''''Way 1
currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))
''''Way 2
With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With
''''Way 3
With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With
I personally prefer this pattern which is slightly clearer and simpler, at the expense of an extra variable:
for (auto it = m.cbegin(), next_it = it; it != m.cend(); it = next_it)
{
++next_it;
if (must_delete)
{
m.erase(it);
}
}
Advantages of this approach:
it
and next_it
remain fixed throughout the iteration, allowing you to easily add additional statements referring to them without headscratching over whether they will work as intended (except of course that you cannot use it
after erasing it).Try Demo Here
var list ={}; var count= Object.keys(list).length;
I found the easiest approach is to use the Distinct Count
option under Value Field Settings
(left click the field in the Values
pane). The option for Distinct Count
is at the very bottom of the list.
Here are the before (TOP; normal Count
) and after (BOTTOM; Distinct Count
)
Add external js file in index.html.
<script src="./assets/vendors/myjs.js"></script>
Here's myjs.js file :
var myExtObject = (function() {
return {
func1: function() {
alert('function 1 called');
},
func2: function() {
alert('function 2 called');
}
}
})(myExtObject||{})
var webGlObject = (function() {
return {
init: function() {
alert('webGlObject initialized');
}
}
})(webGlObject||{})
Then declare it is in component like below
demo.component.ts
declare var myExtObject: any;
declare var webGlObject: any;
constructor(){
webGlObject.init();
}
callFunction1() {
myExtObject.func1();
}
callFunction2() {
myExtObject.func2();
}
demo.component.html
<div>
<p>click below buttons for function call</p>
<button (click)="callFunction1()">Call Function 1</button>
<button (click)="callFunction2()">Call Function 2</button>
</div>
It's working for me...
There's multiple ways of doing things in batch, so if escaping with a double percent %%
isn't working for you, then you could try something like this:
set olddir=%CD%
cd /d "path of folder"
del "file name/ or *.txt etc..."
cd /d "%olddir%"
How this works:
set olddir=%CD%
sets the variable "olddir"
or any other variable name you like to the directory
your batch file was launched from.
cd /d "path of folder"
changes the current directory the batch will be looking at. keep the
quotations and change path of folder to which ever path you aiming for.
del "file name/ or *.txt etc..."
will delete the file in the current directory your batch is looking at, just don't add a directory path before the file name and just have the full file name or, to delete multiple files with the same extension with *.txt
or whatever extension you need.
cd /d "%olddir%"
takes the variable saved with your old path and goes back to the directory you started the batch with, its not important if you don't want the batch going back to its previous directory path, and like stated before the variable name can be changed to whatever you wish by changing the set olddir=%CD% line
.
If you ignore the characteristics of both languages, how do you define "SPEED"? Which features should be in your benchmark and which do you want to omit?
For example:
Conclusion: Your question has no answer because it isn't defined what you want. Even if you made it more clear, the question will probably become academic since you will measure something that doesn't count in real life. For all of my projects, both Java and Python have always been fast enough. Of course, I would prefer one language over the other for a specific problem in a certain context.
For IE 8 there is a simple pure css-based solution:
select:focus {
width: auto;
position: relative;
}
(You need to set the position property, if the selectbox is child of a container with fixed width.)
Unfortunately IE 7 and less do not support the :focus selector.
Visual Studio 2010 has the "Navigate To" command, which might be what you are looking for. The default keyboard shortcut is CTRL + ,. Here is an overview of some of the options for navigating in Visual Studio 2010.
Components cannot be further (From Angular 9) imported through general directory
you should add a specified component path like
import {} from '@angular/material';
import {} from '@angular/material/input';
I have always wanted Visual Studio to include an option to just collapse / expand the regions. I have the following macros which will do just that.
Imports EnvDTE
Imports System.Diagnostics
' Macros for improving keyboard support for "#region ... #endregion"
Public Module CollapseExpandRegions
' Expands all regions in the current document
Sub ExpandAllRegions()
Dim objSelection As TextSelection ' Our selection object
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.StartOfDocument() ' Shoot to the start of the document
' Loop through the document finding all instances of #region. This action has the side benefit
' of actually zooming us to the text in question when it is found and ALSO expanding it since it
' is an outline.
Do While objSelection.FindText("#region", vsFindOptions.vsFindOptionsMatchInHiddenText)
' This next command would be what we would normally do *IF* the find operation didn't do it for us.
'DTE.ExecuteCommand("Edit.ToggleOutliningExpansion")
Loop
objSelection.StartOfDocument() ' Shoot us back to the start of the document
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
' Collapses all regions in the current document
Sub CollapseAllRegions()
Dim objSelection As TextSelection ' Our selection object
ExpandAllRegions() ' Force the expansion of all regions
DTE.SuppressUI = True ' Disable UI while we do this
objSelection = DTE.ActiveDocument.Selection() ' Hook up to the ActiveDocument's selection
objSelection.EndOfDocument() ' Shoot to the end of the document
' Find the first occurence of #region from the end of the document to the start of the document. Note:
' Note: Once a #region is "collapsed" .FindText only sees it's "textual descriptor" unless
' vsFindOptions.vsFindOptionsMatchInHiddenText is specified. So when a #region "My Class" is collapsed,
' .FindText would subsequently see the text 'My Class' instead of '#region "My Class"' for the subsequent
' passes and skip any regions already collapsed.
Do While (objSelection.FindText("#region", vsFindOptions.vsFindOptionsBackwards))
DTE.ExecuteCommand("Edit.ToggleOutliningExpansion") ' Collapse this #region
'objSelection.EndOfDocument() ' Shoot back to the end of the document for
' another pass.
Loop
objSelection.StartOfDocument() ' All done, head back to the start of the doc
DTE.SuppressUI = False ' Reenable the UI
objSelection = Nothing ' Release our object
End Sub
End Module
EDIT: There is now a shortcut called Edit.ToggleOutliningExpansion (Ctrl+M, Ctrl+M) for doing just that.
Assuming your dataframe is mydf:
mydf$task <- factor(mydf$task, levels = c("up", "down", "left", "right", "front", "back"))
Edit — Thanks to Janus Troelsen's comment, I found a better solution:
indeterminate
See w3c reference guide. To make checkbox appear visually indeterminate set it to true:
element.indeterminate = true;
Here is Janus Troelsen's fiddle. Note, however, that:
The indeterminate
state cannot be set in the HTML markup, it can only be done via Javascript (see this JSfiddle test and this detailed article in CSS tricks)
This state doesn't change the value of the checkbox, it is only a visual cue that masks the input's real state.
Browser test: Worked for me in Chrome 22, Firefox 15, Opera 12 and back to IE7. Regarding mobile browsers, Android 2.0 browser and Safari mobile on iOS 3.1 don't have support for it.
Previous answer
Another alternative would be to play with the checkbox transparency for the "some selected" state (as Gmail
doesused to do in previous versions). It will require some javascript and a CSS class. Here I put a particular example that handles a list with checkable items and a checkbox that allows to select all/none of them. This checkbox shows a "some selected" state when some of the list items are selected.Given a checkbox with an ID
#select_all
and several checkboxes with a class.select_one
,The CSS class that fades the "select all" checkbox would be the following:
.some_selected { opacity: 0.5; filter: alpha(opacity=50); }
And the JS code that handles the tri-state of the select all checkbox is the following:
$('#select_all').change (function () { //Check/uncheck all the list's checkboxes $('.select_one').attr('checked', $(this).is(':checked')); //Remove the faded state $(this).removeClass('some_selected'); }); $('.select_one').change (function () { if ($('.select_one:checked').length == 0) $('#select_all').removeClass('some_selected').attr('checked', false); else if ($('.select_one:not(:checked)').length == 0) $('#select_all').removeClass('some_selected').attr('checked', true); else $('#select_all').addClass('some_selected').attr('checked', true); });
You can try it here: http://jsfiddle.net/98BMK/
Hope that helps!
You can use a regular expression to test for a match and capture the first two digits:
import re
for i in range(1000):
match = re.match(r'(1[56])', str(i))
if match:
print(i, 'begins with', match.group(1))
The regular expression (1[56])
matches a 1 followed by either a 5 or a 6 and stores the result in the first capturing group.
Output:
15 begins with 15
16 begins with 16
150 begins with 15
151 begins with 15
152 begins with 15
153 begins with 15
154 begins with 15
155 begins with 15
156 begins with 15
157 begins with 15
158 begins with 15
159 begins with 15
160 begins with 16
161 begins with 16
162 begins with 16
163 begins with 16
164 begins with 16
165 begins with 16
166 begins with 16
167 begins with 16
168 begins with 16
169 begins with 16
Setting the line height to the same as the height of the div will cause the text to center. Only works if there is one line. (such as a button).
Use a media query. Example: This is something im using the original size is 1.0vw but when it hits 1000 the letter gets too small so I scale it up
@media(max-width:600px){
body,input,textarea{
font-size:2.0vw !important;
}
}
This site I m working on is not responsive for >500px but you might need more. The pro,benefit for this solution is you keep font size scaling without having super mini letters and you can keep it js free.
You can also get all fragments like this:
For v4 fragmets
List<Fragment> allFragments = getSupportFragmentManager().getFragments();
For app.fragment
List<Fragment> allFragments = getFragmentManager().getFragments();
This discuss in great detail about shared libraries on linux and performance implications.
If you're using .Net 3.5, you can make cleaner code using:
foreach (Record item in LookupCollection.Intersect(LargeCollection))
{
//dostuff
}
I don't have .Net 3.5 here and so this is untested. It relies on an extension method. Not that LookupCollection.Intersect(LargeCollection)
is probably not the same as LargeCollection.Intersect(LookupCollection)
... the latter is probably much slower.
This assumes LookupCollection is a HashSet
$('.login').toggle(
function(){
$('#panel').animate({
height: "150",
padding:"20px 0",
backgroundColor:'#000000',
opacity:.8
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
},
function(){
$('#panel').animate({
height: "0",
padding:"0px 0",
opacity:.2
}, 500);
$('#otherdiv').animate({
//otherdiv properties here
}, 500);
});
You can create these easily using the floating ability of CSS, for example. I have created a small example on Jsfiddle over here, all the related css and html is also provided there.
.foo {_x000D_
float: left;_x000D_
width: 20px;_x000D_
height: 20px;_x000D_
margin: 5px;_x000D_
border: 1px solid rgba(0, 0, 0, .2);_x000D_
}_x000D_
_x000D_
.blue {_x000D_
background: #13b4ff;_x000D_
}_x000D_
_x000D_
.purple {_x000D_
background: #ab3fdd;_x000D_
}_x000D_
_x000D_
.wine {_x000D_
background: #ae163e;_x000D_
}
_x000D_
<div class="foo blue"></div>_x000D_
<div class="foo purple"></div>_x000D_
<div class="foo wine"></div>
_x000D_
What I ended up doing is create a new KeyContainer name based off of the current DateTime (DateTime.Now.Ticks.ToString()) whenever I need to create a new key and save the container name and public key to the database. Also, whenever I create a new key I would do the following:
public static string ConvertToNewKey(string oldPrivateKey)
{
// get the current container name from the database...
rsa.PersistKeyInCsp = false;
rsa.Clear();
rsa = null;
string privateKey = AssignNewKey(true); // create the new public key and container name and write them to the database...
// re-encrypt existing data to use the new keys and write to database...
return privateKey;
}
public static string AssignNewKey(bool ReturnPrivateKey){
string containerName = DateTime.Now.Ticks.ToString();
// create the new key...
// saves container name and public key to database...
// and returns Private Key XML.
}
before creating the new key.
try this code
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<Script>
$(document).ready(function(){
$("#postcontent").click(function(e) {
$.ajax({type:"POST",url:"add_new_post.php",data:$("#postcontent").serialize(),beforeSend:function(){
$(".post_submitting").show().html("<center><img src='images/loading.gif'/></center>");
},success:function(response){
//alert(response);
$("#return_update_msg").html(response);
$(".post_submitting").fadeOut(1000);
}
});
});
});
</script>
<form name="postcontent" id="postcontent">
<input name="postsubmit" type="button" id="postsubmit" value="POST"/>
<textarea id="postdata" name="postdata" placeholder="What's Up ?"></textarea>
</form>
First you have to ensure that there is a SMTP server listening on port 25.
To look whether you have the service, you can try using TELNET client, such as:
C:\> telnet localhost 25
(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.
$ telnet localhost 25
If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.
If you don't have the service, you can use these:
If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.
You can add line-height:51px
to #AlertDiv h1
if you know it's only ever going to be one line. Also add text-align:center
to #AlertDiv
.
#AlertDiv {
top:198px;
left:365px;
width:62px;
height:51px;
color:white;
position:absolute;
text-align:center;
background-color:black;
}
#AlertDiv h1 {
margin:auto;
line-height:51px;
vertical-align:middle;
}
The demo below also uses negative margins to keep the #AlertDiv
centered on both axis, even when the window is resized.
Demo: jsfiddle.net/KaXY5
Just import the R symbol from the root package
import rootpackage.R;
No rebuild, sync or another things...
Here is a solution using dplyr >= 0.5
.
library(dplyr)
set.seed(123)
df <- data.frame(
x = sample(0:1, 10, replace = T),
y = sample(0:1, 10, replace = T),
z = 1:10
)
> df %>% distinct(x, y, .keep_all = TRUE)
x y z
1 0 1 1
2 1 0 2
3 1 1 4
Newer versions: (from 8.4 - mentioned in release notes)
TABLE mytablename;
Longer but works on all versions:
SELECT * FROM mytablename;
You may wish to use \x
first if it's a wide table, for readability.
For long data:
SELECT * FROM mytable LIMIT 10;
or similar.
For wide data (big rows), in the psql
command line client, it's useful to use \x
to show the rows in key/value form instead of tabulated, e.g.
\x
SELECT * FROM mytable LIMIT 10;
Note that in all cases the semicolon at the end is important.
Based on ademar111190's answer, I have created this method the will pulse the background color of a view between any two colors:
private void animateBackground(View view, int colorFrom, int colorTo, int duration) {
ObjectAnimator objectAnimator = ObjectAnimator.ofObject(view, "backgroundColor", new ArgbEvaluator(), colorFrom, colorTo);
objectAnimator.setDuration(duration);
//objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
// Call this method again, but with the two colors switched around.
animateBackground(view, colorTo, colorFrom, duration);
}
@Override
public void onAnimationCancel(Animator animation) {
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
objectAnimator.start();
}
Another good alternative: Marvin
ASP.NET MVC doesn't work on events like ASP classic; there's no "button click event". Your controller methods correspond to requests sent to the server.
Instead, you need to wrap that form in code something like this:
@using (Html.BeginForm("SignUp", "Account", FormMethod.Post))
{
<!-- form goes here -->
<input type="submit" value="Sign Up" />
}
This will set up a form, and then your submit input will trigger a POST, which will hit your SignUp()
method, assuming your routes are properly set up (the defaults should work).
an other one without cloning:
I have an actual and a nominal element to swap:
$nominal.before('<div />')
$nb=$nominal.prev()
$nominal.insertAfter($actual)
$actual.insertAfter($nb)
$nb.remove()
then insert <div> before
and the remove
afterwards are only needed, if you cant ensure, that there is always an element befor (in my case it is)
Just delete the table and create a new table with a different name. Also Don't delete entire row for that table. It seems when entire row containing table row is delete it damages the DataBodyRange is damaged
Take a look at this video tutorial about Autolayout, they explain it carefully
Unless you get a better answer from a Scala user (which I'm not), here's my understanding.
It only appears as part of an expression beginning with for
, which states how to generate a new list from an existing list.
Something like:
var doubled = for (n <- original) yield n * 2
So there's one output item for each input (although I believe there's a way of dropping duplicates).
This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.
(If you're familiar with C#, it's closer to LINQ's select
operator than it is to yield return
).
RewriteEngine On
RewriteCond %{HTTP_HOST} ^yourdomain.com [NC]
RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]
check this perfect work
and If you want to set proxy for wget you should put these line in your Dockerfile
ENV http_proxy YOUR-PROXY-IP:PORT/
ENV https_proxy YOUR-PROXY-IP:PORT/
ENV all_proxy YOUR-PROXY-IP:PORT/
I was having the same problem - need my GridView control's AutogenerateColumns to be 'true', due to it being bound by a SQL datasource, and thus I needed to hide some columns which must not be displayed in the GridView control.
The way to accomplish this is to add some code to your GridView's '_RowDataBound' event, such as this (let's assume your GridView's ID is = 'MyGridView'):
protected void MyGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[<index_of_cell>].Visible = false;
}
}
That'll do the trick just fine ;-)
I've achieved this by separating them in different , e.g.:
<div class="table">
<div class="row">
<div class="col">TD</div>
<div class="col">TD</div>
<div class="col">TD</div>
<div class="col">TD</div>
<div class="col">TD</div>
</div>
</div>
<div class="table">
<div class="row">
<div class="col">TD</div>
</div>
</div>
or you can define different classes for each tables
<div class="table2">
<div class="row2">
<div class="col2">TD</div>
</div>
</div>
From the user point of view they behave identically.
Granted it doesn't solve all colspan/rowspan problems but it does answer my need of the time.
I use VS Code on my mac OS and GitLab for my project. I tried so many ways but it worked simply for me by resetting the remote origin of your project repository with the below command:
cd <local-project-repo-on-machine>
git remote set-url <remote-name> <remote-url>
for ex: git remote set-url origin https://<project-repository>.git
Hope it helps someone.
Array#splice()
is the way to go, unless you really want to avoid mutating the array. Given 2 arrays arr1
and arr2
, here's how you would insert the contents of arr2
into arr1
after the first element:
const arr1 = ['a', 'd', 'e'];_x000D_
const arr2 = ['b', 'c'];_x000D_
_x000D_
arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']_x000D_
_x000D_
console.log(arr1)
_x000D_
If you are concerned about mutating the array (for example, if using Immutable.js), you can instead use slice()
, not to be confused with splice()
with a 'p'
.
const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];
There is also other way to generate log file.
Before running ansible-playbook
run the following commands to enable logging:
Specify the location for the log file.
export ANSIBLE_LOG_PATH=~/ansible.log
Enable Debug
export ANSIBLE_DEBUG=True
To check that generated log file.
less $ANSIBLE_LOG_PATH
SELECT group, date, checks
FROM table
WHERE checks > 0
GROUP BY group HAVING date = max(date)
should work.
You can choose between the following two methods to set the text of an Entry
widget. For the examples, assume imported library import tkinter as tk
and root window root = tk.Tk()
.
Method A: Use delete
and insert
Widget Entry
provides methods delete
and insert
which can be used to set its text to a new value. First, you'll have to remove any former, old text from Entry
with delete
which needs the positions where to start and end the deletion. Since we want to remove the full old text, we start at 0
and end at wherever the end currently is. We can access that value via END
. Afterwards the Entry
is empty and we can insert new_text
at position 0
.
entry = tk.Entry(root)
new_text = "Example text"
entry.delete(0, tk.END)
entry.insert(0, new_text)
Method B: Use StringVar
You have to create a new StringVar
object called entry_text
in the example. Also, your Entry
widget has to be created with keyword argument textvariable
. Afterwards, every time you change entry_text
with set
, the text will automatically show up in the Entry
widget.
entry_text = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_text)
new_text = "Example text"
entry_text.set(new_text)
Complete working example which contains both methods to set the text via Button
:
This window
is generated by the following complete working example:
import tkinter as tk
def button_1_click():
# define new text (you can modify this to your needs!)
new_text = "Button 1 clicked!"
# delete content from position 0 to end
entry.delete(0, tk.END)
# insert new_text at position 0
entry.insert(0, new_text)
def button_2_click():
# define new text (you can modify this to your needs!)
new_text = "Button 2 clicked!"
# set connected text variable to new_text
entry_text.set(new_text)
root = tk.Tk()
entry_text = tk.StringVar()
entry = tk.Entry(root, textvariable=entry_text)
button_1 = tk.Button(root, text="Button 1", command=button_1_click)
button_2 = tk.Button(root, text="Button 2", command=button_2_click)
entry.pack(side=tk.TOP)
button_1.pack(side=tk.LEFT)
button_2.pack(side=tk.LEFT)
root.mainloop()
If you don't mind losing the history of your current shell terminal you could also do
bash -l
That would fork your shell and open up another child process of bash. The -l
parameter tells bash to run as a login shell, this is required because .bash_profile will not run as a non-login shell, for more info about this read here
If you want to completely replace the current shell you can also do:
exec bash -l
The above will not fork your current shell but replace it completely, so when you type exit
it will completely terminate, rather than dropping you to the previous shell.
Use the partial
argument of sort()
. For the second highest value:
n <- length(x)
sort(x,partial=n-1)[n-1]
You should check for ''
(empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0
will work just fine.
Another method could be to split the string by ":" and then pop off the end.
var newString = string.split(":").pop();
I use a bit of jQuery and old style javascript - less code
$($(this)[0].form)
This is a complete reference to the form containing the element
Maybe this can help: Advanced Python Scheduler
Here's a small piece of code from their documentation:
from apscheduler.schedulers.blocking import BlockingScheduler
def some_job():
print "Decorated job"
scheduler = BlockingScheduler()
scheduler.add_job(some_job, 'interval', hours=1)
scheduler.start()
I faced this problem where the following query doesn't work as expected:
select 1 where getdate()<>null
we expect it to show 1 because getdate() doesn't return null. I guess it has something to do with SQL failing to cast null as datetime and skipping the row! of course we know we should use IS or IS NOT keywords to compare a variable with null but when comparing two parameters it gets hard to handle the null situation. as a solution you can create your own compare function like the following:
CREATE FUNCTION [dbo].[fnCompareDates]
(
@DateTime1 datetime,
@DateTime2 datetime
)
RETURNS bit
AS
BEGIN
if (@DateTime1 is null and @DateTime2 is null) return 1;
if (@DateTime1 = @DateTime2) return 1;
return 0
END
and re writing the query like:
select 1 where dbo.fnCompareDates(getdate(),null)=0
If you really need to go this way, then this is what you can do. There are probably better ways of doing it, but this is all that I have at the moment. I did no database calls, I just used dummy data. Please modify the code to fit in with your scenario. I used jQuery
to populate the HTML table
.
In my controller I have the an action method called GetEmployees
that returns a JSON result
with all the employees. This is where you would call your repository to return the users from a database:
public ActionResult GetEmployees()
{
List<User> userList = new List<User>();
User user1 = new User
{
Id = 1,
FirstName = "First name 1",
LastName = "Last name 1"
};
User user2 = new User
{
Id = 2,
FirstName = "First name 2",
LastName = "Last name 2"
};
userList.Add(user1);
userList.Add(user2);
return Json(userList, JsonRequestBehavior.AllowGet);
}
The User class looks like this:
public class User
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
In your view you could have the following:
<div id="users">
<table></table>
</div>
<script>
$(document).ready(function () {
var url = '/Home/GetEmployees';
$.getJSON(url, function (data) {
$.each(data, function (key, val) {
var user = '<tr><td>' + val.FirstName + '</td></tr>';
$('#users table').append(user);
});
});
});
</script>
Regarding the code above: var url = '/Home/GetEmployees';
Home
is the controller and GetEmployees
is the action method that you defined above.
I hope this helps.
UPDATE:
This is how I would have done it..
I always create a view model class for a view. In this case I would have called it something like UserListViewModel
:
public class UserListViewModel
{
IEnumerable<User> Users { get; set; }
}
In my controller I would populate this Users list from a call to the database returning all the users:
public ActionResult List()
{
UserListViewModel viewModel = new UserListViewModel
{
Users = userRepository.GetAllUsers()
};
return View(viewModel);
}
And in my view I would have the following:
<table>
@foreach(User user in Model.Users)
{
<tr>
<td>First Name:</td>
<td>user.FirstName</td>
</tr>
}
</table>
It is better to define our own process to for upgrade.
Android & iOS : If latest app version available then it will show alert as “Latest version available with more features, To upgrade click on upgrade button” (Alert with “Upgarde” and “No. Thanks” button.) Then app will redirect to playstore/Appstore and it will open latest version.
--- we can do upgrade compulsory or optionally.
Before Upgrade process please make sure that you handled proper db migration process if there is any db schema change.
Here's how you can use it:
#ifndef NEW_FUN_H_
#define NEW_FUN_H_
#include <stdio.h>
typedef int speed;
speed fun(int x);
enum fp {
f1, f2, f3, f4, f5
};
void F1();
void F2();
void F3();
void F4();
void F5();
#endif
#include "New_Fun.h"
speed fun(int x)
{
int Vel;
Vel = x;
return Vel;
}
void F1()
{
printf("From F1\n");
}
void F2()
{
printf("From F2\n");
}
void F3()
{
printf("From F3\n");
}
void F4()
{
printf("From F4\n");
}
void F5()
{
printf("From F5\n");
}
#include <stdio.h>
#include "New_Fun.h"
int main()
{
int (*F_P)(int y);
void (*F_A[5])() = { F1, F2, F3, F4, F5 }; // if it is int the pointer incompatible is bound to happen
int xyz, i;
printf("Hello Function Pointer!\n");
F_P = fun;
xyz = F_P(5);
printf("The Value is %d\n", xyz);
//(*F_A[5]) = { F1, F2, F3, F4, F5 };
for (i = 0; i < 5; i++)
{
F_A[i]();
}
printf("\n\n");
F_A[f1]();
F_A[f2]();
F_A[f3]();
F_A[f4]();
return 0;
}
I hope this helps in understanding Function Pointer.
Here is how you can do it with for-in
loop.
var children = element.childNodes;
for(child in children){
console.log(children[child]);
}
Implementation is up to compiler developers.
If your question is "what will happen with such declaration" - compiler will set first array element to the value you've provided (0) and all others will be set to zero because it is a default value for omitted array elements.
You Can Remove Char using below Line ,
:- First check That String has enough char to remove ,like
string temp="Hello Stack overflow";
if(temp.Length>10)
{
string textIWant = temp.Remove(0, 10);
}
outgoing url in mvc generated based on the current routing schema.
because your Information action method require id parameter, and your route collection has id of your current requested url(/Admin/Information/5), id parameter automatically gotten from existing route collection values.
to solve this problem you should use UrlParameter.Optional:
<a href="@Url.Action("Information", "Admin", new { id = UrlParameter.Optional })">Add an Admin</a>
If you only want to check if an option is selected, then you do not need to iterate through all options. Just do
if($('#mySelectBox').val()){
// do something
} else {
// do something else
}
Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null
Use all()
method - it's designed to return items of Collection:
/**
* Get all of the items in the collection.
*
* @return array
*/
public function all()
{
return $this->items;
}
Doing maven update or reimporting the project did not help. @Sydney's answer is right; in addition I have to recreate the project in different workspace as said in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
The following approach can be used to get any path of a pathname:
some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))
Output:
c
b
a
For current ActiveRecord (4.2.4+) there is a method to_hash
on the Result
object that returns an array of hashes. You can then map over it and convert to symbolized hashes:
# Get an array of hashes representing the result (column => value):
result.to_hash
# => [{"id" => 1, "title" => "title_1", "body" => "body_1"},
{"id" => 2, "title" => "title_2", "body" => "body_2"},
...
]
result.to_hash.map(&:symbolize_keys)
# => [{:id => 1, :title => "title_1", :body => "body_1"},
{:id => 2, :title => "title_2", :body => "body_2"},
...
]
The documentation says that get
takes in an optional cookies
argument allowing you to specify cookies to use:
from the docs:
>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)
>>> r.text
'{"cookies": {"cookies_are": "working"}}'
http://docs.python-requests.org/en/latest/user/quickstart/#cookies
Counter from 1 to 1000:
select tt.row from
(
SELECT cast( concat(t.0,t2.0,t3.0) + 1 As UNSIGNED) as 'row' FROM
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t,
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
(select 0 union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3
) tt
order by tt.row
Credits: answer, comment by Seth McCauley below the answer.
Turn on grep
's line buffering mode when using BSD grep (FreeBSD, Mac OS X etc.)
tail -f file | grep --line-buffered my_pattern
It looks like a while ago --line-buffered
didn't matter for GNU grep (used on pretty much any Linux) as it flushed by default (YMMV for other Unix-likes such as SmartOS, AIX or QNX). However, as of November 2020, --line-buffered
is needed (at least with GNU grep 3.5 in openSUSE, but it seems generally needed based on comments below).
The following is taken from Mozilla Firefox's internal html.css:
sup {
vertical-align: super;
font-size: smaller;
line-height: normal;
}
So, in your case it would be something, like:
.superscript {
vertical-align: super;
font-size: smaller;
line-height: normal;
}
If taskkill /F /T /PID <pid>
does not work.
Try opening your terminal elevated using Run as Administrator
.
Search cmd
in your windows menu, and right click Run as Administrator
,
then run the command again. This worked for me.
For me, this was due to the user PATH environment variable, which didn't seem to work even though the user was correct, so I needed to put the entire executable path into the program field.
Use gist.github.com. There is a multi-language support(java, c, c++, c#, vb, haskell, ruby, javascript, lua, HTML, SQL, Tcl, Perl, JSON, groovy...)
Here is a sample "Generate LiquiBase changeLogs using Groovy"
On small device : 4 columns x 3 (= 12) ==> col-sm-3
On extra small : 3 columns x 4 (= 12) ==> col-xs-4
<footer class="row">
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 1</li>
<li>Text 2</li>
<li>Text 3</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 4</li>
<li>Text 5</li>
<li>Text 6</li>
</ul>
</nav>
<nav class="col-xs-4 col-sm-3">
<ul class="list-unstyled">
<li>Text 7</li>
<li>Text 8</li>
<li>Text 9</li>
</ul>
</nav>
<nav class="hidden-xs col-sm-3">
<ul class="list-unstyled">
<li>Text 10</li>
<li>Text 11</li>
<li>Text 12</li>
</ul>
</nav>
</footer>
As you say, hidden-xs is not enough, you have to combine xs and sm class.
Here is links to the official doc about available responsive classes and about the grid system.
Have in head :
You can instruct tesseract to use only digits, and if that is not accurate enough then best chance of getting better results is to go trough training process: http://www.resolveradiologic.com/blog/2013/01/15/training-tesseract/
in Angular 2.x.x , 4, 5 ...
<form #loginForm="ngForm">
<input type="text" required>
<button type="submit" [disabled]="loginForm.form.invalid">Submit</button>
</form>
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
The suggested answer by Loïc MICHEL blindly writes a new value to the TrustedHosts entry.
I believe, a better way would be to first query TrustedHosts.
As Jeffery Hicks posted in 2010, first query the TrustedHosts entry:
PS C:\> $current=(get-item WSMan:\localhost\Client\TrustedHosts).value
PS C:\> $current+=",testdsk23,alpha123"
PS C:\> set-item WSMan:\localhost\Client\TrustedHosts –value $current
It's an old question, however might be useful for someone like me.
lodash
has _.inRange()
function https://lodash.com/docs/4.17.4#inRange
Example:
_.inRange(3, 2, 4);
// => true
Please note that this method utilizes the Lodash
utility library, and requires access to an installed version of Lodash.
I have been toying with this idea too, but I was trying to achieve a slightly different behavior. My idea was to make a list which inherits itself, thus creating a data structure that by nature allows you to embed lists within lists within lists within lists...infinitely!
Implementation
//InfiniteList<T> is a list of itself...
public class InfiniteList<T> : List<InfiniteList<T>>
{
//This is necessary to allow your lists to store values (of type T).
public T Value { set; get; }
}
T is a generic type parameter. It is there to ensure type safety in your class. When you create an instance of InfiniteList, you replace T with the type you want your list to be populated with, or in this instance, the type of the Value property.
Example
//The InfiniteList.Value property will be of type string
InfiniteList<string> list = new InfiniteList<string>();
A "working" example of this, where T is in itself, a List of type string!
//Create an instance of InfiniteList where T is List<string>
InfiniteList<List<string>> list = new InfiniteList<List<string>>();
//Add a new instance of InfiniteList<List<string>> to "list" instance.
list.Add(new InfiniteList<List<string>>());
//access the first element of "list". Access the Value property, and add a new string to it.
list[0].Value.Add("Hello World");
If I recall correctly Twig doesn't support ||
and &&
operators, but requires or
and and
to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.
{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}
Expressions
Expressions can be used in {% blocks %} and ${ expressions }.
Operator Description
== Does the left expression equal the right expression?
+ Convert both arguments into a number and add them.
- Convert both arguments into a number and substract them.
* Convert both arguments into a number and multiply them.
/ Convert both arguments into a number and divide them.
% Convert both arguments into a number and calculate the rest of the integer division.
~ Convert both arguments into a string and concatenate them.
or True if the left or the right expression is true.
and True if the left and the right expression is true.
not Negate the expression.
For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:
{% if (foo and bar) or (fizz and (foo + bar == 3)) %}
Are there other ways?
Negative margins were also used for horizontal (and vertical!) centering but there are quite a few drawbacks when you resize the window browser: no window slider; the content can't be seen anymore if the size of the window browser is too small.
No surprise as it uses absolute positioning, a beast never completely tamed!
Example: http://bluerobot.com/web/css/center2.html
So that was only FYI as you asked for it, margin: 0 auto;
is a better solution.
For non-printing characters, you can do the following:
Here are some lines of code you can use to reload the page using jQuery.
It uses the jQuery wrapper and extracts the native dom element.
Use this if you just want a jQuery feeling on your code and you don't care about speed/performance of the code.
Just pick from 1 to 10 that suits your needs or add some more based on the pattern and answers before this.
<script>
$(location)[0].reload(); //1
$(location).get(0).reload(); //2
$(window)[0].location.reload(); //3
$(window).get(0).location.reload(); //4
$(window)[0].$(location)[0].reload(); //5
$(window).get(0).$(location)[0].reload(); //6
$(window)[0].$(location).get(0).reload(); //7
$(window).get(0).$(location).get(0).reload(); //8
$(location)[0].href = ''; //9
$(location).get(0).href = ''; //10
//... and many other more just follow the pattern.
</script>
Just wanted to add some info that, we can check this info whether git pull
automatically refers to any branch or not.
If you run the command, git remote show origin
, (assuming origin as the short name for remote), git shows this info, whether any default reference exists for git pull
or not.
Below is a sample output.(taken from git documentation).
$ git remote show origin
* remote origin
Fetch URL: https://github.com/schacon/ticgit
Push URL: https://github.com/schacon/ticgit
HEAD branch: master
Remote branches:
master tracked
dev-branch tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (up to date)
Please note the part where it shows, Local branch configured for git pull.
In this case, git pull
will refer to git pull origin master
Initially, if you have cloned the repository, using git clone, these things are automatically taken care of. But if you have added a remote manually using git remote add, these are missing from the git config. If that is the case, then the part where it shows "Local branch configured for 'git pull':", would be missing from the output of git remote show origin
.
The next steps to follow if no configuration exists for git pull
, have already been explained by other answers.
You can enter these module class suffixes for any module to better control where it will show or be hidden.
.visible-phone
.visible-tablet
.visible-desktop
.hidden-phone
.hidden-tablet
.hidden-desktop
http://twitter.github.com/bootstrap/scaffolding.html scroll to bottom
Do you want to return a full row? Does the default row need to have default values or can it be an empty row? Do you want the default row to have the same column structure as the table in question?
Depending on your requirements, you might do something like this:
1) run the query and put results in a temp table (or table variable) 2) check to see if the temp table has results 3) if not, return an empty row by performing a select statement similar to this (in SQL Server):
select '' as columnA, '' as columnB, '' as columnC from #tempTable
Where columnA, columnB and columnC are your actual column names.
SerialPort (RS-232 Serial COM Port) in C# .NET
This article explains how to use the SerialPort
class in .NET to read and write data, determine what serial ports are available on your machine, and how to send files. It even covers the pin assignments on the port itself.
Example Code:
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace SerialPortExample
{
class SerialPortProgram
{
// Create the serial port with basic settings
private SerialPort port = new SerialPort("COM1",
9600, Parity.None, 8, StopBits.One);
[STAThread]
static void Main(string[] args)
{
// Instatiate this class
new SerialPortProgram();
}
private SerialPortProgram()
{
Console.WriteLine("Incoming Data:");
// Attach a method to be called when there
// is data waiting in the port's buffer
port.DataReceived += new
SerialDataReceivedEventHandler(port_DataReceived);
// Begin communications
port.Open();
// Enter an application loop to keep this thread alive
Application.Run();
}
private void port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
// Show all the incoming data in the port's buffer
Console.WriteLine(port.ReadExisting());
}
}
}
According to the Python os module documentation os.popen has been deprecated since Python 2.6.
I think the solution for modern Python is to use check_output() from the subprocess module.
From the subprocess Python documentation:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) Run command with arguments and return its output as a byte string.
If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
If you run through the following code in Python 2.7 (or later):
import subprocess
try:
print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
print "Ping stdout output:\n", e.output
You should see an output that looks something like this:
Ping stdout output:
Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
The e.output string can be parsed to suit the OPs needs.
If you want the returncode or other attributes, they are in CalledProccessError as can be seen by stepping through with pdb
(Pdb)!dir(e)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
'__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__',
'__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']
Other answers here are correct: is
is used for identity comparison, while ==
is used for equality comparison. Since what you care about is equality (the two strings should contain the same characters), in this case the is
operator is simply wrong and you should be using ==
instead.
The reason is
works interactively is that (most) string literals are interned by default. From Wikipedia:
Interned strings speed up string comparisons, which are sometimes a performance bottleneck in applications (such as compilers and dynamic programming language runtimes) that rely heavily on hash tables with string keys. Without interning, checking that two different strings are equal involves examining every character of both strings. This is slow for several reasons: it is inherently O(n) in the length of the strings; it typically requires reads from several regions of memory, which take time; and the reads fills up the processor cache, meaning there is less cache available for other needs. With interned strings, a simple object identity test suffices after the original intern operation; this is typically implemented as a pointer equality test, normally just a single machine instruction with no memory reference at all.
So, when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)
Since in your interactive session both strings are actually stored in the same memory location, they have the same identity, so the is
operator works as expected. But if you construct a string by some other method (even if that string contains exactly the same characters), then the string may be equal, but it is not the same string -- that is, it has a different identity, because it is stored in a different place in memory.
A function call needs to be performed with objects. You are doing the equivalent of this:
// function declaration/definition
void foo(int) {}
// function call
foo(int); // wat!??
i.e. passing a type where an object is required. This makes no sense in C or C++. You need to be doing
int i = 42;
foo(i);
or
foo(42);
I'd do something like:
private IEnumerable<string> DoWork(IEnumerable<string> data)
{
List<string> newData = new List<string>();
foreach(string item in data)
{
newData.Add(item + "roxxors");
}
return newData;
}
Simple stuff :)
Yes, you can input multiple items from cin
, using exactly the syntax you describe. The result is essentially identical to:
cin >> a;
cin >> b;
cin >> c;
This is due to a technique called "operator chaining".
Each call to operator>>(istream&, T)
(where T
is some arbitrary type) returns a reference to its first argument. So cin >> a
returns cin
, which can be used as (cin>>a)>>b
and so forth.
Note that each call to operator>>(istream&, T)
first consumes all whitespace characters, then as many characters as is required to satisfy the input operation, up to (but not including) the first next whitespace character, invalid character, or EOF.
You can use the Invoke-Sqlcmd
cmdlet
Invoke-Sqlcmd -Query "SELECT GETDATE() AS TimeOfQuery;" -ServerInstance "MyComputer\MyInstance"