Very simply, a delegate provides functionality for how a function pointer SHOULD work. There are many limitations of function pointers in C++. A delegate uses some behind-the-scenes template nastyness to create a template-class function-pointer-type-thing that works in the way you might want it to.
ie - you can set them to point at a given function and you can pass them around and call them whenever and wherever you like.
There are some very good examples here:
Very easy step by step (100% working and tested)
step1: Create method on first view controller
func updateProcessStatus(isCompleted : Bool){
if isCompleted{
self.labelStatus.text = "Process is completed"
}else{
self.labelStatus.text = "Process is in progress"
}
}
step2: Set delegate while push to second view controller
@IBAction func buttonAction(_ sender: Any) {
let secondViewController = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController") as! secondViewController
secondViewController.delegate = self
self.navigationController?.pushViewController(secondViewController, animated: true)
}
step3: set delegate like
class ViewController: UIViewController,ProcessStatusDelegate {
step4: Create protocol
protocol ProcessStatusDelegate:NSObjectProtocol{
func updateProcessStatus(isCompleted : Bool)
}
step5: take a variable
var delegate:ProcessStatusDelegate?
step6: While go back to previous view controller call delegate method so first view controller notify with data
@IBAction func buttonActionBack(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: true)
self.navigationController?.popViewController(animated: true)
}
@IBAction func buttonProgress(_ sender: Any) {
delegate?.updateProcessStatus(isCompleted: false)
self.navigationController?.popViewController(animated: true)
}
There is one way to implement multiple interface.
Just extend one interface from another or create interface that extends predefined interface Ex:
public interface PlnRow_CallBack extends OnDateSetListener {
public void Plan_Removed();
public BaseDB getDB();
}
now we have interface that extends another interface to use in out class just use this new interface who implements two or more interfaces
public class Calculator extends FragmentActivity implements PlnRow_CallBack {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
}
@Override
public void Plan_Removed() {
}
@Override
public BaseDB getDB() {
}
}
hope this helps
json_decode will return the same array that was originally encoded. For instanse, if you
$array = json_decode($json, true);
echo $array['countryId'];
OR
$obj= json_decode($json);
echo $obj->countryId;
These both will echo 84. I think json_encode and json_decode function names are self-explanatory...
The easiest way to do this, with excellent performance and compatibility with both old and new browsers, is to include either Lo-Dash or Underscore in your page.
Then you can use either _.size(object)
or _.keys(object).length
For your obj.Data
, you could test this with:
console.log( _.size(obj.Data) );
or:
console.log( _.keys(obj.Data).length );
Lo-Dash and Underscore are both excellent libraries; you would find either one very useful in your code. (They are rather similar to each other; Lo-Dash is a newer version with some advantanges.)
Alternatively, you could include this function in your code, which simply loops through the object's properties and counts them:
function ObjectLength( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
};
You can test this with:
console.log( ObjectLength(obj.Data) );
That code is not as fast as it could be in modern browsers, though. For a version that's much faster in modern browsers and still works in old ones, you can use:
function ObjectLength_Modern( object ) {
return Object.keys(object).length;
}
function ObjectLength_Legacy( object ) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}
var ObjectLength =
Object.keys ? ObjectLength_Modern : ObjectLength_Legacy;
and as before, test it with:
console.log( ObjectLength(obj.Data) );
This code uses Object.keys(object).length
in modern browsers and falls back to counting in a loop for old browsers.
But if you're going to all this work, I would recommend using Lo-Dash or Underscore instead and get all the benefits those libraries offer.
I set up a jsPerf that compares the speed of these various approaches. Please run it in any browsers you have handy to add to the tests.
Thanks to Barmar for suggesting Object.keys
for newer browsers in his answer.
I believe you are looking for the query functions, isBefore
, isSame
, and isAfter
.
But it's a bit difficult to tell exactly what you're attempting. Perhaps you are just looking to get the difference between the input time and the current time? If so, consider the difference function, diff
. For example:
moment().diff(date_time, 'minutes')
A few other things:
There's an error in the first line:
var date_time = 2013-03-24 + 'T' + 10:15:20:12 + 'Z'
That's not going to work. I think you meant:
var date_time = '2013-03-24' + 'T' + '10:15:20:12' + 'Z';
Of course, you might as well:
var date_time = '2013-03-24T10:15:20:12Z';
You're using: .tz('UTC')
incorrectly. .tz
belongs to moment-timezone. You don't need to use that unless you're working with other time zones, like America/Los_Angeles
.
If you want to parse a value as UTC, then use:
moment.utc(theStringToParse)
Or, if you want to parse a local value and convert it to UTC, then use:
moment(theStringToParse).utc()
Or perhaps you don't need it at all. Just because the input value is in UTC, doesn't mean you have to work in UTC throughout your function.
You seem to be getting the "now" instance by moment(new Date())
. You can instead just use moment()
.
Based on your edit, I think you can just do this:
var date_time = req.body.date + 'T' + req.body.time + 'Z';
var isafter = moment(date_time).isAfter('2014-03-24T01:14:00Z');
Or, if you would like to ensure that your fields are validated to be in the correct format:
var m = moment.utc(req.body.date + ' ' + req.body.time, "YYYY-MM-DD HH:mm:ss");
var isvalid = m.isValid();
var isafter = m.isAfter('2014-03-24T01:14:00Z');
You can use this method to create hidden text field with/without form. If you need form just pass form with object status = true
.
You can also add multiple hidden fields. Use this way:
CustomizePPT.setHiddenFields(
{
"hidden" :
{
'fieldinFORM' : 'thisdata201' ,
'fieldinFORM2' : 'this3' //multiple hidden fields
.
.
.
.
.
'nNoOfFields' : 'nthData'
},
"form" :
{
"status" : "true",
"formID" : "form3"
}
} );
var CustomizePPT = new Object();_x000D_
CustomizePPT.setHiddenFields = function(){ _x000D_
var request = [];_x000D_
var container = '';_x000D_
console.log(arguments);_x000D_
request = arguments[0].hidden;_x000D_
console.log(arguments[0].hasOwnProperty('form'));_x000D_
if(arguments[0].hasOwnProperty('form') == true)_x000D_
{_x000D_
if(arguments[0].form.status == 'true'){_x000D_
var parent = document.getElementById("container");_x000D_
container = document.createElement('form');_x000D_
parent.appendChild(container);_x000D_
Object.assign(container, {'id':arguments[0].form.formID});_x000D_
}_x000D_
}_x000D_
else{_x000D_
container = document.getElementById("container");_x000D_
}_x000D_
_x000D_
//var container = document.getElementById("container");_x000D_
Object.keys(request).forEach(function(elem)_x000D_
{_x000D_
if($('#'+elem).length <= 0){_x000D_
console.log("Hidden Field created");_x000D_
var input = document.createElement('input');_x000D_
Object.assign(input, {"type" : "text", "id" : elem, "value" : request[elem]});_x000D_
container.appendChild(input);_x000D_
}else{_x000D_
console.log("Hidden Field Exists and value is below" );_x000D_
$('#'+elem).val(request[elem]);_x000D_
}_x000D_
});_x000D_
};_x000D_
_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'fieldinFORM' : 'thisdata201' , 'fieldinFORM2' : 'this3'}, "form" : {"status" : "true","formID" : "form3"} } );_x000D_
CustomizePPT.setHiddenFields( { "hidden" : {'withoutFORM' : 'thisdata201','withoutFORM2' : 'this2'}});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
_x000D_
</div>
_x000D_
In VB:
from m in MyTable
take 10
select m.Foo
This assumes that MyTable implements IQueryable. You may have to access that through a DataContext or some other provider.
It also assumes that Foo is a column in MyTable that gets mapped to a property name.
See http://blogs.msdn.com/vbteam/archive/2008/01/08/converting-sql-to-linq-part-7-union-top-subqueries-bill-horst.aspx for more detail.
In Python 2.7.1, you may calculate standard deviation using numpy.std()
for:
numpy.std()
with no additional arguments besides to your data list.numpy.std(< your-list >, ddof=1)
The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.
It calculates sample std rather than population std.
Another way:
>>> [i for i in range(len(a)) if a[i] > 2]
[2, 5]
In general, remember that while find
is a ready-cooked function, list comprehensions are a general, and thus very powerful solution. Nothing prevents you from writing a find
function in Python and use it later as you wish. I.e.:
>>> def find_indices(lst, condition):
... return [i for i, elem in enumerate(lst) if condition(elem)]
...
>>> find_indices(a, lambda e: e > 2)
[2, 5]
Note that I'm using lists here to mimic Matlab. It would be more Pythonic to use generators and iterators.
It looks like you're trying to run it on a version of ASP.NET which is running CLR v2. It's hard to know exactly what's going on without more information about how you've deployed it, what version of IIS you're running etc (and to be frank I wouldn't be very much help at that point anyway, though others would). But basically, check your IIS and ASP.NET set-up, and make sure that everything is running v4. Check your application pool configuration, etc.
I suggest to do 2 things:
here is an example, where the length of the array is changed during execution of the loop
import java.util.ArrayList;
public class VariableArrayLengthLoop {
public static void main(String[] args) {
//create new ArrayList
ArrayList<String> aListFruits = new ArrayList<String>();
//add objects to ArrayList
aListFruits.add("Apple");
aListFruits.add("Banana");
aListFruits.add("Orange");
aListFruits.add("Strawberry");
//iterate ArrayList using for loop
for(int i = 0; i < aListFruits.size(); i++){
System.out.println( aListFruits.get(i) + " i = "+i );
if ( i == 2 ) {
aListFruits.add("Pineapple");
System.out.println( "added now a Fruit to the List ");
}
}
}
}
The Main
method is static inside the Program
class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits()
method static as well.
By default link color is blue and the visited color is purple. Also, the text-decoration is underlined and the color is blue. If you want to keep the same color for visited, hover and focus then follow below code-
For example color is: #000
a:visited, a:hover, a:focus {
text-decoration: none;
color: #000;
}
If you want to use a different color for hover, visited and focus. For example Hover color: red visited color: green and focus color: yellow then follow below code
a:hover {
color: red;
}
a:visited {
color: green;
}
a:focus {
color: yellow;
}
NB: good practice is to use color code.
You installed Python and added it to PATH. You've checked it too(like 64-bit etc). Everything should work but it is not.
what you didn't do is a
terminal/cmd restart
restart your terminal and everything would work like a charm.
I Hope, it helped/might help others.
Use the splice method.
(At least I assume that is the answer, you say you have an object, but the code you give just creates two variables, and there is no sign of how the Array is created)
In Simple words, tabindex
is used to focus on elements.
Syntax: tabindex="numeric_value"
This numeric_value
is the weight of element. Lower value will be accessed first.
In Java 8, you can do it in a simpler and clean way :
if ("POST".equalsIgnoreCase(request.getMethod()))
{
test = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}
This should do the trick:
import pandas as pd
import pymysql
pymysql.install_as_MySQLdb()
from sqlalchemy import create_engine
# Create engine
engine = create_engine('mysql://USER_NAME_HERE:PASS_HERE@HOST_ADRESS_HERE/DB_NAME_HERE')
# Create the connection and close it(whether successed of failed)
with engine.begin() as connection:
df.to_sql(name='INSERT_TABLE_NAME_HERE/INSERT_NEW_TABLE_NAME', con=connection, if_exists='append', index=False)
As simple as joining lists in python itself.
ansible -m debug -a msg="{{ '-'.join(('list', 'joined', 'together')) }}" localhost
localhost | SUCCESS => {
"msg": "list-joined-together" }
Works the same way using variables:
ansible -m debug -a msg="{{ '-'.join((var1, var2, var3)) }}" localhost
Use jq -s add
:
$ echo '{"a":"foo","b":"bar"} {"c":"baz","a":0}' | jq -s add
{
"a": 0,
"b": "bar",
"c": "baz"
}
This reads all JSON texts from stdin into an array (jq -s
does that) then it "reduces" them.
(add
is defined as def add: reduce .[] as $x (null; . + $x);
, which iterates over the input array's/object's values and adds them. Object addition == merge.)
If you just need a very simple call, you can use URL directly:
import java.net.URL;
new URL("http://wheredatapp.com").openStream();
I have users who have not been completing all required data.
<cfset unloadCheck=0>//a ColdFusion precheck in my page generation to see if unload check is needed
var erMsg="";
$(document).ready(function(){
<cfif q.myData eq "">
<cfset unloadCheck=1>
$("#myInput").change(function(){
verify(); //function elsewhere that checks all fields and populates erMsg with error messages for any fail(s)
if(erMsg=="") window.onbeforeunload = null; //all OK so let them pass
else window.onbeforeunload = confirmExit(); //borrowed from Jantimon above;
});
});
<cfif unloadCheck><!--- if any are outstanding, set the error message and the unload alert --->
verify();
window.onbeforeunload = confirmExit;
function confirmExit() {return "Data is incomplete for this Case:"+erMsg;}
</cfif>
Similarly to scatter plot you can also use normal plot with circle line style. Using markersize
parameter you can adjust radius of a circle:
import matplotlib.pyplot as plt
plt.plot(200, 2, 'o', markersize=7)
I am sharing our nodejs implementation of the solution as implemented by @Raymond Hettinger.
var crypto = require('crypto');
var s = 'she sells sea shells by the sea shore';
console.log(BigInt('0x' + crypto.createHash('sha1').update(s).digest('hex'))%(10n ** 8n));
That really depends on a specific case -- both options are available for a reason. IMO it boils down to three cases:
Make sure you remove the .git repository if you are trying to check thing out into the current directory.
rm -rf .git
then git clone https://github.com/symfony/symfony-sandbox.git
The error message proved to be true as Apache Ant isn't in the path of Mac OS X Mavericks anymore.
Bulletproof solution:
Download and install Homebrew by executing following command in terminal:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Install Apache Ant via Homebrew by executing
brew install ant
Run the PhoneGap build again and it should successfully compile and install your Android app.
This is a pretty old post, but none of the answers here really answered the question in my opinion, so I hope my post will help people!
I found this solution on another question that works really well for me:
mysql -Nse 'show tables' DB_NAME | while read table; do mysql -e "SET FOREIGN_KEY_CHECKS=0; truncate table \`$table\`" DB_NAME; done
That will actually empty all your tables in the database DB_NAME
, and not only display the TRUNCATE
command line.
Hope this helps!
Check out php.ini the value set for session.gc_maxlifetime is the ID lifetime in seconds.
I believe the default is 1440 seconds (24 mins)
http://www.php.net/manual/en/session.configuration.php
Edit: As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to implement session lifetimes is available here:
Shift+J removes the line change character from the current line, so by pressing "J" at any place in the line you can combine the current line and the next line in the way you want.
In your image you've putting the padding outside the child. This is not the case. Padding adds to the width of an element, so if you add padding and give it a width of 100% it will have a width of 100% + padding. In order to what you are wanting you just need to either add padding to the parent div, or add a margin to the inner div. Because divs are block-level elements they will automatically expand to the width of their parent.
Change your getTaskCount Method to this:
public int getTaskCount(long tasklist_id){
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor= db.rawQuery("SELECT COUNT (*) FROM " + TABLE_TODOTASK + " WHERE " + KEY_TASK_TASKLISTID + "=?", new String[] { String.valueOf(tasklist_id) });
cursor.moveToFirst();
int count= cursor.getInt(0);
cursor.close();
return count;
}
Then, update the click handler accordingly:
public void onItemClick(AdapterView<?> arg0, android.view.View v, int position, long id) {
db = new TodoTask_Database(getApplicationContext());
// Get task list id
int tasklistid = adapter.getItem(position).getTaskListId();
if(db.getTaskCount(tasklistid) > 0) {
System.out.println(c);
Intent taskListID = new Intent(getApplicationContext(), AddTask_List.class);
taskListID.putExtra("TaskList_ID", tasklistid);
startActivity(taskListID);
} else {
Intent addTask = new Intent(getApplicationContext(), Add_Task.class);
startActivity(addTask);
}
}
“Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.
reference https://docs.python.org/2/tutorial/classes.html#private-variables-and-class-local-references
umount -l
At the time of writing, the top-voted answer recommends using umount -l
.
umount -l
is dangerous or at best unsafe. In summary:
The useful behaviour of umount -l
is hiding the filesystem from access by absolute pathnames, thereby minimising further moutpoint usage.
This same behaviour can be achieved by mounting an empty directory with permissions 000
over the directory to be unmounted.
Then any new accesses to filenames in the below the mountpoint will hit the newly overlaid directory with zero permissions - new blockers to the unmount are thereby prevented.
remount,ro
The major unmount achievement to be unlocked is the read-only remount. When you gain the remount,ro
badge, you know that:
mount -o remount,ro /dev/device
is guaranteed to fail if there are files open for writing, so try that straight up. You may be feeling lucky, punk!
If you are unlucky, focus only on processes with files open for writing:
lsof +f -- /dev/<devicename> | awk 'NR==1 || $4~/[0-9]+[uw -]/'
You should then be able to remount the device read-only and ensure a consistent state.
If you can't remount read-only at this point, investigate some of the other possible causes listed here.
Read-only re-mount achievement unlocked ?
Congratulations, your data on the mountpoint is now consistent and protected from future writing.
fuser
is inferior to lsof
Why not use use fuser
earlier? Well, you could have, but fuser
operates upon a directory, not a device, so if you wanted to remove the mountpoint from the file name space and still use fuser
, you'd need to:
mount -o bind /media/hdd /mnt
to another locationHere's how:
null_dir=$(sudo mktemp --directory --tmpdir empty.XXXXX")
sudo chmod 000 "$null_dir"
# A request to remount,ro will fail on a `-o bind,ro` duplicate if there are
# still files open for writing on the original as each mounted instance is
# checked. https://unix.stackexchange.com/a/386570/143394
# So, avoid remount, and bind mount instead:
sudo mount -o bind,ro "$original" "$original_duplicate"
# Don't propagate/mirror the empty directory just about hide the original
sudo mount --make-private "$original_duplicate"
# Hide the original mountpoint
sudo mount -o bind,ro "$null_dir" "$original"
You'd then have:
fuser
.This is more convoluted[1], but allows you to use:
fuser -vmMkiw <mountpoint>
which will interactively ask to kill the processes with files open for writing. Of course, you could do this without hiding the mount point at all, but the above mimicks umount -l
, without any of the dangers.
The -w
switch restricts to writing processes, and the -i
is interactive, so after a read-only remount, if you're it a hurry you could then use:
fuser -vmMk <mountpoint>
to kill all remaining processes with files open under the mountpoint.
Hopefully at this point, you can unmount the device. (You'll need to run umount
on the mountpoint twice if you've bind mounted a mode 000
directory on top.)
Or use:
fuser -vmMki <mountpoint>
to interactively kill the remaining read-only processes blocking the unmount.
target is busy
!Open files aren't the only unmount blocker. See here and here for other causes and their remedies.
Even if you've got some lurking gremlin which is preventing you from fully unmounting the device, you have at least got your filesystem in a consistent state.
You can then use lsof +f -- /dev/device
to list all processes with open files on the device containing the filesystem, and then kill them.
[1] It is less convoluted to use mount --move
, but that requires mount --make-private /parent-mount-point
which has implications. Basically, if the mountpoint is mounted under the /
filesystem, you'd want to avoid this.
What I did is first check what are the running processes by
SELECT * FROM pg_stat_activity WHERE state = 'active';
Find the process you want to kill, then type:
SELECT pg_cancel_backend(<pid of the process>)
This basically "starts" a request to terminate gracefully, which may be satisfied after some time, though the query comes back immediately.
If the process cannot be killed, try:
SELECT pg_terminate_backend(<pid of the process>)
Set the href
attribute with
$(selector).attr('href', 'url_goes_here');
and read it using
$(selector).attr('href');
Where "selector" is any valid jQuery selector for your <a>
element (".myClass" or "#myId" to name the most simple ones).
Hope this helps !
Running this on the command line should fix it
/Applications/Postgres.app/Contents/Versions/9.4/bin/createdb <Mac OSX Username Here>
You should use the print()
function which is available since Python 2.6+
from __future__ import print_function # Only needed for Python 2
print("hi there", file=f)
For Python 3 you don't need the import
, since the print()
function is the default.
The alternative would be to use:
f = open('myfile', 'w')
f.write('hi there\n') # python will convert \n to os.linesep
f.close() # you can omit in most cases as the destructor will call it
Quoting from Python documentation regarding newlines:
On output, if newline is None, any
'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
Adding the @ElementCollection
to the List field solved this issue:
@Column
@ElementCollection(targetClass=Integer.class)
private List<Integer> countries;
http://www.mrexcel.com/td0097.html
Dim WS as Worksheet
Set WS = Sheets.Add
You don't have to know where it's located, or what it's name is, you just refer to it as WS.
If you still want to do this the "old fashioned" way, try this:
Sheets.Add.Name = "Test"
When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately.
On consumer sites, you could also be hand-wavier under a minute. "Less than a minute ago" or "just now" could be good enough.
Here is a very simple and easy way to do this using MVVM.
Bind your textBox with an integer property in the view model, and this will work like a gem ... it will even show validation when a non-integer is entered in the textbox.
XAML code:
<TextBox x:Name="contactNoTxtBox" Text="{Binding contactNo}" />
View model code:
private long _contactNo;
public long contactNo
{
get { return _contactNo; }
set
{
if (value == _contactNo)
return;
_contactNo = value;
OnPropertyChanged();
}
}
Try running task manager to determine if your program is still running.
If it is running then stop it and run it again. the [Error] ld returned 1 exit status will not come back
<a href="@Url.Action("DeleteBlog")" class="btn btn-sm btn-danger" onclick="return confirm ('Are you sure want to delete blog?');">
A different method - using setTag() and getTag() methods of the View class.
use setTag() in the onBindViewHolder method of your adapter
@Override
public void onBindViewHolder(myViewHolder viewHolder, int position) {
viewHolder.mCardView.setTag(position);
}
where mCardView is defined in the myViewHolder class
private class myViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public View mCardView;
public myViewHolder(View view) {
super(view);
mCardView = (CardView) view.findViewById(R.id.card_view);
mCardView.setOnClickListener(this);
}
}
use getTag() in your OnClickListener implementation
@Override
public void onClick(View view) {
int position = (int) view.getTag();
//display toast with position of cardview in recyclerview list upon click
Toast.makeText(view.getContext(),Integer.toString(position),Toast.LENGTH_SHORT).show();
}
see https://stackoverflow.com/a/33027953/4658957 for more details
in laragon delete all internal data files from "C:\laragon\data\mysql" and restart it, that worked for me
For Windows 10:
First of all, install the intelhaxm-android.exe located in the folder SDK\extras\Intel\Hardware_Accelerated_Execution_Manager if it gives error during installation then try these solution.
First all enable the virtualization from bios setting. To enable this, restart the computer, when the computer started then press Esc, then select the F2 if the manufacturer is dell.
Even if you have enabled the Virtualization (VT) in BIOS settings, some antivirus options prevent HAXM installation.
For example: In Avast antivirus under Settings (parameters) tab > Troubleshooting (depannage), you should uncheck "Enable Hardware-assisted Virtualization" ("activer l'assistance a la virtualisation").
Now restart your computer and re-install the Intel's HAXM, which can be found under SDK\extras\intel\Hardware_Accelerated_Execution_Manager
. You can also manually download the standalone HAXM installer from Intel's website.
Check that hyper-v is disabled. To disable it, go to the control panel then select the Programs --> Program and Features--> Turn windows Feature on or off (located on left side), then find the HYPER-V, uncheck the check box and restart the computer and try to install the hxm again.
Go to properties of "This PC" by right clicking on it, then select the advanced system setting (located on left side) then in Advance (tab) under performance click the setting button, then select the Data Execution Prevention (tab), then select this option: "turn on the DEP for all programs and services except those I select" and restart the computer and try to install the hxm.
Solution 3 works for me.
I have to dedupe a very big table with many columns and speed is important. Thus I use this method which works for any table:
delete T from
(select Row_Number() Over(Partition By BINARY_CHECKSUM(*) order by %%physloc%% ) As RowNumber, * From MyTable) T
Where T.RowNumber > 1
I think in this case concat
is what you want:
In [12]:
pd.concat([df,df1], axis=0, ignore_index=True)
Out[12]:
attr_1 attr_2 attr_3 id quantity
0 0 1 NaN 1 20
1 1 1 NaN 2 23
2 1 1 NaN 3 19
3 0 0 NaN 4 19
4 1 NaN 0 5 8
5 0 NaN 1 6 13
6 1 NaN 1 7 20
7 1 NaN 1 8 25
by passing axis=0
here you are stacking the df's on top of each other which I believe is what you want then producing NaN
value where they are absent from their respective dfs.
If you don't wish to compile bootstrap, copy the following and insert it in your custom css file. It's not recommended to change the original bootstrap css file. Also, you won't be able to modify the bootstrap original css if you are loading it from a cdn.
Paste this in your custom css file:
@media (min-width:992px)
{
.container{width:960px}
}
@media (min-width:1200px)
{
.container{width:960px}
}
I am here setting my container to 960px for anything that can accommodate it, and keeping the rest media sizes to default values. You can set it to 940px for this problem.
It happened to me today with /home/user/public_html/index.php and the solution was to do chmod o+x /home/user
as this directory has to have the X as otherwise the apache server can't list files (i.e. do ls
)
If you're using the variable result:
result = result == "true";
The steps you took are not appropriate because the cell you want formatted is not the trigger cell (presumably won't normally be blank). In your case you want formatting to apply to one set of cells according to the status of various other cells. I suggest with data layout as shown in the image (and with thanks to @xQbert for a start on a suitable formula) you select ColumnA and:
HOME > Styles - Conditional Formatting, New Rule..., Use a formula to determine which cells to format and Format values where this formula is true::
=AND(LEN(E1)*LEN(F1)*LEN(G1)*LEN(H1)=0,NOT(ISBLANK(A1)))
Format..., select formatting, OK, OK.
where I have filled yellow the cells that are triggering the red fill result.
try this code worked for me
SELECT user_display_image AS user_image,
user_display_name AS user_name,
invitee_phone,
(CASE WHEN invitee_status = 1 THEN "attending"
WHEN invitee_status = 2 THEN "unsure"
WHEN invitee_status = 3 THEN "declined"
WHEN invitee_status = 0 THEN "notreviwed"
END) AS invitee_status
FROM your_table
If you are using C++ 17 you can just use the inline
specifier (see https://stackoverflow.com/a/11711082/55721)
If using older versions of the C++ standard, you must add the definitions to match your declarations of X and Y
unsigned char test::X;
unsigned char test::Y;
somewhere. You might want to also initialize a static member
unsigned char test::X = 4;
and again, you do that in the definition (usually in a CXX file) not in the declaration (which is often in a .H file)
Use ajax, a simple example,
HTML
<button id="button">Get Data</button>
Javascript
var button = document.getElementById("button");
button.addEventListener("click" ajaxFunction, false);
var ajaxFunction = function () {
// ajax code here
}
Alternatively look into jquery ajax
http://api.jquery.com/jQuery.ajax/
preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);
first of all, try to give the format you want to the current date time of your server:
Obtain current date time
$current_date = getdate();
Separate date and time to manage them as you wish:
$current_date_only = $current_date[year].'-'.$current_date[mon].'-'.$current_date[mday]; $current_time_only = $current_date['hours'].':'.$current_date['minutes'].':'.$current_date['seconds'];
Compare it depending if you are using donly date or datetime in your DB:
$today = $current_date_only.' '.$current_time_only;
or
$today = $current_date_only;
if($today < $expireDate)
hope it helps
TextView txtvw = (TextView)findViewById(R.id.TextView01);
txtvw.setText(readTxt());
private String readTxt()
{
InputStream raw = getResources().openRawResource(R.raw.hello);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
int i;
try
{
i = raw.read();
while (i != -1)
{
byteArrayOutputStream.write(i);
i = raw.read();
}
raw.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return byteArrayOutputStream.toString();
}
TextView01:: txtview in linearlayout hello:: .txt file in res/raw folder (u can access ny othr folder as wel)
Ist 2 lines are 2 written in onCreate() method
rest is to be written in class extending Activity!!
You can access the timezone by the following script:
SELECT * FROM pg_timezone_names WHERE name = current_setting('TIMEZONE');
output will be :
name- Europe/Berlin,
abbrev - CET,
utc_offset- 01:00:00,
is_dst- false
In case this helps anyone Googling around like I was, I had this error message trying to access a SVG file on my server, e.g. https://example.com/images/file.svg. Other file types seemed fine, just SVG were failing.
I hunted around /etc/httpd
conf files and checked every require all denied
type of configuration, and just could not find what config was having this effect.
I turned LogLevel to debug in the VirtualHost config and could see the mod_authz_core logging specifying there was a 'Require all denied' in effect:
[Mon Jun 10 13:09:54.321022 2019] [authz_core:debug] [pid 23459:tid 140576341206784] mod_authz_core.c(817): [client 127.0.0.1:54626] AH01626: authorization result of Require all denied: denied
[Mon Jun 10 13:09:54.321038 2019] [authz_core:debug] [pid 23459:tid 140576341206784] mod_authz_core.c(817): [client 127.0.0.1:54626] AH01626: authorization result of <RequireAny>: denied
[Mon Jun 10 13:09:54.321082 2019] [authz_core:error] [pid 23459:tid 140576341206784] [client 127.0.0.1:54626] AH01630: client denied by server configuration: /home/blah/htdocs/images/file.svg
Through blind testing I moved the file to the root of the web root, and found I could then access it at https://example.com/file.svg .. so it only failed in the 'images' folder. This led me to an .htaccess file in the images folder that I had no idea was there.
Turns out Zen Cart 1.5 comes with an images/.htaccess file that has:
# deny *everything*
<FilesMatch ".*">
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
<IfModule !mod_authz_core.c>
Order Allow,Deny
Deny from all
</IfModule>
</FilesMatch>
# but now allow just *certain* necessary files:
<FilesMatch "(?i).*\.(jpe?g|gif|webp|png|swf)$" >
<IfModule mod_authz_core.c>
Require all granted
</IfModule>
<IfModule !mod_authz_core.c>
Order Allow,Deny
Allow from all
</IfModule>
</FilesMatch>
This was very annoying and I hope this might remind others to check .htaccess files at every level of the file system leading to the file you're having trouble accessing in case there is this kind of tom foolery going on.
All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:
public int Position {get; set}
In your view model builder you set the position 1 through 4.
BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:
<div class="@Model.GridCSS">
Move the switch statement to your view model builder and populate the CSS class there.
Is above javascript code the one you're using in your web application ? If so - i would like to point few errors in it: firstly - it has an additional '{' sign in definition of 'success' callback function secondly - it has no ')' sign after definition of ajax callback. Valid code should look like:
$.ajax({
type:'POST',
data: 'args',
url: '@Url.Action("PostBack")',
success: function (data, textStatus, jqXHR) {
alert(data.message);
}
});
try using above code - it gave me 'Yay' alert on all 3 IE versions ( 7,8,9 ).
Lu55 Option 1 how to...
Add test only application.yml inside a seperated resources folder.
+-- main ¦ +-- java ¦ +-- resources ¦ +-- application.yml +-- test +-- java +-- resources +-- application.yml
In this project structure the application.yml under main is loaded if the code under main is running, the application.yml under test is used in a test.
To setup this structure add a new Package folder test/recources if not present.
Eclipse right click on your project -> Properties -> Java Build Path -> Source Tab -> (Dialog ont the rigth side) "Add Folder ..."
Inside Source Folder Selection -> mark test -> click on "Create New Folder ..." button -> type "resources" inside the Textfeld -> Click the "Finish" button.
After pushing the "Finisch" button you can see the sourcefolder {projectname}/src/test/recources (new)
Optional: Arrange folder sequence for the Project Explorer view.
Klick on Order and Export Tab mark and move {projectname}/src/test/recources to bottom.
Apply and Close
!!! Clean up Project !!!
Eclipse -> Project -> Clean ...
Now there is a separated yaml for test and the main application.
protected void finalize() throws Throwable {}
- every class inherits the
finalize()
method from java.lang.Object- the method is called by the garbage collector when it determines no more references to the object exist
- the Object finalize method performs no actions but it may be overridden by any class
- normally it should be overridden to clean-up non-Java resources ie closing a file
if overridding
finalize()
it is good programming practice to use a try-catch-finally statement and to always callsuper.finalize()
. This is a safety measure to ensure you do not inadvertently miss closing a resource used by the objects calling classprotected void finalize() throws Throwable { try { close(); // close open files } finally { super.finalize(); } }
any exception thrown by
finalize()
during garbage collection halts the finalization but is otherwise ignoredfinalize()
is never run more than once on any object
quoted from: http://www.janeg.ca/scjp/gc/finalize.html
You could also check this article:
You can achieve this using simple css as shown in below example
button {_x000D_
overflow: visible;_x000D_
width: auto;_x000D_
}_x000D_
button.link {_x000D_
font-family: "Verdana" sans-serif;_x000D_
font-size: 1em;_x000D_
text-align: left;_x000D_
color: blue;_x000D_
background: none;_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: none;_x000D_
cursor: pointer;_x000D_
_x000D_
-moz-user-select: text;_x000D_
_x000D_
/* override all your button styles here if there are any others */_x000D_
}_x000D_
button.link span {_x000D_
text-decoration: underline;_x000D_
}_x000D_
button.link:hover span,_x000D_
button.link:focus span {_x000D_
color: black;_x000D_
}
_x000D_
<button type="submit" class="link"><span>Button as Link</span></button>
_x000D_
Make sure your escaping the HTML characters
E.g.
// Always check an input variable is set before you use it
if (isset($_POST['contact_list'])) {
// Escape any html characters
echo htmlentities($_POST['contact_list']);
}
This would occur because of the angle brackets and the browser thinking they are tags.
Interestingly putting <httpCookies httpOnlyCookies="false"/>
doesn't seem to disable httpOnlyCookies
in ASP.NET 2.0. Check this article about SessionID and Login Problems With ASP .NET 2.0.
Looks like Microsoft took the decision to not allow you to disable it from the web.config. Check this post on forums.asp.net
not really... I used
<system.webServer>
<httpProtocol allowKeepAlive="true" >
<customHeaders>
<add name="X-Frame-Options" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
I don't see any problem with that. Pre-ARC, I've always made my IBOutlets assign
, as they're already retained by their superviews. If you make them weak
, you shouldn't have to nil them out in viewDidUnload, as you point out.
One caveat: You can support iOS 4.x in an ARC project, but if you do, you can't use weak
, so you'd have to make them assign
, in which case you'd still want to nil the reference in viewDidUnload
to avoid a dangling pointer. Here's an example of a dangling pointer bug I've experienced:
A UIViewController has a UITextField for zip code. It uses CLLocationManager to reverse geocode the user's location and set the zip code. Here's the delegate callback:
-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation {
Class geocoderClass = NSClassFromString(@"CLGeocoder");
if (geocoderClass && IsEmpty(self.zip.text)) {
id geocoder = [[geocoderClass alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if (self.zip && IsEmpty(self.zip.text)) {
self.zip.text = [[placemarks objectAtIndex:0] postalCode];
}
}];
}
[self.locationManager stopUpdatingLocation];
}
I found that if I dismissed this view at the right time and didn't nil self.zip in viewDidUnload
, the delegate callback could throw a bad access exception on self.zip.text.
For zsh and bash:
export PATH="$HOME/.config/composer/vendor/bin:$PATH"
source ~/.zshrc
source ~/.bashrc
For bash only:
export PATH=~/.config/composer/vendor/bin:$PATH
source ~/.bashrc
For those can not create PHP session and working with live domain at local. You should delete live sites secure cookie first.
Full answer ; https://stackoverflow.com/a/64073275/1067434
This will not work java -cp lib\*.jar -jar myproject.jar
. You have to put it jar by jar.
So in case of commons-codec-1.3.jar
.
java -cp lib/commons-codec-1.3.jar;lib/next_jar.jar
and so on.
The other solution might be putting all your jars to ext
directory of your JRE. This is ok if you are using a standalone JRE. If you are using the same JRE for running more than one application I do not recommend doing it.
ERBuilder can generate ER diagram from PostgreSQL databases (reverse engineer feature).
Below step to follow to generate an ER diagram:
• Click on Menu -> File -> reverse engineer
• Click on new connection
• Fill in PostgresSQL connection information
• Click on OK
• Click on next
• Select objects (tables, triggers, sequences…..) that you want to reverse engineer.
• Click on next.
XML has a much wider application than f.ex. HTML. It doesn't have an intrinsic, or default "application". So, while you might not really care that web pages are also governed by what's allowed, from the author's side, you'll probably want to precisely define what an XML document may and may not contain.
It's like designing a database.
The thing about XML technologies is that they are textual in nature. With XSD, it means you have a data structure definition framework that can be "plugged in" to text processing tools like PHP. So not only can you manipulate the data itself, but also very easily change and document the structure, and even auto-generate front-ends.
Viewed like this, XSD is the "glue" or "middleware" between data (XML) and data-processing tools.
The keys are not shuffled or renumbered. The unset()
key is simply removed and the others remain.
$a = array(1,2,3,4,5);
unset($a[2]);
print_r($a);
Array
(
[0] => 1
[1] => 2
[3] => 4
[4] => 5
)
Refer to this answer: How can we play YouTube embeded code in an Android application using webview?
It uses WebViews
and loads an iframe
in it... and yes it works.
This won't get rid of the close button, but it will stop someone closing the window.
Put this in your code behind file:
protected override void OnClosing(CancelEventArgs e)
{
base.OnClosing(e);
e.Cancel = true;
}
The biggest advantage of interpreted source code over compiled source code is PORTABILITY.
If your source code is compiled, you need to compile a different executable for each type of processor and/or platform that you want your program to run on (e.g. one for Windows x86, one for Windows x64, one for Linux x64, and so on). Furthermore, unless your code is completely standards compliant and does not use any platform-specific functions/libraries, you will actually need to write and maintain multiple code bases!
If your source code is interpreted, you only need to write it once and it can be interpreted and executed by an appropriate interpreter on any platform! It's portable! Note that an interpreter itself is an executable program that is written and compiled for a specific platform.
An advantage of compiled code is that it hides the source code from the end user (which might be intellectual property) because instead of deploying the original human-readable source code, you deploy an obscure binary executable file.
This solution worked better for me:
Note: You will have to check the box "Do not show this message again" the first time for the organized imports, but it works as expected after that.
step 2. with: Edit -> Macros -> "Start Macro Recording"
step 6. with: Edit -> Macros -> "Stop Macro Recording"
Everything else remains the same.
8. The Preferences contain the Keymap settings. Use the input field to filter the content, as shown in the screenshot.
The jQuery UI sortable
feature includes a serialize
method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id
. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize
option, it will create a POST query string like this: item[]=1&item[]=2
etc. So if you make use - for example - your database IDs in the id
attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
You can remove it from the repo and commit the change.
git rm .idea/ -r --cached
git add -u .idea/
git commit -m "Removed the .idea folder"
After that, you can push it to the remote and every checkout/clone after that will be ok.
Make sure you aren't connected to a VPN on another domain\user. Or, conversely, make sure you are connected, if that is what is required.
The following worked fine for me:
<style name="MyAlertDialogTheme" parent="Base.Theme.AppCompat.Light.Dialog.Alert">
<item name="windowFixedWidthMajor">90%</item>
<item name="windowFixedWidthMinor">90%</item>
</style>
(note: windowMinWidthMajor/Minor as suggested in previous answers didn't do the trick. My dialogs kept changing sizes depending on the content)
and then:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.MyAlertDialogTheme);
if guess == number:
print ("Good")
elif guess == 2:
print ("Bad")
else:
print ("Also bad")
Make sure you have your identation right. The syntax is ok.
The question is tagged SQL Server 2000 but for the benefit of people developing on the latest version I'll address that first.
SQL Server 2014
In addition to the methods of adding constraint based indexes discussed below SQL Server 2014 also allows non unique indexes to be specified directly with inline syntax on table variable declarations.
Example syntax for that is below.
/*SQL Server 2014+ compatible inline index syntax*/
DECLARE @T TABLE (
C1 INT INDEX IX1 CLUSTERED, /*Single column indexes can be declared next to the column*/
C2 INT INDEX IX2 NONCLUSTERED,
INDEX IX3 NONCLUSTERED(C1,C2) /*Example composite index*/
);
Filtered indexes and indexes with included columns can not currently be declared with this syntax however SQL Server 2016 relaxes this a bit further. From CTP 3.1 it is now possible to declare filtered indexes for table variables. By RTM it may be the case that included columns are also allowed but the current position is that they "will likely not make it into SQL16 due to resource constraints"
/*SQL Server 2016 allows filtered indexes*/
DECLARE @T TABLE
(
c1 INT NULL INDEX ix UNIQUE WHERE c1 IS NOT NULL /*Unique ignoring nulls*/
)
SQL Server 2000 - 2012
Can I create a index on Name?
Short answer: Yes.
DECLARE @TEMPTABLE TABLE (
[ID] [INT] NOT NULL PRIMARY KEY,
[Name] [NVARCHAR] (255) COLLATE DATABASE_DEFAULT NULL,
UNIQUE NONCLUSTERED ([Name], [ID])
)
A more detailed answer is below.
Traditional tables in SQL Server can either have a clustered index or are structured as heaps.
Clustered indexes can either be declared as unique to disallow duplicate key values or default to non unique. If not unique then SQL Server silently adds a uniqueifier to any duplicate keys to make them unique.
Non clustered indexes can also be explicitly declared as unique. Otherwise for the non unique case SQL Server adds the row locator (clustered index key or RID for a heap) to all index keys (not just duplicates) this again ensures they are unique.
In SQL Server 2000 - 2012 indexes on table variables can only be created implicitly by creating a UNIQUE
or PRIMARY KEY
constraint. The difference between these constraint types are that the primary key must be on non nullable column(s). The columns participating in a unique constraint may be nullable. (though SQL Server's implementation of unique constraints in the presence of NULL
s is not per that specified in the SQL Standard). Also a table can only have one primary key but multiple unique constraints.
Both of these logical constraints are physically implemented with a unique index. If not explicitly specified otherwise the PRIMARY KEY
will become the clustered index and unique constraints non clustered but this behavior can be overridden by specifying CLUSTERED
or NONCLUSTERED
explicitly with the constraint declaration (Example syntax)
DECLARE @T TABLE
(
A INT NULL UNIQUE CLUSTERED,
B INT NOT NULL PRIMARY KEY NONCLUSTERED
)
As a result of the above the following indexes can be implicitly created on table variables in SQL Server 2000 - 2012.
+-------------------------------------+-------------------------------------+
| Index Type | Can be created on a table variable? |
+-------------------------------------+-------------------------------------+
| Unique Clustered Index | Yes |
| Nonunique Clustered Index | |
| Unique NCI on a heap | Yes |
| Non Unique NCI on a heap | |
| Unique NCI on a clustered index | Yes |
| Non Unique NCI on a clustered index | Yes |
+-------------------------------------+-------------------------------------+
The last one requires a bit of explanation. In the table variable definition at the beginning of this answer the non unique non clustered index on Name
is simulated by a unique index on Name,Id
(recall that SQL Server would silently add the clustered index key to the non unique NCI key anyway).
A non unique clustered index can also be achieved by manually adding an IDENTITY
column to act as a uniqueifier.
DECLARE @T TABLE
(
A INT NULL,
B INT NULL,
C INT NULL,
Uniqueifier INT NOT NULL IDENTITY(1,1),
UNIQUE CLUSTERED (A,Uniqueifier)
)
But this is not an accurate simulation of how a non unique clustered index would normally actually be implemented in SQL Server as this adds the "Uniqueifier" to all rows. Not just those that require it.
I think this is what you need if I'm understanding you correctly:
<div id="wrapperHeader">
<div id="header">
<img src="images/logo.png" alt="logo" />
</div>
</div>
div#wrapperHeader {
width:100%;
height;200px; /* height of the background image? */
background:url(images/header.png) repeat-x 0 0;
text-align:center;
}
div#wrapperHeader div#header {
width:1000px;
height:200px;
margin:0 auto;
}
div#wrapperHeader div#header img {
width:; /* the width of the logo image */
height:; /* the height of the logo image */
margin:0 auto;
}
Ensure that your network is brought down before loading module:
sudo stop networking
It helped me - https://help.ubuntu.com/community/UbuntuBonding
if you want to know a remote redis server's version, just connect to that server and issue command "info server", you will get things like this:
...
redis_version:3.2.12
redis_git_sha1:00000000
redis_git_dirty:0
redis_build_id:9c3b73db5f7822b7
redis_mode:standalone
os:Linux 2.6.32.43-tlinux-1.0.26-default x86_64
arch_bits:64
multiplexing_api:epoll
gcc_version:4.9.4
process_id:5034
run_id:a45b2ffdc31d7f40a1652c235582d5d277eb5eec
I prefer the clean formatting of yaml
:
import yaml
print(yaml.dump(cars))
output:
A:
color: 2
speed: 70
B:
color: 3
speed: 60
TL; DR
This might also be caused by applying OR
to string columns / literals.
Full version
I got the same error message for a simple INSERT
statement involving a view:
insert into t1 select * from v1
although all the source and target columns were of type VARCHAR
. After some debugging, I found the root cause; the view contained this fragment:
string_col1 OR '_' OR string_col2 OR '_' OR string_col3
which presumably was the result of an automatic conversion of the following snippet from Oracle:
string_col1 || '_' || string_col2 || '_' || string_col3
(||
is string concatenation in Oracle). The solution was to use
concat(string_col1, '_', string_col2, '_', string_col3)
instead.
Using Firebase's Query API, you might be tempted to try this:
// !!! THIS WILL NOT WORK !!!
ref
.orderBy('genre')
.startAt('comedy').endAt('comedy')
.orderBy('lead') // !!! THIS LINE WILL RAISE AN ERROR !!!
.startAt('Jack Nicholson').endAt('Jack Nicholson')
.on('value', function(snapshot) {
console.log(snapshot.val());
});
But as @RobDiMarco from Firebase says in the comments:
multiple
orderBy()
calls will throw an error
So my code above will not work.
I know of three approaches that will work.
What you can do is execute one orderBy().startAt()./endAt()
on the server, pull down the remaining data and filter that in JavaScript code on your client.
ref
.orderBy('genre')
.equalTo('comedy')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
if (movie.lead == 'Jack Nicholson') {
console.log(movie);
}
});
If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_lead": "comedy_Jack Nicholson"
}, //...
You're essentially building your own multi-column index that way and can query it with:
ref
.orderBy('genre_lead')
.equalTo('comedy_Jack Nicholson')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
David East has written a library called QueryBase that helps with generating such properties.
You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:
"movie1": {
"genre": "comedy",
"name": "As good as it gets",
"lead": "Jack Nicholson",
"genre_year": "comedy_1997"
}, //...
And then query for comedies of the 90s with:
ref
.orderBy('genre_year')
.startAt('comedy_1990')
.endAt('comedy_2000')
.on('child_added', function(snapshot) {
var movie = snapshot.val();
console.log(movie);
});
If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25"
. This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.
This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.
A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.
Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:
"movies"
// the same structure you have today
"by_genre"
"comedy"
"by_lead"
"Jack Nicholson"
"movie1"
"Jim Carrey"
"movie3"
"Horror"
"by_lead"
"Jack Nicholson"
"movie2"
There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063
If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.
Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.
Python uses the ;
as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.
If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.
I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11
And if you need to calculate the MD5 to see whether it matches the MD5 of an Azure blob, then this SO question and answer might be helpful: MD5 hash of blob uploaded on Azure doesnt match with same file on local machine
You just need 775
for /var/www/html
as long as you are logging in as myuser. The 7
octal in the middle (which is for "group" acl) ensures that the group has permission to read/write/execute. As long as you belong to the group that owns the files, "myuser" should be able to write to them. You may need to give group permissions to all the files in the docuemnt root, though:
chmod -R g+w /var/www/html
easy replace
sed -i 's/utf8mb4_unicode_520_ci/utf8mb4_unicode_ci/g' your_sql_file.sql
Note that it is NOT safe to use onSaveInstanceState
and onRestoreInstanceState
for persistent data, according to the documentation on Activity states in http://developer.android.com/reference/android/app/Activity.html.
The document states (in the 'Activity Lifecycle' section):
Note that it is important to save persistent data in
onPause()
instead ofonSaveInstanceState(Bundle)
because the later is not part of the lifecycle callbacks, so will not be called in every situation as described in its documentation.
In other words, put your save/restore code for persistent data in onPause()
and onResume()
!
EDIT: For further clarification, here's the onSaveInstanceState()
documentation:
This method is called before an activity may be killed so that when it comes back some time in the future it can restore its state. For example, if activity B is launched in front of activity A, and at some point activity A is killed to reclaim resources, activity A will have a chance to save the current state of its user interface via this method so that when the user returns to activity A, the state of the user interface can be restored via
onCreate(Bundle)
oronRestoreInstanceState(Bundle)
.
To decode json, you have to pass the json string. Currently you're trying to pass an object:
>>> response = urlopen(url)
>>> response
<addinfourl at 2146100812 whose fp = <socket._fileobject object at 0x7fe8cc2c>>
You can fetch the data with response.read()
.
You should use the datetime functions of whatever language you're using, but, just for fun here's the code:
int milliseconds = someNumber;
int seconds = milliseconds / 1000;
int minutes = seconds / 60;
seconds %= 60;
int hours = minutes / 60;
minutes %= 60;
int days = hours / 24;
hours %= 24;
I think facebook app is not written in native code (by native code I mean, using layouts in Android) but they have used webview for it and have used some javascript ui libraries like sencha. It can be easily achieved using sencha framework.
This gets part way there. There is no ActualFontSize property but there is an ActualHeight and that would relate to the FontSize. Right now this only sizes for the original render. I could not figure out how to register the Converter as resize event. Actually maybe need to register the FontSize as a resize event. Please don't mark me down for an incomplete answer. I could not put code sample in a comment.
<Window.Resources>
<local:WidthConverter x:Key="widthConverter"/>
</Window.Resources>
<Grid>
<Grid>
<StackPanel VerticalAlignment="Center" Orientation="Vertical" >
<Viewbox Margin="100,0,100,0">
<TextBlock x:Name="headerText" Text="Lorem ipsum dolor" Foreground="Black"/>
</Viewbox>
<TextBlock Margin="150,0,150,0" FontSize="{Binding ElementName=headerText, Path=ActualHeight, Converter={StaticResource widthConverter}}" x:Name="subHeaderText" Text="Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, Lorem ipsum dolor, Lorem ipsum dolor, lorem isum dolor, " TextWrapping="Wrap" Foreground="Gray" />
</StackPanel>
</Grid>
</Grid>
Converter
[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
double width = (double)value*.7;
return width; // columnsCount;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
By entering $PATH
on its own at the command prompt, you're trying to run it. This isn't like Windows where you can get your path output by simply typing path
.
If you want to see what the path is, simply echo it:
echo $PATH
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
Use get_browser()
From Manual:
echo $_SERVER['HTTP_USER_AGENT'] . "\n\n";
$browser = get_browser(null, true);
print_r($browser);
Will return:
Array
(
[browser_name_regex] => ^mozilla/5\.0 (windows; .; windows nt 5\.1; .*rv:.*) gecko/.* firefox/0\.9.*$
[browser_name_pattern] => Mozilla/5.0 (Windows; ?; Windows NT 5.1; *rv:*) Gecko/* Firefox/0.9*/
[parent] => Firefox 0.9
[platform] => WinXP
[browser] => Firefox
[version] => 0.9
[majorver] => 0
[minorver] => 9
[cssversion] => 2
[frames] => 1
[iframes] => 1
[tables] => 1
[cookies] => 1
[backgroundsounds] =>
[vbscript] =>
[javascript] => 1
[javaapplets] => 1
[activexcontrols] =>
[cdf] =>
[aol] =>
[beta] => 1
[win16] =>
[crawler] =>
[stripper] =>
[wap] =>
[netclr] =>
)
If t
is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.
x = exp( -t.^2 )
or
x = exp( -t.*t )
try this.
if (ViewState["CurrentTable"] != null)
{
DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];
DataRow drCurrentRow = null;
if (dtCurrentTable.Rows.Count > 0)
{
for (int i = 1; i <= dtCurrentTable.Rows.Count; i++)
{
//extract the TextBox values
TextBox box1 = (TextBox)Gridview1.Rows[i].Cells[1].FindControl("txt_type");
TextBox box2 = (TextBox)Gridview1.Rows[i].Cells[2].FindControl("txt_total");
TextBox box3 = (TextBox)Gridview1.Rows[i].Cells[3].FindControl("txt_max");
TextBox box4 = (TextBox)Gridview1.Rows[i].Cells[4].FindControl("txt_min");
TextBox box5 = (TextBox)Gridview1.Rows[i].Cells[5].FindControl("txt_rate");
drCurrentRow = dtCurrentTable.NewRow();
drCurrentRow["RowNumber"] = i + 1;
dtCurrentTable.Rows[i - 1]["Column1"] = box1.Text;
dtCurrentTable.Rows[i - 1]["Column2"] = box2.Text;
dtCurrentTable.Rows[i - 1]["Column3"] = box3.Text;
dtCurrentTable.Rows[i - 1]["Column4"] = box4.Text;
dtCurrentTable.Rows[i - 1]["Column5"] = box5.Text;
rowIndex++;
}
dtCurrentTable.Rows.Add(drCurrentRow);
ViewState["CurrentTable"] = dtCurrentTable;
Gridview1.DataSource = dtCurrentTable;
Gridview1.DataBind();
}
}
else
{
Response.Write("ViewState is null");
}
You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get()
and http.post()
like this:
const headerDict = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Access-Control-Allow-Headers': 'Content-Type',
}
const requestOptions = {
headers: new Headers(headerDict),
};
return this.http.get(this.heroesUrl, requestOptions)
Or, if it's a POST request:
const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);
Since Angular 7 and up you have to use HttpHeaders
class instead of Headers
:
const requestOptions = {
headers: new HttpHeaders(headerDict),
};
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
Do you override .ToString() on all of your objects that are in the properties? Otherwise, that second comparison could come back with null.
Also, in that second comparison, I'm on the fence about the construct of !( A == B) compared to (A != B), in terms of readability six months/two years from now. The line itself is pretty wide, which is ok if you've got a wide monitor, but might not print out very well. (nitpick)
Are all of your objects always using properties such that this code will work? Could there be some internal, non-propertied data that could be different from one object to another, but all exposed data is the same? I'm thinking of some data which could change over time, like two random number generators that happen to hit the same number at one point, but are going to produce two different sequences of information, or just any data that doesn't get exposed through the property interface.
$('#myDiv').text()
Although you'd be better off doing something like:
var txt = $('#myDiv p').text();_x000D_
alert(txt);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"><p>Some Text</p></div>
_x000D_
Make sure you're linking to your jQuery file too :)
If the path you want is the one to the workbook running the macro, and that workbook has been saved, then
ThisWorkbook.Path
is what you would use.
Remove everything after first digit (was adequate for my use case): LEFT(field,PATINDEX('%[0-9]%',field+'0')-1)
Remove trailing digits: LEFT(field,len(field)+1-PATINDEX('%[^0-9]%',reverse('0'+field))
In Flash Builder (v 4.5 and up), and Aptana Studio (at least v 2.0.5) there is a toolbar button to toggle block select. It is between the 'mark occurrences' and 'show whitespace characters' buttons. There is also a Alt + Shift + A shortcut. Not surprisingly, this is basically the same as for Eclipse, but I'm including here for completeness.
I think the most pythonic way would be:
num = 65 # Input number
array = n.random.random((10))*100 # Given array
nearest_idx = n.where(abs(array-num)==abs(array-num).min())[0] # If you want the index of the element of array (array) nearest to the the given number (num)
nearest_val = array[abs(array-num)==abs(array-num).min()] # If you directly want the element of array (array) nearest to the given number (num)
This is the basic code. You can use it as a function if you want
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.
I was not able to find the logs under Manjaro 20/Arch Linux. Instead i just stopped the docker daemon process and restarted daemon in debug mode with $ sudo dockerd -D
to produce logs. It's unfortunate that the official Docker docs don't provide this info for Arch.
This should not only work for Arch, but for other systems in general.
If you have only one checkbox, you can do this easily with just ng-model:
<input type="checkbox" ng-model="checked"/>
<button ng-disabled="!checked"> Next </button>
And initialize $scope.checked in your Controller (default=false). The official doc discourages the use of ng-init in that case.
Create an new Style with any name, in my case "Theme.Alert.NoActionBar"
<style name="Theme.Alert.NoActionBar" parent="Theme.AppCompat.Dialog">
<item name="windowNoTitle">true</item>
<item name="windowActionBar">false</item>
</style>
set its parent as "Theme.AppCompat.Dialog" like in the above code
open AndoridManifest.xml and customize the activity you want to show as Alert Dialog like this
<activity
android:excludeFromRecents="true"
android:theme="@style/Theme.Alert.NoActionBar"
android:name=".activities.UserLoginActivity" />
in my app i want show my user login activity as Alert Dialog, these are the codes i used. hope this works for you!!!
OOXML files like those that come from Excel 2007 are encoded in UTF-8, according to wikipedia. I don't know about CSV files, but it stands to reason it would use the same format...
Yes, there's a command git commit --amend
which is used to "fix" last commit.
In your case it would be called as:
git add the_left_out_file
git commit --amend --no-edit
The --no-edit flag allow to make amendment to commit without changing commit message.
EDIT: Warning You should never amend public commits, that you already pushed to public repository, because what amend does is actually removing from history last commit and creating new commit with combined changes from that commit and new added when amending.
The issue of EOLs in mixed-platform projects has been making my life miserable for a long time. The problems usually arise when there are already files with different and mixed EOLs already in the repo. This means that:
CRLF
and LF
in the same file.How this happens is not the issue here, but it does happen.
I ran some conversion tests on Windows for the various modes and their combinations.
Here is what I got, in a slightly modified table:
| Resulting conversion when | Resulting conversion when | committing files with various | checking out FROM repo - | EOLs INTO repo and | with mixed files in it and | core.autocrlf value: | core.autocrlf value: -------------------------------------------------------------------------------- File | true | input | false | true | input | false -------------------------------------------------------------------------------- Windows-CRLF | CRLF -> LF | CRLF -> LF | as-is | as-is | as-is | as-is Unix -LF | as-is | as-is | as-is | LF -> CRLF | as-is | as-is Mac -CR | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF | as-is | as-is | as-is | as-is | as-is | as-is Mixed-CRLF+LF+CR | as-is | as-is | as-is | as-is | as-is | as-is
As you can see, there are 2 cases when conversion happens on commit (3 left columns). In the rest of the cases the files are committed as-is.
Upon checkout (3 right columns), there is only 1 case where conversion happens when:
core.autocrlf
is true
and LF
EOL.Most surprising for me, and I suspect, the cause of many EOL problems is that there is no configuration in which mixed EOL like CRLF
+LF
get normalized.
Note also that "old" Mac EOLs of CR
only also never get converted.
This means that if a badly written EOL conversion script tries to convert a mixed ending file with CRLF
s+LF
s, by just converting LF
s to CRLF
s, then it will leave the file in a mixed mode with "lonely" CR
s wherever a CRLF
was converted to CRCRLF
.
Git will then not convert anything, even in true
mode, and EOL havoc continues. This actually happened to me and messed up my files really badly, since some editors and compilers (e.g. VS2010) don't like Mac EOLs.
I guess the only way to really handle these problems is to occasionally normalize the whole repo by checking out all the files in input
or false
mode, running a proper normalization and re-committing the changed files (if any). On Windows, presumably resume working with core.autocrlf true
.
Update 2017
Depending on the environment, conditional comments have been officially deprecated and removed in IE10+.
Original
The simplest way is probably to use an Internet Explorer conditional comment in your HTML:
<!--[if IE]>
<style>
.actual-form table {
width: 100%;
}
</style>
<![endif]-->
There are numerous hacks (e.g. the underscore hack) you can use that will allow you to target only IE within your stylesheet, but it gets very messy if you want to target all versions of IE on all platforms.
SELECT CAST(GETDATE() AS DATE)
Returns the current date with the time part removed.
DATETIME
s are not "stored in the following format". They are stored in a binary format.
SELECT CAST(GETDATE() AS BINARY(8))
The display format in the question is independent of storage.
Formatting into a particular display format should be done by your application.
You can also do this without VBA from the find/replace dialogue box. My answer was at https://stackoverflow.com/a/6116681/509840 .
If you are inside a batch script, you can use argument variable tricks to get the filesize:
filesize.bat:
@echo off
echo %~z1
This gives results like the ones you suggest in your question.
Type
help call
at the command prompt for all of the crazy variable manipulation options. Also see this article for more information.
Edit: This only works in Windows 2000 and later
You can check this like below :
if varDate = "#01/01/0001#" then
' blank date. do something.
else
' Date is not blank. Do some other thing
end if
Very simple way
I do this in all my projects, and work like a dream. In your declarations layout.xml
just add this single line:
android:focusableInTouchMode="true"
Full code example:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:focusableInTouchMode="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content">
</ListView>
</android.support.constraint.ConstraintLayout>
The code
my_list = [(1, 2), (3, 4), (5, 6)]
for t in my_list:
print t
prints
(1, 2)
(3, 4)
(5, 6)
The loop iterates over my_list
, and assigns the elements of my_list
to t
one after the other. The elements of my_list
happen to be tuples, so t
will always be a tuple. To access the first element of the tuple t
, use t[0]
:
for t in my_list:
print t[0]
To access the first element of the tuple at the given index i
in the list, you can use
print my_list[i][0]
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
It's not at all related to "tidyr" and "dplyr", but here's another option to consider: merged.stack
from my "splitstackshape" package, V1.4.0 and above.
library(splitstackshape)
merged.stack(df, id.vars = c("id", "time"),
var.stubs = c("Q3.2.", "Q3.3."),
sep = "var.stubs")
# id time .time_1 Q3.2. Q3.3.
# 1: 1 2009-01-01 1. -0.62645381 1.35867955
# 2: 1 2009-01-01 2. 1.51178117 -0.16452360
# 3: 1 2009-01-01 3. 0.91897737 0.39810588
# 4: 2 2009-01-02 1. 0.18364332 -0.10278773
# 5: 2 2009-01-02 2. 0.38984324 -0.25336168
# 6: 2 2009-01-02 3. 0.78213630 -0.61202639
# 7: 3 2009-01-03 1. -0.83562861 0.38767161
# <<:::SNIP:::>>
# 24: 8 2009-01-08 3. -1.47075238 -1.04413463
# 25: 9 2009-01-09 1. 0.57578135 1.10002537
# 26: 9 2009-01-09 2. 0.82122120 -0.11234621
# 27: 9 2009-01-09 3. -0.47815006 0.56971963
# 28: 10 2009-01-10 1. -0.30538839 0.76317575
# 29: 10 2009-01-10 2. 0.59390132 0.88110773
# 30: 10 2009-01-10 3. 0.41794156 -0.13505460
# id time .time_1 Q3.2. Q3.3.
As discussed in the jQuery UI forums, you should not use accordions for this.
If you want something that looks and acts like an accordion, that is fine. Use their classes to style them, and implement whatever functionality you need. Then adding a button to open or close them all is pretty straightforward. Example
HTML
By using the jquery-ui classes, we keep our accordions looking just like the "real" accordions.
<div id="accordion" class="ui-accordion ui-widget ui-helper-reset">
<h3 class="accordion-header ui-accordion-header ui-helper-reset ui-state-default ui-accordion-icons ui-corner-all">
<span class="ui-accordion-header-icon ui-icon ui-icon-triangle-1-e"></span>
Section 1
</h3>
<div class="ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom">
Content 1
</div>
</div>?
Roll your own accordions
Mostly we just want accordion headers to toggle the state of the following sibling, which is it's content area. We have also added two custom events "show" and "hide" which we will hook into later.
var headers = $('#accordion .accordion-header');
var contentAreas = $('#accordion .ui-accordion-content ').hide();
var expandLink = $('.accordion-expand-all');
headers.click(function() {
var panel = $(this).next();
var isOpen = panel.is(':visible');
// open or close as necessary
panel[isOpen? 'slideUp': 'slideDown']()
// trigger the correct custom event
.trigger(isOpen? 'hide': 'show');
// stop the link from causing a pagescroll
return false;
});
Expand/Collapse All
We use a boolean isAllOpen
flag to mark when the button has been changed, this could just as easily have been a class, or a state variable on a larger plugin framework.
expandLink.click(function(){
var isAllOpen = $(this).data('isAllOpen');
contentAreas[isAllOpen? 'hide': 'show']()
.trigger(isAllOpen? 'hide': 'show');
});
Swap the button when "all open"
Thanks to our custom "show" and "hide" events, we have something to listen for when panels are changing. The only special case is "are they all open", if yes the button should be a "Collapse all", if not it should be "Expand all".
contentAreas.on({
// whenever we open a panel, check to see if they're all open
// if all open, swap the button to collapser
show: function(){
var isAllOpen = !contentAreas.is(':hidden');
if(isAllOpen){
expandLink.text('Collapse All')
.data('isAllOpen', true);
}
},
// whenever we close a panel, check to see if they're all open
// if not all open, swap the button to expander
hide: function(){
var isAllOpen = !contentAreas.is(':hidden');
if(!isAllOpen){
expandLink.text('Expand all')
.data('isAllOpen', false);
}
}
});?
Edit for comment: Maintaining "1 panel open only" unless you hit the "Expand all" button is actually much easier. Example
I know this is long stagnant topic, but in case anyone searches here is how I deal with multi table foreign keys. With this technique you do not have any DBA enforced cascade operations, so please make sure you deal with DELETE
and such in your code.
Table 1 Fruit
pk_fruitid, name
1, apple
2, pear
Table 2 Meat
Pk_meatid, name
1, beef
2, chicken
Table 3 Entity's
PK_entityid, anme
1, fruit
2, meat
3, desert
Table 4 Basket (Table using fk_s)
PK_basketid, fk_entityid, pseudo_entityrow
1, 2, 2 (Chicken - entity denotes meat table, pseudokey denotes row in indictaed table)
2, 1, 1 (Apple)
3, 1, 2 (pear)
4, 3, 1 (cheesecake)
SO Op's Example would look like this
deductions
--------------
type id name
1 khce1 gold
2 khsn1 silver
types
---------------------
1 employees_ce
2 employees_sn
If you are at the root of your working directory, you can do git checkout -- .
to check-out all files in the current HEAD and replace your local files.
You can also do git reset --hard
to reset your working directory and replace all changes (including the index).
I just ran into this problem and stumbled across a different situation. Although it's probably just a unicorn, I thought I'd lay it out.
I had one session that was smaller, and I noticed that the font sizes were different: the smaller session had the smaller fonts. Apparently, I had changed window font sizes for some reason.
So in OS X, I just did Cmd-+
on the smaller sized session, and it snapped back into place.
Try SQLDeveloper - there is a migration workbench there
http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html
In order to give a value in the table, we need to give a command:
php artisan make:migration create_users_table
and after then this command line
php artisan migrate
......
Use this code to read an Internet resource into a String
:
public static String readToString(String targetURL) throws IOException
{
URL url = new URL(targetURL);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(url.openStream()));
StringBuilder stringBuilder = new StringBuilder();
String inputLine;
while ((inputLine = bufferedReader.readLine()) != null)
{
stringBuilder.append(inputLine);
stringBuilder.append(System.lineSeparator());
}
bufferedReader.close();
return stringBuilder.toString().trim();
}
This is based on here.
$name = $_POST['name'];
$email = $_POST['email'];
$reciver = '/* Reciver Email address */';
if (filter_var($reciver, FILTER_VALIDATE_EMAIL)) {
$subject = $name;
// To send HTML mail, the Content-type header must be set.
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' . $email. "\r\n"; // Sender's Email
//$headers .= 'Cc:' . $email. "\r\n"; // Carbon copy to Sender
$template = '<div style="padding:50px; color:white;">Hello ,<br/>'
. '<br/><br/>'
. 'Name:' .$name.'<br/>'
. 'Email:' .$email.'<br/>'
. '<br/>'
. '</div>';
$sendmessage = "<div style=\"background-color:#7E7E7E; color:white;\">" . $template . "</div>";
// Message lines should not exceed 70 characters (PHP rule), so wrap it.
$sendmessage = wordwrap($sendmessage, 70);
// Send mail by PHP Mail Function.
mail($reciver, $subject, $sendmessage, $headers);
echo "Your Query has been received, We will contact you soon.";
} else {
echo "<span>* invalid email *</span>";
}
this is your answer:
<div class="test">Hello</div>
<div class="one">World</div>
The following jQuery Won't work:
$(data).find('div.test');
as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter
$(data).filter('div.test');
Another same question: Use Jquery Selectors on $.AJAX loaded HTML?
I believe it was already mentioned in other threads:
calc(){ awk "BEGIN { print "$*" }"; }
then you can simply type :
calc 7.5/3.2
2.34375
In your case it will be:
x=20; y=3;
calc $x/$y
or if you prefer, add this as a separate script and make it available in $PATH so you will always have it in your local shell:
#!/bin/bash
calc(){ awk "BEGIN { print $* }"; }
You could also do something like this:
df = df[['x', 'y', 'a', 'b']]
You can get the list of columns with:
cols = list(df.columns.values)
The output will produce something like this:
['a', 'b', 'x', 'y']
...which is then easy to rearrange manually before dropping it into the first function
You can regroup your steps functions calls in a facade function :
sub facade()
call step1()
call step2()
call step3()
call step4()
call step5()
end sub
Then, let your error handling be in an upper function that calls the facade :
sub main()
On error resume next
call facade()
If Err.Number <> 0 Then
' MsgBox or whatever. You may want to display or log your error there
msgbox Err.Description
Err.Clear
End If
On Error Goto 0
end sub
Now, let's suppose step3()
raises an error. Since facade()
doesn't handle errors (there is no On error resume next
in facade()
), the error will be returned to main()
and step4()
and step5()
won't be executed.
Your error handling is now refactored in 1 code block
As Mike stated, the best way is to use information_schema
. As long as you're not in the master database, system stored procedures won't be returned.
SELECT *
FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):
SELECT *
FROM [master].INFORMATION_SCHEMA.ROUTINES
WHERE ROUTINE_TYPE = 'PROCEDURE'
AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')
Try the following commands in terminal, this will work better:
apt-get install curl
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py
string XMLWriteStringWithoutIllegalCharacters(string UnfilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.EncodeName(UnfilteredString);
}
string XMLReadStringWithoutIllegalCharacters(string FilteredString)
{
if (UnfilteredString == null)
return string.Empty;
return XmlConvert.DecodeName(UnfilteredString);
}
This simple method replace the invalid characters with the same value but accepted in the XML context.
To write string use XMLWriteStringWithoutIllegalCharacters(string UnfilteredString).
To read string use XMLReadStringWithoutIllegalCharacters(string FilteredString).
Try:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes
After that you have:
To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:
openssl pkcs12 -in path.p12 -out newfile.pem -nodes
Or, if you want to provide a password for the private key, omit -nodes
and input a password:
openssl pkcs12 -in path.p12 -out newfile.pem
If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}
:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'
TLS client certificates are not sent in HTTP headers. They are transmitted by the client as part of the TLS handshake, and the server will typically check the validity of the certificate during the handshake as well.
If the certificate is accepted, most web servers can be configured to add headers for transmitting the certificate or information contained on the certificate to the application. Environment variables are populated with certificate information in Apache and Nginx which can be used in other directives for setting headers.
As an example of this approach, the following Nginx config snippet will validate a client certificate, and then set the SSL_CLIENT_CERT
header to pass the entire certificate to the application. This will only be set when then certificate was successfully validated, so the application can then parse the certificate and rely on the information it bears.
server {
listen 443 ssl;
server_name example.com;
ssl_certificate /path/to/chainedcert.pem; # server certificate
ssl_certificate_key /path/to/key; # server key
ssl_client_certificate /path/to/ca.pem; # client CA
ssl_verify_client on;
proxy_set_header SSL_CLIENT_CERT $ssl_client_cert;
location / {
proxy_pass http://localhost:3000;
}
}
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
Update (2017):
In modern browsers which follow the ECMAScript 2016 (ES7) standard, you can use the function Array.prototype.includes, which makes it way more easier to check if an item is present in an array:
const array = [1, 2, 3];_x000D_
const value = 1;_x000D_
const isInArray = array.includes(value);_x000D_
console.log(isInArray); // true
_x000D_
My solution is:
#include <iostream>
int fib(int number);
void call_fib(void);
int main()
{
call_fib();
return 0;
}
void call_fib(void)
{
int input;
std::cout<<"enter a number\t";
std::cin>> input;
if (input <0)
{
input=0;
std::cout<<"that is not a valid input\n" ;
call_fib();
}
else
{
std::cout<<"the "<<input <<"th fibonacci number is "<<fib(input);
}
}
int fib(int x)
{
if (x==0){return 0;}
else if (x==2 || x==1)
{
return 1;
}
else if (x>0)
{
return fib(x-1)+fib(x-2);
}
else
return -1;
}
it returns fib(0)=0 and error if negitive
You can use this:
response.sendRedirect(String.format("%s%s", request.getContextPath(), "/views/equipment/createEquipment.jsp"));
The last part is your path in your web-app
<!DOCTYPE html>
<?php
$con = new mysqli("localhost","root","","form");
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
$(document).ready(function(){
//$("form").submit(function(e){
$("#btn1").click(function(e){
e.preventDefault();
// alert('here');
$(".apnew").append('<input type="text" placeholder="Enter youy Name" name="e1[]"/><br>');
});
//}
});
</script>
</head>
<body>
<h2><b>Register Form<b></h2>
<form method="post" enctype="multipart/form-data">
<table>
<tr><td>Name:</td><td><input type="text" placeholder="Enter youy Name" name="e1[]"/>
<div class="apnew"></div><button id="btn1">Add</button></td></tr>
<tr><td>Image:</td><td><input type="file" name="e5[]" multiple="" accept="image/jpeg,image/gif,image/png,image/jpg"/></td></tr>
<tr><td>Address:</td><td><textarea cols="20" rows="4" name="e2"></textarea></td></tr>
<tr><td>Contact:</td><td><div id="textnew"><input type="number" maxlength="10" name="e3"/></div></td></tr>
<tr><td>Gender:</td><td><input type="radio" name="r1" value="Male" checked="checked"/>Male<input type="radio" name="r1" value="feale"/>Female</td></tr>
<tr><td><input id="submit" type="submit" name="t1" value="save" /></td></tr>
</table>
<?php
//echo '<pre>';print_r($_FILES);exit();
if(isset($_POST['t1']))
{
$values = implode(", ", $_POST['e1']);
$imgarryimp=array();
foreach($_FILES["e5"]["tmp_name"] as $key=>$val){
move_uploaded_file($_FILES["e5"]["tmp_name"][$key],"images/".$_FILES["e5"]["name"][$key]);
$fname = $_FILES['e5']['name'][$key];
$imgarryimp[]=$fname;
//echo $fname;
if(strlen($fname)>0)
{
$img = $fname;
}
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
}
exit;
// echo $values;exit;
//foreach($_POST['e1'] as $row)
//{
$d="insert into form(name,address,contact,gender,image)values('$values','$_POST[e2]','$_POST[e3]','$_POST[r1]','$img')";
if($con->query($d)==TRUE)
{
echo "Yoy Data Save Successfully!!!";
}
//}
//exit;
}
?>
</form>
<table>
<?php
$t="select * from form";
$y=$con->query($t);
foreach ($y as $q);
{
?>
<tr>
<td>Name:<?php echo $q['name'];?></td>
<td>Address:<?php echo $q['address'];?></td>
<td>Contact:<?php echo $q['contact'];?></td>
<td>Gender:<?php echo $q['gender'];?></td>
</tr>
<?php }?>
</table>
</body>
</html>
There is a solution here : Add
/full /netfx at the end of the path!
This should clear almost all. You should only be left with SQL Server.
function isValidDate(year, month, day) {
var d = new Date(year, month - 1, day, 0, 0, 0, 0);
return (!isNaN(d) && (d.getDate() == day && d.getMonth() + 1 == month && d.getYear() == year));
}
Blow codes could help you...
Fetch Numbers:
return string.Concat(input.Where(char.IsNumber));
Fetch Letters:
return string.Concat(input.Where(char.IsLetter));
The Java heap size limits for Windows are:
This doesn't help you getting a bigger Java heap, but now you know you can't go beyond these values.
The short answer: seems like a totally reasonable approach to the asynchrony problem to me. With a couple caveats.
I had a very similar line of thought when working on a new project we just started at my job. I was a big fan of vanilla Redux's elegant system for updating the store and rerendering components in a way that stays out of the guts of a React component tree. It seemed weird to me to hook into that elegant dispatch
mechanism to handle asynchrony.
I ended up going with a really similar approach to what you have there in a library I factored out of our project, which we called react-redux-controller.
I ended up not going with the exact approach you have above for a couple reasons:
dispatch
itself via lexical scope. This limits the options for refactoring once that connect
statement gets out of hand -- and it's looking pretty unwieldy with just that one update
method. So you need some system for letting you compose those dispatcher functions if you break them up into separate modules.Take together, you have to rig up some system to allow dispatch
and the store to be injected into your dispatching functions, along with the parameters of the event. I know of three reasonable approaches to this dependency injection:
dispatch
middleware approaches, but I assume they're basically the same.connect
, rather than having to work directly with the raw, normalized store.this
context, through a variety of possible mechanisms.Update
It occurs to me that part of this conundrum is a limitation of react-redux. The first argument to connect
gets a state snapshot, but not dispatch. The second argument gets dispatch but not the state. Neither argument gets a thunk that closes over the current state, for being able to see updated state at the time of a continuation/callback.
It looks like you forgot to include the ngRoute module in your dependency for myApp.
In Angular 1.2, they've made ngRoute optional (so you can use third-party route providers, etc.) and you have to explicitly depend on it in modules, along with including the separate file.
'use strict';
angular.module('myApp', ['ngRoute']).
config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/home'});
}]);
targetList = sourceList.stream().flatmap(List::stream).collect(Collectors.toList());
To get it working, I had to go to myaccount.google.com -> "connected apps & sites", and turn "Allow less secure apps" to "ON" (near the bottom of the page).
I've tested this for my project, it finds the max/min in O(n) time:
from django.db.models import Max
# Find the maximum value of the rating and then get the record with that rating.
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)
This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).
try to add this in your payload
grant_type=password&username=pippo&password=pluto
You can use the below method, which will take your target URL as the only input (Don't forget http://)
void GoToURL(String url){
Uri uri = Uri.parse(url);
Intent intent= new Intent(Intent.ACTION_VIEW,uri);
startActivity(intent);
}
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
You provide credentials in a URLRequest
instance, like this in Swift 3:
let username = "user"
let password = "pass"
let loginString = String(format: "%@:%@", username, password)
let loginData = loginString.data(using: String.Encoding.utf8)!
let base64LoginString = loginData.base64EncodedString()
// create the request
let url = URL(string: "http://www.example.com/")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
Or in an NSMutableURLRequest
in Swift 2:
// set up the base64-encoded credentials
let username = "user"
let password = "pass"
let loginString = NSString(format: "%@:%@", username, password)
let loginData: NSData = loginString.dataUsingEncoding(NSUTF8StringEncoding)!
let base64LoginString = loginData.base64EncodedStringWithOptions([])
// create the request
let url = NSURL(string: "http://www.example.com/")
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")
// fire off the request
// make sure your class conforms to NSURLConnectionDelegate
let urlConnection = NSURLConnection(request: request, delegate: self)
Idk if you guys solved it but I recommend another way to do it, and it works :)
ServiceUtil = ig.Class.extend({
base_url : 'someurl',
sendRequest: function(request)
{
var url = this.base_url + request;
var requestVar = new XMLHttpRequest();
dataGet = false;
$.ajax({
url: url,
async: false,
type: "get",
success: function(data){
ServiceUtil.objDataReturned = data;
}
});
return ServiceUtil.objDataReturned;
}
})
So the main idea here is that, by adding async: false, then you make everything waits until the data is retrieved. Then you assign it to a static variable of the class, and everything magically works :)
\includegraphics{myfig.pdf}
Based on Jason Sebring's very useful tip, and on the stuff covered here and there, I found a perfect solution for my case:
Pseudo code with Javascript snippets:
immediately create a blank popup on user action
var importantStuff = window.open('', '_blank');
(Enrich the call to window.open
with whatever additional options you need.)
Optional: add some "waiting" info message. Examples:
a) An external HTML page: replace the above line with
var importantStuff = window.open('http://example.com/waiting.html', '_blank');
b) Text: add the following line below the above one:
importantStuff.document.write('Loading preview...');
fill it with content when ready (when the AJAX call is returned, for instance)
importantStuff.location.href = 'https://example.com/finally.html';
Alternatively, you could close the window here if you don't need it after all (if ajax request fails
, for example - thanks to @Goose for the comment):
importantStuff.close();
I actually use this solution for a mailto redirection, and it works on all my browsers (windows 7, Android). The _blank
bit helps for the mailto redirection to work on mobile, btw.
I use Xcode 4.3.2, and my problem was that in there where a folder inside another folder with the same name, e.g myFolder/myFolder/.
The solution was to change the second folder's name e.g myFolder/_myFolder and the problem was solved.
I hope this can help some one.
SELECT * FROM users WHERE Id Between 15 and 25
it will print from 15 to 25 as like limit in MYSQl
For v5
<Link
to={{
pathname: "/courses",
search: "?sort=name",
hash: "#the-hash",
state: { fromDashboard: true }
}}
/>
SELECT CONVERT(NVARCHAR(10), PaymentDate, 120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(10), PaymentDate, 120)
ORDER BY [Month]
You could also try:
SELECT DATEPART(Year, PaymentDate) Year, DATEPART(Month, PaymentDate) Month, SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY DATEPART(Year, PaymentDate), DATEPART(Month, PaymentDate)
ORDER BY Year, Month
plt.axis('scaled')
works well for me.
The example above can be simplify a bit. Additionally you can put date manually from keyboard instead of selecting it via datepicker only. When clearing the value you need to handle also 'on clearDate' action to remove startDate/endDate boundary:
JS file:
$(".from_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var startDate = new Date(selected.date.valueOf());
$('.to_date').datepicker('setStartDate', startDate);
}).on('clearDate', function (selected) {
$('.to_date').datepicker('setStartDate', null);
});
$(".to_date").datepicker({
format: 'yyyy-mm-dd',
autoclose: true,
}).on('changeDate', function (selected) {
var endDate = new Date(selected.date.valueOf());
$('.from_date').datepicker('setEndDate', endDate);
}).on('clearDate', function (selected) {
$('.from_date').datepicker('setEndDate', null);
});
HTML:
<input class="from_date" placeholder="Select start date" type="text" name="from_date">
<input class="to_date" placeholder="Select end date" type="text" name="to_date">
toolbarHeight
property in your AppBarExample :
AppBar(
title: Text('Flutter is great'),
toolbarHeight: 100,
),
You can add
flexibleSpace
property in your appBar for more flexibility
Output:
Example :
appBar: PreferredSize(
preferredSize: Size(100, 80), //width and height
// The size the AppBar would prefer if there were no other constraints.
child: SafeArea(
child: Container(
height: 100,
color: Colors.red,
child: Center(child: Text('Fluter is great')),
),
),
),
Don't forget to use a
SafeArea
widget if you don't have a safeArea
Output :
Like this:
var $aWithId = $('.parent a[id]');
Following OP's comment, test it like this:
if($aWithId.length) //or without using variable: if ($('.parent a[id]').length)
Will return all anchor tags inside elements with class parent which have an attribute ID specified
I edit cybergen answer for make viewpager to change height depending on selected item The class is the same of cybergen's, but I added a Vector of integers that is all viewpager's child views heights and we can access it when page change to update height
This is the class:
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.viewpager.widget.ViewPager;
import java.util.Vector;
public class WrapContentHeightViewPager extends ViewPager {
private Vector<Integer> heights = new Vector<>();
public WrapContentHeightViewPager(@NonNull Context context) {
super(context);
}
public WrapContentHeightViewPager(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
for(int i=0;i<getChildCount();i++) {
View view = getChildAt(i);
if (view != null) {
view.measure(widthMeasureSpec, heightMeasureSpec);
heights.add(measureHeight(heightMeasureSpec, view));
}
}
setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, getChildAt(0)));
}
public int getHeightAt(int position){
return heights.get(position);
}
private int measureHeight(int measureSpec, View view) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
result = specSize;
} else {
if (view != null) {
result = view.getMeasuredHeight();
}
if (specMode == MeasureSpec.AT_MOST) {
result = Math.min(result, specSize);
}
}
return result;
}
}
Then in your activity add an OnPageChangeListener
WrapContentHeightViewPager viewPager = findViewById(R.id.my_viewpager);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
@Override
public void onPageSelected(int position) {
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) viewPager.getLayoutParams();
params.height = viewPager.getHeightAt(position);
viewPager.setLayoutParams(params);
}
@Override
public void onPageScrollStateChanged(int state) {}
});
And here is xml:
<com.example.example.WrapContentHeightViewPager
android:id="@+id/my_viewpager"
android:fillViewport="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
Please correct my English if necessary
Here are three Observables A
, B
, and C
with marble diagrams to explore the difference between first
, take
, and single
operators:
* Legend:
--o--
value
----!
error
----|
completion
Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .
Already having all the answers, I wanted to add a more visual explanation
Hope it helps someone
mbaird's answer works fine. Just be aware that there seems to be a bug in Android (2.1 at least), that if you set any individual corner's radius to 0, it forces all the corners to 0 (at least that's the case with "dp" units; I didn't try it with any other units).
I needed a shape where the top corners were rounded and the bottom corners were square. I got achieved this by setting the corners I wanted to be square to a value slightly larger than 0: 0.1dp. This still renders as square corners, but it doesn't force the other corners to be 0 radius.
If you don't need to access your array, (just a simple for loop) you can use upto or each :
Upto:
1.9.3p392 :030 > 2.upto(4) {|i| puts i}
2
3
4
=> 2
Each:
1.9.3p392 :031 > (2..4).each {|i| puts i}
2
3
4
=> 2..4
Perl was likely the first language to use it. Groovy is another language that supports it. Basically instead of returning 1
(true
) or 0
(false
) depending on whether the arguments are equal or unequal, the spaceship operator will return 1
, 0
, or -1
depending on the value of the left argument relative to the right argument.
a <=> b :=
if a < b then return -1
if a = b then return 0
if a > b then return 1
if a and b are not comparable then return nil
It's useful for sorting an array.
Some people seem to be confusing these macros with assert()
.
These macros implement a compile-time test, while assert()
is a runtime test.
First thing first, button()
is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:
$("#filter").click(function(){
alert('clicked!');
});
Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func)
which execute the callback once the DOM is ready.
Usage:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
So even if the order is this it will work:
$(function(){
$("#filter").click(function(){
alert('clicked!');
});
});
<input type="button" id="filter" name="filter" value="Filter" />
Doing nvm install 10.14
, for example, will nvm use
that version for the current shell session but it will not always set it as the default for future sessions as you would expect. The node version you get in a new shell session is determined by nvm alias default
. Confusingly, nvm install
will only set the default alias if it is not already set. To get the expected behaviour, do this:
nvm alias default ''; nvm install 10.14
This will ensure that that version is downloaded, use it for the current session and set it as the default for future sessions.
By default, the locations of Temporary Internet Files (for Internet Explorer) are:
Windows 95, Windows 98, and Windows ME
c:\WINDOWS\Temporary Internet Files
Windows 2000 and Windows XP
C:\Documents and Settings\\[User]\Local Settings\Temporary Internet Files
Windows Vista and Windows 7
%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files
%userprofile%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low
Windows 8
%userprofile%\AppData\Local\Microsoft\Windows\INetCache
Windows 10
%localappdata%\Microsoft\Windows\INetCache\IE
Some information came from The Windows Club.
Consider having multiple matlab sessions. Keep the main session window (the pretty one with all the colours, file manager, command history, workspace, editor etc.) for running stuff that you know will terminate.
Stuff that you are experimenting with, say you are messing with ode suite and you get lots of warnings: matrix singular, because you altered some parameter and didn't predict what would happen, run in a separate session:
dos('matlab -automation -r &')
You can kill that without having to restart the whole of Matlab.
I faced a similar issue while copying a sheet to another workbook. I prefer to avoid using 'activesheet' though as it has caused me issues in the past. Hence I wrote a function to perform this inline with my needs. I add it here for those who arrive via google as I did:
The main issue here is that copying a visible sheet to the last index position results in Excel repositioning the sheet to the end of the visible sheets. Hence copying the sheet to the position after the last visible sheet sorts this issue. Even if you are copying hidden sheets.
Function Copy_WS_to_NewWB(WB As Workbook, WS As Worksheet) As Worksheet
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim WSInd As Integer: WSInd = 1
Dim CWS As Worksheet
'Determine the index of the last visible worksheet
For Each CWS In WB.Worksheets
If CWS.Visible Then If CWS.Index > WSInd Then WSInd = CWS.Index
Next CWS
WS.Copy after:=WB.Worksheets(WSInd)
Set Copy_WS_to_NewWB = WB.Worksheets(WSInd + 1)
End Function
To use this function for the original question (ie in the same workbook) could be done with something like...
Set test = Copy_WS_to_NewWB(Workbooks(1), Workbooks(1).Worksheets(1))
test.name = "test sheet name"
EDIT 04/11/2020 from –user3598756 Adding a slight refactoring of the above code
Function CopySheetToWorkBook(targetWb As Workbook, shToBeCopied As Worksheet, copiedSh As Worksheet) As Boolean
'Creates a copy of the specified worksheet in the specified workbook
' Accomodates the fact that there may be hidden sheets in the workbook
Dim lastVisibleShIndex As Long
Dim iSh As Long
On Error GoTo SafeExit
With targetWb
'Determine the index of the last visible worksheet
For iSh = .Sheets.Count To 1 Step -1
If .Sheets(iSh).Visible Then
lastVisibleShIndex = iSh
Exit For
End If
Next
shToBeCopied.Copy after:=.Sheets(lastVisibleShIndex)
Set copiedSh = .Sheets(lastVisibleShIndex + 1)
End With
CopySheetToWorkBook = True
Exit Function
SafeExit:
End Function
other than using different (more descriptive?) variable names, the refactoring manily deals with:
turning the Function type into a `Boolean while including returned (copied) worksheet within function parameters list this, to let the calling Sub hande possible errors, like
Dim WB as Workbook: Set WB = ThisWorkbook ' as an example
Dim sh as Worksheet: Set sh = ActiveSheet ' as an example
Dim copiedSh as Worksheet
If CopySheetToWorkBook(WB, sh, copiedSh) Then
' go on with your copiedSh sheet
Else
Msgbox "Error while trying to copy '" & sh.Name & "'" & vbcrlf & err.Description
End If
having the For - Next loop stepping from last sheet index backwards and exiting at first visible sheet occurence, since we're after the "last" visible one
If this is just for debugging output, you can use the following to see all the types and values as well.
var_dump($obj);
If you want more control over the output you can use this:
foreach ($obj as $key => $value) {
echo "$key => $value\n";
}
This is the problem
double a[] = null;
Since a
is null
, NullPointerException
will arise every time you use it until you initialize it. So this:
a[i] = var;
will fail.
A possible solution would be initialize it when declaring it:
double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7
IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.
java.lang.NullPointerException
This exception means there's a variable with null
value being used. How to solve? Just make sure the variable is not null
before being used.
at twoten.TwoTenB.(TwoTenB.java:29)
This line has two parts:
<init>
method in class TwoTenB
declared in package twoten
. When you encounter an error message with SomeClassName.<init>
, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).a[i] = var;
.From this line, other lines will be similar to tell you where the error arose. So when reading this:
at javapractice.JavaPractice.main(JavaPractice.java:32)
It means that you were trying to instantiate a TwoTenB
object reference inside the main
method of your class JavaPractice
declared in javapractice
package.
Standard way of passing data from one activity to another:
If you want to send large number of data from one activity to another activity then you can put data in a bundle and then pass it using putExtra()
method.
//Create the `intent`
Intent i = new Intent(this, ActivityTwo.class);
String one="xxxxxxxxxxxxxxx";
String two="xxxxxxxxxxxxxxxxxxxxx";
//Create the bundle
Bundle bundle = new Bundle();
//Add your data to bundle
bundle.putString(“ONE”, one);
bundle.putString(“TWO”, two);
//Add the bundle to the intent
i.putExtras(bundle);
//Fire that second activity
startActivity(i);
otherwise you can use putExtra()
directly with intent to send data and getExtra()
to get data.
Intent i=new Intent(this, ActivityTwo.class);
i.putExtra("One",one);
i.putExtra("Two",two);
startActivity(i);
The answer mentioned by @HaNdTriX is a great, but we are not sure if DOM is completely loaded in the below code:
var loadTime = window.performance.timing.domContentLoadedEventEnd- window.performance.timing.navigationStart;
This works perfectly when used with onload as:
window.onload = function () {
var loadTime = window.performance.timing.domContentLoadedEventEnd-window.performance.timing.navigationStart;
console.log('Page load time is '+ loadTime);
}
Edit 1: Added some context to answer
Note: loadTime
is in milliseconds, you can divide by 1000 to get seconds as mentioned by @nycynik
"bad enough not having a traditional for(;;) looper"?? What?
Are you trying to do
import string
for c in string.lowercase:
...do something with c...
Or perhaps you're using string.uppercase
or string.letters
?
Python doesn't have for(;;)
because there are often better ways to do it. It also doesn't have character math because it's not necessary, either.
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers: http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7