$("#logo").css('opacity','0');_x000D_
_x000D_
$("#select_logo").click(function(e){_x000D_
e.preventDefault();_x000D_
$("#logo").trigger('click');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="select_logo">Select Logo</a> <input type="file" id="logo">
_x000D_
for IE add this:
$("#logo").css('filter','alpha(opacity = 0');
It is not possible to use relative paths for AuthUserFile:
File-path is the path to the user file. If it is not absolute (i.e., if it doesn't begin with a slash), it is treated as relative to the
ServerRoot
.
You have to accept and work around that limitation.
We're using IfDefine
together with an apache2 command line parameter:
.htaccess
(suitable for both development and live systems):<IfDefine !development>
AuthType Basic
AuthName "Say the secret word"
AuthUserFile /var/www/hostname/.htpasswd
Require valid-user
</IfDefine>
Append the following to /etc/apache2/envvars
:
export APACHE_ARGUMENTS=-Ddevelopment
Restart your apache afterwards and you'll get a password prompt only when you're not on the development server.
You can of course add another IfDefine for the development server, just copy the block and remove the !
.
@ericholscher says on Twitter, "The one in the official docs.."
It's a great point, you should do what the docs say.
Quoted from the official pip installation instructions at http://www.pip-installer.org/en/latest/installing.html:
$ curl -O https://github.com/pypa/virtualenv/raw/master/virtualenv.py
$ python virtualenv.py my_new_env
$ . my_new_env/bin/activate
(my_new_env)$ pip install ...
I personally generate XSL:FO from PHP and use Apache FOP to convert it to PDF. Not a PHP-native solution, not very efficient either, but it works well even if you need to generate PDF with very complex layouts.
Yes, you can. But if you have non-unique entries on your table, it will fail. Here is the how to add unique constraint on your table. If you're using PostgreSQL 9.x you can follow below instruction.
CREATE UNIQUE INDEX constraint_name ON table_name (columns);
As other option, you can do something like below
Group Valuation amount
0 BKB Tube 156
1 BKB Tube 143
2 BKB Tube 67
3 BAC Tube 176
4 BAC Tube 39
5 JDK Tube 75
6 JDK Tube 35
7 JDK Tube 155
8 ETH Tube 38
9 ETH Tube 56
Below script, you can use for above data
import pandas as pd
data = pd.read_csv("daata1.csv")
bytreatment = data.groupby('Group')
bytreatment['amount'].sum()
On MySQL 5.7 its work for me, I'm using CentOS7.
For taking Dump.
Command :
mysqldump -u user_name -p database_name -R -E > file_name.sql
Exemple :
mysqldump -u root -p mr_sbc_clean -R -E > mr_sbc_clean_dump.sql
For deploying Dump.
Command :
mysql -u user_name -p database_name < file_name.sql
Exemple :
mysql -u root -p mr_sbc_clean_new < mr_sbc_clean_dump.sql
you can follow the code below which works for me:
var loopStop = false;
YOUR_ARRAY.forEach(function loop(){
if(loopStop){ return; }
if(condition){ loopStop = true; }
});
$gender = $_POST['gender'];
echo $gender;
it will echoes the selected value.
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
FWIW the only thing that worked for me in PR builds was ${CHANGE_BRANCH}
(may not work on master
, haven't seen that yet)
The following regex will work for both:
text = text.replaceAll("('|\")", "\\\\$1");
If you are going to use multiple buffers, I think the most important thing is to set hidden so that it will let you switch buffers even if you have unsaved changes in the one you are leaving.
I have found that a button works, but that you'll want to add style="height: 100%;"
to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1
I've run into this problem with ICS/JB because the default buttons for the Holo theme consist of images that are slightly transparent. For a background this is especially noticeable.
Gingerbread vs. ICS+:
Copying over all of the drawable states and images for each resolution and making the transparent images solid is a pain, so I've opted for a dirtier solution: wrap the button in a holder that has a white background. Here's a crude XML drawable (ButtonHolder) which does exactly that:
Your XML file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Content">
<RelativeLayout style="@style/ButtonHolder">
<Button android:id="@+id/myButton"
style="@style/Button"
android:text="@string/proceed"/>
</RelativeLayout>
</LinearLayout>
ButtonHolder.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
</shape>
</item>
</layer-list>
styles.xml
.
.
.
<style name="ButtonHolder">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:background">@drawable/buttonholder</item>
</style>
<style name="Button" parent="@android:style/Widget.Button">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">wrap_content</item>
<item name="android:textStyle">bold</item>
</style>
.
.
.
However, this results in a white border because the Holo button images include margins to account for the pressed space:
So the solution is to give the white background a margin (4dp worked for me) and rounded corners (2dp) to completely hide the white yet make the button solid:
ButtonHolder.xml
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="@android:color/transparent"/>
</shape>
</item>
<item android:top="4dp" android:bottom="4dp" android:left="4dp" android:right="4dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
<corners android:radius="2dp" />
</shape>
</item>
</layer-list>
The final result looks like this:
You should target this style for v14+, and tweak or exclude it for Gingerbread/Honeycomb because their native button image sizes are different from ICS and JB's (e.g. this exact style behind a Gingerbread button results in a small bit of white below the button).
Marshaling refers to converting the signature and parameters of a function into a single byte array. Specifically for the purpose of RPC.
Serialization more often refers to converting an entire object / object tree into a byte array Marshaling will serialize object parameters in order to add them to the message and pass it across the network. *Serialization can also be used for storage to disk.*
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Just to add on @Lukas Eder answer.
An improvement to avoid creating tables and inserting values
(we could use select from dual
and unpivot
to achieve the same result "on the fly"):
with all_likes as
(select * from
(select '%val1%' like_1, '%val2%' like_2, '%val3%' like_3, '%val4%' as like_4, '%val5%' as like_5 from dual)
unpivot (
united_columns for subquery_column in ("LIKE_1", "LIKE_2", "LIKE_3", "LIKE_4", "LIKE_5"))
)
select * from tbl
where exists (select 1 from all_likes where tbl.my_col like all_likes.united_columns)
For this the System.Timers.Timer
works best
// Create a timer
myTimer = new System.Timers.Timer();
// Tell the timer what to do when it elapses
myTimer.Elapsed += new ElapsedEventHandler(myEvent);
// Set it to go off every five seconds
myTimer.Interval = 5000;
// And start it
myTimer.Enabled = true;
// Implement a call with the right signature for events going off
private void myEvent(object source, ElapsedEventArgs e) { }
See Timer Class (.NET 4.6 and 4.5) for details
Change string[] lines = File.ReadLines("c:\\file.txt");
to IEnumerable<string> lines = File.ReadLines("c:\\file.txt");
The rest of your code should work fine.
Try this:
try{
Thread.sleep(100);
}catch(Exception e)
{
System.out.println("Exception caught");
}
For me, i wanted my devl to be back to the master after it was ahead.
While on develop:
git checkout master
git pull
git checkout develop
git pull
git reset --hard origin/master
git push -f
Ok, so I'm sorry but most of these answers are incomplete or have some minor bug in them. The very complete answer from @austyn-mahoney is correct and the source for this answer, but it's complicated and you probably just want to style a switch. 'Styling' controls across different versions of Android is an epic pain in the ass. After pulling my hair out for days on a project with very tight design constraints I finally broke down and wrote a test app and then really dug in and tested the various solutions out there for styling switches and check-boxes, since when a design has one it frequently has the other. Here's what I found...
First: You can't actually style either of them, but you can apply a theme to all of them, or just one of them.
Second: You can do it all from XML and you don't need a second values-v21/styles.xml.
Third: when it comes to switches you have two basic choices if you want to support older versions of Android (like I'm sure you do)...
SwitchCompat
and you will be able to make it look the same across platforms.Switch
and you will be able to theme it with the rest of your theme, or just that particular switch and on older versions of Android you'll just see an unstyled older square switch.Ok now for the simple reference code. Again if you create a simple Hello World! and drop this code in you can play to your hearts content. All of that is boiler plate here so I'm just going to include the XML for the activity and the style...
activity_main.xml...
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' SwitchCompat" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_item"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"
app:switchTextAppearance="@style/BrandedSwitch.text"
app:theme="@style/BrandedSwitch.control"
app:showText="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed SwitchCompat" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switch_item2"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed Switch" />
<Switch
android:id="@+id/switch_item3"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' Switch" />
<Switch
android:id="@+id/switch_item4"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:textOff="OFF"
android:textOn="ON"
android:theme="@style/BrandedSwitch"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="'Styled' CheckBox" />
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"
android:theme="@style/BrandedCheckBox"/>
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.kunai.switchtest.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Themed CheckBox" />
<CheckBox
android:id="@+id/checkbox2"
android:layout_width="wrap_content"
android:layout_height="46dp"
android:layout_alignParentEnd="true"
android:layout_marginEnd="16dp"
android:checked="true"
android:longClickable="false"/>
</RelativeLayout>
styles.xml...
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#3F51B5</item>
<item name="colorPrimaryDark">#303F9F</item>
<item name="colorAccent">#FF4081</item>
</style>
<style name="BrandedSwitch.control" parent="Theme.AppCompat.Light">
<!-- active thumb & track color (30% transparency) -->
<item name="colorControlActivated">#e6e600</item>
<item name="colorSwitchThumbNormal">#cc0000</item>
</style>
<style name="BrandedSwitch.text" parent="Theme.AppCompat.Light">
<item name="android:textColor">#ffa000</item>
<item name="android:textSize">9dp</item>
</style>
<style name="BrandedCheckBox" parent="AppTheme">
<item name="colorAccent">#aaf000</item>
<item name="colorControlNormal">#ff0000</item>
</style>
<style name="BrandedSwitch" parent="AppTheme">
<item name="colorAccent">#39ac39</item>
</style>
I know, I know, you are too lazy to build this, you just want to get your code written and check it in so you can close this pain in the ass Android compatibility nightmare bug so that the designer on your team will finally be happy. I get it. Here's what it looks like when you run it...
API_21:
API_18:
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
The answer provided by Evan Mulawski will work perfectly. The catch is that you have to set the background color for the view to clearColor and the masksToBounds property to NO.
You can set whatever color you want for the view, set it like
v.layer.backgroundColor = your color;
Hope this helps..
https://github.com/f500/ansible-dumpall
FYI: this github project shows you how to list 90% of variables across all hosts. I find it more globally useful than single host commands. The README includes instructions for building a simple inventory report. It's even more valuable to run this at the end of a playbook to see all the Facts. To also debug Task behaviour use register:
The result is missing a few items: - included YAML file variables - extra-vars - a number of the Ansible internal vars described here: Ansible Behavioural Params
I had this error, was able to overcome it by using :
patch -p1 < example.patch
I took it from here: https://www.drupal.org/node/1129120
import sys
print(sys.argv[0])
This will print foo.py
for python foo.py
, dir/foo.py
for python dir/foo.py
, etc. It's the first argument to python
. (Note that after py2exe it would be foo.exe
.)
I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.
var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));
So you could do something like this
Function Errorthingy(pParam)
On Error GoTo HandleErr
' your code here
ExitHere:
' your finally code
Exit Function
HandleErr:
Select Case Err.Number
' different error handling here'
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "ErrorThingy"
End Select
Resume ExitHere
End Function
If you want to bake in custom exceptions. (e.g. ones that violate business rules) use the example above but use the goto to alter the flow of the method as necessary.
JQuery 1.5 introduces promises, and here's the simplest implementation I've seen to control order of execution. Full documentation at http://api.jquery.com/jquery.when/
$.when( $('#myDiv').css('background-color', 'red') )
.then( alert('hi!') )
.then( myClickFunction( $('#myID') ) )
.then( myThingToRunAfterClick() );
[
stands for single dimension array
Ljava.lang.String
stands for the string class (L followed by class/interface name)
Few Examples:
Class.forName("[D")
-> Array of primitive doubleClass.forName("[[Ljava.lang.String")
-> Two dimensional array of strings.List of notations:
Element Type : Notation
boolean : Z
byte : B
char : C
class or interface : Lclassname
double : D
float : F
int : I
long : J
short : S
For anyone who came here looking for how to get the true accordion effect and only allow one row to be expanded at a time, you can add an event handler for show.bs.collapse like so:
$('.collapse').on('show.bs.collapse', function () {
$('.collapse.in').collapse('hide');
});
I modified this example to do so here: http://jsfiddle.net/QLfMU/116/
If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.
The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.
Edit: Yeah, I guess I was wrong. See top entry. :)
You can use find_all
in the following way to find every a
element that has an href
attribute, and print each one:
from BeautifulSoup import BeautifulSoup
html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''
soup = BeautifulSoup(html)
for a in soup.find_all('a', href=True):
print "Found the URL:", a['href']
The output would be:
Found the URL: some_url
Found the URL: another_url
Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll
. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all
instead.
If you want all tags with an href
, you can omit the name
parameter:
href_tags = soup.find_all(href=True)
Register your element.
var vr = document.registerElement('v-r'); // vertical rule please, yes!
*The -
is mandatory in all custom elements.
v-r {
height: 100%;
width: 1px;
border-left: 1px solid gray;
/*display: inline-block;*/
/*margin: 0 auto;*/
}
*You might need to fiddle a bit with display:inline-block|inline
because inline
won't expand to containing element's height. Use the margin to center the line within a container.
js: document.body.appendChild(new vr());
or
HTML: <v-r></v-r>
*Unfortunately you can't create custom self-closing tags.
<h1>THIS<v-r></v-r>WORKS</h1>
example: http://html5.qry.me/vertical-rule
Simply apply this CSS class to your designated element.
.vr {
height: 100%;
width: 1px;
border-left: 1px solid gray;
/*display: inline-block;*/
/*margin: 0 auto;*/
}
*See notes above.
I had similar troubles in eclipse and the only way to fix it for me was to
Just make sure you configure the web module before applying it as by default it will look for your web files in /WebContent/ and this is not what Maven project structure should be.
EDIT:
Here is a second way in case nothing else helps
org.eclipse.wst.common.project.facet.core.xml
, make backup, and remove the web module entry. Python comes with numerous ways of formatting strings:
New style .format()
, which supports a rich formatting mini-language:
>>> temperature = 10
>>> print("the furnace is now {} degrees!".format(temperature))
the furnace is now 10 degrees!
Old style %
format specifier:
>>> print("the furnace is now %d degrees!" % temperature)
the furnace is now 10 degrees!
In Py 3.6 using the new f""
format strings:
>>> print(f"the furnace is now {temperature} degrees!")
the furnace is now 10 degrees!
Or using print()
s default sep
arator:
>>> print("the furnace is now", temperature, "degrees!")
the furnace is now 10 degrees!
And least effectively, construct a new string by casting it to a str()
and concatenating:
>>> print("the furnace is now " + str(temperature) + " degrees!")
the furnace is now 10 degrees!
Or join()
ing it:
>>> print(' '.join(["the furnace is now", str(temperature), "degrees!"]))
the furnace is now 10 degrees!
Shadowbox is your best choice. Check it out.
how to access iFrame parent page using jquery
window.parent.document.
jQuery is a library on top of JavaScript, not a complete replacement for it. You don't have to replace every last JavaScript expression with something involving $.
If it doesn't need to be a macro, then just put =A1*1.1
into (say) D7, then drag the formula fill handle across, then down.
Also consider the <strong>
tag. It's much better for screen readers and therefore better for accessibility. Search engines also use <strong>
tags to determine important content similar to how they use header tags <h1>
, <h2>
, etc (although <b>
will also have similar meaning to search engines). If you want to stress importance of text, use <strong>
. If you don't want to stress importance, use the <b>
tag or use the font-weight:bold;
style on the element or in the CSS.
Although, if you are bolding the entire paragraph, it's probably better to use the CSS option. This will reduce the affect on screen readers and it probably doesn't make sense to have an entire paragraph emphasized. But on the other hand, I've seen bold used to emphasize an entire paragraph before for good reason. In which case, font-weight:bold;
is what you want to use, likely in a class/style.
In the end, <strong>
, <b>
or font-weight:bold;
will all work and accomplish something similar visually (probably exactly the same), but they have slightly different meanings. Also, make sure that if what you're bolding is a header, use the header tags: <h1>
, <h2>
, etc.
solution from: Display jquery ui auto-complete list on focus event
The solution to make it work more than once
<script type="text/javascript">
$(function() {
$('#id').autocomplete({
source: ["ActionScript",
/* ... */
],
minLength: 0
}).focus(function(){
//Use the below line instead of triggering keydown
$(this).data("autocomplete").search($(this).val());
});
});
Here is how to restore a backup as an additional db with a unique db name.
For SQL 2005 this works very quickly. I am sure newer versions will work the same.
First, you don't have to take your original db offline. But for safety sake, I like to. In my example, I am going to mount a clone of my "billing" database and it will be named "billingclone".
1) Make a good backup of the billing database
2) For safety, I took the original offline as follows:
3) Open a new Query window
**IMPORTANT! Keep this query window open until you are all done! You need to restore the db from this window!
Now enter the following code:
-- 1) free up all USER databases
USE master;
GO
-- 2) kick all other users out:
ALTER DATABASE billing SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- 3) prevent sessions from re-establishing connection:
ALTER DATABASE billing SET OFFLINE;
3) Next, in Management Studio, rt click Databases in Object Explorer, choose "Restore Database"
4) enter new name in "To Database" field. I.E. billingclone
5) In Source for Restore, click "From Device" and click the ... navigate button
6) Click Add and navigate to your backup
7) Put a checkmark next to Restore (Select the backup sets to restore)
8) next select the OPTIONS page in upper LH corner
9) Now edit the database file names in RESTORE AS. Do this for both the db and the log. I.E. billingclone.mdf and billingclone_log.ldf
10) now hit OK and wait for the task to complete.
11) Hit refresh in your Object Explorer and you will see your new db
12) Now you can put your billing db back online. Use the same query window you used to take billing offline. Use this command:
-- 1) free up all USER databases
USE master; GO
-- 2) restore access to all users:
ALTER DATABASE billing SET MULTI_USER WITH ROLLBACK IMMEDIATE;GO
-- 3) put the db back online:
ALTER DATABASE billing SET ONLINE;
done!
set datestr=%date%
set result=%datestr:/=-%
@echo %result%
pause
git clone --depth 1 --branch <tag_name> <repo_url>
--depth 1
is optional but if you only need the state at that one revision, you probably want to skip downloading all the history up to that revision.
@Mysticial got it. A short is usually 16-bit and will illustrate the answer:
int main()
{
unsigned int x = 65529;
int y = (int) x;
printf("%d\n", y);
unsigned short z = 65529;
short zz = (short)z;
printf("%d\n", zz);
}
65529
-7
Press any key to continue . . .
So let's look at 65529 decimal. It can be represented as FFF9h
in hexadecimal. We can also represent that in binary as:
11111111 11111001
When we declare short zz = 65529;
, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1
, so it is treated as a negative number. That's why it prints out -7
.
For an unsigned short
, we don't care about sign since it's unsigned
. So when we print it out using %d
, we use all 16 bits, so it's interpreted as 65529
.
I am getting day
, month
and year
using dedicated functions moment().date(), moment().month() and moment().year() of momentjs
.
let day = moment('2014-07-28', 'YYYY/MM/DD').date();_x000D_
let month = 1 + moment('2014-07-28', 'YYYY/MM/DD').month();_x000D_
let year = moment('2014-07-28', 'YYYY/MM/DD').year();_x000D_
_x000D_
console.log(day);_x000D_
console.log(month);_x000D_
console.log(year);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
_x000D_
I don't know why there are 48 upvotes for @Chris Schmitz answer which is not 100% correct.
Month is in form of array and starts from 0 so to get exact value we should use 1 + moment().month()
enter code here<form id="form">
<input type="text"><input type="text"><input type="text">
<input type="button" id="new">
</form>
<form id="form1">
<input type="text"><input type="text"><input type="text">
<input type="button" id="new1">
</form>
<script type="text/javascript">
$(document).ready(function(e) {
$("#new").click( function(){
//alert("fegf");
$("#form input").val('');
});
$("#new1").click( function(){
//alert("fegf");
$("#form1 input").val('');
});
});
</script>
Old question but anyway !
Same thing happen to me this morning, everything was working fine for weeks before...... yes guess what ... I change my windows PC user account password yesterday night !!!!! (how stupid was I !!!)
So easy fix : IIS -> authentication -> Anonymous authentication -> edit and set the user and new PASSWORD !!!!!
The type of the elements of an std::map
(which is also the type of an expression obtained by dereferencing an iterator of that map) whose key is K
and value is V
is std::pair<const K, V>
- the key is const
to prevent you from interfering with the internal sorting of map values.
std::pair<>
has two members named first
and second
(see here), with quite an intuitive meaning. Thus, given an iterator i
to a certain map, the expression:
i->first
Which is equivalent to:
(*i).first
Refers to the first (const
) element of the pair
object pointed to by the iterator - i.e. it refers to a key in the map. Instead, the expression:
i->second
Which is equivalent to:
(*i).second
Refers to the second element of the pair
- i.e. to the corresponding value in the map.
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.
Just to add on to the list if you are using Powershell.
sc.exe query "ServiceName" | findstr RUNNING
The command below does not work because sc
is an alias to Set-Content within Powershell.
sc query "ServiceName" | findstr RUNNING
find
also does not work on Powershell for some reason unknown to me.
sc.exe query "ServiceName" | find RUNNING
I prefer to use length
on the vertical-align. This aligns the baseline of the element at the given length above the baseline of its parent.
sup {
font-size: .83em;
vertical-align: 0.25em;
line-height: 0;
}
Few answers that may be useful, especially if you have dynamic content.
$('#dialogueForm').live("dialogclose", function(){
//your code to run on dialog close
});
Or, when opening the modal, have a callback.
$( "#dialogueForm" ).dialog({
autoOpen: false,
height: "auto",
width: "auto",
modal: true,
my: "center",
at: "center",
of: window,
close : function(){
// functionality goes here
}
});
Many years later there seems to still be a usability problem with the Python logger. Here's some explanations with examples:
import logging
# This sets the root logger to write to stdout (your console).
# Your script/app needs to call this somewhere at least once.
logging.basicConfig()
# By default the root logger is set to WARNING and all loggers you define
# inherit that value. Here we set the root logger to NOTSET. This logging
# level is automatically inherited by all existing and new sub-loggers
# that do not set a less verbose level.
logging.root.setLevel(logging.NOTSET)
# The following line sets the root logger level as well.
# It's equivalent to both previous statements combined:
logging.basicConfig(level=logging.NOTSET)
# You can either share the `logger` object between all your files or the
# name handle (here `my-app`) and call `logging.getLogger` with it.
# The result is the same.
handle = "my-app"
logger1 = logging.getLogger(handle)
logger2 = logging.getLogger(handle)
# logger1 and logger2 point to the same object:
# (logger1 is logger2) == True
# Convenient methods in order of verbosity from highest to lowest
logger.debug("this will get printed")
logger.info("this will get printed")
logger.warning("this will get printed")
logger.error("this will get printed")
logger.critical("this will get printed")
# In large applications where you would like more control over the logging,
# create sub-loggers from your main application logger.
component_logger = logger.getChild("component-a")
component_logger.info("this will get printed with the prefix `my-app.component-a`")
# If you wish to control the logging levels, you can set the level anywhere
# in the hierarchy:
#
# - root
# - my-app
# - component-a
#
# Example for development:
logger.setLevel(logging.DEBUG)
# If that prints too much, enable debug printing only for your component:
component_logger.setLevel(logging.DEBUG)
# For production you rather want:
logger.setLevel(logging.WARNING)
A common source of confusion comes from a badly initialised root logger. Consider this:
import logging
log = logging.getLogger("myapp")
log.warning("woot")
logging.basicConfig()
log.warning("woot")
Output:
woot
WARNING:myapp:woot
Depending on your runtime environment and logging levels, the first log line (before basic config) might not show up anywhere.
I m using the followung code and its working fine for me .
private void sendNotification(String msg) {
Log.d(TAG, "Preparing to send notification...: " + msg);
mNotificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("GCM Notification")
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_ALL)
.setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
.setContentText(msg);
mBuilder.setContentIntent(contentIntent);
mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
Log.d(TAG, "Notification sent successfully.");
}
Since typeof
is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof
and _Alignof
are also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;
can only be determined at run time.
This is an Inequality operator.
Also,this might be helpful for future: Operators listed by Functionality
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
Set a start page.
When I had this problem, I went into the solution explorer, found the page I wanted to see first (in my case "Home.aspx), right clicked on it and selected "Set As Start Page." This fixed my issue (which sounded really similar to yours). This was in Visual Studio 2012 Professional and I ran it in Firefox.
you can add async option to false and return outside the ajax call.
function testAjax() {
var result="";
$.ajax({
url:"getvalue.php",
async: false,
success:function(data) {
result = data;
}
});
return result;
}
Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z'
and Java 8 you could do
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);
Update: For pre 26 use Joda time
String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);
In app/build.gradle file, add like this-
dependencies {
compile 'joda-time:joda-time:2.9.4'
}
An easy approach would be making all the blank cells NA
and only keeping complete cases. You might also look for na.omit
examples. It is a widely discussed topic.
df[df==""]<-NA
df<-df[complete.cases(df),]
I found the best way to send input is to use cat and a text file to pass along whatever input you need.
cat "input.txt" | ./Script.sh
If you're running ubuntu container directly without a local Dockerfile you can ssh into the container and enable root control by entering su
then apt-get install -y wget
SQL Server Management Studio 2008 R2 Express commandline:
The answer by dyslexicanaboko hits the crucial point, but this one is even simpler and suited for command line (unattended scenarios):
(tried out with SQL Server 2008 R2 Express, one instance installed and having downloaded SQLManagementStudio_x64_ENU.exe)
As pointed out in this thread often enough, it is better to use the original SQL server setup (e.g. SQL Express with Tools), if possible, but there are some scenarios, where you want to add SSMS at a SQL derivative without that tools, afterwards:
I´ve already put it in a batch syntax here:
@echo off
"%~dp0SQLManagementStudio_x64_ENU.exe" /Q /ACTION="Install" /FEATURES="SSMS" /IACCEPTSQLSERVERLICENSETERMS
Remarks:
For 2008 without R2 it should be enough to omit the /IACCEPTSQLSERVERLICENSETERMS flag, i guess.
The /INDICATEPROGRESS parameter is useless here, the whole command takes a number of minutes and is 100% silent without any acknowledgement. Just look at the start menu, if the command is ready, if it has succeeded.
This should work for the "ADV_SSMS" Feature (instead of "SSMS") too, which is the management studio extended variant (profiling, reporting, tuning, etc.)
def is_valid_ip(ip):
"""Validates IP addresses.
"""
return is_valid_ipv4(ip) or is_valid_ipv6(ip)
IPv4:
def is_valid_ipv4(ip):
"""Validates IPv4 addresses.
"""
pattern = re.compile(r"""
^
(?:
# Dotted variants:
(?:
# Decimal 1-255 (no leading 0's)
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2} # Hexadecimal 0x0 - 0xFF (possible leading 0's)
|
0+[1-3]?[0-7]{0,2} # Octal 0 - 0377 (possible leading 0's)
)
(?: # Repeat 0-3 times, separated by a dot
\.
(?:
[3-9]\d?|2(?:5[0-5]|[0-4]?\d)?|1\d{0,2}
|
0x0*[0-9a-f]{1,2}
|
0+[1-3]?[0-7]{0,2}
)
){0,3}
|
0x0*[0-9a-f]{1,8} # Hexadecimal notation, 0x0 - 0xffffffff
|
0+[0-3]?[0-7]{0,10} # Octal notation, 0 - 037777777777
|
# Decimal notation, 1-4294967295:
429496729[0-5]|42949672[0-8]\d|4294967[01]\d\d|429496[0-6]\d{3}|
42949[0-5]\d{4}|4294[0-8]\d{5}|429[0-3]\d{6}|42[0-8]\d{7}|
4[01]\d{8}|[1-3]\d{0,9}|[4-9]\d{0,8}
)
$
""", re.VERBOSE | re.IGNORECASE)
return pattern.match(ip) is not None
IPv6:
def is_valid_ipv6(ip):
"""Validates IPv6 addresses.
"""
pattern = re.compile(r"""
^
\s* # Leading whitespace
(?!.*::.*::) # Only a single whildcard allowed
(?:(?!:)|:(?=:)) # Colon iff it would be part of a wildcard
(?: # Repeat 6 times:
[0-9a-f]{0,4} # A group of at most four hexadecimal digits
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
){6} #
(?: # Either
[0-9a-f]{0,4} # Another group
(?:(?<=::)|(?<!::):) # Colon unless preceeded by wildcard
[0-9a-f]{0,4} # Last group
(?: (?<=::) # Colon iff preceeded by exacly one colon
| (?<!:) #
| (?<=:) (?<!::) : #
) # OR
| # A v4 address with NO leading zeros
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
(?: \.
(?:25[0-4]|2[0-4]\d|1\d\d|[1-9]?\d)
){3}
)
\s* # Trailing whitespace
$
""", re.VERBOSE | re.IGNORECASE | re.DOTALL)
return pattern.match(ip) is not None
The IPv6 version uses "(?:(?<=::)|(?<!::):)
", which could be replaced with "(?(?<!::):)
" on regex engines that support conditionals with look-arounds. (i.e. PCRE, .NET)
Edit:
Edit2:
I found some links discussing how to parse IPv6 addresses with regex:
Edit3:
Finally managed to write a pattern that passes all tests, and that I am also happy with.
This depends on what you mean by "get the range of selection". If you mean getting the range address (like "A1:B1") then use the Address property of Selection object - as Michael stated Selection object is much like a Range object, so most properties and methods works on it.
Sub test()
Dim myString As String
myString = Selection.Address
End Sub
Try this:
class Flonetwork(Object):
def __init__(self,adj = {},flow={}):
self.adj = adj
self.flow = flow
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
add "throws IOException" to your method like this:
public static void main(String args[]) throws IOException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}
select age from student group by id having age<(select max(age) from student)order by age limit 1
A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.
View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.
A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.
Check this article : View vs Stored Procedures . Exactly what you are looking for
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
find($id)
takes an id and returns a single model. If no matching model exist, it returns null
.
findOrFail($id)
takes an id and returns a single model. If no matching model exist, it throws an error1.
first()
returns the first record found in the database. If no matching model exist, it returns null
.
firstOrFail()
returns the first record found in the database. If no matching model exist, it throws an error1.
get()
returns a collection of models matching the query.
pluck($column)
returns a collection of just the values in the given column. In previous versions of Laravel this method was called lists
.
toArray()
converts the model/collection into a simple PHP array.
Note: a collection is a beefed up array. It functions similarly to an array, but has a lot of added functionality, as you can see in the docs.
Unfortunately, PHP doesn't let you use a collection object everywhere you can use an array. For example, using a collection in a foreach
loop is ok, put passing it to array_map
is not. Similarly, if you type-hint an argument as array
, PHP won't let you pass it a collection. Starting in PHP 7.1, there is the iterable
typehint, which can be used to accept both arrays and collections.
If you ever want to get a plain array from a collection, call its all()
method.
1 The error thrown by the findOrFail
and firstOrFail
methods is a ModelNotFoundException
. If you don't catch this exception yourself, Laravel will respond with a 404, which is what you want most of the time.
string userName="";
string userId = "";
int uid = 0;
if (HttpContext.Current != null && HttpContext.Current.User != null
&& HttpContext.Current.User.Identity.Name != null)
{
userName = HttpContext.Current.User.Identity.Name;
}
using (DevEntities context = new DevEntities())
{
uid = context.Users.Where(x => x.UserName == userName).Select(x=>x.Id).FirstOrDefault();
return uid;
}
return uid;
Try:
DataTable.Rows[RowNo].ItemArray[columnIndex].ToString()
(This is C# code. Change this to VB equivalent)
The complete regular expression is:
-?(?:[_a-z]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])(?:[_a-z0-9-]|[\200-\377]|\\[0-9a-f]{1,6}(\r\n|[ \t\r\n\f])?|\\[^\r\n\f0-9a-f])*
So all of your listed character except “-
” and “_
” are not allowed if used directly. But you can encode them using a backslash foo\~bar
or using the unicode notation foo\7E bar
.
Try this.
Dim Workbk as workbook
Set Workbk = thisworkbook
Now everything you program will apply just for your containing macro workbook.
If you don't want to do it manually use Apache Commons - Codec library. The class you are looking at is: org.apache.commons.codec.net.URLCodec
String final url = "http://www.google.com?...."
String final urlSafe = org.apache.commons.codec.net.URLCodec.encode(url);
builder.setAutoCancel(true);
Tested on Android 9 also.
It really depends on the situation, for me its in fpm as I'm using PHP5-FPM. A solution to your problem could be a universal php.ini and then using a symbolic link created like:
ln -s /etc/php5/php.ini php.ini
Then any modifications you make will be in one general .ini file. This is probably not really the best solution though, you might want to look into modifying some configuration so that you literally use one file, on one location. Not multiple locations hacked together.
The standard Java classloader is a stickler for directory structure. Each entry in the classpath is a directory or jar file (or zip file, really), which it then searches for the given class file. For example, if your classpath is ".;my.jar", it will search for com.example.Foo in the following locations:
./com/example/
my.jar:/com/example/
That is, it will look in the subdirectory that has the 'modified name' of the package, where '.' is replaced with the file separator.
Also, it is noteworthy that you cannot nest .jar files.
Save the number of cents rather than dollars, and just do the format to dollars when you output it. That way you can use an integer which doesn't suffer from the precision issues.
In Eclipse goto Run->Run Configuration find the Name of the class you have been running, select it, click the Target tab then in "Additional Emulator Command Line Options" add:
-Xms512M -Xmx1524M
then click apply.
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
import java.util.Date;
public class IsDateBetween {
public static void main (String[] args) {
IsDateBetween idb=new IsDateBetween("12/05/2010"); // passing your Date
}
public IsDateBetween(String dd) {
long from=Date.parse("01/01/2000"); // From some date
long to=Date.parse("12/12/2010"); // To Some Date
long check=Date.parse(dd);
int x=0;
if((check-from)>0 && (to-check)>0)
{
x=1;
}
System.out.println ("From Date is greater Than ToDate : "+x);
}
}
This should do the trick for you.
For one word:
if (!string.Contains("One"))
For two words:
if (!(string.Contains("One") && string.Contains("Two")))
Just use break, like that:
int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
if(cont==50) { //if listViewItem reach 50 break out.
break;
}
cont++; //increment cont.
}
In my case, I had an Object-C file which was also in the same Target Membership. I fixed by adding #import "YourObjectCFileHeader.h"
inside file Bridging-Header.h
Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.
We had this issue as the host server had been updated to use TLS V1.2 and we were connecting using standard SSL. This was an update made as part of pen testing of the sites. We saw the issue in code connection, but not browsers going to the wsdl. Below code resolved:
if (System.Net.ServicePointManager.SecurityProtocol == (SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls))
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
Taken from here: How do I disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)
Html
$('#save').click(function(event) {
var jenis = $('#jenis').val();
var model = $('#model').val();
var harga = $('#harga').val();
var json = { "jenis" : jenis, "model" : model, "harga": harga};
$.ajax({
url: 'phone/save',
data: JSON.stringify(json),
type: "POST",
beforeSend: function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data){
alert(data);
}
});
event.preventDefault();
});
Controller
@Controller
@RequestMapping(value="/phone")
public class phoneController {
phoneDao pd=new phoneDao();
@RequestMapping(value="/save",method=RequestMethod.POST)
public @ResponseBody
int save(@RequestBody Smartphones phone)
{
return pd.save(phone);
}
Dao
public Integer save(Smartphones i) {
int id = 0;
Session session=HibernateUtil.getSessionFactory().openSession();
Transaction trans=session.beginTransaction();
try {
session.save(i);
id=i.getId();
trans.commit();
}
catch(HibernateException he){}
return id;
}
I discovered that the order of adding roles and features is important. On a fresh system I activate the role "application server" and there check explicitly .net, web server support and finally process activation service Then automatically a dialogue comes up that the role "Web server" needs to be added also.
James's answer works just fine if you know the name of the actual constraint. The tricky thing is that in legacy and other real world scenarios you may not know what the constraint is called.
If this is the case you risk creating duplicate constraints, to avoid you can use:
create function fnGetForeignKeyName
(
@ParentTableName nvarchar(255),
@ParentColumnName nvarchar(255),
@ReferencedTableName nvarchar(255),
@ReferencedColumnName nvarchar(255)
)
returns nvarchar(255)
as
begin
declare @name nvarchar(255)
select @name = fk.name from sys.foreign_key_columns fc
join sys.columns pc on pc.column_id = parent_column_id and parent_object_id = pc.object_id
join sys.columns rc on rc.column_id = referenced_column_id and referenced_object_id = rc.object_id
join sys.objects po on po.object_id = pc.object_id
join sys.objects ro on ro.object_id = rc.object_id
join sys.foreign_keys fk on fk.object_id = fc.constraint_object_id
where
po.object_id = object_id(@ParentTableName) and
ro.object_id = object_id(@ReferencedTableName) and
pc.name = @ParentColumnName and
rc.name = @ReferencedColumnName
return @name
end
go
declare @name nvarchar(255)
declare @sql nvarchar(4000)
-- hunt for the constraint name on 'Badges.BadgeReasonTypeId' table refs the 'BadgeReasonTypes.Id'
select @name = dbo.fnGetForeignKeyName('dbo.Badges', 'BadgeReasonTypeId', 'dbo.BadgeReasonTypes', 'Id')
-- if we find it, the name will not be null
if @name is not null
begin
set @sql = 'alter table Badges drop constraint ' + replace(@name,']', ']]')
exec (@sql)
end
[answer written based on python 3.4; the metaclass syntax differs in 2 but I think the technique will still work]
You can do this with a metaclass...mostly. Dappawit's almost works, but I think it has a flaw:
class MetaFoo(type):
@property
def thingy(cls):
return cls._thingy
class Foo(object, metaclass=MetaFoo):
_thingy = 23
This gets you a classproperty on Foo, but there's a problem...
print("Foo.thingy is {}".format(Foo.thingy))
# Foo.thingy is 23
# Yay, the classmethod-property is working as intended!
foo = Foo()
if hasattr(foo, "thingy"):
print("Foo().thingy is {}".format(foo.thingy))
else:
print("Foo instance has no attribute 'thingy'")
# Foo instance has no attribute 'thingy'
# Wha....?
What the hell is going on here? Why can't I reach the class property from an instance?
I was beating my head on this for quite a while before finding what I believe is the answer. Python @properties are a subset of descriptors, and, from the descriptor documentation (emphasis mine):
The default behavior for attribute access is to get, set, or delete the attribute from an object’s dictionary. For instance,
a.x
has a lookup chain starting witha.__dict__['x']
, thentype(a).__dict__['x']
, and continuing through the base classes oftype(a)
excluding metaclasses.
So the method resolution order doesn't include our class properties (or anything else defined in the metaclass). It is possible to make a subclass of the built-in property decorator that behaves differently, but (citation needed) I've gotten the impression googling that the developers had a good reason (which I do not understand) for doing it that way.
That doesn't mean we're out of luck; we can access the properties on the class itself just fine...and we can get the class from type(self)
within the instance, which we can use to make @property dispatchers:
class Foo(object, metaclass=MetaFoo):
_thingy = 23
@property
def thingy(self):
return type(self).thingy
Now Foo().thingy
works as intended for both the class and the instances! It will also continue to do the right thing if a derived class replaces its underlying _thingy
(which is the use case that got me on this hunt originally).
This isn't 100% satisfying to me -- having to do setup in both the metaclass and object class feels like it violates the DRY principle. But the latter is just a one-line dispatcher; I'm mostly okay with it existing, and you could probably compact it down to a lambda or something if you really wanted.
Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
mystring = mystring + chr(char)
print mystring
I experienced the same issue, but after turning off Hyper-V and enabling VT-x on my BIOS I still couldn't install the intelhaxm-android.exe program.
To fix my issue I had to turn off Windows defender Memory integrity
check here for steps -> https://github.com/intel/haxm/issues/105
Now, is more easy with HTML 5 and CSS 3:
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body > div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
}
</style>
</head>
<body>
<div>
<div>TODO write content</div>
</div>
</body>
</html>
var Data=[{"id": "name2", "label": "Quantity"}]
Pass the string variable into Json parse :
Objdata= Json.parse(Data);
This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.
Syntax example :
// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]>
This is the safest approach, considering it prevents accessing indexes out of the boundaries.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
& { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }
Tests :
var myFixedLengthArray: FixedLengthArray< [string, string, string]>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? INVALID INDEX ERROR
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR
(*) This solution requires the noImplicitAny
typescript configuration directive to be enabled in order to work (commonly recommended practice)
This solution behaves as an augmentation of the Array
type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.
Syntax example :
let foo: FixedLengthArray<string, 3>
Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.
Implementation :
type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
& {
readonly length: L
[ I : number ] : T
[Symbol.iterator]: () => IterableIterator<T>
}
Tests :
var myFixedLengthArray: FixedLengthArray<string,3>
// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ] // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ] // ? TYPE ERROR
myFixedLengthArray = [ 'a' ] // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ] // ? LENGTH ERROR
// Index assignment tests
myFixedLengthArray[1] = 'foo' // ? OK
myFixedLengthArray[1000] = 'foo' // ? SHOULD FAIL
// Methods that mutate array length
myFixedLengthArray.push('foo') // ? MISSING METHOD ERROR
myFixedLengthArray.pop() // ? MISSING METHOD ERROR
// Direct length manipulation
myFixedLengthArray.length = 123 // ? READ-ONLY ERROR
// Destructuring
var [ a ] = myFixedLengthArray // ? OK
var [ a, b ] = myFixedLengthArray // ? OK
var [ a, b, c ] = myFixedLengthArray // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL
def solution(A, K):
if len(A) == 0:
return A
K = K % len(A)
return A[-K:] + A[:-K]
# use case
A = [1, 2, 3, 4, 5, 6]
K = 3
print(solution(A, K))
For example, given
A = [3, 8, 9, 7, 6]
K = 3
the function should return [9, 7, 6, 3, 8]
. Three rotations were made:
[3, 8, 9, 7, 6] -> [6, 3, 8, 9, 7]
[6, 3, 8, 9, 7] -> [7, 6, 3, 8, 9]
[7, 6, 3, 8, 9] -> [9, 7, 6, 3, 8]
For another example, given
A = [0, 0, 0]
K = 1
the function should return [0, 0, 0]
Given
A = [1, 2, 3, 4]
K = 4
the function should return [1, 2, 3, 4]
I had a similar issue running unit tests using MSTEST under Jenkins. The fix in my case was to remove "Version=6.0.0.0, " as shown below:
Old:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=xxxx" requirePermission="false" />
New:
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Culture=neutral, PublicKeyToken=xxxx" requirePermission="false" />
I had to make this change is several App.config and Web.config files in my multi-project solution.
The problem is that t.join() blocks the click event, the main thread does not get back to the event loop to process repaints. See Why ttk Progressbar appears after process in Tkinter or TTK progress bar blocked when sending email
I make it work by using threading and handler/message. Steps as follow: Declare a progress Dialog
ProgressDialog loadingdialog;
Create a function to close dialog when operation is finished.
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
loadingdialog.dismiss();
}
};
Code your Execution details:
public void startUpload(String filepath) {
loadingdialog = ProgressDialog.show(MainActivity.this, "Uploading", "Uploading Please Wait", true);
final String _path = filepath;
new Thread() {
public void run() {
try {
UploadFile(_path, getHostName(), getPortNo());
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e("threadmessage", e.getMessage());
}
}
}.start();
}
Do yourself a favor by dropping the Windows compatibility layer.
The normal shortcut for entering Visual-Block mode is <C-v>
.
Others have dealt with recording macros, here are a few other ideas:
Using only visual-block mode.
Put the cursor on the second word:
asd |a|sd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom:
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
asd [a]sd asd asd asd;
Hit I"<Esc>
to obtain:
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
Put the cursor on the last char of the third word:
asd "asd as|d| asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
asd "asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom:
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
asd "asd as[d] asd asd;
Hit A"<Esc>
to obtain:
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
With visual-block mode and Surround.vim.
Put the cursor on the second word:
asd |a|sd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
asd asd asd asd asd;
Hit <C-v>
to enter visual-block mode and expand your selection toward the bottom and the right:
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
asd [asd asd] asd asd;
Hit S"
to surround your selection with ":
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
With visual-line mode and :normal
.
Hit V
to select the whole line and expand it toward the bottom:
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
[asd asd asd asd asd;]
Execute this command: :'<,'>norm ^wi"<C-v><Esc>eea"<CR>
to obtain:
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
asd "asd asd" asd asd;
:norm[al]
allows you to execute normal mode commands on a range of lines (the '<,'>
part is added automatically by Vim and means "act on the selected area")
^
puts the cursor on the first char of the line
w
moves to the next word
i"
inserts a "
before the cursor
<C-v><Esc>
is Vim's way to input a control character in this context, here it's <Esc>
used to exit insert mode
ee
moves to the end of the next word
a"
appends a "
after the cursor
<CR>
executes the command
Using Surround.vim, the command above becomes
:'<,'>norm ^wvees"<CR>
In Objective-C, a selector's signature consists of:
Selectors have no knowledge of:
Here's a class implementation where performMethodsViaSelectors method performs the other class methods by way of selectors:
@implementation ClassForSelectors
- (void) fooNoInputs {
NSLog(@"Does nothing");
}
- (void) fooOneIput:(NSString*) first {
NSLog(@"Logs %@", first);
}
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
NSLog(@"Logs %@ then %@", first, second);
}
- (void) performMethodsViaSelectors {
[self performSelector:@selector(fooNoInputs)];
[self performSelector:@selector(fooOneInput:) withObject:@"first"];
[self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first" withObject:@"second"];
}
@end
The method you want to create a selector for has a single input, so you would create a selector for it like so:
SEL myTestSelector = @selector(myTest:);
Sometimes e.preventDefault(); works then developers are happy but sometimes not work then developers are sad then I found solution why sometimes not works
first code sometimes works
$("#prospects_form").submit(function(e) {
e.preventDefault();
});
second option why not work? This doesn't work because jquery or other javascript library not loading properly you can check it in console that all jquery and javascript files are loaded properly or not.
This solves my problem. I hope this will be helpful for you.
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
You're remarkably close.
Here's the code you wrote in the question:
questionText.replace(/[0-9]/g, '');
The code you've written does indeed look at the questionText variable, and produce output which is the original string, but with the digits replaced with empty string.
However, it doesn't assign it automatically back to the original variable. You need to specify what to assign it to:
questionText = questionText.replace(/[0-9]/g, '');
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
if you POJO contains any other model inside that should also implements Serializable
Found this example... Will test...
import java.text.DecimalFormat;
class TestingAndQualityAssuranceDepartment
{
public static void main(String [] args)
{
int x=1;
DecimalFormat df = new DecimalFormat("00");
System.out.println(df.format(x));
}
}
Tested this and:
String.format("%05d",number);
Both work, for my purposes I think String.Format is better and more succinct.
I think what you're looking for is !!val==false
which can be turned to !val
(even shorter):
You see:
function checkValue(value) {
console.log(!!value);
}
checkValue(); // false
checkValue(null); // false
checkValue(undefined); // false
checkValue(false); // false
checkValue(""); // false
checkValue(true); // true
checkValue({}); // true
checkValue("any string"); // true
That works by flipping the value by using the !
operator.
If you flip null
once for example like so :
console.log(!null) // that would output --> true
If you flip it twice like so :
console.log(!!null) // that would output --> false
Same with undefined
or false
.
Your code:
if(val==null || val===false){
;
}
would then become:
if(!val) {
;
}
That would work for all cases even when there's a string but it's length is zero.
Now if you want it to also work for the number 0 (which would become false
if it was double flipped) then your if would become:
if(!val && val !== 0) {
// code runs only when val == null, undefined, false, or empty string ""
}
I use mostly 978px width for my designs. Adv. of 978px : can be divided by 2,3.
Did you try passwd -d root
? Most likely, this will do what you want.
You can also manually edit /etc/shadow
: (Create a backup copy. Be sure that you can log even if you mess up, for example from a rescue system.) Search for "root". Typically, the root entry looks similar to
root:$X$SK5xfLB1ZW:0:0...
There, delete the second field (everything between the first and second colon):
root::0:0...
Some systems will make you put an asterisk (*) in the password field instead of blank, where a blank field would allow no password (CentOS 8 for example)
root:*:0:0...
Save the file, and try logging in as root. It should skip the password prompt. (Like passwd -d
, this is a "no password" solution. If you are really looking for a "blank password", that is "ask for a password, but accept if the user just presses Enter", look at the manpage of mkpasswd
, and use mkpasswd
to create the second field for the /etc/shadow.)
There are 2 options to find matching text; string.match
or string.find
.
Both of these perform a regex search on the string to find matches.
string.find()
string.find(subject string, pattern string, optional start position, optional plain flag)
Returns the startIndex
& endIndex
of the substring found.
The plain
flag allows for the pattern to be ignored and intead be interpreted as a literal. Rather than (tiger)
being interpreted as a regex capture group matching for tiger
, it instead looks for (tiger)
within a string.
Going the other way, if you want to regex match but still want literal special characters (such as .()[]+-
etc.), you can escape them with a percentage; %(tiger%)
.
You will likely use this in combination with string.sub
str = "This is some text containing the word tiger."
if string.find(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
string.match()
string.match(s, pattern, optional index)
Returns the capture groups found.
str = "This is some text containing the word tiger."
if string.match(str, "tiger") then
print ("The word tiger was found.")
else
print ("The word tiger was not found.")
end
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019
(depending on the current date)
To see where the data directory is, use this query.
show data_directory;
To see all the run-time parameters, use
show all;
You can create tablespaces to store database objects in other parts of the filesystem. To see tablespaces, which might not be in that data directory, use this query.
SELECT * FROM pg_tablespace;
Both are used to send some data and receive some response using that data.
GET: Get information stored in the server. (i.e. search, tweet, person information). If you want to send information then get request send request using process.php?name=subroto
So it basically sends information through url. Url cannot handle more than 2036 char. So for blog post can you remember it is not possible?
POST: Post do same thing as GET. User registration, User login, Big data send, Blog Post. If you need to send secure information then use post or for big data as it not go through url.
AJAX: $.get()
and $.post()
contain features that are subsets of $.ajax()
. It has more configuration.
$.get ()
method, which is a kind of shorthand for $.ajax()
. When using $.get ()
, instead of passing in an object, you pass in arguments. At minimum, you’ll need the first two arguments, which are the URL of the file you want to retrieve (eg. test.txt) and a success callback.
From: http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html
Class path entries can contain the basename wildcard character
*
, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entryfoo/*
specifies all JAR files in the directory named foo. A classpath entry consisting simply of*
expands to a list of all the jar files in the current directory.
This should work in Java6, not sure about Java5
(If it seems it does not work as expected, try putting quotes. eg: "foo/*"
)
To capitalize the first letter of the input string, we first split the string on space and then use the collection transformation procedure provided by map
<T, R> Array<out T>.map(
transform: (T) -> R
): List<R>
to transform, each split string to first in lowercase then capitalize the first letter. This map transformation will return a list that needs to convert into a string by using joinToString function.
KOTLIN
fun main() {
/*
* Program that first convert all uper case into lower case then
* convert fist letter into uppercase
*/
val str = "aLi AzAZ alam"
val calStr = str.split(" ").map{it.toLowerCase().capitalize()}
println(calStr.joinToString(separator = " "))
}
OUTPUT
Simply obj instanceof Object[]
(tested on JShell).
class App extends React.Component {_x000D_
constructor() {_x000D_
super();_x000D_
this.state = {value : ''}_x000D_
}_x000D_
handleChange = (e) =>{ _x000D_
this.setState({value: e.target.value});_x000D_
}_x000D_
render() {_x000D_
return (_x000D_
<div>_x000D_
<input type="text" value={this.state.value} onChange={this.handleChange}/>_x000D_
<div>{this.state.value}</div>_x000D_
</div>_x000D_
)_x000D_
}_x000D_
}_x000D_
ReactDOM.render(<App/>, document.getElementById('app'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.js"></script>_x000D_
<div id="app"></div>
_x000D_
Even though this isn't entirely in the SO spirit, I love this question, because I had the same trouble when I started, so I'll give you a quick guide. Obviously you don't understand the principles behind them (don't take it as an offense, but if you did you wouldn't be asking).
Django is server-side. It means, say a client goes to a URL, you have a function inside views
that renders what he sees and returns a response in HTML. Let's break it up into examples:
views.py:
def hello(request):
return HttpResponse('Hello World!')
def home(request):
return render_to_response('index.html', {'variable': 'world'})
index.html:
<h1>Hello {{ variable }}, welcome to my awesome site</h1>
urls.py:
url(r'^hello/', 'myapp.views.hello'),
url(r'^home/', 'myapp.views.home'),
That's an example of the simplest of usages. Going to 127.0.0.1:8000/hello
means a request to the hello()
function, going to 127.0.0.1:8000/home
will return the index.html
and replace all the variables as asked (you probably know all this by now).
Now let's talk about AJAX. AJAX calls are client-side code that does asynchronous requests. That sounds complicated, but it simply means it does a request for you in the background and then handles the response. So when you do an AJAX call for some URL, you get the same data you would get as a user going to that place.
For example, an AJAX call to 127.0.0.1:8000/hello
will return the same thing it would as if you visited it. Only this time, you have it inside a JavaScript function and you can deal with it however you'd like. Let's look at a simple use case:
$.ajax({
url: '127.0.0.1:8000/hello',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});
The general process is this:
127.0.0.1:8000/hello
as if you opened a new tab and did it yourself.Now what would happen here? You would get an alert with 'hello world' in it. What happens if you do an AJAX call to home? Same thing, you'll get an alert stating <h1>Hello world, welcome to my awesome site</h1>
.
In other words - there's nothing new about AJAX calls. They are just a way for you to let the user get data and information without leaving the page, and it makes for a smooth and very neat design of your website. A few guidelines you should take note of:
console.log
things to debug. I won't explain in detail, just google around and find out about it. It would be very helpful to you.csrf_token
. With AJAX calls, a lot of times you'd like to send data without refreshing the page. You'll probably face some trouble before you'd finally remember that - wait, you forgot to send the csrf_token
. This is a known beginner roadblock in AJAX-Django integration, but after you learn how to make it play nice, it's easy as pie.That's everything that comes to my head. It's a vast subject, but yeah, there's probably not enough examples out there. Just work your way there, slowly, you'll get it eventually.
Now W3c provides an official difference on their site:
For the right triangle, for each row :
rowNumber - 1 - i
. \*
from rowNumber - 1 - i
to rowNumber
.Note: i
is the row index from 0 to rowNumber
and rowNumber
is number of rows.
For the centre triangle: it looks like "right triangle" plus adding \*
according to the row index (for ex : in first row you will add nothing because the index is 0 , in the second row you will add one ' * ', and so on).
public class InitHelloWorld implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("BeforeInitialization : " + beanName);
return bean; // you can return any other object as well
}
public Object postProcessAfterInitialization(Object bean,
String beanName) throws BeansException {
System.out.println("AfterInitialization : " + beanName);
return bean; // you can return any other object as well
}
}
There is one important thing to mention:
$("#txt_name").val();
will return the current real value of a text field, for example if the user typed something there after a page load.
But:
$("#txt_name").attr('value')
will return value from DOM/HTML.
Saw this today a little late but just want to put this here in case someone else needed. just separate the function to make it reusable. the code below will wait 1/2 second after typing stop.
var timeOutVar
$(selector).on('keyup', function() {
clearTimeout(timeOutVar);
timeOutVar= setTimeout(function(){ console.log("Hello"); }, 500);
});
Please remove e.preventDefault()
, because event.cancelable
of touchmove is false
.
So you can't call this method.
I found this solution:
This query select last not null value for each column.
Example
If you have a table:
id|title|body
1 |t1 |b1
2 |NULL |b2
3 |t3 |NULL
you get:
title|body
t3 |b2
Query
SELECT DISTINCT (
SELECT title
FROM test
WHERE title IS NOT NULL
ORDER BY id DESC
LIMIT 1
) title, (
SELECT body
FROM test
WHERE body IS NOT NULL
ORDER BY id DESC
LIMIT 1
) body
FROM test
I hope help you.
You can unload a ClassLoader but you cannot unload specific classes. More specifically you cannot unload classes created in a ClassLoader that's not under your control.
If possible, I suggest using your own ClassLoader so you can unload.
You have a JSON object that contains an Array. You need to access the array results
. Change your code to:
this.data = res.json().results
i = ++a + ++a + a++;
is
i = 6 + 7 + 7
Working: increment a to 6 (current value 6) + increment a to 7 (current value 7). Sum is 13 now add it to current value of a (=7) and then increment a to 8. Sum is 20 and value of a after the assignment completes is 8.
i = a++ + ++a + ++a;
is
i = 5 + 7 + 8
Working: At the start value of a is 5. Use it in the addition and then increment it to 6 (current value 6). Increment a from current value 6 to 7 to get other operand of +. Sum is 12 and current value of a is 7. Next increment a from 7 to 8 (current value = 8) and add it to previous sum 12 to get 20.
Consider Moshi's JsonWriter class (source). It has a wonderful API and it reduces copying to a minimum, everything is nicely streamed to the OutputStream.
OutputStream os = ...;
JsonWriter json = new JsonWriter(Okio.sink(os));
json
.beginObject()
.name("id").value(userID)
.name("type").value(methodn)
...
.endObject();
I made a small recursive function that goes through the entire json object and saves the key path and its value.
// My stored keys and values from the json object
HashMap<String,String> myKeyValues = new HashMap<String,String>();
// Used for constructing the path to the key in the json object
Stack<String> key_path = new Stack<String>();
// Recursive function that goes through a json object and stores
// its key and values in the hashmap
private void loadJson(JSONObject json){
Iterator<?> json_keys = json.keys();
while( json_keys.hasNext() ){
String json_key = (String)json_keys.next();
try{
key_path.push(json_key);
loadJson(json.getJSONObject(json_key));
}catch (JSONException e){
// Build the path to the key
String key = "";
for(String sub_key: key_path){
key += sub_key+".";
}
key = key.substring(0,key.length()-1);
System.out.println(key+": "+json.getString(json_key));
key_path.pop();
myKeyValues.put(key, json.getString(json_key));
}
}
if(key_path.size() > 0){
key_path.pop();
}
}
On Windows 8.1 I had to run cmd.exe as administrator (even though I was logged in as admin). Otherwise I got an error when trying to execute: httpd.exe -k uninstall
Error: C:\Program Files\Apache\bin>(OS 5)Access is denied. : AH00373: Apache2.4: OpenS ervice failed
The default namespace in Python is "__main__"
. When you use import scipy
, Python creates a separate namespace as your module name.
The rule in Pyhton is: when you want to call an attribute from another namespaces you have to use the fully qualified attribute name.
For this problem,
What i did is:
app/tmp/
and then, close the terminal which we are running the current app and close the tab (in, browser window)
after that, again open the terminal by going inside the folder, and then do, rails s
window.onload = function() {
var txts = document.getElementsByTagName('TEXTAREA');
for(var i = 0, l = txts.length; i < l; i++) {
if(/^[0-9]+$/.test(txts[i].getAttribute("maxlength"))) {
var func = function() {
var len = parseInt(this.getAttribute("maxlength"), 10);
if(this.value.length > len) {
alert('Maximum length exceeded: ' + len);
this.value = this.value.substr(0, len);
return false;
}
}
txts[i].onkeyup = func;
txts[i].onblur = func;
}
};
}
You're close. A really simple solution is just to get the length from the 'run' objects returned. No need to bother with 'load' or 'loads':
len(data['result'][0]['run'])
before you run in cmd prompt, make sure "appsettings.json" has same values as "appsettings.Development.json".
In command prompt, go all the way to bin/debug/netcoreapp2.0 folder. then run "dotnet applicationname.dll"
If you have empty rows, not NAs, you can do:
data[!apply(data == "", 1, all),]
To remove both (NAs and empty):
data <- data[!apply(is.na(data) | data == "", 1, all),]
Wrap them in another class so that you can end up with a single array or List
of those objects.
public class Data {
private String txtFileName;
private String imgFileName;
// Add/generate c'tor, getter/setter, equals, hashCode and other boilerplate.
}
Usage example:
List<Data> list = new ArrayList<Data>();
list.add(new Data("H1.txt", "e1.jpg"));
list.add(new Data("H2.txt", "e2.jpg"));
// ...
Collections.shuffle(list);
I totally agree with the answers before. I just like to mention that the difference between expose and ports is part of the security concept in docker. It goes hand in hand with the networking of docker. For example:
Imagine an application with a web front-end and a database back-end. The outside world needs access to the web front-end (perhaps on port 80), but only the back-end itself needs access to the database host and port. Using a user-defined bridge, only the web port needs to be opened, and the database application doesn’t need any ports open, since the web front-end can reach it over the user-defined bridge.
This is a common use case when setting up a network architecture in docker. So for example in a default bridge network, not ports are accessible from the outer world. Therefor you can open an ingresspoint with "ports". With using "expose" you define communication within the network. If you want to expose the default ports you don't need to define "expose" in your docker-compose file.
git shortlog
is one way.
It could be the way you are applying the DataContext to the Page. In WPF, everytime you navigate to a Page everything gets re-initialized, constructor gets called, loaded methods, everything. so if you are setting your DataContext inside your View you will no doubt be blowing away that SelectedItem that the user selected. In order to avoid that use the KeepAlive property of your pages.
<Page KeepAlive="True" ...>
...
</Page>
This will result in only the Loaded event being fired when navigating back to a page you have already visited. So you will need to ensure that you are setting the DataContext on Initialize (either externally or within the constructor) rather than Load.
However, this will only work for that instance of the Page. If you navigate to a new instance of that page it constructor will be called again.
Clear text:
"Text field with a clear text trailing icon."
If set, an icon is displayed when text is present and pressing it clears the input text.
...
app:endIconMode="clear_text">
?
...
?
</com.google.android.material.textfield.TextInputLayout>
I leave it here:
You can try this:
#!/bin/sh
nohup java -jar /web/server.jar &
The & symbol, switches the program to run in the background.
The nohup utility makes the command passed as an argument run in the background even after you log out.
In computer science, declarative programming is a programming paradigm that expresses the logic of a computation without describing its control flow.
From http://en.wikipedia.org/wiki/Declarative_programming
in a nutshell the declarative language is simpler because it lacks the complexity of control flow ( loops, if statements, etc. )
A good comparison is the ASP.Net 'code-behind' model. You have declarative '.ASPX' files and then the imperative 'ASPX.CS' code files. I often find that if I can do all I need in the declarative half of the script a lot more people can follow what's being done.
You can union the queries as long as the columns match.
SELECT name,
games,
goals
FROM tblMadrid
WHERE id = 1
UNION ALL
SELECT name,
games,
goals
FROM tblBarcelona
WHERE id = 2
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
http://en.wikipedia.org/wiki/Unix_time#History explains a little about the origins of Unix time and the chosen epoch. The definition of unix time and the epoch date went through a couple of changes before stabilizing on what it is now.
But it does not say why exactly 1/1/1970 was chosen in the end.
Notable excerpts from the Wikipedia page:
The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".
Because of [the] limited range, the epoch was redefined more than once, before the rate was changed to 1 Hz and the epoch was set to its present value.
Several later problems, including the complexity of the present definition, result from Unix time having been defined gradually by usage rather than fully defined to start with.
I'd use something like:
dim customer = (from c in xmldoc...<Customer>
where c.<ID>.Value=22
select c).SingleOrDefault
Edit:
missed the c# tag, sorry......the example is in VB.NET
You can find every content type here: http://www.iana.org/assignments/media-types/media-types.xhtml
The most common type are:
Type application
application/java-archive
application/EDI-X12
application/EDIFACT
application/javascript
application/octet-stream
application/ogg
application/pdf
application/xhtml+xml
application/x-shockwave-flash
application/json
application/ld+json
application/xml
application/zip
application/x-www-form-urlencoded
Type audio
audio/mpeg
audio/x-ms-wma
audio/vnd.rn-realaudio
audio/x-wav
Type image
image/gif
image/jpeg
image/png
image/tiff
image/vnd.microsoft.icon
image/x-icon
image/vnd.djvu
image/svg+xml
Type multipart
multipart/mixed
multipart/alternative
multipart/related (using by MHTML (HTML mail).)
multipart/form-data
Type text
text/css
text/csv
text/html
text/javascript (obsolete)
text/plain
text/xml
Type video
video/mpeg
video/mp4
video/quicktime
video/x-ms-wmv
video/x-msvideo
video/x-flv
video/webm
Type vnd :
application/vnd.android.package-archive
application/vnd.oasis.opendocument.text
application/vnd.oasis.opendocument.spreadsheet
application/vnd.oasis.opendocument.presentation
application/vnd.oasis.opendocument.graphics
application/vnd.ms-excel
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.ms-powerpoint
application/vnd.openxmlformats-officedocument.presentationml.presentation
application/msword
application/vnd.openxmlformats-officedocument.wordprocessingml.document
application/vnd.mozilla.xul+xml
Here are a few more tips:
In Arch Linux the global one is at /etc/vimrc
. There are some comments in there with helpful details.
Since the filename starts with a .
, it's hidden unless you use ls -a
to show ALL files.
Typing :version
while in Vim will show you a bunch of interesting information including the file location.
If you're not sure what ~/.vimrc
means look at this question.
Bit late to the party, but was surprised not to see what I think is the simplest solution here:
import io
import subprocess
proc = subprocess.Popen(["prog", "arg"], stdout=subprocess.PIPE)
for line in io.TextIOWrapper(proc.stdout, encoding="utf-8"): # or another encoding
# do something with line
(This requires Python 3.)
Here you go: http://mochajs.org/#test-level
it('accesses the network', function(done){
this.timeout(500);
[Put network code here, with done() in the callback]
})
For arrow function use as follows:
it('accesses the network', (done) => {
[Put network code here, with done() in the callback]
}).timeout(500);
Use this method (No need to xml file)
If you want scale to quarter(half x,half y)
view.animate().scaleX(0.5f).scaleY(0.5f)
If you want scale and move to bottom right
view.animate().scaleX(0.5f).scaleY(0.5f)
.translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())
If you want move to top use (-view.height/4)
and for left (-view.width/4)
If you want do something after animation ends use withEndAction(Runnable runnable)
function.
You can use some other property like alpha and rotation
Full code
view.animate()
.scaleX(0.5f).scaleY(0.5f)//scale to quarter(half x,half y)
.translationY((view.height/4).toFloat()).translationX((view.width/4).toFloat())// move to bottom / right
.alpha(0.5f) // make it less visible
.rotation(360f) // one round turns
.setDuration(1000) // all take 1 seconds
.withEndAction(new Runnable() {
@Override
public void run() {
//animation ended
}
});
Inspite of using all the matchers, I was getting the same issue:
"org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Invalid use of argument matchers!
1 matchers expected, 3 recorded:"
It took me little while to figure this out that the method I was trying to mock was a static method of a class(say Xyz.class) which contains only static method and I forgot to write following line:
PowerMockito.mockStatic(Xyz.class);
May be it will help others as it may also be the cause of the issue.
For Java 9 :
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>9</source>
<target>9</target>
</configuration>
</plugin>
</plugins>
</build>
The suggested answer only works for certain versions of ruby. Some commenters suggest using ruby-dev; that didn't work for me either.
sudo apt-get install ruby-all-dev
worked for me.
Just use the build-in feature of Angular CLI
ng update
to update to the latest version.
You don't need regular expressions. Python has a built-in string method that does what you need:
mystring.replace(" ", "_")
This approach seems more straightforward, avoiding the need to individually select each file:
# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours
or
# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours
Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull
Example:
ALTER TABLE [Employees] ADD Seniority int not null default 0 GO
Using COUNT instead of SUM removes the requirement for an ELSE statement:
SELECT jobId, jobName,
COUNT(CASE WHEN Priority=1 THEN 1 END) AS Priority1,
COUNT(CASE WHEN Priority=2 THEN 1 END) AS Priority2,
COUNT(CASE WHEN Priority=3 THEN 1 END) AS Priority3,
COUNT(CASE WHEN Priority=4 THEN 1 END) AS Priority4,
COUNT(CASE WHEN Priority=5 THEN 1 END) AS Priority5
FROM TableName
GROUP BY jobId, jobName
A solution to take the backup of your Database in "dbBackup" Folder / Directory
<?php
error_reporting(E_ALL);
/* Define database parameters here */
define("DB_USER", 'root');
define("DB_PASSWORD", 'root');
define("DB_NAME", 'YOUR_DATABASE_NAME');
define("DB_HOST", 'localhost');
define("OUTPUT_DIR", 'dbBackup'); // Folder Path / Directory Name
define("TABLES", '*');
/* Instantiate Backup_Database and perform backup */
$backupDatabase = new Backup_Database(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
$status = $backupDatabase->backupTables(TABLES, OUTPUT_DIR) ? 'OK' : 'KO';
echo "Backup result: " . $status;
/* The Backup_Database class */
class Backup_Database {
private $conn;
/* Constructor initializes database */
function __construct( $host, $username, $passwd, $dbName, $charset = 'utf8' ) {
$this->dbName = $dbName;
$this->connectDatabase( $host, $username, $passwd, $charset );
}
protected function connectDatabase( $host, $username, $passwd, $charset ) {
$this->conn = mysqli_connect( $host, $username, $passwd, $this->dbName);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
exit();
}
/* change character set to $charset Ex : "utf8" */
if (!mysqli_set_charset($this->conn, $charset)) {
printf("Error loading character set ".$charset.": %s\n", mysqli_error($this->conn));
exit();
}
}
/* Backup the whole database or just some tables Use '*' for whole database or 'table1 table2 table3...' @param string $tables */
public function backupTables($tables = '*', $outputDir = '.') {
try {
/* Tables to export */
if ($tables == '*') {
$tables = array();
$result = mysqli_query( $this->conn, 'SHOW TABLES' );
while ( $row = mysqli_fetch_row($result) ) {
$tables[] = $row[0];
}
} else {
$tables = is_array($tables) ? $tables : explode(',', $tables);
}
$sql = 'CREATE DATABASE IF NOT EXISTS ' . $this->dbName . ";\n\n";
$sql .= 'USE ' . $this->dbName . ";\n\n";
/* Iterate tables */
foreach ($tables as $table) {
echo "Backing up " . $table . " table...";
$result = mysqli_query( $this->conn, 'SELECT * FROM ' . $table );
// Return the number of fields in result set
$numFields = mysqli_num_fields($result);
$sql .= 'DROP TABLE IF EXISTS ' . $table . ';';
$row2 = mysqli_fetch_row( mysqli_query( $this->conn, 'SHOW CREATE TABLE ' . $table ) );
$sql.= "\n\n" . $row2[1] . ";\n\n";
for ($i = 0; $i < $numFields; $i++) {
while ($row = mysqli_fetch_row($result)) {
$sql .= 'INSERT INTO ' . $table . ' VALUES(';
for ($j = 0; $j < $numFields; $j++) {
$row[$j] = addslashes($row[$j]);
// $row[$j] = ereg_replace("\n", "\\n", $row[$j]);
if (isset($row[$j])) {
$sql .= '"' . $row[$j] . '"';
} else {
$sql.= '""';
}
if ($j < ($numFields - 1)) {
$sql .= ',';
}
}
$sql.= ");\n";
}
} // End :: for loop
mysqli_free_result($result); // Free result set
$sql.="\n\n\n";
echo " OK <br/>" . "";
}
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return $this->saveFile($sql, $outputDir);
}
/* Save SQL to file @param string $sql */
protected function saveFile(&$sql, $outputDir = '.') {
if (!$sql)
return false;
try {
$handle = fopen($outputDir . '/db-backup-' . $this->dbName . '-' . date("Ymd-His", time()) . '.sql', 'w+');
fwrite($handle, $sql);
fclose($handle);
mysqli_close( $this->conn );
} catch (Exception $e) {
var_dump($e->getMessage());
return false;
}
return true;
}
} // End :: class Backup_Database
?>
Please post your code,
<?php
echo $_GET['link'];
?>
or
<?php
echo $_REQUEST['link'];
?>
do work...
Why not just use, toggleClass on click?
js:
$(this).toggleClass("up");
css:
button.up {
-webkit-transform: rotate(180deg);
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);
/* IE6–IE9 */
filter: progid:DXImageTransform.Microsoft.Matrix(M11=0.9914448613738104, M12=-0.13052619222005157,M21=0.13052619222005157, M22=0.9914448613738104, sizingMethod='auto expand');
zoom: 1;
}
you can also add this to the css:
button{
-webkit-transition: all 500ms ease-in-out;
-moz-transition: all 500ms ease-in-out;
-o-transition: all 500ms ease-in-out;
-ms-transition: all 500ms ease-in-out;
}
which will add the animation.
PS...
to answer your original question:
you said that it rotates but never stops. When using set timeout you need to make sure you have a condition that will not call settimeout or else it will run forever. So for your code:
<script type="text/javascript">
$(function() {
var $elie = $("#bkgimg");
rotate(0);
function rotate(degree) {
// For webkit browsers: e.g. Chrome
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
// For Mozilla browser: e.g. Firefox
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
/* add a condition here for the extremity */
if(degree < 180){
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
}
}
});
</script>
I was bored and playing around JSPerf trying to beat the currently selected answer prepending a zero no matter what and using slice(-2)
. It's a clever approach but the performance gets a lot worse as the string gets longer.
For numbers zero to ten (one and two character strings) I was able to beat by about ten percent, and the fastest approach was much better when dealing with longer strings by using charAt
so it doesn't have to traverse the whole string.
This follow is not quit as simple as slice(-2)
but is 86%-89% faster when used across mostly 3 digit numbers (3 character strings).
var prepended = ( 1 === string.length && string.charAt( 0 ) !== "0" ) ? '0' + string : string;
(i, j, n + 1) = k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
(k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))
To continue a statement from one line to the next, type a space followed by the line-continuation character [the underscore character on your keyboard (_)].
You can break a line at an operator, list separator, or period.
To accomodate all three points:
The file dialog is a setting in the browser.
For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
let dataURL = canvas.toDataURL('image/png');
let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
downloadLink.setAttribute('href', url);
downloadLink.click();
}
Another, somewhat cleaner, approach is using Canvas.toBlob():
function DownloadCanvasAsImage(){
let downloadLink = document.createElement('a');
downloadLink.setAttribute('download', 'CanvasAsImage.png');
let canvas = document.getElementById('myCanvas');
canvas.toBlob(function(blob) {
let url = URL.createObjectURL(blob);
downloadLink.setAttribute('href', url);
downloadLink.click();
});
}
Neither solution is 100% cross browser compatible, so check the client
For an inheritance-friendly implementation, check out Tal Cohen's solution, How Do I Correctly Implement the equals() Method?
Summary:
In his book Effective Java Programming Language Guide (Addison-Wesley, 2001), Joshua Bloch claims that "There is simply no way to extend an instantiable class and add an aspect while preserving the equals contract." Tal disagrees.
His solution is to implement equals() by calling another nonsymmetric blindlyEquals() both ways. blindlyEquals() is overridden by subclasses, equals() is inherited, and never overridden.
Example:
class Point {
private int x;
private int y;
protected boolean blindlyEquals(Object o) {
if (!(o instanceof Point))
return false;
Point p = (Point)o;
return (p.x == this.x && p.y == this.y);
}
public boolean equals(Object o) {
return (this.blindlyEquals(o) && o.blindlyEquals(this));
}
}
class ColorPoint extends Point {
private Color c;
protected boolean blindlyEquals(Object o) {
if (!(o instanceof ColorPoint))
return false;
ColorPoint cp = (ColorPoint)o;
return (super.blindlyEquals(cp) &&
cp.color == this.color);
}
}
Note that equals() must work across inheritance hierarchies if the Liskov Substitution Principle is to be satisfied.
Have a look at the mainpage
command.
Also, have a look this answer to another thread: How to include custom files in Doxygen. It states that there are three extensions which doxygen classes as additional documentation files: .dox
, .txt
and .doc
. Files with these extensions do not appear in the file index but can be used to include additional information into your final documentation - very useful for documentation that is necessary but that is not really appropriate to include with your source code (for example, an FAQ)
So I would recommend having a mainpage.dox
(or similarly named) file in your project directory to introduce you SDK. Note that inside this file you need to put one or more C/C++ style comment blocks.
I know this has already been answered, but still, this is a good way to do it:
if ($("#checkbox").is(":checked")==false) {
//Do stuff here like: $(".span").html("<span>Lorem</span>");
}
This should work:
//iterate the array
for (int i = 0; i < theData.Length; i+=3)
{
//grab 3 items at a time and do db insert, continue until all items are gone. 'theData' will always be divisible by 3.
var a = theData[i];
var b = theData[i + 1];
var c = theData[i + 2];
}
I've been downvoted for this answer once. I'm pretty sure it is related to the use of theData.Length for the upperbound. The code as is works fine because array is guaranteed to be a multiple of three as the question states. If this guarantee wasn't in place, you would need to check the upper bound with theData.Length - 2 instead.
After messing with this for days, my final fix for our issues required two things;
1) We added this line of code to all of our .Net libraries that make out bound api calls to other vendors that had also disabled their SSL v3.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // (.Net 4 and below)
2) This is the final and FULL registry changes you will need when you are running ASP.Net 4.0 sites and will need to be slightly changed after you upgrade to ASP.Net 4.5.
After we rebooted the servers - all problems went away after this.
Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"DisabledByDefault"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000
dict.items()
returns a list of 2-tuples ([(key, value), (key, value), ...]
), whereas dict.iteritems()
is a generator that yields 2-tuples. The former takes more space and time initially, but accessing each element is fast, whereas the second takes less space and time initially, but a bit more time in generating each element.
You could use the -I
command line switch or :load_paths
option from Ruby code to add sub_directory_a
to Sass's load path. So if you're running Sass from root_directory
, do something like this:
sass -I sub_directory_a --watch sub_directory_b:sub_directory_b
Then you can simply use @import "common"
in more_styles.scss
.
Put this in a file and make it executable:
#!/bin/bash
start=`grep -n $1 < $3 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[0]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find start pattern!" 1>&2
exit 1
fi
stop=`tail -n +$start < $3 | grep -n $2 | head -n1 | cut -d: -f1; exit ${PIPESTATUS[1]}`
if [ ${PIPESTATUS[0]} -ne 0 ]; then
echo "couldn't find end pattern!" 1>&2
exit 1
fi
stop=$(( $stop + $start - 1))
sed "$start,$stop!d" < $3
Execute the file with arguments (NOTE that the script does not handle spaces in arguments!):
To use with your example, use arguments: 1234 5555 myfile.txt
Includes lines with starting and stopping pattern.
@Multipart
@POST("user/updateprofile")
Observable<ResponseBody> updateProfile(@Part("user_id") RequestBody id,
@Part("full_name") RequestBody fullName,
@Part MultipartBody.Part image,
@Part("other") RequestBody other);
//pass it like this
File file = new File("/storage/emulated/0/Download/Corrections 6.jpg");
RequestBody requestFile =
RequestBody.create(MediaType.parse("multipart/form-data"), file);
// MultipartBody.Part is used to send also the actual file name
MultipartBody.Part body =
MultipartBody.Part.createFormData("image", file.getName(), requestFile);
// add another part within the multipart request
RequestBody fullName =
RequestBody.create(MediaType.parse("multipart/form-data"), "Your Name");
service.updateProfile(id, fullName, body, other);
Look at the way I am passing the multipart and string params. Hope this will help you!
Not logging but if you're troubleshooting slow running queries in realtime, you can query the pg_stat_activity
view to see which queries are active, the user/connection they came from, when they started, etc. Eg...
SELECT *
FROM pg_stat_activity
WHERE state = 'active'
See the pg_stat_activity
view docs.
You should probably be using a more unobtrusive approach. Here's the benefits
- Separation of functionality (the "behavior layer") from a Web page's structure/content and presentation
- Best practices to avoid the problems of traditional JavaScript programming (such as browser inconsistencies and lack of scalability)
- Progressive enhancement to support user agents that may not support advanced JavaScript functionality
Your JavaScript
function exportToForm(a, b, c, d, e) {
console.log(a, b, c, d, e);
}
var images = document.getElementsByTagName("img");
for (var i=0, len=images.length, img; i<len; i++) {
img = images[i];
img.addEventListener("click", function() {
var a = img.getAttribute("data-a"),
b = img.getAttribute("data-b"),
c = img.getAttribute("data-c"),
d = img.getAttribute("data-d"),
e = img.getAttribute("data-e");
exportToForm(a, b, c, d, e);
});
}
Your images will look like this
<img data-a="1" data-b="2" data-c="3" data-d="4" data-e="5" src="image.jpg">
This article sums it up pretty well
Summary: It's implementation dependent, as there is no specified limit in the RFC. It'd be safe to use up to 2000 characters (IE's limit.) If you are anywhere near this length, you should make sure you really need URIs that long, maybe an alternative design could get around that.
URIs should be readable, even when used to send data.
Packages serve two purposes. One is to uniquely identify your app in the Google Play Store. The other is to name the package for the R.java class
which is generated when you build your project. You can think of the first purpose as the external package and the second as the internal package. Assuming you want to change the external package so you can identify in the Play store, there's a convenient way to do this.
In Android Studio,
choose File -> Project Structure -> Choose your app's module -> Click on the
Flavors tab -> change the Application id.
Now, when you build your project, your APK and manifest will use this new package name.
The first time you run the page, the query_age index doesn't exist because it hasn't been sent over from the form.
When you submit the form it will then exist, and it won't complain about it.
#so change
$_GET['query_age'];
#to:
(!empty($_GET['query_age']) ? $_GET['query_age'] : null);
rows and cols are required attributes, so you should have them whether you really need them or not. They set the number of rows and number of columns respectively.
With standart binding you need to use converters that looks little windy. So, I recommend you to look at my project CalcBinding, which was developed specially to resolve this problem and some others. With advanced binding you can write expressions with many source properties directly in xaml. Say, you can write something like:
<Button IsEnabled="{c:Binding Path=!IsReadOnly}" />
or
<Button Content="{c:Binding ElementName=grid, Path=ActualWidth+Height}"/>
or
<Label Content="{c:Binding A+B+C }" />
or
<Button Visibility="{c:Binding IsChecked, FalseToVisibility=Hidden}" />
where A, B, C, IsChecked - properties of viewModel and it will work properly
Yes, there is a difference;
throw ex
resets the stack trace (so your errors would appear to originate from HandleException
)throw
doesn't - the original offender would be preserved.
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.Write(ex.StackTrace.ToString());
Console.ReadKey();
}
}
private static void Method2()
{
try
{
Method1();
}
catch (Exception ex)
{
//throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
throw ex;
}
}
private static void Method1()
{
try
{
throw new Exception("Inside Method1");
}
catch (Exception)
{
throw;
}
}
The main point of the differences as pointed out @BizApps is that Load event happens right after the ViewState is populated while PreRender event happens later, right before Rendering phase, and after all individual children controls' action event handlers are already executing. Therefore, any modifications done by the controls' actions event handler should be updated in the control hierarchy during PreRender as it happens after.
Use let instead of var in code :
for(let i=1;i<=5;i++){setTimeout(()=>{console.log(i)},1000);}