An Oracle DATE
does not store times with more precision than a second. You cannot store millisecond precision data in a DATE
column.
Your two options are to either truncate the string of the milliseconds before converting it into a DATE
, i.e.
to_date( substr('23.12.2011 13:01:001', 1, 19), 'DD.MM.YYYY HH24:MI:SS' )
or to convert the string into a TIMESTAMP
that does support millisecond precision
to_timestamp( '23.12.2011 13:01:001', 'DD.MM.YYYY HH24:MI:SSFF3' )
Oracle
stores only the fractions up to second in a DATE
field.
Use TIMESTAMP
instead:
SELECT TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM dual
, possibly casting it to a DATE
then:
SELECT CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM dual
As offer_date
is an number, and is of lower accuracy than your real dates, this may work...
- Convert your real date to a string of format YYYYMM
- Conver that value to an INT
- Compare the result you your offer_date
SELECT
*
FROM
offers
WHERE
offer_date = (SELECT CAST(to_char(create_date, 'YYYYMM') AS INT) FROM customers where id = '12345678')
AND offer_rate > 0
Also, by doing all the manipulation on the create_date
you only do the processing on one value.
Additionally, had you manipulated the offer_date
you would not be able to utilise any index on that field, and so force SCANs instead of SEEKs.
Log in the Keycloak admin console website, select the realm and its client, then make sure all URIs of the client are prefixed with the protocol, that is, with http://
for example. An example would be http://localhost:8082/*
Another way to solve the issue, is to view the Keycloak server console output, locate the line stating the request was refused, copy from it the redirect_uri
displayed value and paste it in the * Valid Redirect URIs
field of the client in the Keycloak admin console website. The requested URI is then one of the acceptables.
I know it's way way overdue, but I have an alternative solution, which is lighter and simpler. Derive a class from System.Windows.Controls.RadioButton
and declare two dependency properties RadioValue
and RadioBinding
. Then in the class code, override OnChecked
and set the RadioBinding
property value to that of the RadioValue
property value. In the other direction, trap changes to the RadioBinding
property using a callback, and if the new value is equal to the value of the RadioValue
property, set its IsChecked
property to true
.
Here's the code:
public class MyRadioButton : RadioButton
{
public object RadioValue
{
get { return (object)GetValue(RadioValueProperty); }
set { SetValue(RadioValueProperty, value); }
}
// Using a DependencyProperty as the backing store for RadioValue.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty RadioValueProperty =
DependencyProperty.Register(
"RadioValue",
typeof(object),
typeof(MyRadioButton),
new UIPropertyMetadata(null));
public object RadioBinding
{
get { return (object)GetValue(RadioBindingProperty); }
set { SetValue(RadioBindingProperty, value); }
}
// Using a DependencyProperty as the backing store for RadioBinding.
This enables animation, styling, binding, etc...
public static readonly DependencyProperty RadioBindingProperty =
DependencyProperty.Register(
"RadioBinding",
typeof(object),
typeof(MyRadioButton),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
OnRadioBindingChanged));
private static void OnRadioBindingChanged(
DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
MyRadioButton rb = (MyRadioButton)d;
if (rb.RadioValue.Equals(e.NewValue))
rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
}
protected override void OnChecked(RoutedEventArgs e)
{
base.OnChecked(e);
SetCurrentValue(RadioBindingProperty, RadioValue);
}
}
XAML usage:
<my:MyRadioButton GroupName="grp1" Content="Value 1"
RadioValue="val1" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 2"
RadioValue="val2" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 3"
RadioValue="val3" RadioBinding="{Binding SelectedValue}"/>
<my:MyRadioButton GroupName="grp1" Content="Value 4"
RadioValue="val4" RadioBinding="{Binding SelectedValue}"/>
Hope someone finds this useful after all this time :)
You need to provide a default value:
new_field = models.CharField(max_length=140, default='SOME STRING')
The easiest way I thought of was to just project the point onto the axis of the rectangle. Let me explain:
If you can get the vector from the center of the rectangle to the top or bottom edge and the left or right edge. And you also have a vector from the center of the rectangle to your point, you can project that point onto your width and height vectors.
P = point vector, H = height vector, W = width vector
Get Unit vector W', H' by dividing the vectors by their magnitude
proj_P,H = P - (P.H')H' proj_P,W = P - (P.W')W'
Unless im mistaken, which I don't think I am... (Correct me if I'm wrong) but if the magnitude of the projection of your point on the height vector is less then the magnitude of the height vector (which is half of the height of the rectangle) and the magnitude of the projection of your point on the width vector is, then you have a point inside of your rectangle.
If you have a universal coordinate system, you might have to figure out the height/width/point vectors using vector subtraction. Vector projections are amazing! remember that.
What about the ansicolors library? You can simple do:
from colors import color, red, blue
# common colors
print(red('This is red'))
print(blue('This is blue'))
# colors by name or code
print(color('Print colors by name or code', 'white', '#8a2be2'))
Using the Joda-Time 2.4 library. The DateTimeFormat
class is a factory of DateTimeFormatter
formatters. That class offers a forStyle
method to access formatters appropriate to a Locale
.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );
The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.
Note that we specified both a Locale and a time zone. Some people confuse the two.
We need all those pieces to properly generate a string representation of a date-time value.
[In Python3]
Let's say you want to handle an IndexError
and print the traceback, you can do the following:
from traceback import print_tb
empty_list = []
try:
x = empty_list[100]
except IndexError as index_error:
print_tb(index_error.__traceback__)
Note: You can use the format_tb
function instead of print_tb
to get the traceback as a string for logging purposes.
Hope this helps.
I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):
SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)
The simplest by far will be Simple http://simple.sourceforge.net, you only need to annotate a single object like so
@Root
public class Entry {
@Attribute
private String a
@Attribute
private int b;
@Element
private Date c;
public String getSomething() {
return a;
}
}
@Root
public class Configuration {
@ElementList(inline=true)
private List<Entry> entries;
public List<Entry> getEntries() {
return entries;
}
}
Then all you have to do to read the whole file is specify the location and it will parse and populate the annotated POJO's. This will do all the type conversions and validation. You can also annotate for persister callbacks if required. Reading it can be done like so.
Serializer serializer = new Persister();
Configuration configuraiton = serializer.read(Configuration.class, fileLocation);
Zip your file (.zip) and IE will give the user the option to open or download the file.
Like Gusdor said above, "Multiple action tags in a single intent-filter tag will also cause the same error." (Give him the credit! I could just kiss Gusdor for this!)
I didn't find any docs for this fact!
I had added a new (USB) action and being clever, I lumped it in the same intent-filter. And it broke the launch.
Like Gusdor said, one intent filter, one action!
Apparently each action should go in its own intent filter.
It should look like this...
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
</intent-filter>
When I did this, WAZOO! it worked!
Using the .val()
function on a multi-select list will return an array of the selected values:
var selectedValues = $('#multipleSelect').val();
and in your html:
<select id="multipleSelect" multiple="multiple">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
<option value="3">Text 3</option>
</select>
Give your form an id only, and your input a name only:
<form id="myform">
<input type="text" name="foo">
Then the most standards-compliant and least problematic way to access your input element is via:
document.getElementById("myform").elements["foo"]
using .elements["foo"]
instead of just .foo
is preferable because the latter might return a property of the form named "foo" rather than a HTML element!
In case you're using apache's http-client 4:
SSLConnectionSocketFactory sslConnectionSocketFactory =
new SSLConnectionSocketFactory(sslContext,
new String[] { "TLSv1.2" }, null, new HostnameVerifier() {
public boolean verify(String arg0, SSLSession arg1) {
return true;
}
});
Check out this one-liner plugin that scales a background image responsively.
All you need to do is:
1. Include the library:
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
2. Call the method:
$.backstretch("http://dl.dropbox.com/u/515046/www/garfield-interior.jpg");
I used it for a simple "under construction website" site I had and it worked perfectly.
I think the following would work well with lesser line of codes.
session()->flash('toast', [
'status' => 'success',
'body' => 'Body',
'topic' => 'Success']
);
I'm using a toaster package, but you can have something like this in your view.
toastr.{{session('toast.status')}}(
'{{session('toast.body')}}',
'{{session('toast.topic')}}'
);
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
The new
keyword allocates memory on the Java heap. The heap is the main pool of memory, accessible to the whole of the application. If there is not enough memory available to allocate for that object, the JVM attempts to reclaim some memory from the heap with a garbage collection. If it still cannot obtain enough memory, an OutOfMemoryError
is thrown, and the JVM exits.
The heap is split into several different sections, called generations. As objects survive more garbage collections, they are promoted into different generations. The older generations are not garbage collected as often. Because these objects have already proven to be longer lived, they are less likely to be garbage collected.
When objects are first constructed, they are allocated in the Eden Space. If they survive a garbage collection, they are promoted to Survivor Space, and should they live long enough there, they are allocated to the Tenured Generation. This generation is garbage collected much less frequently.
There is also a fourth generation, called the Permanent Generation, or PermGen. The objects that reside here are not eligible to be garbage collected, and usually contain an immutable state necessary for the JVM to run, such as class definitions and the String constant pool. Note that the PermGen space is planned to be removed from Java 8, and will be replaced with a new space called Metaspace, which will be held in native memory. reference:http://www.programcreek.com/2013/04/jvm-run-time-data-areas/
My reset.css
was margin: 0, padding: 0
. After several hours of looking and troubleshooting this worked:
li {
list-style: disc outside none;
margin-left: 1em;
}
ul {
margin: 1em;
}
In MySql between the values are inclusive therefore when you give try to get between '2011-01-01' and '2011-01-31'
it will include from 2011-01-01 00:00:00
upto 2011-01-31 00:00:00
therefore nothing actually in 2011-01-31 since its time should go from 2011-01-31 00:00:00 ~ 2011-01-31 23:59:59
For the upper bound you can change to 2011-02-01
then it will get all data upto 2011-01-31 23:59:59
$cs = mysql_query("describe tbl_info");
$column_count = mysql_num_rows($cs);
Or just:
$column_count = mysql_num_rows(mysql_query("describe tbl_info"));
I guess what you're looking for is pyquery:
pyquery: a jquery-like library for python.
An example of what you want may be like:
from pyquery import PyQuery
html = # Your HTML CODE
pq = PyQuery(html)
tag = pq('div#id') # or tag = pq('div.class')
print tag.text()
And it uses the same selectors as Firefox's or Chrome's inspect element. For example:
The inspected element selector is 'div#mw-head.noprint'. So in pyquery, you just need to pass this selector:
pq('div#mw-head.noprint')
//create the url
$profile_pic = "http://graph.facebook.com/".$uid."/picture";
//echo the image out
echo "<img src=\"" . $profile_pic . "\" />";
Works fine for me
If you want to scroll down to the div (id="div1"). Then you can use this code.
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 1500);
<img draggable="false" src="images/testimg1.jpg" alt=""/>
Thanks to all, for me this solution worked: Magento 404 page in backoffice after login
Here's a comparison of the two:
Entity Type
Message consumption
Use Case
Persistence
Consumer Type
Sample applications
TRY THIS
IF EXISTS
(
SELECT name FROM master.dbo.sysdatabases
WHERE name = N'New_Database'
)
BEGIN
SELECT 'Database Name already Exist' AS Message
END
ELSE
BEGIN
CREATE DATABASE [New_Database]
SELECT 'New Database is Created'
END
JSON official site is where you should look at. It provides various libraries which can be used with Java, I've personally used this one, JSON-lib which is an implementation of the work in the site, so it has exactly the same class - methods etc in this page.
If you click the html links there you can find anything you want.
In short:
to create a json object and a json array, the code is:
JSONObject obj = new JSONObject();
obj.put("variable1", o1);
obj.put("variable2", o2);
JSONArray array = new JSONArray();
array.put(obj);
o1, o2, can be primitive types (long, int, boolean), Strings or Arrays.
The reverse process is fairly simple, I mean converting a string to json object/array.
String myString;
JSONObject obj = new JSONObject(myString);
JSONArray array = new JSONArray(myString);
In order to be correctly parsed you just have to know if you are parsing an array or an object.
Use re.sub
directly, this allows you to specify a count
:
regex.sub('', url, 1)
(Note that the order of arguments is replacement
, original
not the opposite, as might be suspected.)
I have two get methods with same or no parameters
[Route("api/ControllerName/FirstList")]
[HttpGet]
public IHttpActionResult FirstList()
{
}
[Route("api/ControllerName/SecondList")]
[HttpGet]
public IHttpActionResult SecondList()
{
}
Just define custom routes in AppStart=>WebApiConfig.cs
=> under register method
config.Routes.MapHttpRoute(
name: "GetFirstList",
routeTemplate: "api/Controllername/FirstList"
);
config.Routes.MapHttpRoute(
name: "GetSecondList",
routeTemplate: "api/Controllername/SecondList"
);
So the above answers are cute but they all have (imo) a big flaw: they are calculating the height of the image, based on the width of the user's device.
To have a truly responsive (i.e. width: 100%, height: auto
) implementation, what you really want to be doing, is calculating the height of the image, based on the width of the parent container.
Luckily for us, React Native provides us with a way to get the parent container width, thanks to the onLayout View method.
So all we need to do is create a View with width: "100%"
, then use onLayout
to get the width of that view (i.e. the container width), then use that container width to calculate the height of our image appropriately.
The below solution could be improved upon further, by using RN's Image.getSize, to grab the image dimensions within the ResponsiveImage component itself.
JavaScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import { Image, StyleSheet, View } from "react-native";
const ResponsiveImage = props => {
const [containerWidth, setContainerWidth] = useState(0);
const _onViewLayoutChange = event => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
TypeScript:
// ResponsiveImage.ts
import React, { useMemo, useState } from "react";
import {
Image,
ImageSourcePropType,
LayoutChangeEvent,
StyleSheet,
View
} from "react-native";
interface ResponsiveImageProps {
src: ImageSourcePropType;
srcWidth: number;
srcHeight: number;
}
const ResponsiveImage: React.FC<ResponsiveImageProps> = props => {
const [containerWidth, setContainerWidth] = useState<number>(0);
const _onViewLayoutChange = (event: LayoutChangeEvent) => {
const { width } = event.nativeEvent.layout;
setContainerWidth(width);
}
const imageStyles = useMemo(() => {
const ratio = containerWidth / props.srcWidth;
return {
width: containerWidth,
height: props.srcHeight * ratio
};
}, [containerWidth]);
return (
<View style={styles.container} onLayout={_onViewLayoutChange}>
<Image source={props.src} style={imageStyles} />
</View>
);
};
const styles = StyleSheet.create({
container: { width: "100%" }
});
export default ResponsiveImage;
// Example usage...
import ResponsiveImage from "../components/ResponsiveImage";
...
<ResponsiveImage
src={require("./images/your-image.jpg")}
srcWidth={910} // replace with your image width
srcHeight={628} // replace with your image height
/>
join()
means waiting for a thread to complete. This is a blocker method. Your main thread (the one that does the join()
) will wait on the t1.join()
line until t1
finishes its work, and then will do the same for t2.join()
.
I want to enhance Mr. Kamran Ali's answer with pictorial view.
- Go to "Database" Menu option
- Select the "Reverse Engineer" option.
- A wizard will come. Select from "Stored Connection" and press "Next" button.
- Then "Next"..to.."Finish"
Enjoy :)
My solution neither uses any third-party library nor forces you to call custom methods on SQLiteOpenHelper
subclass to initialize the database on creation. It also takes care of database upgrades as well. All that needs to be done is to subclass SQLiteOpenHelper
.
android_metadata
with an attribute locale
having the value en_US
in addition to the tables unique to your app.SQLiteOpenHelper
:SQLiteOpenHelper
.private
method within the SQLiteOpenHelper
subclass. This method contains the logic to copy database contents from the database file in the 'assets' folder to the database created in the application package context.onCreate
, onUpgrade
and onOpen
methods of SQLiteOpenHelper
.Enough said. Here goes the SQLiteOpenHelper
subclass:
public class PlanDetailsSQLiteOpenHelper extends SQLiteOpenHelper {
private static final String TAG = "SQLiteOpenHelper";
private final Context context;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "my_custom_db";
private boolean createDb = false, upgradeDb = false;
public PlanDetailsSQLiteOpenHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
}
/**
* Copy packaged database from assets folder to the database created in the
* application package context.
*
* @param db
* The target database in the application package context.
*/
private void copyDatabaseFromAssets(SQLiteDatabase db) {
Log.i(TAG, "copyDatabase");
InputStream myInput = null;
OutputStream myOutput = null;
try {
// Open db packaged as asset as the input stream
myInput = context.getAssets().open("path/to/shipped/db/file");
// Open the db in the application package context:
myOutput = new FileOutputStream(db.getPath());
// Transfer db file contents:
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
// Set the version of the copied database to the current
// version:
SQLiteDatabase copiedDb = context.openOrCreateDatabase(
DATABASE_NAME, 0, null);
copiedDb.execSQL("PRAGMA user_version = " + DATABASE_VERSION);
copiedDb.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error(TAG + " Error copying database");
} finally {
// Close the streams
try {
if (myOutput != null) {
myOutput.close();
}
if (myInput != null) {
myInput.close();
}
} catch (IOException e) {
e.printStackTrace();
throw new Error(TAG + " Error closing streams");
}
}
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.i(TAG, "onCreate db");
createDb = true;
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "onUpgrade db");
upgradeDb = true;
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.i(TAG, "onOpen db");
if (createDb) {// The db in the application package
// context is being created.
// So copy the contents from the db
// file packaged in the assets
// folder:
createDb = false;
copyDatabaseFromAssets(db);
}
if (upgradeDb) {// The db in the application package
// context is being upgraded from a lower to a higher version.
upgradeDb = false;
// Your db upgrade logic here:
}
}
}
Finally, to get a database connection, just call getReadableDatabase()
or getWritableDatabase()
on the SQLiteOpenHelper
subclass and it will take care of creating a db, copying db contents from the specified file in the 'assets' folder, if the database does not exist.
In short, you can use the SQLiteOpenHelper
subclass to access the db shipped in the assets folder just as you would use for a database that is initialized using SQL queries in the onCreate()
method.
firstElementChild might not be available in IE<9 (only firstChild)
on IE<9 firstChild is the firstElementChild because MS DOM (IE<9) is not storing empty text nodes. But if you do so on other browsers they will return empty text nodes...
my solution
child=(elem.firstElementChild||elem.firstChild)
this will give the firstchild even on IE<9
In MRI 1.8.7 or greater:
'foobarbaz'.each_char.first
I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.
Generally it means that you are providing an index for which a list element does not exist.
E.g, if your list was [1, 3, 5, 7]
, and you asked for the element at index 10, you would be well out of bounds and receive an error, as only elements 0 through 3 exist.
Simple functions,
function Encrypt(value)
{
var result="";
for(i=0;i<value.length;i++)
{
if(i<value.length-1)
{
result+=value.charCodeAt(i)+10;
result+="-";
}
else
{
result+=value.charCodeAt(i)+10;
}
}
return result;
}
function Decrypt(value)
{
var result="";
var array = value.split("-");
for(i=0;i<array.length;i++)
{
result+=String.fromCharCode(array[i]-10);
}
return result;
}
function showViewPortSize(display) {
if (display) {
var height = window.innerHeight;
var width = window.innerWidth;
jQuery('body')
.prepend('<div id="viewportsize" style="z-index:9999;position:fixed;bottom:0px;left:0px;color:#fff;background:#000;padding:10px">Height: ' + height + '<br>Width: ' + width + '</div>');
jQuery(window)
.resize(function() {
height = window.innerHeight;
width = window.innerWidth;
jQuery('#viewportsize')
.html('Height: ' + height + '<br>Width: ' + width);
});
}
}
$(document)
.ready(function() {
showViewPortSize(true);
});
I was going insane trying to get my js files to refresh and I tried everything. Then I did a header check and remembered I was using Cloudflare!
In Cloudflare you can use dev mode to disable proxy.
Complementing the accepted answer, if you use SELECT2 plugin, you need to recall select2 script to make changes is all select2 fields:
function resetForm(formId){
$('#'+formId).find('input:text, input:password, input:file, select, select2, textarea').val('');
$('#'+formId).find('input:radio, input:checkbox').removeAttr('checked').removeAttr('selected');
$('.select2').select2();
}
cd DIRECTORY
tar -czf NAME.tar.gz *
the asterisk will include everything even hidden ones
Found Answer.......!!!!!!!
Officially Microsoft Office 2003 Interop is not supported on Windows server 2008 by Microsoft.
But after a lot of permutations & combinations with the code and search, we came across one solution which works for our scenario.
The solution is to plug the difference between the way Windows 2003 and 2008 maintains its folder structure, because Office Interop depends on the desktop folder for file open/save intermediately. The 2003 system houses the desktop folder under systemprofile which is absent in 2008.
So when we create this folder on 2008 under the respective hierarchy as indicated below; the office Interop is able to save the file as required. This Desktop folder is required to be created under
C:\Windows\System32\config\systemprofile
AND
C:\Windows\SysWOW64\config\systemprofile
This worked for me...
Also do check if .NET 1.1 is installed because its needed by Interop and ot preinstalled by Windows Server 2008
Or you can also Use SaveCopyas() method ist just take onargument as filename string)
Thanks Guys..!
I'd use STUFF
to insert dividing chars and then use CONVERT
with the appropriate style. Something like this:
DECLARE @dt VARCHAR(100)='111290';
SELECT CONVERT(DATETIME,STUFF(STUFF(@dt,3,0,'/'),6,0,'/'),3)
First you use two times STUFF
to get 11/12/90 instead of 111290, than you use the 3 to convert this to datetime
(or any other fitting format: use .
for german, -
for british...) More details on CAST and CONVERT
Best was, to store date and time values properly.
yyyyMMdd
yyyy-MM-dd
or yyyy-MM-ddThh:mm:ss
More details on ISO8601Any culture specific format will lead into troubles sooner or later...
You can use functions in pyspark.sql.functions
: functions like year
, month
, etc
refer to here: https://spark.apache.org/docs/latest/api/python/pyspark.sql.html#pyspark.sql.DataFrame
from pyspark.sql.functions import *
newdf = elevDF.select(year(elevDF.date).alias('dt_year'), month(elevDF.date).alias('dt_month'), dayofmonth(elevDF.date).alias('dt_day'), dayofyear(elevDF.date).alias('dt_dayofy'), hour(elevDF.date).alias('dt_hour'), minute(elevDF.date).alias('dt_min'), weekofyear(elevDF.date).alias('dt_week_no'), unix_timestamp(elevDF.date).alias('dt_int'))
newdf.show()
+-------+--------+------+---------+-------+------+----------+----------+
|dt_year|dt_month|dt_day|dt_dayofy|dt_hour|dt_min|dt_week_no| dt_int|
+-------+--------+------+---------+-------+------+----------+----------+
| 2015| 9| 6| 249| 0| 0| 36|1441497601|
| 2015| 9| 6| 249| 0| 0| 36|1441497601|
| 2015| 9| 6| 249| 0| 0| 36|1441497603|
| 2015| 9| 6| 249| 0| 1| 36|1441497694|
| 2015| 9| 6| 249| 0| 20| 36|1441498808|
| 2015| 9| 6| 249| 0| 20| 36|1441498811|
| 2015| 9| 6| 249| 0| 20| 36|1441498815|
Here are the all keycodes.
Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.
http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php
Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.
Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12
JButton close = new JButton("Close");
close.addActionListener(this);
public void actionPerformed(ActionEvent closing) {
// getSource() checks for the source of clicked Button , compares with the name of button in which here is close .
if(closing.getSource()==close)
System.exit(0);
// This exit Your GUI
}
/*Some Answers were asking for @override which is overriding the method the super class or the parent class and creating different objects and etc which makes the answer too long . Note : we just need to import java.awt.*; and java.swing.*; and Adding this command : class className implements actionListener{} */
>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}
My problem and the solution
I have a 32 bit third party dll which I have installed in 2008 R2 machine which is 64 bit.
I have a wcf service created in .net 4.5 framework which calls the 32 bit third party dll for process. Now I have build property set to target 'any' cpu and deployed it to the 64 bit machine.
When Ii tried to invoke the wcf service got error "80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG"
Now Ii used ProcMon.exe to trace the com registry issue and identified that the process is looking for the registry entry at HKLM\CLSID and HKCR\CLSID where there is no entry.
Came to know that Microsoft will not register the 32 bit com components to the paths HKLM\CLSID, HKCR\CLSID in 64 bit machine rather it places the entry in HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID paths.
Now the conflict is 64 bit process trying to invoke 32 bit process in 64 bit machine which will look for the registry entry in HKLM\CLSID, HKCR\CLSID. The solution is we have to force the 64 bit process to look at the registry entry at HKLM\Wow6432Node\CLSID and HKCR\Wow6432Node\CLSID.
This can be achieved by configuring the wcf service project properties to target to 'X86' machine instead of 'Any'.
After deploying the 'X86' version to the 2008 R2 server got the issue "System.BadImageFormatException: Could not load file or assembly"
Solution to this badimageformatexception is setting the 'Enable32bitApplications' to 'True' in IIS Apppool properties for the right apppool.
If you want to continue to use passwords and not use key exchange then you can accomplish this with 'expect' like so:
#!/usr/bin/expect -f
spawn ssh user@hostname
expect "password:"
sleep 1
send "<your password>\r"
command1
command2
commandN
This is known as type assertion
in golang, and it is a common practice.
Here is the explanation from a tour of go:
A type assertion provides access to an interface value's underlying concrete value.
t := i.(T)
This statement asserts that the interface value i holds the concrete type T and assigns the underlying T value to the variable t.
If i does not hold a T, the statement will trigger a panic.
To test whether an interface value holds a specific type, a type assertion can return two values: the underlying value and a boolean value that reports whether the assertion succeeded.
t, ok := i.(T)
If i holds a T, then t will be the underlying value and ok will be true.
If not, ok will be false and t will be the zero value of type T, and no panic occurs.
NOTE: value i
should be interface type.
Even if i
is an interface type, []i
is not interface type. As a result, in order to convert []i
to its value type, we have to do it individually:
// var items []i
for _, item := range items {
value, ok := item.(T)
dosomethingWith(value)
}
As for performance, it can be slower than direct access to the actual value as show in this stackoverflow answer.
I have a slightly different way of doing this than the accepted answer. This way you can avoid using GROUP_CONCAT which has a limit of 1024 characters and will not work if you have a lot of fields.
SET @sql = '';
SELECT
@sql := CONCAT(@sql,if(@sql='','',', '),temp.output)
FROM
(
SELECT
DISTINCT
CONCAT(
'MAX(IF(pa.fieldname = ''',
fieldname,
''', pa.fieldvalue, NULL)) AS ',
fieldname
) as output
FROM
product_additional
) as temp;
SET @sql = CONCAT('SELECT p.id
, p.name
, p.description, ', @sql, '
FROM product p
LEFT JOIN product_additional AS pa
ON p.id = pa.id
GROUP BY p.id');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
If your button does not require a transparent background, then you can create an illusion of a border using a Frame Layout. Just adjust the FrameLayout's "padding" attribute to change the thickness of the border.
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="1sp"
android:background="#000000">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your text goes here"
android:background="@color/white"
android:textColor="@color/black"
android:padding="10sp"
/>
</FrameLayout>
I'm not sure if the shape xml files have dynamically-editable border colors. But I do know that with this solution, you can dynamically change the color of the border by setting the FrameLayout background.
For Swift 4 and higher that is a good way:
let attributsBold = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .bold)]
let attributsNormal = [NSAttributedString.Key.font : UIFont.systemFont(ofSize: 16, weight: .regular)]
var attributedString = NSMutableAttributedString(string: "Hi ", attributes:attributsNormal)
let boldStringPart = NSMutableAttributedString(string: "John", attributes:attributsBold)
attributedString.append(boldStringPart)
yourLabel.attributedText = attributedString
In the Label the Text looks like: "Hi John"
To obtain the perspective-corrected co-ordinates, just divide by the z
co-ordinate:
xc = x / z
yc = y / z
The above works assuming that the camera is at (0, 0, 0)
and you are projecting onto the plane at z = 1
-- you need to translate the co-ords relative to the camera otherwise.
There are some complications for curves, insofar as projecting the points of a 3D Bezier curve will not in general give you the same points as drawing a 2D Bezier curve through the projected points.
For something with 2 parameters, you could use BiFunction
. If you need more, you can define your own function interface, like so:
@FunctionalInterface
public interface FourParameterFunction<T, U, V, W, R> {
public R apply(T t, U u, V v, W w);
}
If there is more than one parameter, you need to put parentheses around the argument list, like so:
FourParameterFunction<String, Integer, Double, Person, String> myLambda = (a, b, c, d) -> {
// do something
return "done something";
};
In addition to @odano 's answer, it seems using d.clear()
is faster if you would like to clear the dict for many times.
import timeit
p1 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d = {}
for i in xrange(1000):
d[i] = i * i
'''
p2 = '''
d = {}
for i in xrange(1000):
d[i] = i * i
for j in xrange(100):
d.clear()
for i in xrange(1000):
d[i] = i * i
'''
print timeit.timeit(p1, number=1000)
print timeit.timeit(p2, number=1000)
The result is:
20.0367929935
19.6444659233
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
document.querySelector('img[name="edit-save"]');
and change the src with
document.querySelector('img[name="edit-save"]').src = "..."
so you could achieve the desired effect with
var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
this.src = "..." // this is the reference to the image itself
};
otherwise, as other suggested, if you're in control of the code, it's better to assign an id
to the image a get a reference with getElementById
(since it's the fastest method to retrieve an element)
Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link
function of the directive.
There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls
Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.
EDIT: Rather than using $(element)
, you can make use of angular.element(element)
when using AngularJS with jQuery
add your editText
android:imeOptions="actionNext"
android:singleLine="true"
add property to activity in manifest
android:windowSoftInputMode="adjustResize|stateHidden"
in layout file ScrollView set as root or parent layout all ui
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.ukuya.marketplace.activity.SignInActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--your items-->
</ScrollView>
</LinearLayout>
if you do not want every time it adds, create style: add style in values/style.xml
default/style:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="editTextStyle">@style/AppTheme.CustomEditText</item>
</style>
<style name="AppTheme.CustomEditText" parent="android:style/Widget.EditText">
//...
<item name="android:imeOptions">actionNext</item>
<item name="android:singleLine">true</item>
</style>
JavaScript is always synchronous and single-threaded. If you're executing a JavaScript block of code on a page then no other JavaScript on that page will currently be executed.
JavaScript is only asynchronous in the sense that it can make, for example, Ajax calls. The Ajax call will stop executing and other code will be able to execute until the call returns (successfully or otherwise), at which point the callback will run synchronously. No other code will be running at this point. It won't interrupt any other code that's currently running.
JavaScript timers operate with this same kind of callback.
Describing JavaScript as asynchronous is perhaps misleading. It's more accurate to say that JavaScript is synchronous and single-threaded with various callback mechanisms.
jQuery has an option on Ajax calls to make them synchronously (with the async: false
option). Beginners might be tempted to use this incorrectly because it allows a more traditional programming model that one might be more used to. The reason it's problematic is that this option will block all JavaScript on the page until it finishes, including all event handlers and timers.
DECLARE @dd VARCHAR(200) = 'Net Operating Loss - 2007';
SELECT SUBSTRING(@dd, 1, CHARINDEX('-', @dd) -1) F1,
SUBSTRING(@dd, CHARINDEX('-', @dd) +1, LEN(@dd)) F2
to_char
actually lets you pull out the Year and month in one fell swoop!
select to_char(date('2014-05-10'),'Mon-YY') as year_month; --'May-14'
select to_char(date('2014-05-10'),'YYYY-MM') as year_month; --'2014-05'
or in the case of the user's example above:
select to_char(date,'YY-Mon') as year_month
sum("Sales") as "Sales"
from some_table
group by 1;
This image displayed below gives a clear understanding and shows the exact difference between .append()
, .prepend()
, .after()
and .before()
You can see from the image that .append()
and .prepend()
adds the new elements as child elements (brown colored) to the target.
And .after()
and .before()
adds the new elements as sibling elements (black colored) to the target.
Here is a DEMO for better understanding.
EDIT: the flipped versions of those functions:
Using this code:
var $target = $('.target');
$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');
$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);
on this target:
<div class="target">
This is the target div to which new elements are associated using jQuery
</div>
So although these functions flip the parameter order, each creates the same element nesting:
var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))
...but they return a different element. This matters for method chaining.
I had the same problem after upgrading from Windows 7
to Windows 10
. Tried all the popular answers which did not work. Finally, I understood that Windows had changed the name of the adapter. Virtual Box
was configured to use Realtek PCIe GBE Family Controller
while device manager had this as Realtek PCIe GBE Family Controller #2
. Selecting proper controller fixed the problem.
Am I missing something? You can just convert offer_date in the comparison:
SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
offer_rate > 0
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
I use #3. Same for long lists, tuples, etc. It doesn't require adding any extra spaces beyond the indentations. As always, be consistent.
mydict = {
"key1": 1,
"key2": 2,
"key3": 3,
}
mylist = [
(1, 'hello'),
(2, 'world'),
]
nested = {
a: [
(1, 'a'),
(2, 'b'),
],
b: [
(3, 'c'),
(4, 'd'),
],
}
Similarly, here's my preferred way of including large strings without introducing any whitespace (like you'd get if you used triple-quoted multi-line strings):
data = (
"iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABG"
"l0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAAEN"
"xBRpFYmctaKCfwrBSCrRLuL3iEW6+EEUG8XvIVjYWNgJdhFjIX"
"rz6pKtPB5e5rmq7tmxk+hqO34e1or0yXTGrj9sXGs1Ib73efh1"
"AAAABJRU5ErkJggg=="
)
If you're working with massive data, a memoized approach would be best:
# First create a dictionary of manually stored values
color_dict = {'Z':'red'}
# Second, build a dictionary of "other" values
color_dict_other = {x:'green' for x in df['Set'].unique() if x not in color_dict.keys()}
# Next, merge the two
color_dict.update(color_dict_other)
# Finally, map it to your column
df['color'] = df['Set'].map(color_dict)
This approach will be fastest when you have many repeated values. My general rule of thumb is to memoize when: data_size
> 10**4
& n_distinct
< data_size/4
E.x. Memoize in a case 10,000 rows with 2,500 or fewer distinct values.
The browser extension uBlock’s setting “Block remote fonts” will cause this error. (Note: Grammarly was not the problem, at least for me.)
Usually this isn’t a problem. When a remote font is blocked, you fall back to some other font and a console warning saying “ERR_BLOCKED_BY_CLIENT” is issued. However, this can be a serious problem when a site uses Font Awesome, because the icons show as boxes.
There’s not much a website can do about fixing this (but you can prevent it from being too bad by e.g. labeling font-based icons). Changing the CSP (or adding one) will not fix it. Serving the fonts from your website (and not a CDN) will not fix it either.
The uBlock user, on the other hand, has the power to fix this by doing one of the following:
Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).
In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.
Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:
You can use .indexOf()
and .substr()
like this:
var val = $("input").val();
var myString = val.substr(val.indexOf("?") + 1)
You can test it out here. If you're sure of the format and there's only one question mark, you can just do this:
var myString = $("input").val().split("?").pop();
Enter the command which php
in the terminal to see which version of PHP you are using. If it's not the PHP version from MAMP, the $PATH variable used by Bash will need to be updated.
First, you should use command "cd /Applications/MAMP/bin/php" to check which php version from MAMP and take note of the version (eg, php5.6.7).
Once you know the version, you should edit the ~/.bash_profile
file (that is, the .bash_profile
that is in your home directory) and add an export line:
export PATH=/Applications/MAMP/bin/php/php5.6.7/bin:$PATH
Make sure that you replace php5.6.7 with the version of PHP that you have selected in MAMP.
Once the file has been saved, make sure that you close close your Terminal and open it again. Once that has been done, you will be using the PHP that ships with MAMP.
One way to easily find what the line should be that you need to put inside your .bash_profile
is to run the following command inside your terminal:
echo export PATH=`cat /Applications/MAMP/conf/apache/httpd.conf \
| grep php | grep -i LoadModule | head -n1 \
| sed -e 's/^[^\/]*\/\(.*\)\/mod.*/\/\1/'`/bin:\$PATH
Copying and pasting those three lines into your terminal will correctly output the PHP version that has been selected inside the MAMP control panel.
Make sure that your path
contains /usr/local/bin/
(Homebrew) or /opt/local/bin
(MacPorts) if you are using PHP that comes with either of these two package managers.
You can find the exact location of PHP using MacPorts with the following command:
port contents php70 | grep bin/php
Note that you should replace php70
with the version of PHP that you have installed.
Homebrew-php (https://github.com/Homebrew/homebrew-php) is a tap that has various different versions of PHP.
You can find the exact location of PHP using Homebrew with the following command:
brew --prefix homebrew/php/php56
Note that you should replace php56
with the version of PHP that you have installed.
for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time: =0%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g
echo %DateNtime%
Or, from the command line:
for /f "tokens=2-8 delims=.:/ " %a in ("%date% %time: =0%") do echo %c-%a-%b_%d-%e-%f.%g
EDIT: As per bryce's non-standard time/date specs. (03-Sep-12 9:06:21.54
)
@echo off
setlocal enabledelayedexpansion
for /f "tokens=1-7 delims=.:/- " %%a in ("%date% %time%") do (
if "%%b"=="Jan" set MM=01
if "%%b"=="Feb" set MM=02
if "%%b"=="Mar" set MM=03
if "%%b"=="Apr" set MM=04
if "%%b"=="May" set MM=05
if "%%b"=="Jun" set MM=06
if "%%b"=="Jul" set MM=07
if "%%b"=="Aug" set MM=08
if "%%b"=="Sep" set MM=09
if "%%b"=="Oct" set MM=10
if "%%b"=="Nov" set MM=11
if "%%b"=="Dec" set MM=12
set HH=0%%d
set HH=!HH:~-2!
echo 20%%c-!MM!-%%a_!HH!-%%e-%%f.%%g
)
endlocal
You get an apparently random set because ROWNUM is applied before the ORDER BY. So your query takes the first ten rows and sorts them.0 To select the top ten salaries you should use an analytic function in a subquery, then filter that:
select * from
(select empno,
ename,
sal,
row_number() over(order by sal desc nulls last) rnm
from emp)
where rnm<=10
scope: false
transclude: false
and you will have the same scope(with parent element)
$scope.$watch(...
There are a lot of ways how to access parent scope depending on this two options scope& transclude.
Declare the array size will solve your problem
String[] title = {
"Abundance",
"Anxiety",
"Bruxism",
"Discipline",
"Drug Addiction"
};
String urlbase = "http://www.somewhere.com/data/";
String imgSel = "/logo.png";
String[] mStrings = new String[title.length];
for(int i=0;i<title.length;i++) {
mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;
System.out.println(mStrings[i]);
}
Unfortunately, phpMyAdmin is one of the first php application that talk to MySQL about charset correctly. Your problem is most likely due to the fact that the database does not store the correct UTF-8 strings at first place.
In order to correctly display the characters correctly in phpMyAdmin, the data must be correctly stored in the database. However, convert the database into correct charset often breaks web apps that does not aware charset-related feature provided by MySQL.
May I ask: is MySQL > version 4.1? What web app is the database for? phpBB? Was the database migrated from an older version of the web app, or an older version of MySQL?
My suggestion is not to brother if the web app you are using is too old and not supported. Only convert database to real UTF-8 if you are sure the web app can read them correctly.
Edit:
Your MySQL is > 4.1, that means it's charset-aware. What's the charset collation settings for you database? I am pretty sure you are using latin1
, which is MySQL name for ASCII, to store the UTF-8 text in 'bytes', into the database.
For charset-insensitive clients (i.e. mysql-cli and php-mod-mysql), characters get displayed correctly since they are being transfer to/from database as bytes. In phpMyAdmin, bytes get read and displayed as ASCII characters, that's the garbage text you seem.
Countless hours had been spend years ago (2005?) when MySQL 4.0 went obsolete, in many parts of Asia. There is a standard way to deal with your problem and gobbled data:
.sql
charset collation latin1_general_ci
, replace latin1
to utf8
.mysql_query("SET NAMES UTF8");
after mysql_connect()
, now the question marks will be gone.Add the following configuration my.ini
for mysql-cli:
# CLIENT SECTION
[mysql]
default-character-set=utf8
# SERVER SECTION
[mysqld]
default-character-set=utf8
For more information about charset on MySQL, please refer to manual: http://dev.mysql.com/doc/refman/5.0/en/charset-server.html
Note that I assume your web app is using php-mod-mysql to connect to the database (hence the mysql_connect()
function), since php-mod-mysql is the only extension I can think of that still trigger the problem TO THIS DAY.
phpMyAdmin use php-mod-mysqli to connect to MySQL. I never learned how to use it because switch to frameworks* to develop my php projects. I strongly encourage you do that too.
That's constructor initialisation. It is the correct way to initialise members in a class constructor, as it prevents the default constructor being invoked.
Consider these two examples:
// Example 1
Foo(Bar b)
{
bar = b;
}
// Example 2
Foo(Bar b)
: bar(b)
{
}
In example 1:
Bar bar; // default constructor
bar = b; // assignment
In example 2:
Bar bar(b) // copy constructor
It's all about efficiency.
There seems to be a few details left out of your explanation, but I will do my best...
If these are NUL-terminated strings or the memory is pre-zeroed, you can just iterate down the length of the memory segment until you hit a NUL (0) character or the maximum length (whichever comes first). Use the string constructor, passing the buffer and the size determined in the previous step.
string retrieveString( char* buf, int max ) {
size_t len = 0;
while( (len < max) && (buf[ len ] != '\0') ) {
len++;
}
return string( buf, len );
}
If the above is not the case, I'm not sure how you determine where a string ends.
I'm currently using the following solution I found in the AngularJS google group.
$http .post('/echo/json/', 'json=' + encodeURIComponent(angular.toJson(data)), { headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).success(function(data) { $scope.data = data; });
Note that if you're using PHP, you'll need to use something like Symfony 2 HTTP component's Request::createFromGlobals()
to read this, as $_POST won't automatically loaded with it.
Here is the function I use to prevent chrome and opera from showing the invalid input dialog even when using novalidate.
window.submittingForm = false;
$('input[novalidate]').bind('invalid', function(e) {
if(!window.submittingForm){
window.submittingForm = true;
$(e.target.form).submit();
setTimeout(function(){window.submittingForm = false;}, 100);
}
e.preventDefault();
return false;
});
At its simplest, the difference is one of plurality:
I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.
So, the mnemonic is:
I hope this helps!
I thought all of them were great but I had troubles actually getting them to work with javascript and c#. Here is what I did. Hope it helps someone else.
//put this at the top of the page
<script src="https://www.google.com/recaptcha/api.js"></script>
//put this under the script tag
<script>
var isCaptchaValid = false;
function doCaptchaValidate(source, args) {
args.IsValid = isCaptchaValid;
}
var verifyCallback = function (response) {
isCaptchaValid = true;
};
</script>
//retrieved from google and added callback
<div class="g-recaptcha" data-sitekey="sitekey" data-callback="verifyCallback">
//created a custom validator and added error message and ClientValidationFucntion
<asp:CustomValidator runat="server" ID="CustomValidator1" ValidationGroup="Initial" ErrorMessage="Captcha Required" ClientValidationFunction="doCaptchaValidate"/>
No, objects don't have a built in identifier, though you can add one by modifying the object prototype. Here's an example of how you might do that:
(function() {
var id = 0;
function generateId() { return id++; };
Object.prototype.id = function() {
var newId = generateId();
this.id = function() { return newId; };
return newId;
};
})();
That said, in general modifying the object prototype is considered very bad practice. I would instead recommend that you manually assign an id to objects as needed or use a touch
function as others have suggested.
add following lines in gitignore, from all undesirable files
/target/
*/target/**
**/META-INF/
!.mvn/wrapper/maven-wrapper.jar
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/build/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
Typically, git commit
brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR
environment variable) for you to edit your commit message in. When you save and exit, the commit completes.
You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.
Why not try this
na.zero <- function (x) {
x[is.na(x)] <- 0
return(x)
}
na.zero(df)
Without knowing more about the problem domain, it's hard to answer your question. Unless you are certain that you need to do something more, the pythonic way to initialize a list is:
verts = []
Are you actually seeing a performance problem? If so, what is the performance bottleneck? Don't try to solve a problem that you don't have. It's likely that performance cost to dynamically fill an array to 1000 elements is completely irrelevant to the program that you're really trying to write.
The array class is useful if the things in your list are always going to be a specific primitive fixed-length type (e.g. char, int, float). But, it doesn't require pre-initialization either.
Think about what a pinch
event is: two fingers on an element, moving toward or away from each other.
Gesture events are, to my knowledge, a fairly new standard, so probably the safest way to go about this is to use touch events like so:
(ontouchstart
event)
if (e.touches.length === 2) {
scaling = true;
pinchStart(e);
}
(ontouchmove
event)
if (scaling) {
pinchMove(e);
}
(ontouchend
event)
if (scaling) {
pinchEnd(e);
scaling = false;
}
To get the distance between the two fingers, use the hypot
function:
var dist = Math.hypot(
e.touches[0].pageX - e.touches[1].pageX,
e.touches[0].pageY - e.touches[1].pageY);
max_allowed_packet=64M
Adding this line into my.cnf
file solves my problem.
This is useful when the columns have large values, which cause the issues, you can find the explanation here.
On Windows this file is located at: "C:\ProgramData\MySQL\MySQL Server 5.6"
On Linux (Ubuntu): /etc/mysql
I know your question does not specify if you are trying to open all a tags in a new window or only the external links.
But in case you only want external links to open in a new tab you can do this:
$( 'a[href^="http://"]' ).attr( 'target','_blank' )
$( 'a[href^="https://"]' ).attr( 'target','_blank' )
define a String variable using the JSP tags
<%!
String test = new String();
%>
then refer to that variable in your loop as
<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>
Simple Steps
I had this problem and I nearly tore my hair out, and I wasn't able to find the appropriate answer on the net. I was trying to control the background color of the selected row in a WPF DataGrid. It just wouldn't do it. In my case, the reason was that I also had a CellStyle in my datagrid, and the CellStyle overrode the RowStyle I was setting. Interestingly so, because the CellStyle wasn't even setting the background color, which was instead bing set by the RowBackground and AlternateRowBackground properties. Nevertheless, trying to set the background colour of the selected row did not work at all when I did this:
<DataGrid ... >
<DataGrid.RowBackground>
...
</DataGrid.RowBackground>
<DataGrid.AlternatingRowBackground>
...
</DataGrid.AlternatingRowBackground>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Pink"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Foreground" Value="{Binding MyProperty}" />
</Style>
</DataGrid.CellStyle>
and it did work when I moved the desired style for the selected row out of the row style and into the cell style, like so:
<DataGrid ... >
<DataGrid.RowBackground>
...
</DataGrid.RowBackground>
<DataGrid.AlternatingRowBackground>
...
</DataGrid.AlternatingRowBackground>
<DataGrid.CellStyle>
<Style TargetType="{x:Type DataGridCell}">
<Setter Property="Foreground" Value="{Binding MyProperty}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="Pink"/>
<Setter Property="Foreground" Value="White"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.CellStyle>
Just posting this in case someone has the same problem.
$image = 'http://images.itracki.com/2011/06/favicon.png';
// Read image path, convert to base64 encoding
$imageData = base64_encode(file_get_contents($image));
// Format the image SRC: data:{mime};base64,{data};
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
// Echo out a sample image
echo '<img src="' . $src . '">';
Just checked in Excel 2016 and this piece of code worked for me:
Sub ImmediateClear()
Application.VBE.Windows("Immediate").SetFocus
Application.SendKeys "^{END} ^+{HOME}{DEL}"
End Sub
The HTML attribute for the purpose is rules=none
(to be inserted into the table
tag).
in coffee-script:
class StringStream extends Readable
constructor: (@str) ->
super()
_read: (size) ->
@push @str
@push null
use it:
new StringStream('text here').pipe(stream1).pipe(stream2)
The CSS element()
function may eventually help some people here, even though it's not a direct answer to the question. It allows you to use an element (and all children, including videos, cross-domain iframes, etc.) as a background image (and anywhere else that you'd normally use url(...)
in your CSS code). Here's a blog post that shows what you can do with it.
It has been implemented in Firefox since 2011, and is being considered in Chromium/Chrome (don't forget to give the issue a star if you care about this functionality).
for customized local notification, in AndroidManifest.xml add following meta-data then it will work.
<application
android:name="xxxxxx"
android:label="xxxxxx"
android:icon="@mipmap/ic_launcher"
>
<meta-data
android:name="your_apps_bundle_id.default_notification_icon"
android:resource="@drawable/ic_notif" />
......
function myFunction(arg) {
alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}
myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });
Try this:
var frm = document.getElementById('search-theme-form') || null;
if(frm) {
frm.action = 'whatever_you_need.ext'
}
To replace a path within files (avoiding escape characters) you may use the following command:
sed -i 's@old_path@new_path@g'
The @ sign means that all of the special characters should be ignored in a following string.
I would recommend %20
.
Are you hard-coding them?
This is not very consistent across languages, though.
If I'm not mistaken, in PHP urlencode()
treats spaces as +
whereas Python's urlencode()
treats them as %20
.
EDIT:
It seems I'm mistaken. Python's urlencode()
(at least in 2.7.2) uses quote_plus()
instead of quote()
and thus encodes spaces as "+".
It seems also that the W3C recommendation is the "+" as per here: http://www.w3.org/TR/html4/interact/forms.html#h-17.13.4.1
And in fact, you can follow this interesting debate on Python's own issue tracker about what to use to encode spaces: http://bugs.python.org/issue13866.
EDIT #2:
I understand that the most common way of encoding " " is as "+", but just a note, it may be just me, but I find this a bit confusing:
import urllib
print(urllib.urlencode({' ' : '+ '})
>>> '+=%2B+'
here is mine
echo Math+
ECHO First num:
SET /P a=
ECHO Second num:
SET /P b=
set /a s=%a%+%b%
echo Result: %s%
This is the answer, hope it helps someone :)
First there are two variations on how the xml can be written:
<row>
<IdInvernadero>8</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>8</IdCaracteristica1>
<IdCaracteristica2>8</IdCaracteristica2>
<Cantidad>25</Cantidad>
<Folio>4568457</Folio>
</row>
<row>
<IdInvernadero>3</IdInvernadero>
<IdProducto>3</IdProducto>
<IdCaracteristica1>1</IdCaracteristica1>
<IdCaracteristica2>2</IdCaracteristica2>
<Cantidad>72</Cantidad>
<Folio>4568457</Folio>
</row>
Answer:
SELECT
Tbl.Col.value('IdInvernadero[1]', 'smallint'),
Tbl.Col.value('IdProducto[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica1[1]', 'smallint'),
Tbl.Col.value('IdCaracteristica2[1]', 'smallint'),
Tbl.Col.value('Cantidad[1]', 'int'),
Tbl.Col.value('Folio[1]', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
<row IdInvernadero="8" IdProducto="3" IdCaracteristica1="8" IdCaracteristica2="8" Cantidad ="25" Folio="4568457" />
<row IdInvernadero="3" IdProducto="3" IdCaracteristica1="1" IdCaracteristica2="2" Cantidad ="72" Folio="4568457" />
Answer:
SELECT
Tbl.Col.value('@IdInvernadero', 'smallint'),
Tbl.Col.value('@IdProducto', 'smallint'),
Tbl.Col.value('@IdCaracteristica1', 'smallint'),
Tbl.Col.value('@IdCaracteristica2', 'smallint'),
Tbl.Col.value('@Cantidad', 'int'),
Tbl.Col.value('@Folio', 'varchar(7)')
FROM @xml.nodes('//row') Tbl(Col)
Taken from:
just type:
cat *.sql |mysql -uroot -p
and mysql will import all the sql file in sequence
Env: macOS Mojave 10.14.4
Install: homebrew
Location:/usr/local/Cellar/mongodb/4.0.3_1
Note :If update version by
brew upgrade mongo
,the folder 4.0.4_1
will be removed and replace with the new version folder
On Chrome and Firefox 32+, navigator.languages contains an array of locales in order of user preference, and is more accurate than navigator.language, however to make it backwards-compatible (Tested Chrome / IE / Firefox / Safari), then use this:
function getLang()
{
if (navigator.languages != undefined)
return navigator.languages[0];
else
return navigator.language;
}
Have you tried:
#!/usr/local/bin/php
I.e. without the -q
part? That's what the error message "Could not open input file: -q" means. The first argument to php
if it doesn't look like an option is the name of the PHP file to execute, and -q
is CGI only.
EDIT: A couple of (non-related) tips:
?>
. In fact, it is often better not to.STDIN
to fopen("php://stdin", "r")
. You can use that instead of opening "php://stdin"
a second time: $fd = STDIN;
Starting Python 3.8
, the standard library provides the NormalDist
object as part of the statistics
module.
It can be used to get the probability density function (pdf
- likelihood that a random sample X will be near the given value x) for a given mean (mu
) and standard deviation (sigma
):
from statistics import NormalDist
NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994
Also note that the NormalDist
object also provides the cumulative distribution function (cdf
- probability that a random sample X will be less than or equal to x):
NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634
Use FileMode.Truncate
everytime you create the file. Also place the File.Create
inside a try
catch
.
You can simply use the below function, You can also change the type element.
$("input[type=hidden]").bind("change", function() {
alert($(this).val());
});
Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.
HTML
<div id="message"></div>
<input type="hidden" id="testChange" value="0" />
JAVASCRIPT
var $message = $('#message');
var $testChange = $('#testChange');
var i = 1;
function updateChange() {
$message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');
}
$testChange.on('change', updateChange);
setInterval(function() {
$testChange.val(++i).trigger('change');;
console.log("value changed" +$testChange.val());
}, 3000);
updateChange();
should work as expected.
I've all done, setting JAVA_HOME, JAVA8_HOME, ... and i had always the error. For me the solution was to set the version 2.1.0 of gradle to work with Jdk 1.8.0_92 and android studio 2.11
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0'
//classpath 'com.android.tools.build:gradle:2.+'
}
I was creating a mp3 player for android, I wanted to update the current time every 500ms so I did it like this
private void update() {
new android.os.Handler().postDelayed(new Runnable() {
@Override
public void run() {
long cur = player.getCurrentPosition();
long dur = player.getDuration();
currentTime = millisecondsToTime(cur);
currentTimeView.setText(currentTime);
if (cur < dur) {
updatePlayer();
}
// update seekbar
seekBar.setProgress( (int) Math.round((float)cur / (float)dur * 100f));
}
}, 500);
}
which calls the same method recursively
I tried using disabled along with click event. Below is the snippet , the accepted answer also worked perfectly fine , I am adding this answer to give an example how it can be used with disabled and click properties.
<button (click)="!planNextDisabled && planNext()" [disabled]="planNextDisabled"></button>
PDF Vision is good. However, you have to have Full Trust to use it. I already emailed and asked why my HTML wasn't being converted on the server but it worked fine on localhost.
In code to load a resource in the executing assembly where my image Freq.png
was in the folder Icons
and defined as Resource
:
this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/"
+ Assembly.GetExecutingAssembly().GetName().Name
+ ";component/"
+ "Icons/Freq.png", UriKind.Absolute));
I also made a function:
/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
if (assembly == null)
{
assembly = Assembly.GetCallingAssembly();
}
if (pathInApplication[0] == '/')
{
pathInApplication = pathInApplication.Substring(1);
}
return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute));
}
Usage (assumption you put the function in a ResourceHelper class):
this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");
Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml
The recommendation is was to start their name with "X-". E.g. X-Forwarded-For
, X-Requested-With
. This is also mentioned in a.o. section 5 of RFC 2047.
Update 1: On June 2011, the first IETF draft was posted to deprecate the recommendation of using the "X-" prefix for non-standard headers. The reason is that when non-standard headers prefixed with "X-" become standard, removing the "X-" prefix breaks backwards compatibility, forcing application protocols to support both names (E.g, x-gzip
& gzip
are now equivalent). So, the official recommendation is to just name them sensibly without the "X-" prefix.
Update 2: On June 2012, the deprecation of recommendation to use the "X-" prefix has become official as RFC 6648. Below are cites of relevance:
3. Recommendations for Creators of New Parameters
...
- SHOULD NOT prefix their parameter names with "X-" or similar constructs.
4. Recommendations for Protocol Designers
...
SHOULD NOT prohibit parameters with an "X-" prefix or similar constructs from being registered.
MUST NOT stipulate that a parameter with an "X-" prefix or similar constructs needs to be understood as unstandardized.
MUST NOT stipulate that a parameter without an "X-" prefix or similar constructs needs to be understood as standardized.
Note that "SHOULD NOT" ("discouraged") is not the same as "MUST NOT" ("forbidden"), see also RFC 2119 for another spec on those keywords. In other words, you can keep using "X-" prefixed headers, but it's not officially recommended anymore and you may definitely not document them as if they are public standard.
Summary:
This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.
Use this bash script:
#!/bin/bash
for VARIABLE in *.jar
do
jar -tf $VARIABLE |grep "\.class"|awk -v arch=$VARIABLE '{print arch ":" $4}'|sed 's/\//./g'|sed 's/\.\.//g'|sed 's/\.class//g'
done
this will list the classes inside jars in your directory in the form:
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file1.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
file2.jar:fullyqualifiedclassName
Sample output:
commons-io.jar:org.apache.commons.io.ByteOrderMark
commons-io.jar:org.apache.commons.io.Charsets
commons-io.jar:org.apache.commons.io.comparator.AbstractFileComparator
commons-io.jar:org.apache.commons.io.comparator.CompositeFileComparator
commons-io.jar:org.apache.commons.io.comparator.DefaultFileComparator
commons-io.jar:org.apache.commons.io.comparator.DirectoryFileComparator
commons-io.jar:org.apache.commons.io.comparator.ExtensionFileComparator
commons-io.jar:org.apache.commons.io.comparator.LastModifiedFileComparator
In windows you can use powershell:
Get-ChildItem -File -Filter *.jar |
ForEach-Object{
$filename = $_.Name
Write-Host $filename
$classes = jar -tf $_.Name |Select-String -Pattern '.class' -CaseSensitive -SimpleMatch
ForEach($line in $classes) {
write-host $filename":"(($line -replace "\.class", "") -replace "/", ".")
}
}
There's actually quite a simple native method for this:
if( $('#myfav')[0].hasChildNodes() ) { ... }
Note that this also includes simple text nodes, so it will be true for a <div>text</div>
.
You want to use transform
this will return a Series with the index aligned to the df so you can then add it as a new column:
In [74]:
df = pd.DataFrame({'Date': ['2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05', '2015-05-08', '2015-05-07', '2015-05-06', '2015-05-05'], 'Sym': ['aapl', 'aapl', 'aapl', 'aapl', 'aaww', 'aaww', 'aaww', 'aaww'], 'Data2': [11, 8, 10, 15, 110, 60, 100, 40],'Data3': [5, 8, 6, 1, 50, 100, 60, 120]})
?
df['Data4'] = df['Data3'].groupby(df['Date']).transform('sum')
df
Out[74]:
Data2 Data3 Date Sym Data4
0 11 5 2015-05-08 aapl 55
1 8 8 2015-05-07 aapl 108
2 10 6 2015-05-06 aapl 66
3 15 1 2015-05-05 aapl 121
4 110 50 2015-05-08 aaww 55
5 60 100 2015-05-07 aaww 108
6 100 60 2015-05-06 aaww 66
7 40 120 2015-05-05 aaww 121
I don't know what the .tex extension on your file means. If we are saying that it is any file with any extension you have several methods of reading it.
I have to assume you are using windows because you have mentioned notepad++.
Use notepad++. Right click on the file and choose "edit with notepad++"
Use notepad Change the filename extension to .txt and double click the file.
Use command prompt. Open the folder that your file is in. Hold down shift and right click. (not on the file, but in the folder that the file is in.) Choose "open command window here" from the command prompt type: "type filename.tex"
If these don't work, I would need more detail as to how they are not working. Errors that you may be getting or what you may expect to be in the file might help.
Use the astype
method.
>>> x = np.array([[1.0, 2.3], [1.3, 2.9]])
>>> x
array([[ 1. , 2.3],
[ 1.3, 2.9]])
>>> x.astype(int)
array([[1, 2],
[1, 2]])
If you don't remember your password, then run this command in the Shell:
mysqladmin.exe -u root password NewPassword
where 'NewPassword' is your new password.
This does exactly what you are asking, checks the rows, and inserts a blank empty row at each change in column A:
sub AddBlankRows()
'
dim iRow as integer, iCol as integer
dim oRng as range
set oRng=range("a1")
irow=oRng.row
icol=oRng.column
do
'
if cells(irow+1, iCol)<>cells(irow,iCol) then
cells(irow+1,iCol).entirerow.insert shift:=xldown
irow=irow+2
else
irow=irow+1
end if
'
loop while not cells (irow,iCol).text=""
'
end sub
I hope that gets you started, let us know!
Philip
http://site.mockito.org/mockito/docs/1.10.19/org/mockito/Matchers.html
anyObject()
should fit your needs.
Also, you can always consider implementing hashCode()
and equals()
for the Bazoo
class. This would make your code example work the way you want.
With postgres, I had to adjust the solution with this to work for me:
UPDATE BookingPitches AS p
SET extrasPrice = t.sumPrice
FROM
(
SELECT PitchID, SUM(Price) sumPrice
FROM BookingPitchExtras
WHERE [required] = 1
GROUP BY PitchID
) t
WHERE t.PitchID = p.ID AND p.bookingID = 1
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
You could use the :first-child and :last-child pseudo-selectors
:
tr td:first-child{
color:red;
}
tr td:last-child {
color:green
}
Or you can use other way like
// To first child
tr td:nth-child(1){
color:red;
}
// To last child
tr td:nth-last-child(1){
color:green;
}
Both way are perfectly working
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";
CREATE TABLE #tmp
(
sizeId Varchar(MAX)
)
INSERT #tmp
VALUES ('44'),
('44,45,46'),
('44,45,46'),
('44,45,46'),
('44,45,46'),
('44,45,46'),
('44,45,46')
SELECT * FROM #tmp
DECLARE @SqlStr VARCHAR(MAX)
SELECT @SqlStr = STUFF((SELECT ',' + sizeId
FROM #tmp
ORDER BY sizeId
FOR XML PATH('')), 1, 1, '')
SELECT TOP 1 * FROM (
select items, count(*)AS Occurrence
FROM dbo.Split(@SqlStr,',')
group by items
having count(*) > 1
)K
ORDER BY K.Occurrence DESC
If I set my backend to template
in ~/.matplotlib/matplotlibrc
,
then I can reproduce your symptoms:
~/.matplotlib/matplotlibrc:
# backend : GtkAgg
backend : template
Note that the file matplotlibrc
may not be in directory ~/.matplotlib/
. In this case, the following code shows where it is:
>>> import matplotlib
>>> matplotlib.matplotlib_fname()
In [1]: import matplotlib.pyplot as p
In [2]: p.plot(range(20),range(20))
Out[2]: [<matplotlib.lines.Line2D object at 0xa64932c>]
In [3]: p.show()
If you edit ~/.matplotlib/matplotlibrc
and change the backend to something like GtkAgg
, you should see a plot. You can list all the backends available on your machine with
import matplotlib.rcsetup as rcsetup
print(rcsetup.all_backends)
It should return a list like:
['GTK', 'GTKAgg', 'GTKCairo', 'FltkAgg', 'MacOSX', 'QtAgg', 'Qt4Agg',
'TkAgg', 'WX', 'WXAgg', 'CocoaAgg', 'agg', 'cairo', 'emf', 'gdk', 'pdf',
'ps', 'svg', 'template']
Reference:
I tried replacing value
with Value
and it worked out. It has set the value
in input
tag now.
I for myself prefer Lukas Edger's solution.
But you might want to know there is also a function SYS_GUID which can be applied as a default value to a column and generate unique ids.
you can read more about pros and cons here
The output of EXPLAIN PLAN is a debug output from Oracle's query optimiser. The COST is the final output of the Cost-based optimiser (CBO), the purpose of which is to select which of the many different possible plans should be used to run the query. The CBO calculates a relative Cost for each plan, then picks the plan with the lowest cost.
(Note: in some cases the CBO does not have enough time to evaluate every possible plan; in these cases it just picks the plan with the lowest cost found so far)
In general, one of the biggest contributors to a slow query is the number of rows read to service the query (blocks, to be more precise), so the cost will be based in part on the number of rows the optimiser estimates will need to be read.
For example, lets say you have the following query:
SELECT emp_id FROM employees WHERE months_of_service = 6;
(The months_of_service
column has a NOT NULL constraint on it and an ordinary index on it.)
There are two basic plans the optimiser might choose here:
months_of_service=6
).months_of_service=6
(this results in a set of ROWIDs), then access the table based on the ROWIDs returned.Let's imagine the "employees" table has 1,000,000 (1 million) rows. Let's further imagine that the values for months_of_service range from 1 to 12 and are fairly evenly distributed for some reason.
The cost of Plan 1, which involves a FULL SCAN, will be the cost of reading all the rows in the employees table, which is approximately equal to 1,000,000; but since Oracle will often be able to read the blocks using multi-block reads, the actual cost will be lower (depending on how your database is set up) - e.g. let's imagine the multi-block read count is 10 - the calculated cost of the full scan will be 1,000,000 / 10; Overal cost = 100,000.
The cost of Plan 2, which involves an INDEX RANGE SCAN and a table lookup by ROWID, will be the cost of scanning the index, plus the cost of accessing the table by ROWID. I won't go into how index range scans are costed but let's imagine the cost of the index range scan is 1 per row; we expect to find a match in 1 out of 12 cases, so the cost of the index scan is 1,000,000 / 12 = 83,333; plus the cost of accessing the table (assume 1 block read per access, we can't use multi-block reads here) = 83,333; Overall cost = 166,666.
As you can see, the cost of Plan 1 (full scan) is LESS than the cost of Plan 2 (index scan + access by rowid) - which means the CBO would choose the FULL scan.
If the assumptions made here by the optimiser are true, then in fact Plan 1 will be preferable and much more efficient than Plan 2 - which disproves the myth that FULL scans are "always bad".
The results would be quite different if the optimiser goal was FIRST_ROWS(n) instead of ALL_ROWS - in which case the optimiser would favour Plan 2 because it will often return the first few rows quicker, at the cost of being less efficient for the entire query.
like "a darren" answer but minor modification
li
{
background: url("images/bullet.gif") left center no-repeat;
padding-left: 14px;
margin-left: 24px;
}
it works cross browser, just adjust the padding and margin
Edit for nested: add this style to add margin-left to the sub-nested list
ul ul{ margin-left:15px; }
I got null from the Cursor
.
Then found a solution to convert the Uri
into Bitmap
that works perfectly.
Here is the solution that works for me:
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
{
if (resultCode == Activity.RESULT_OK) {
if (requestCode == YOUR_REQUEST_CODE) {
if (data != null) {
if (data.getData() != null) {
Uri contentURI = data.getData();
ex_one.setImageURI(contentURI);
Log.d(TAG, "onActivityResult: " + contentURI.toString());
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), contentURI);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (data.getClipData() != null) {
ClipData mClipData = data.getClipData();
ArrayList<Uri> mArrayUri = new ArrayList<Uri>();
for (int i = 0; i < mClipData.getItemCount(); i++) {
ClipData.Item item = mClipData.getItemAt(i);
Uri uri = item.getUri();
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
}
}
Your interior <div>
elements should likely both be float:left
. Divs size to 100% the size of their container width automatically. Try using display:inline-block
instead of width:auto
on the container div. Or possibly float:left
the container and also apply overflow:auto
. Depends on what you're after exactly.
Some might want certain class constants public while others private.
private keyword can be used to limit the scope of constants within the same swift file.
class MyClass {
struct Constants {
static let testStr = "test"
static let testStrLen = testStr.characters.count
//testInt will not be accessable by other classes in different swift files
private static let testInt = 1
}
func ownFunction()
{
var newInt = Constants.testInt + 1
print("Print testStr=\(Constants.testStr)")
}
}
Other classes will be able to access your class constants like below
class MyClass2
{
func accessOtherConstants()
{
print("MyClass's testStr=\(MyClass.Constants.testStr)")
}
}
You can prevent tables from expanding beyond their parent div by using table-layout:fixed
.
The CSS below will make your tables expand to the width of the div surrounding it.
table
{
table-layout:fixed;
width:100%;
}
I found this trick here.
One can also try below:
public class RandomInt {
public static void main(String[] args) {
int n1 = Integer.parseInt(args[0]);
int n2 = Integer.parseInt(args[1]);
double Random;
if (n1 != n2)
{
if (n1 > n2)
{
Random = n2 + (Math.random() * (n1 - n2));
System.out.println("Your random number is: " + Random);
}
else
{
Random = n1 + (Math.random() * (n2 - n1));
System.out.println("Your random number is: " +Random);
}
} else {
System.out.println("Please provide valid Range " +n1+ " " +n2+ " are equal numbers." );
}
}
}
Following script will work with table schema along with latest Types like (MAX), IMAGE, and etc. change your collation type according to your need on this line (SET @collate = 'DATABASE_DEFAULT';)
SQL SCRIPT HERE:
BEGIN
DECLARE @collate nvarchar(100);
declare @schema nvarchar(255);
DECLARE @table nvarchar(255);
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length varchar(100);
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
SET @collate = 'DATABASE_DEFAULT';
DECLARE tbl_cursor CURSOR FOR SELECT (s.[name])schemaName, (o.[name])[tableName]
FROM sysobjects sy
INNER JOIN sys.objects o on o.name = sy.name
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE OBJECTPROPERTY(sy.id, N'IsUserTable') = 1
OPEN tbl_cursor FETCH NEXT FROM tbl_cursor INTO @schema,@table
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE tbl_cursor_changed CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, c.max_length
, c.column_id
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id like OBJECT_ID(@schema+'.'+@table)
ORDER BY c.column_id
OPEN tbl_cursor_changed
FETCH NEXT FROM tbl_cursor_changed
INTO @row_id, @column_name, @data_type, @max_length, @column_id
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@max_length = -1) SET @max_length = 'MAX';
IF (@data_type LIKE '%char%')
BEGIN TRY
SET @sql = 'ALTER TABLE ' +@schema+'.'+ @table + ' ALTER COLUMN ' + @column_name + ' ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate
print @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR:'
PRINT @sql
END CATCH
FETCH NEXT FROM tbl_cursor_changed
INTO @row_id, @column_name, @data_type, @max_length, @column_id
END
CLOSE tbl_cursor_changed
DEALLOCATE tbl_cursor_changed
FETCH NEXT FROM tbl_cursor
INTO @schema, @table
END
CLOSE tbl_cursor
DEALLOCATE tbl_cursor
PRINT 'Collation For All Tables Done!'
END
virtualenv
permission problems might occur when you create the virtualenv
as sudo
and then operate without sudo
in the virtualenv
.
As found out in your question's comment, the solution here is to create the virtualenv
without sudo
to be able to work (esp. write) in it without sudo
.
There is a class, Class
, that can do this:
Class c = Class.forName("MyClass"); // if you want to specify a class
Class c = this.getClass(); // if you want to use the current class
System.out.println("Package: "+c.getPackage()+"\nClass: "+c.getSimpleName()+"\nFull Identifier: "+c.getName());
If c
represented the class MyClass
in the package mypackage
, the above code would print:
Package: mypackage
Class: MyClass
Full Identifier: mypackage.MyClass
You can take this information and modify it for whatever you need, or go check the API for more information.
Update 2020 for Bootstrap 4
To change the primary, or any of the theme colors in Bootstrap 4 SASS, set the appropriate variables before importing bootstrap.scss
. This allows your custom scss to override the !default values...
$primary: purple;
$danger: red;
@import "bootstrap";
Demo: https://codeply.com/go/f5OmhIdre3
In some cases, you may want to set a new color from another existing Bootstrap variable. For this @import the functions and variables first so they can be referenced in the customizations...
/* import the necessary Bootstrap files */
@import "bootstrap/functions";
@import "bootstrap/variables";
$theme-colors: (
primary: $purple
);
/* finally, import Bootstrap */
@import "bootstrap";
Demo: https://codeply.com/go/lobGxGgfZE
Also see: this answer, this answer or changing the button color in (CSS or SASS)
It's also possible to change the primary color with CSS only but it requires a lot of additional CSS since there are many -primary
variations (btn-primary, alert-primary, bg-primary, text-primary, table-primary, border-primary, etc...) and some of these classes have slight colors variations on borders, hover, and active states. Therefore, if you must use CSS it's better to use target one component such as changing the primary button color.
These solutions will also work for Bootstrap 5 alpha
It doesn't work because it's not supported
The
DEFAULT
clause specifies a default value for a column. With one exception, the default value must be a constant; it cannot be a function or an expression. This means, for example, that you cannot set the default for a date column to be the value of a function such asNOW()
orCURRENT_DATE
. The exception is that you can specifyCURRENT_TIMESTAMP
as the default for aTIMESTAMP
column
Java 8 provides a set of unsigned long operations that allows you to directly treat those Long variables as unsigned Long, here're some commonly used ones:
And additions, subtractions, and multiplications are the same for signed and unsigned longs.
Before:
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
After:
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
Worked for me.
I had to extract numbers first from a list of float strings:
df4['sscore'] = df4['simscore'].str.findall('\d+\.\d+')
then each convert to a float:
ad=[]
for z in range(len(df4)):
ad.append([float(i) for i in df4['sscore'][z]])
in the end assign all floats to a dataframe as float64:
df4['fscore'] = np.array(ad,dtype=float)
Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....
Prior answers focused on nominal data (e.g. unordered). If there is a reason to impose order for an ordinal variable, then one would use:
# Transform to category
df['zipcode_category'] = df['zipcode_category'].astype('category')
# Add ordered category
df['zipcode_ordered'] = df['zipcode_category']
# Setup the ordering
df.zipcode_ordered.cat.set_categories(
new_categories = [90211, 90210], ordered = True, inplace = True
)
# Output IDs
df['zipcode_ordered_id'] = df.zipcode_ordered.cat.codes
print(df)
# zipcode_category zipcode_ordered zipcode_ordered_id
# 90210 90210 1
# 90211 90211 0
More details on setting ordered categories can be found at the pandas website:
https://pandas.pydata.org/pandas-docs/stable/user_guide/categorical.html#sorting-and-order
Things to check when enabling the bundle optimization;
BundleTable.EnableOptimizations = true;
and
webconfig debug = "false"
bundles.IgnoreList.Clear();
this will ignore the minified assets of your bundles like *.min.css
or *.min.js
which can cause an undefine error of your script. To fix is replace the .min
asset to original. if you do this you may not need the bundles.IgnoreList.Clear();
e.g.
bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
.Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
Make sure the names of the bundles of your css and js are unique.
bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );
bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );
Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.
@Styles.Render("~/bundles/datatablescss")
@Scripts.Render("~/bundles/datatablesjs")
With the Jetbrains Anko library, you can use the doAsync{..} method to automatically execute database calls. This takes care of the verbosity problem you seemed to have been having with mcastro's answer.
Example usage:
doAsync {
Application.database.myDAO().insertUser(user)
}
I use this frequently for inserts and updates, however for select queries I reccommend using the RX workflow.
There is very easy solution to show headers at the top of multi columns list box. Just change the property value to "true" for "columnheads" which is false by default.
After that Just mention the data range in property "rowsource" excluding header from the data range and header should be at first top row of data range then it will pick the header automatically and you header will be freezed.
if suppose you have data in range "A1:H100" and header at "A1:H1" which is the first row then your data range should be "A2:H100" which needs to mention in property "rowsource" and "columnheads" perperty value should be true
Regards, Asif Hameed
Its due to access control security policies specifically when SELinux is enabled it won't allow external executables to create temporary files in the system locations.
Disable SELinux by issuing below command:
echo 0 >/selinux/enforce
You can now start mysql it wont give any permission related errror while reading/writing to /tmp or system directories.
In case you wish to enable the SELinux security back change 0 to 1 in above command.
Sometimes you can have a bunch of keys in your ~/.ssh
directory, and don't know which matches the fingerprint shown by GitHub/Gitlab/etc.
Here's how to show the key filenames and MD5 fingerprints of all the keys in your ~/.ssh
directory:
cd ~/.ssh
find . -type f -exec printf "\n{}\n" \; -exec ssh-keygen -E md5 -lf {} \;
(For what the parameters mean, refer to this answer about the find
command.
Note that the private/public files that belong to one key have the same fingerprint, so you'll see duplicates.
You forgot the #
on the id selector:
if ($("#EventStartTimeMin").val() === "") {
// ...
}
With recent versions of Docker, you would set the value of the data-root
parameter to your custom path, in /etc/docker/daemon.json
(according to https://docs.docker.com/engine/reference/commandline/dockerd/#daemon-configuration-file).
With older versions, you can change Docker's storage base directory (where container and images go) using the -g
option when starting the Docker daemon. (check docker --help
).
You can have this setting applied automatically when Docker starts by adding it to /etc/default/docker
For those people who are trying to select from the DIV instead of the text field, here is the code. The code is self-explanatory but comment here if you want more information:
import React from 'react';
....
//set ref to your div
setRef = (ref) => {
// debugger; //eslint-disable-line
this.dialogRef = ref;
};
createMarkeup = content => ({
__html: content,
});
//following function select and copy data to the clipboard from the selected Div.
//Please note that it is only tested in chrome but compatibility for other browsers can be easily done
copyDataToClipboard = () => {
try {
const range = document.createRange();
const selection = window.getSelection();
range.selectNodeContents(this.dialogRef);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
this.showNotification('Macro copied successfully.', 'info');
this.props.closeMacroWindow();
} catch (err) {
// console.log(err); //eslint-disable-line
//alert('Macro copy failed.');
}
};
render() {
return (
<div
id="macroDiv"
ref={(el) => {
this.dialogRef = el;
}}
// className={classes.paper}
dangerouslySetInnerHTML={this.createMarkeup(this.props.content)}
/>
);
}
I suggest you using bootstrap which works perfectly:
@import url('http://getbootstrap.com/dist/css/bootstrap.css');_x000D_
html, body, .container-table {_x000D_
height: 100%;_x000D_
}_x000D_
.container-table {_x000D_
display: table;_x000D_
}_x000D_
.vertical-center-row {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1.0" />_x000D_
<title>Login Page | ... </title>_x000D_
_x000D_
<script src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.1.0/bootstrap.min.js"></script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
<div class="container container-table">_x000D_
<div class="row vertical-center-row">_x000D_
<div class="text-center col-md-4 col-md-offset-4" style="">_x000D_
<form id="login" action="dashboard.html" method="post">_x000D_
_x000D_
<div class="username">_x000D_
<div class="usernameinner">_x000D_
<input type="text" name="username" id="username" placeholder="Login" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="password">_x000D_
<div class="passwordinner">_x000D_
<input type="password" name="password" id="password" placeholder="Mot de passe" />_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="login-button">Connexion</button>_x000D_
_x000D_
<div class="keep"><input type="checkbox" /> Gardez moi connecté</div>_x000D_
_x000D_
</form>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:
argument_list ::= positional_arguments ["," starred_and_keywords]
["," keywords_arguments]
| starred_and_keywords ["," keywords_arguments]
| keywords_arguments
Specifically, a keyword argument looks like this: tag='insider trading!'
while a positional argument looks like this: ..., exchange, ...
. The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.
Also, when an argument has a default value, such as price=None
, that means you don't have to provide it. If you don't provide it, it will use the default value instead.
To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity)
# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)
# Some positional, some keyword (all keywords at end):
order_id = kite.order_place(self, exchange, tradingsymbol,
transaction_type, quantity, tag='insider trading!')
This will do the trick for you:
ng update @angular/cli @angular/core
ng s
or ng build
respectively.public static DateTime ConvertDateTime(string Date)
{
DateTime date=new DateTime();
try
{
string CurrentPattern = Thread.CurrentThread.CurrentCulture.DateTimeFormat.ShortDatePattern;
string[] Split = new string[] {"-","/",@"\","."};
string[] Patternvalue = CurrentPattern.Split(Split,StringSplitOptions.None);
string[] DateSplit = Date.Split(Split,StringSplitOptions.None);
string NewDate = "";
if (Patternvalue[0].ToLower().Contains("d") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("y")==true)
{
NewDate = DateSplit[1] + "/" + DateSplit[0] + "/" + DateSplit[2];
}
else if (Patternvalue[0].ToLower().Contains("m") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("y")==true)
{
NewDate = DateSplit[0] + "/" + DateSplit[1] + "/" + DateSplit[2];
}
else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("m")==true && Patternvalue[2].ToLower().Contains("d")==true)
{
NewDate = DateSplit[2] + "/" + DateSplit[0] + "/" + DateSplit[1];
}
else if (Patternvalue[0].ToLower().Contains("y") == true && Patternvalue[1].ToLower().Contains("d")==true && Patternvalue[2].ToLower().Contains("m")==true)
{
NewDate = DateSplit[2] + "/" + DateSplit[1] + "/" + DateSplit[0];
}
date = DateTime.Parse(NewDate, Thread.CurrentThread.CurrentCulture);
}
catch (Exception ex)
{
}
finally
{
}
return date;
}
You can do like this:
public static void main(String[] args) {
int x=2 , y=7, z=14;
int max1= Math.max(x,y);
System.out.println("Max value is: "+ Math.max(max1, z));
}
The below listed query will list highest salary in each department.
select deptname, max(salary) from department, employee where
department.deptno=employee.deptno group by deptname;
I executed this query successfully on Oracle database.
This works for me. Just greps it out of the command line arguments, strips off the unwanted text, does a dirname and finally gets the full path from that:
args <- commandArgs(trailingOnly = F)
scriptPath <- normalizePath(dirname(sub("^--file=", "", args[grep("^--file=", args)])))
As mentioned by @pinouchon you can pass it with the help of array index
my_array[0] value
my_array[1] value
In addition to this, to pass list of hashes, you can follow something like:
my_array[0][key1] value1
my_array[0][key2] value2
Example:
To pass param1=[{name:test_name, value:test_value}, {...}]
param1[0][name] test_name
param1[0][value] test_value
As others pointed out, the most straightforward way to deploy a WAR is to copy it to the webapps
of the Tomcat install. Another option would be to use the manager application if it is installed (this is not always the case), if it's properly configured (i.e. if you have the credentials of a user assigned to the appropriate group) and if it you can access it over an insecure network like Internet (but this is very unlikely and you didn't mention any VPN access). So this leaves you with the webapp
directory.
Now, if Tomcat is installed and running on bilgin.ath.cx
(as this is the machine where you uploaded the files), I noticed that Apache is listening to port 80
on that machien so I would bet that Tomcat is not directly exposed and that requests have to go through Apache. In that case, I think that deploying a new webapp and making it visible to the Internet will involve the edit of Apache configuration files (mod_jk
?, mod_proxy
?). You should either give us more details or discuss this with your hosting provider.
Update: As expected, the bilgin.ath.cx
is using Apache Tomcat + Apache HTTPD + mod_jk. The configuration usually involves two files: the worker.properties
file to configure the workers and the httpd.conf
for Apache. Now, without seeing the current configuration, it's not easy to give a definitive answer but, basically, you may have to add a JkMount
directive in Apache httpd.conf
for your new webapp1. Refer to the mod_jk documentation, it has a simple configuration example. Note that modifying httpd.conf
will require access to (obviously) and proper rights and that you'll have to restart Apache after the modifications.
1 I don't think you'll need to define a new worker if you are deploying to an already used Tomcat instance, especially if this sounds like Chinese for you :)
Simply Use
FragmentManager fm = getActivity().getSupportFragmentManager();
Remember always when accessing fragment inflating in MainLayout use
Casting or getActivity()
.
There are two situations:
It is possible that an object is [NSNull null]
, or it is impossible.
Your application usually shouldn't use [NSNull null];
you only use it if you want to put a "null" object into an array, or use it as a dictionary value. And then you should know which arrays or dictionaries might contain null values, and which might not.
If you think that an array never contains [NSNull null]
values, then don't check for it. If there is an [NSNull null]
, you might get an exception but that is fine: Objective-C exceptions indicate programming errors. And you have a programming error that needs fixing by changing some code.
If an object could be [NSNull null]
, then you check for this quite simply by testing
(object == [NSNull null])
. Calling isEqual
or checking the class of the object is nonsense. There is only one [NSNull null]
object, and the plain old C operator checks for it just fine in the most straightforward and most efficient way.
If you check an NSString
object that cannot be [NSNull null]
(because you know it cannot be [NSNull null]
or because you just checked that it is different from [NSNull null]
, then you need to ask yourself how you want to treat an empty string, that is one with length 0. If you treat it is a null
string like nil
, then test (object.length == 0)
. object.length will return 0 if object == nil
, so this test covers nil objects and strings with length 0. If you treat a string of length 0 different from a nil string, just check if object == nil
.
Finally, if you want to add a string to an array or a dictionary, and the string could be nil, you have the choice of not adding it, replacing it with @""
, or replacing it with [NSNull null]
. Replacing it with @""
means you lose the ability to distinguish between "no string" and "string of length 0". Replacing it with [NSNull null]
means you have to write code when you access the array or dictionary that checks for [NSNull null]
objects.
gcc can actually compile c++ code just fine. The errors you received are linker errors, not compiler errors.
Odds are that if you change the compilation line to be this:
gcc info.C -lstdc++
which makes it link to the standard c++ library, then it will work just fine.
However, you should just make your life easier and use g++.
EDIT:
Rup says it best in his comment to another answer:
[...] gcc will select the correct back-end compiler based on file extension (i.e. will compile a .c as C and a .cc as C++) and links binaries against just the standard C and GCC helper libraries by default regardless of input languages; g++ will also select the correct back-end based on extension except that I think it compiles all C source as C++ instead (i.e. it compiles both .c and .cc as C++) and it includes libstdc++ in its link step regardless of input languages.
Another R package for aggregating multiple regression models into LaTeX tables is texreg.
Not really an answer to your question as asked, but thought I'd chip in about your general objective.
There already is a method to generate random file names in .NET.
See System.Path.GetTempFileName and GetRandomFileName.
Alternatively, it is a common practice to use a GUID to name random files.
To answer your bonus question, the general answer is no, you don't need to set variables to "Nothing" in short .VBS scripts like yours, that get called by Wscript or Cscript.
The reason you might do this in the middle of a longer script is to release memory back to the operating system that VB would otherwise have been holding. These days when 8GB of RAM is typical and 16GB+ relatively common, this is unlikely to produce any measurable impact, even on a huge script that has several megabytes in a single variable. At this point it's kind of a hold-over from the days where you might have been working in 1MB or 2MB of RAM.
You're correct, the moment your .VBS script completes, all of your variables get destroyed and the memory is reclaimed anyway. Setting variables to "Nothing" simply speeds up that process, and allows you to do it in the middle of a script.
Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.
<script src="test.js?random=<?php echo uniqid(); ?>"></script>
EDIT: Or you could use the file modification time so that it's cached on the client.
<script src="test.js?random=<?php echo filemtime('test.js'); ?>"></script>
You can use the _contains function from the underscore.js library to achieve this:
if (_.contains(haystack, needle)) {
console.log("Needle found.");
};
pip
/ conda
After extensively documenting a similar problem with Git (How can I make git accept a self signed certificate?), here we are again behind a corporate firewall with a proxy giving us a MitM "attack" that we should trust and:
NEVER disable all SSL verification!
This creates a bad security culture. Don't be that person.
pip config set global.cert path/to/ca-bundle.crt
pip config list
conda config --set ssl_verify path/to/ca-bundle.crt
conda config --show ssl_verify
# Bonus while we are here...
git config --global http.sslVerify true
git config --global http.sslCAInfo path/to/ca-bundle.crt
But where do we get ca-bundle.crt
?
cURL publishes an extract of the Certificate Authorities bundled with Mozilla Firefox
https://curl.haxx.se/docs/caextract.html
I recommend you open up this cacert.pem
file in a text editor as we will need to add our self-signed CA to this file.
Certificates are a document complying with X.509 but they can be encoded to disk a few ways. The below article is a good read but the short version is that we are dealing with the base64 encoding which is often called PEM in the file extensions. You will see it has the format:
----BEGIN CERTIFICATE----
....
base64 encoded binary data
....
----END CERTIFICATE----
Below are a few options on how to get our self signed certificate:
echo quit | openssl s_client -showcerts -servername "curl.haxx.se" -connect curl.haxx.se:443 > cacert.pem
Thanks to this answer and the linked blog, it shows steps (on Windows) how to view the certificate and then copy to file using the base64 PEM encoding option.
Copy the contents of this exported file and paste it at the end of your cacerts.pem
file.
For consistency rename this file cacerts.pem
--> ca-bundle.crt
and place it somewhere easy like:
# Windows
%USERPROFILE%\certs\ca-bundle.crt
# or *nix
$HOME/certs/cabundle.crt
Thanks to all the brilliant answers in:
How to get response SSL certificate from requests in python?
I have put together the following to attempt to take it a step further.
https://github.com/neozenith/get-ca-py
Set the configuration in pip and conda so that it knows where this CA store resides with our extra self-signed CA.
pip config set global.cert %USERPROFILE%\certs\ca-bundle.crt
conda config --set ssl_verify %USERPROFILE%\certs\ca-bundle.crt
OR
pip config set global.cert $HOME/certs/ca-bundle.crt
conda config --set ssl_verify $HOME/certs/ca-bundle.crt
THEN
pip config list
conda config --show ssl_verify
# Hot tip: use -v to show where your pip config file is...
pip config list -v
# Example output for macOS and homebrew installed python
For variant 'global', will try loading '/Library/Application Support/pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.pip/pip.conf'
For variant 'user', will try loading '/Users/jpeak/.config/pip/pip.conf'
For variant 'site', will try loading '/usr/local/Cellar/python/3.7.4/Frameworks/Python.framework/Versions/3.7/pip.conf'
As I found by the previous answers, three steps are needed to change the type of a column:
Step 1:
Generate a new migration file using this code:
rails g migration sample_name_change_column_type
Step 2:
Go to /db/migrate
folder and edit the migration file you made. There are two different solutions.
def change
change_column(:table_name, :column_name, :new_type)
end
2.
def up
change_column :table_name, :column_name, :new_type
end
def down
change_column :table_name, :column_name, :old_type
end
Step 3:
Don't forget to do this command:
rake db:migrate
I have tested this solution for Rails 4 and it works well.
Keeping things tidy with f-strings:
import os
import pandas as pd
data_files = '../data_folder/'
csv_name = 'data.csv'
pd.read_csv(f"{data_files}{csv_name}")
Although it is quite old question - one may find these useful (not written to be fast):
function d_h_m_s__string1($seconds)
{
$ret = '';
$divs = array(86400, 3600, 60, 1);
for ($d = 0; $d < 4; $d++)
{
$q = (int)($seconds / $divs[$d]);
$r = $seconds % $divs[$d];
$ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
$seconds = $r;
}
return $ret;
}
function d_h_m_s__string2($seconds)
{
if ($seconds == 0) return '0s';
$can_print = false; // to skip 0d, 0d0m ....
$ret = '';
$divs = array(86400, 3600, 60, 1);
for ($d = 0; $d < 4; $d++)
{
$q = (int)($seconds / $divs[$d]);
$r = $seconds % $divs[$d];
if ($q != 0) $can_print = true;
if ($can_print) $ret .= sprintf("%d%s", $q, substr('dhms', $d, 1));
$seconds = $r;
}
return $ret;
}
function d_h_m_s__array($seconds)
{
$ret = array();
$divs = array(86400, 3600, 60, 1);
for ($d = 0; $d < 4; $d++)
{
$q = $seconds / $divs[$d];
$r = $seconds % $divs[$d];
$ret[substr('dhms', $d, 1)] = $q;
$seconds = $r;
}
return $ret;
}
echo d_h_m_s__string1(0*86400+21*3600+57*60+13) . "\n";
echo d_h_m_s__string2(0*86400+21*3600+57*60+13) . "\n";
$ret = d_h_m_s__array(9*86400+21*3600+57*60+13);
printf("%dd%dh%dm%ds\n", $ret['d'], $ret['h'], $ret['m'], $ret['s']);
result:
0d21h57m13s
21h57m13s
9d21h57m13s
I've also struggled with this. I had functions as data members of a class, as a simplified example:
from multiprocessing import Pool
import itertools
pool = Pool()
class Example(object):
def __init__(self, my_add):
self.f = my_add
def add_lists(self, list1, list2):
# Needed to do something like this (the following line won't work)
return pool.map(self.f,list1,list2)
I needed to use the function self.f in a Pool.map() call from within the same class and self.f did not take a tuple as an argument. Since this function was embedded in a class, it was not clear to me how to write the type of wrapper other answers suggested.
I solved this problem by using a different wrapper that takes a tuple/list, where the first element is the function, and the remaining elements are the arguments to that function, called eval_func_tuple(f_args). Using this, the problematic line can be replaced by return pool.map(eval_func_tuple, itertools.izip(itertools.repeat(self.f), list1, list2)). Here is the full code:
File: util.py
def add(a, b): return a+b
def eval_func_tuple(f_args):
"""Takes a tuple of a function and args, evaluates and returns result"""
return f_args[0](*f_args[1:])
File: main.py
from multiprocessing import Pool
import itertools
import util
pool = Pool()
class Example(object):
def __init__(self, my_add):
self.f = my_add
def add_lists(self, list1, list2):
# The following line will now work
return pool.map(util.eval_func_tuple,
itertools.izip(itertools.repeat(self.f), list1, list2))
if __name__ == '__main__':
myExample = Example(util.add)
list1 = [1, 2, 3]
list2 = [10, 20, 30]
print myExample.add_lists(list1, list2)
Running main.py will give [11, 22, 33]. Feel free to improve this, for example eval_func_tuple could also be modified to take keyword arguments.
On another note, in another answers, the function "parmap" can be made more efficient for the case of more Processes than number of CPUs available. I'm copying an edited version below. This is my first post and I wasn't sure if I should directly edit the original answer. I also renamed some variables.
from multiprocessing import Process, Pipe
from itertools import izip
def spawn(f):
def fun(pipe,x):
pipe.send(f(x))
pipe.close()
return fun
def parmap(f,X):
pipe=[Pipe() for x in X]
processes=[Process(target=spawn(f),args=(c,x)) for x,(p,c) in izip(X,pipe)]
numProcesses = len(processes)
processNum = 0
outputList = []
while processNum < numProcesses:
endProcessNum = min(processNum+multiprocessing.cpu_count(), numProcesses)
for proc in processes[processNum:endProcessNum]:
proc.start()
for proc in processes[processNum:endProcessNum]:
proc.join()
for proc,c in pipe[processNum:endProcessNum]:
outputList.append(proc.recv())
processNum = endProcessNum
return outputList
if __name__ == '__main__':
print parmap(lambda x:x**x,range(1,5))
As now to day CKEditor 4+ launched we have to use it.ekeditor 4 setData documentation
CKEDITOR.instances['editor1'].setData(value);
Where editor1
is textarea Id.
Old methods such as insertHtml('html data')
and insertText('text data')
also works fine.
and to get data use
var ckdata = CKEDITOR.instances['editor1'].getData();
var data = CKEDITOR.instances.editor1.getData();
If you are using STS and your server is Pivotal Just double click on the server and go to >Modules tab >display Configure the Web Modules on this server.>you can just remove modules and run once again.
This is how we do it in our application
def store_location
session[:return_to] = request.fullpath if request.get? and controller_name != "user_sessions" and controller_name != "sessions"
end
def redirect_back_or_default(default)
redirect_to(session[:return_to] || default)
end
This way you only store last GET request in :return_to
session param, so all forms, even when multiple time POSTed would work with :return_to
.
Awesome tutorial: 3 Different Ways to Display Progress in an ASP.NET AJAX Application
I was facing this issue, then I put my dropdown in nav tag. Worked for me that way.
This won't sum up the number; instead it will concatenate it:
var x = y + z;
You need to do:
var x = (y)+(z);
You must use parseInt in order to specify the operation on numbers. Example:
var x = parseInt(y) + parseInt(z); [final soulution, as everything us]
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
1st Reason could be the ending tag of your application's web.xml file which could not have been closed properly.
web.xml might be ending with <web-app>
, but must end with </web-app>
2nd Reason which worked in my case could be the lib folder of your tomcat must contain the supporting jar file of your database.
ojdbc
on case of Oracle or sqljdbc
in case of SqlServer
You can use:
str.replace(/text/g, "replaced text");
There are 2 main kinds of transactions; connection transactions and ambient transactions. A connection transaction (such as SqlTransaction) is tied directly to the db connection (such as SqlConnection), which means that you have to keep passing the connection around - OK in some cases, but doesn't allow "create/use/release" usage, and doesn't allow cross-db work. An example (formatted for space):
using (IDbTransaction tran = conn.BeginTransaction()) {
try {
// your code
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
Not too messy, but limited to our connection "conn". If we want to call out to different methods, we now need to pass "conn" around.
The alternative is an ambient transaction; new in .NET 2.0, the TransactionScope object (System.Transactions.dll) allows use over a range of operations (suitable providers will automatically enlist in the ambient transaction). This makes it easy to retro-fit into existing (non-transactional) code, and to talk to multiple providers (although DTC will get involved if you talk to more than one).
For example:
using(TransactionScope tran = new TransactionScope()) {
CallAMethodThatDoesSomeWork();
CallAMethodThatDoesSomeMoreWork();
tran.Complete();
}
Note here that the two methods can handle their own connections (open/use/close/dispose), yet they will silently become part of the ambient transaction without us having to pass anything in.
If your code errors, Dispose() will be called without Complete(), so it will be rolled back. The expected nesting etc is supported, although you can't roll-back an inner transaction yet complete the outer transaction: if anybody is unhappy, the transaction is aborted.
The other advantage of TransactionScope is that it isn't tied just to databases; any transaction-aware provider can use it. WCF, for example. Or there are even some TransactionScope-compatible object models around (i.e. .NET classes with rollback capability - perhaps easier than a memento, although I've never used this approach myself).
All in all, a very, very useful object.
Some caveats:
Use immediate children selector >
:
$('#tblOne > tbody > tr')
Description: Selects all direct child elements specified by "child" of elements specified by "parent".
It depend on your access right but for me this work on phpmyadmin sql console
SHOW VARIABLES;
then after to change some variables you can do
SET GLOBAL max_connections = 1000;
or
SET @@GLOBAL.max_connections = 1000;
give a try