IMDB themselves seem to distribute data, but only in text files:
http://www.imdb.com/interfaces
there are several APIs around this that you can Google. Screen scraping is explicitly forbidden. A official API seems to be in the works, but has been that for years already.
For Django 2
and python 3
install psycopg2
using pip3
:
pip3 install psycopg2
In normal situations the following should work:
var can = CanvasElement.getContext('2d'); //get context
var lineHeight = /[0-9]+(?=pt|px)/.exec(can.font); //get height from font variable
Import all Angular Material modules in Angular 9.
Create material.module.ts file in your_project/src/app/ directory and paste this code.
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatCheckboxModule } from '@angular/material/checkbox';
import { MatButtonModule } from '@angular/material/button';
import { MatInputModule } from '@angular/material/input';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatMenuModule } from '@angular/material/menu';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatBadgeModule } from '@angular/material/badge';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatListModule } from '@angular/material/list';
import { MatGridListModule } from '@angular/material/grid-list';
import { MatCardModule } from '@angular/material/card';
import { MatStepperModule } from '@angular/material/stepper';
import { MatTabsModule } from '@angular/material/tabs';
import { MatExpansionModule } from '@angular/material/expansion';
import { MatButtonToggleModule } from '@angular/material/button-toggle';
import { MatChipsModule } from '@angular/material/chips';
import { MatIconModule } from '@angular/material/icon';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatDialogModule } from '@angular/material/dialog';
import { MatTooltipModule } from '@angular/material/tooltip';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatPaginatorModule } from '@angular/material/paginator';
@NgModule( {
imports: [
CommonModule,
BrowserAnimationsModule,
MatCheckboxModule,
MatCheckboxModule,
MatButtonModule,
MatInputModule,
MatAutocompleteModule,
MatDatepickerModule,
MatFormFieldModule,
MatRadioModule,
MatSelectModule,
MatSliderModule,
MatSlideToggleModule,
MatMenuModule,
MatSidenavModule,
MatBadgeModule,
MatToolbarModule,
MatListModule,
MatGridListModule,
MatCardModule,
MatStepperModule,
MatTabsModule,
MatExpansionModule,
MatButtonToggleModule,
MatChipsModule,
MatIconModule,
MatProgressSpinnerModule,
MatProgressBarModule,
MatDialogModule,
MatTooltipModule,
MatSnackBarModule,
MatTableModule,
MatSortModule,
MatPaginatorModule
],
exports: [
MatButtonModule,
MatToolbarModule,
MatIconModule,
MatSidenavModule,
MatBadgeModule,
MatListModule,
MatGridListModule,
MatInputModule,
MatFormFieldModule,
MatSelectModule,
MatRadioModule,
MatDatepickerModule,
MatChipsModule,
MatTooltipModule,
MatTableModule,
MatPaginatorModule
],
providers: [
MatDatepickerModule,
]
} )
export class AngularMaterialModule { }
How about simply (Please note, come up with a better name for the class name this is simply an example):
.centerText{
text-align: center;
}
<div>
<table style="width:100%">
<tbody>
<tr>
<td class="centerText">Cell 1</td>
<td>Cell 2</td>
</tr>
<tr>
<td class="centerText">Cell 3</td>
<td>Cell 4</td>
</tr>
</tbody>
</table>
</div>
Example here
You can place the css
in a separate file, which is recommended.
In my example, I created a file called styles.css
and placed my css
rules in it.
Then include it in the html document in the <head>
section as follows:
<head>
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
The alternative, not creating a seperate css file, not recommended at all...
Create <style>
block in your <head>
in the html document. Then just place your rules there.
<head>
<style type="text/css">
.centerText{
text-align: center;
}
</style>
</head>
you can update the setting under init.ora in oraclexe\app\oracle\product\11.2.0\server\config\scripts
If USB Debugging Mode is enabled and does not work, you should install your device driver.
For Nexus Devices;
For Another Devices;
Hope it helps!
$count = DB::table('category_issue')->count();
will give you the number of items.
For more detailed information check Fluent Query Builder section in beautiful Laravel Documentation.
here is your answer
String userName = "xxxx";
String password = "xxxx";
String url = "jdbc:sqlserver:xxx.xxx.xxx.xxx;databaseName=asdfzxcvqwer;integratedSecurity=true";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection(url, userName, password);
} catch (Exception e)
{
e.printStackTrace();
}
You could use IIF
statement like in the next example:
SELECT
IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
TABLE_NAME
The examples to os.walk in the documentation show how to do this:
for root, dirs, filenames in os.walk(indir):
for f in filenames:
log = open(os.path.join(root, f),'r')
How did you expect the "open" function to know that the string "1" is supposed to mean "/home/des/test/1" (unless "/home/des/test" happens to be your current working directory)?
Assuming that you're constrained to using Date
, you can do the following:
Date diff = new Date(d2.getTime() - d1.getTime());
Here you're computing the differences in milliseconds since the "epoch", and creating a new Date object at an offset from the epoch. Like others have said: the answers in the duplicate question are probably better alternatives (if you aren't tied down to Date
).
Short answer is: No, it's not possible to prevent CSS inheritance. You can only override the styles that are set on the parents. See the spec:
Every element in an HTML document will inherit all inheritable properties from its parent except the root element (
html
), which doesn’t have a parent. -W3C
Apart from overriding every single inherited property. You can also use initial
keyword, e.g. color: initial;
. It also can be used together with all
, e.g. all: initial;
, that will reset all properties at once. Example:
.container {_x000D_
color: blue;_x000D_
font-style: italic;_x000D_
}_x000D_
.initial {_x000D_
all: initial;_x000D_
}
_x000D_
<div class="container">_x000D_
The quick brown <span class="initial">fox</span> jumps over the lazy dog_x000D_
</div>
_x000D_
Browser support tables according to Can I use...
all
(Currently no support in both IE and Edge, others are good)initial
(Currently no support in IE, others are good)You may find it useful by using direct children selector >
in some cases. Example:
.list > li {_x000D_
border: 1px solid red;_x000D_
color: blue;_x000D_
}
_x000D_
<ul class="list">_x000D_
<li>_x000D_
<span>HEADING 1</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
<li>_x000D_
<span>HEADING 2</span>_x000D_
<ul>_x000D_
<li>sub-heading A</li>_x000D_
<li>sub-heading B</li>_x000D_
</ul>_x000D_
</li>_x000D_
</ul>
_x000D_
The border style has been applied only to the direct children <li>
s, as border
is an non-inherited property. But text color has been applied to all the children, as color
is an inherited property.
Therefore, >
selector would be only useful with non-inherited properties, when it comes to preventing inheritance.
This is quite an old question now, but someone may come here looking for an answer:
echo $order->id;
This should return the order id without "#".
EDIT (feb/2018)
The current way of accomplishing this is by using:
$order->get_id();
@marc_s's answer is very great and I've been using it for few years. However, I noticed that the script misses data in some columnstore indexes and doesn't show complete picture. E.g. when you do SUM(TotalSpace)
against the script and compare it with total space database property in Management Studio the numbers don't match in my case (Management Studio shows larger numbers). I modified the script to overcome this issue and extended it a little bit:
select
tables.[name] as table_name,
schemas.[name] as schema_name,
isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown') as database_name,
sum(allocation_units.total_pages) * 8 as total_space_kb,
cast(round(((sum(allocation_units.total_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as total_space_mb,
sum(allocation_units.used_pages) * 8 as used_space_kb,
cast(round(((sum(allocation_units.used_pages) * 8) / 1024.00), 2) as numeric(36, 2)) as used_space_mb,
(sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8 as unused_space_kb,
cast(round(((sum(allocation_units.total_pages) - sum(allocation_units.used_pages)) * 8) / 1024.00, 2) as numeric(36, 2)) as unused_space_mb,
count(distinct indexes.index_id) as indexes_count,
max(dm_db_partition_stats.row_count) as row_count,
iif(max(isnull(user_seeks, 0)) = 0 and max(isnull(user_scans, 0)) = 0 and max(isnull(user_lookups, 0)) = 0, 1, 0) as no_reads,
iif(max(isnull(user_updates, 0)) = 0, 1, 0) as no_writes,
max(isnull(user_seeks, 0)) as user_seeks,
max(isnull(user_scans, 0)) as user_scans,
max(isnull(user_lookups, 0)) as user_lookups,
max(isnull(user_updates, 0)) as user_updates,
max(last_user_seek) as last_user_seek,
max(last_user_scan) as last_user_scan,
max(last_user_lookup) as last_user_lookup,
max(last_user_update) as last_user_update,
max(tables.create_date) as create_date,
max(tables.modify_date) as modify_date
from
sys.tables
left join sys.schemas on schemas.schema_id = tables.schema_id
left join sys.indexes on tables.object_id = indexes.object_id
left join sys.partitions on indexes.object_id = partitions.object_id and indexes.index_id = partitions.index_id
left join sys.allocation_units on partitions.partition_id = allocation_units.container_id
left join sys.dm_db_index_usage_stats on tables.object_id = dm_db_index_usage_stats.object_id and indexes.index_id = dm_db_index_usage_stats.index_id
left join sys.dm_db_partition_stats on tables.object_id = dm_db_partition_stats.object_id and indexes.index_id = dm_db_partition_stats.index_id
group by schemas.[name], tables.[name], isnull(db_name(dm_db_index_usage_stats.database_id), 'Unknown')
order by 5 desc
Hope it will be helpful for someone. This script was tested against large TB-wide databases with hundreds of different tables, indexes and schemas.
Add this little function and use it as so: $('div').scrollTo(500);
jQuery.fn.extend(
{
scrollTo : function(speed, easing)
{
return this.each(function()
{
var targetOffset = $(this).offset().top;
$('html,body').animate({scrollTop: targetOffset}, speed, easing);
});
}
});
Less than or equal:
User.objects.filter(userprofile__level__lte=0)
Greater than or equal:
User.objects.filter(userprofile__level__gte=0)
Likewise, lt
for less than and gt
for greater than. You can find them all in the documentation.
You can set a call timeout to cover the entire cycle from resolving DNS, connecting, writing the request body, server processing, and reading the response body.
val client = OkHttpClient().newBuilder().callTimeout(CALL_TIMEOUT_IN_MINUTES, TimeUnit.MINUTES).build()
Summary:
PagingAndSortingRepository extends CrudRepository
JpaRepository extends PagingAndSortingRepository
The CrudRepository interface provides methods for CRUD operations, so it allows you to create, read, update and delete records without having to define your own methods.
The PagingAndSortingRepository provides additional methods to retrieve entities using pagination and sorting.
Finally the JpaRepository add some more functionality that is specific to JPA.
Close, but not the same. They're getting the same element, but the jQuery version is wrapped in a jQuery object.
The equivalent would be this
var contents = $('#contents').get(0);
or this
var contents = $('#contents')[0];
These will pull the element out of the jQuery object.
SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U'
Here is a list of other object types you can search for as well:
Used font-size:0
in parent TD
which has the image.
This can be accomplished in a 'nicer' way using only binding and the GalaSoft MVVM Light library's EventToCommand. In your VM add a command which will be called when the selected item is changed, and initialize the command to perform whatever action is necessary. In this example I used a RelayCommand and will just set the SelectedCluster property.
public class ViewModel
{
public ViewModel()
{
SelectedClusterChanged = new RelayCommand<Cluster>( c => SelectedCluster = c );
}
public RelayCommand<Cluster> SelectedClusterChanged { get; private set; }
public Cluster SelectedCluster { get; private set; }
}
Then add the EventToCommand behavior in your xaml. This is really easy using blend.
<TreeView
x:Name="lstClusters"
ItemsSource="{Binding Path=Model.Clusters}"
ItemTemplate="{StaticResource HoofdCLusterTemplate}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="SelectedItemChanged">
<GalaSoft_MvvmLight_Command:EventToCommand Command="{Binding SelectedClusterChanged}" CommandParameter="{Binding ElementName=lstClusters,Path=SelectedValue}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</TreeView>
Here is an option to read the cookies and turn them into an object of Key, Value pairs for client side, could also use it server side.
Note: If there is a =
in the value, no worries. If there is an =
in the key, trouble in paradise.
More Notes: Some may argue readability so break it down as you like.
I Like Notes: Adding an error handler (try catch) wouldn't hurt.
const iLikeCookies = () => {
return Object.fromEntries(document.cookie.split('; ').map(v => v.split(/=(.+)/)));
}
const main = () => {
// Add Test Cookies
document.cookie = `name=Cookie Monster;expires=false;domain=localhost`
document.cookie = `likesCookies=yes=withARandomEquals;expires=false;domain=localhost`;
// Show the Objects
console.log(document.cookie)
console.log('The Object:', iLikeCookies())
// Get a value from key
console.log(`Username: ${iLikeCookies().name}`)
console.log(`Enjoys Cookies: ${iLikeCookies().likesCookies}`)
}
iLikeCookies()
will split the cookies by ;
(space after ;
):
["name=Cookie Monster", "likesCookies=yes=withARandomEquals"]
Then we map that array and split by first occurrence of =
using regex capturing parens:
[["name", "Cookie Monster"], ["likesCookies", "yes=withARandomEquals"]]
Then use our friend `Object.fromEntries to make this an object of key, val pairs.
Nooice.
You should check the EOF after reading from file.
fscanf_s // read from file
while(condition) // check EOF
{
fscanf_s // read from file
}
This command can explicitly set the base URL for your rewrites. If you wish to start in the root of your domain, you would include the following line before your RewriteRule:
RewriteBase /
If you need pixel level control over canvas you can do using createImageData and putImageData.
HTML:
<canvas id="qrCode" width="200", height="200">
QR Code
</canvas>
And JavaScript:
function setPixel(imageData, pixelData) {
var index = (pixelData.x + pixelData.y * imageData.width) * 4;
imageData.data[index+0] = pixelData.r;
imageData.data[index+1] = pixelData.g;
imageData.data[index+2] = pixelData.b;
imageData.data[index+3] = pixelData.a;
}
element = document.getElementById("qrCode");
c = element.getContext("2d");
pixcelSize = 4;
width = element.width;
height = element.height;
imageData = c.createImageData(width, height);
for (i = 0; i < 1000; i++) {
x = Math.random() * width / pixcelSize | 0; // |0 to Int32
y = Math.random() * height / pixcelSize| 0;
for(j=0;j < pixcelSize; j++){
for(k=0;k < pixcelSize; k++){
setPixel( imageData, {
x: x * pixcelSize + j,
y: y * pixcelSize + k,
r: 0 | 0,
g: 0 | 0,
b: 0 * 256 | 0,
a: 255 // 255 opaque
});
}
}
}
c.putImageData(imageData, 0, 0);
String strLong = Long.toString(longNumber);
Simple and works fine :-)
EDIT : 31/10/2017
The same code/approach will work for Asp.Net Core 2.0 as well. The major difference is, In asp.net core, both web api controllers and Mvc controllers are merged together to single controller model. So your return type might be IActionResult
or one of it's implementation (Ex :OkObjectResult
)
Use
contentType:"application/json"
You need to use JSON.stringify
method to convert it to JSON string when you send it,
And the model binder will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
Result
contentType
property tells the server that we are sending the data in JSON format. Since we sent a JSON data structure,model binding will happen properly.
If you inspect the ajax request's headers, you can see that the Content-Type
value is set as application/json
.
If you do not specify contentType explicitly, It will use the default content type which is application/x-www-form-urlencoded;
Edit on Nov 2015 to address other possible issues raised in comments
Let's say you have a complex view model class as your web api action method parameter like this
public class CreateUserViewModel
{
public int Id {set;get;}
public string Name {set;get;}
public List<TagViewModel> Tags {set;get;}
}
public class TagViewModel
{
public int Id {set;get;}
public string Code {set;get;}
}
and your web api end point is like
public class ProductController : Controller
{
[HttpPost]
public CreateUserViewModel Save([FromBody] CreateUserViewModel m)
{
// I am just returning the posted model as it is.
// You may do other stuff and return different response.
// Ex : missileService.LaunchMissile(m);
return m;
}
}
At the time of this writing, ASP.NET MVC 6 is the latest stable version and in MVC6, Both Web api controllers and MVC controllers are inheriting from Microsoft.AspNet.Mvc.Controller
base class.
To send data to the method from client side, the below code should work fine
//Build an object which matches the structure of our view model class
var model = {
Name: "Shyju",
Id: 123,
Tags: [{ Id: 12, Code: "C" }, { Id: 33, Code: "Swift" }]
};
$.ajax({
type: "POST",
data: JSON.stringify(model),
url: "../product/save",
contentType: "application/json"
}).done(function(res) {
console.log('res', res);
// Do something with the result :)
});
If you do not decorate the web api method parameter with [FromBody]
attribute
[HttpPost]
public CreateUserViewModel Save(CreateUserViewModel m)
{
return m;
}
And send the model(raw javascript object, not in JSON format) without specifying the contentType property value
$.ajax({
type: "POST",
data: model,
url: "../product/save"
}).done(function (res) {
console.log('res', res);
});
Model binding will work for the flat properties on the model, not the properties where the type is complex/another type. In our case, Id
and Name
properties will be properly bound to the parameter m
, But the Tags
property will be an empty list.
The same problem will occur if you are using the short version, $.post
which will use the default Content-Type when sending the request.
$.post("../product/save", model, function (res) {
//res contains the markup returned by the partial view
console.log('res', res);
});
Any of the below three options works for you:
echo[
echo(
echo.
For example:
@echo off
echo There will be a blank line below
echo[
echo Above line is blank
echo(
echo The above line is also blank.
echo.
echo The above line is also blank.
Catch mouse-drag and viewport events (onmouseup, onresize, onscroll).
When a drag ends do a comparison of the dragged item boundary with all "elements of interest" (ie, elements with class "dont_hide" or an array of ids). Do the same with window.onscroll and window.onresize. Mark any elements hidden with a special attribute or classname or simply perform whatever action you want then and there.
The hidden tests are pretty easy. For "totally hidden" you want to know if ALL corners are either inside the dragged-item boundary or outside the viewport. For partially hidden you're looking for a single corner matching the same test.
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
In relative layout you need specify textview height:
android:layout_height="100dp"
Or specify lines attribute:
android:lines="3"
Terminates this process and gives the underlying operating system the specified exit code.
https://msdn.microsoft.com/en-us/library/system.environment.exit%28v=vs.110%29.aspx
[Environment]::Exit(1)
This will allow you to exit with a specific exit code, that can be picked up from the caller.
If the performance is an issue, you can use this command in MS_DOS:
dir /OD >d:\dir.txt
This command generate a dir.txt file in **d:** root the have all files sorted by date. And then read the file from your code. Also, you add other filters by * and ?.
Calendar cal = Calendar.getInstance();
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Today's date is "+dateFormat.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println("Yesterday's date was "+dateFormat.format(cal.getTime()));
Use Calender Api
To implement simple SOAP clients in Java, you can use the SAAJ framework (it is shipped with JSE 1.6 and above):
SOAP with Attachments API for Java (SAAJ) is mainly used for dealing directly with SOAP Request/Response messages which happens behind the scenes in any Web Service API. It allows the developers to directly send and receive soap messages instead of using JAX-WS.
See below a working example (run it!) of a SOAP web service call using SAAJ. It calls this web service.
import javax.xml.soap.*;
public class SOAPClientSAAJ {
// SAAJ - SOAP Client Testing
public static void main(String args[]) {
/*
The example below requests from the Web Service at:
http://www.webservicex.net/uszip.asmx?op=GetInfoByCity
To call other WS, change the parameters below, which are:
- the SOAP Endpoint URL (that is, where the service is responding from)
- the SOAP Action
Also change the contents of the method createSoapEnvelope() in this class. It constructs
the inner part of the SOAP envelope that is actually sent.
*/
String soapEndpointUrl = "http://www.webservicex.net/uszip.asmx";
String soapAction = "http://www.webserviceX.NET/GetInfoByCity";
callSoapWebService(soapEndpointUrl, soapAction);
}
private static void createSoapEnvelope(SOAPMessage soapMessage) throws SOAPException {
SOAPPart soapPart = soapMessage.getSOAPPart();
String myNamespace = "myNamespace";
String myNamespaceURI = "http://www.webserviceX.NET";
// SOAP Envelope
SOAPEnvelope envelope = soapPart.getEnvelope();
envelope.addNamespaceDeclaration(myNamespace, myNamespaceURI);
/*
Constructed SOAP Request Message:
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:myNamespace="http://www.webserviceX.NET">
<SOAP-ENV:Header/>
<SOAP-ENV:Body>
<myNamespace:GetInfoByCity>
<myNamespace:USCity>New York</myNamespace:USCity>
</myNamespace:GetInfoByCity>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
*/
// SOAP Body
SOAPBody soapBody = envelope.getBody();
SOAPElement soapBodyElem = soapBody.addChildElement("GetInfoByCity", myNamespace);
SOAPElement soapBodyElem1 = soapBodyElem.addChildElement("USCity", myNamespace);
soapBodyElem1.addTextNode("New York");
}
private static void callSoapWebService(String soapEndpointUrl, String soapAction) {
try {
// Create SOAP Connection
SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
SOAPConnection soapConnection = soapConnectionFactory.createConnection();
// Send SOAP Message to SOAP Server
SOAPMessage soapResponse = soapConnection.call(createSOAPRequest(soapAction), soapEndpointUrl);
// Print the SOAP Response
System.out.println("Response SOAP Message:");
soapResponse.writeTo(System.out);
System.out.println();
soapConnection.close();
} catch (Exception e) {
System.err.println("\nError occurred while sending SOAP Request to Server!\nMake sure you have the correct endpoint URL and SOAPAction!\n");
e.printStackTrace();
}
}
private static SOAPMessage createSOAPRequest(String soapAction) throws Exception {
MessageFactory messageFactory = MessageFactory.newInstance();
SOAPMessage soapMessage = messageFactory.createMessage();
createSoapEnvelope(soapMessage);
MimeHeaders headers = soapMessage.getMimeHeaders();
headers.addHeader("SOAPAction", soapAction);
soapMessage.saveChanges();
/* Print the request message, just for debugging purposes */
System.out.println("Request SOAP Message:");
soapMessage.writeTo(System.out);
System.out.println("\n");
return soapMessage;
}
}
If you're using .NET 2.0, try XmlReader
and its subclasses XmlTextReader
, and XmlValidatingReader
. They provide a fast, lightweight (memory usage, etc.), forward-only way to parse an XML file.
If you need XPath
capabilities, try the XPathNavigator
. If you need the entire document in memory try XmlDocument
.
When you Abandon()
a Session, you (or rather the user) will get a new SessionId (on the next request).
When you Clear()
a Session, all stored values are removed, but the SessionId stays intact.
Adding the following line of CSS works for Chrome, but not Internet Explorer or Firefox.
text-shadow: #fff 0px 1px 1px;
I use
chartRange = xlWorkSheet.Rows[1];
chartRange.Font.Bold = true;
to turn the first-row-cells-font into bold. And it works, and I am using also Excel 2007.
You can call in VBA directly
ActiveCell.Font.Bold = True
With this code I create a timestamp in the active cell, with bold font and yellow background
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
ActiveCell.Value = Now()
ActiveCell.Font.Bold = True
ActiveCell.Interior.ColorIndex = 6
End Sub
You can use CSS3 transitions or maybe CSS3 animations to slide in an element.
For browser support: http://caniuse.com/
I made two quick examples just to show you how I mean.
CSS transition (on hover)
Relevant Code
.wrapper:hover #slide {
transition: 1s;
left: 0;
}
In this case, Im just transitioning the position from left: -100px;
to 0;
with a 1s. duration. It's also possible to move the element using transform: translate();
CSS animation
#slide {
position: absolute;
left: -100px;
width: 100px;
height: 100px;
background: blue;
-webkit-animation: slide 0.5s forwards;
-webkit-animation-delay: 2s;
animation: slide 0.5s forwards;
animation-delay: 2s;
}
@-webkit-keyframes slide {
100% { left: 0; }
}
@keyframes slide {
100% { left: 0; }
}
Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode
to forwards
, which will persist the end state, keeping the div visible when the animation ends.
Like I said, two quick example to show you how it could be done.
EDIT: For details regarding CSS Animations and Transitions see:
Animations
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations
Transitions
https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions
Hope this helped.
You can also do the following:
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
DROP TABLE #TEMPTABLE
With Apache Commons Library, you can simply use Stringutils.replaceEach:
public static String replaceEach(String text,
String[] searchList,
String[] replacementList)
From the documentation:
Replaces all occurrences of Strings within another String.
A null reference passed to this method is a no-op, or if any "search string" or "string to replace" is null, that replace will be ignored. This will not repeat. For repeating replaces, call the overloaded method.
StringUtils.replaceEach(null, *, *) = null
StringUtils.replaceEach("", *, *) = ""
StringUtils.replaceEach("aba", null, null) = "aba"
StringUtils.replaceEach("aba", new String[0], null) = "aba"
StringUtils.replaceEach("aba", null, new String[0]) = "aba"
StringUtils.replaceEach("aba", new String[]{"a"}, null) = "aba"
StringUtils.replaceEach("aba", new String[]{"a"}, new String[]{""}) = "b"
StringUtils.replaceEach("aba", new String[]{null}, new String[]{"a"}) = "aba"
StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"w", "t"}) = "wcte"
(example of how it does not repeat)
StringUtils.replaceEach("abcde", new String[]{"ab", "d"}, new String[]{"d", "t"}) = "dcte"
As you are trying to add a string of CSS to <head>
with JavaScript?
injecting a string of CSS into a page it is easier to do this with the <link>
element than the <style>
element.
The following adds p { color: green; }
rule to the page.
<link rel="stylesheet" type="text/css" href="data:text/css;charset=UTF-8,p%20%7B%20color%3A%20green%3B%20%7D" />
You can create this in JavaScript simply by URL encoding your string of CSS and adding it the HREF
attribute. Much simpler than all the quirks of <style>
elements or directly accessing stylesheets.
var linkElement = this.document.createElement('link');
linkElement.setAttribute('rel', 'stylesheet');
linkElement.setAttribute('type', 'text/css');
linkElement.setAttribute('href', 'data:text/css;charset=UTF-8,' + encodeURIComponent(myStringOfstyles));
This will work in IE 5.5 upwards
The solution you have marked will work but this solution requires fewer dom operations and only a single element.
IF both POS_History_bim_data_*.zip and POS_History_bim_data_*.zip.trg exists in Y:\ExternalData\RSIDest\ Folder then Delete File Y:\ExternalData\RSIDest\Target_slpos_unzip_done.dat
this question asked in 2009 but i want to share my codes:
Public Function RowSearch(ByVal dttable As DataTable, ByVal searchcolumns As String()) As DataTable
Dim x As Integer
Dim y As Integer
Dim bln As Boolean
Dim dttable2 As New DataTable
For x = 0 To dttable.Columns.Count - 1
dttable2.Columns.Add(dttable.Columns(x).ColumnName)
Next
For x = 0 To dttable.Rows.Count - 1
For y = 0 To searchcolumns.Length - 1
If String.IsNullOrEmpty(searchcolumns(y)) = False Then
If searchcolumns(y) = CStr(dttable.Rows(x)(y + 1) & "") & "" Then
bln = True
Else
bln = False
Exit For
End If
End If
Next
If bln = True Then
dttable2.Rows.Add(dttable.Rows(x).ItemArray)
End If
Next
Return dttable2
End Function
try it works easy
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
card_view:cardBackgroundColor="#fff"
card_view:cardCornerRadius="9dp"
card_view:cardElevation="4dp"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingTop="10dp"
android:paddingBottom="10dp">
Here's a sloppy one-liner that I use from time to time:
var isHTML = RegExp.prototype.test.bind(/(<([^>]+)>)/i);
It will basically return true
for strings containing a <
followed by ANYTHING
followed by >
.
By ANYTHING
, I mean basically anything except an empty string.
It's not great, but it's a one-liner.
Usage
isHTML('Testing'); // false
isHTML('<p>Testing</p>'); // true
isHTML('<img src="hello.jpg">'); // true
isHTML('My < weird > string'); // true (caution!!!)
isHTML('<>'); // false
As you can see it's far from perfect, but might do the job for you in some cases.
Go through http://nodejs.org/api/fs.html
One important thing - you can use sync functions also. (It will work like C program)
Assuming there is a column named business:
SELECT Business, COUNT(*) FROM eventsTable GROUP BY Business
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height"
and turn that into a variable height
using the window[]
command.
If you are using Mysql with Hibernate v3 it's ok to use GenerationType.AUTO
because internally it will use GenerationType.IDENTITY
, which is the most optimal in for MySQL.
However in Hibernate v5, It has changed. GenerationType.AUTO
will use GenerationType.TABLE
which generates to much queries for the insertion.
You can avoid that using GenerationType.IDENTITY
(if MySQL is the only database you are using) or with these notations (if you have multiple databases):
@GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
@GenericGenerator(name = "native", strategy = "native")
Just go to References and add "System.IO.Compression.FileSystem".
Use Pypdf or its successor PyPDF2:
A Pure-Python library built as a PDF toolkit. It is capable of:
* splitting documents page by page,
* merging documents page by page,
(and much more)
Here's a sample program that works with both versions.
#!/usr/bin/env python
import sys
try:
from PyPDF2 import PdfFileReader, PdfFileWriter
except ImportError:
from pyPdf import PdfFileReader, PdfFileWriter
def pdf_cat(input_files, output_stream):
input_streams = []
try:
# First open all the files, then produce the output file, and
# finally close the input files. This is necessary because
# the data isn't read from the input files until the write
# operation. Thanks to
# https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733
for input_file in input_files:
input_streams.append(open(input_file, 'rb'))
writer = PdfFileWriter()
for reader in map(PdfFileReader, input_streams):
for n in range(reader.getNumPages()):
writer.addPage(reader.getPage(n))
writer.write(output_stream)
finally:
for f in input_streams:
f.close()
if __name__ == '__main__':
if sys.platform == "win32":
import os, msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
pdf_cat(sys.argv[1:], sys.stdout)
Of course, Mike's answer doesn't work if you pass the string programmatically. In this case you need to pass a attributed string and change it's style.
NSMutableAttributedString * attrString = [[NSMutableAttributedString alloc] initWithString:@"Your \nregular \nstring"];
NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
[style setLineSpacing:4];
[attrString addAttribute:NSParagraphStyleAttributeName
value:style
range:NSMakeRange(0, attrString.length)];
_label.attributedText = attrString;
I can think of a cheeky way to do it, I don't think this will be the best option but it will work.
Create the header as a separate table then place the other in a div and set a max size, then allow the scroll to come in by using overflow
.
table {_x000D_
width: 500px;_x000D_
}_x000D_
_x000D_
.scroll {_x000D_
max-height: 60px;_x000D_
overflow: auto;_x000D_
}
_x000D_
<table border="1">_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</table>_x000D_
<div class="scroll">_x000D_
<table>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>More Text</td><td>More Text</td><td>More Text</td><td>More Text</td></tr>_x000D_
<tr><td>Text Text</td><td>Text Text</td><td>Text Text</td><td>Text Text</td></tr>_x000D_
<tr><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td><td>Even More Text Text</td></tr>_x000D_
</table>_x000D_
</div>
_x000D_
Click on Project settings which you want to delete-->General project settings-->Expand-->Advanced settings-->Remove project.
Organizing your application using class make it easy to you and others who work with you to debug problems and improve the app easily.
You can easily organize your application like this:
class hello(Tk):
def __init__(self):
super(hello, self).__init__()
self.btn = Button(text = "Click me", command=close)
self.btn.pack()
def close():
self.destroy()
app = hello()
app.mainloop()
If you're getting source in Content Use the following method
try
{
var response = restClient.Execute<List<EmpModel>>(restRequest);
var jsonContent = response.Content;
var data = JsonConvert.DeserializeObject<List<EmpModel>>(jsonContent);
foreach (EmpModel item in data)
{
listPassingData?.Add(item);
}
}
catch (Exception ex)
{
Console.WriteLine($"Data get mathod problem {ex} ");
}
It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"]
.
I reproduced here the text from OpenQA concerning this issue (found here):
HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "
") with a single space. All visible newlines (<br>
,<p>
, and<pre>
formatted new lines) should be preserved.We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "
" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "
" markers in your test case to assertText on a field that contains "
".) You may also put extra newlines and spaces in your Selenese<td>
tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "
foo
". But if you simply write<td>foo </td>
in your Selenese test case, we'll replace your extra spaces with just one space.This problem has a simple workaround. We've defined a variable in Selenese,
${space}
, whose value is a single space. You can use${space}
to insert a space that won't be automatically trimmed, like this:<td>foo${space}${space}${space}</td>
. We've also included a variable${nbsp}
, that you can use to insert a non-breaking space.Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like
//div[text()="hello world"]
but the HTML of the link is really "hello world
", you'll need to insert a real "
" into your Selenese test case to get it to match, like this://div[text()="hello${nbsp}world"]
.
This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List
in an EditorTemplate.
I have a model like this:
public class Foo
{
public string FooName { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string BarName { get; set; }
}
And this is my main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
@Html.EditorFor(m => m.Bars)
And this is my Bar EditorTemplate (Bar.cshtml)
@model List<Bar>
<div class="some-style">
@foreach (var item in Model)
{
<label>@item.BarName</label>
}
</div>
And I got this error:
The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]
The reason for this error is that EditorFor
already iterates the List
for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.
This is how I fixed this problem:
Brought the styles outside of the editor template, and into the main view:
@model Foo
@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })
<div class="some-style">
@Html.EditorFor(m => m.Bars)
</div>
And changed the EditorTemplate (Bar.cshtml) to this:
@model Bar
<label>@Model.BarName</label>
Did you override the run() method? If you overrided __init__
, did you make sure to call the base threading.Thread.__init__()
?
After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?
And finally, are you getting any unhandled exceptions?
Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:
module.directive('myDirectiveContainer', function () {
return {
controller: function ($scope) {
this.scope = $scope;
}
};
});
module.directive('myDirective', function () {
return {
require: '^myDirectiveContainer',
link: function (scope, element, attrs, containerController) {
// use containerController.scope here...
}
};
});
and then
<div my-directive-container="">
<div my-directive="">
</div>
</div>
Maybe not the most graceful solution, but it got the job done.
It is not elegant but possible to do it as one-liner <a>
element
<a href onclick="event.preventDefault(); location+='&like=like'">Like</a>
_x000D_
This happens when your table structure and model class no longer in sync. You need to update the table structure according to the model class or vice versa -- this is when your data is important and must not be deleted. If your data structure has changed and the data isn't important to you, you can use the DropCreateDatabaseIfModelChanges
feature (formerly known as 'RecreateDatabaseIfModelChanges
' feature) by adding the following code in your Global.asax.cs:
Database.SetInitializer<MyDbContext>(new DropCreateDatabaseIfModelChanges<MyDbContext>());
Run your application again.
As the name implies, this will drop your database and recreate according to your latest model class (or classes) -- provided you believe the table structure definitions in your model classes are the most current and latest; otherwise change the property definitions of your model classes instead.
If you are not having a stroke you can use
colorDrawable = resources.getDrawable(R.drawable.x_sd_circle);
colorDrawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
but this will also change stroke color
Can also use groupby() with no need to join and stack().
Use above example data:
import pandas as pd
import numpy as np
df = pd.DataFrame({'ItemQty': {0: 3, 1: 25},
'Seatblocks': {0: '2:218:10:4,6', 1: '1:13:36:1,12 1:13:37:1,13'},
'ItemExt': {0: 60, 1: 300},
'CustomerName': {0: 'McCartney, Paul', 1: 'Lennon, John'},
'CustNum': {0: 32363, 1: 31316},
'Item': {0: 'F04', 1: 'F01'}},
columns=['CustNum','CustomerName','ItemQty','Item','Seatblocks','ItemExt'])
print(df)
CustNum CustomerName ItemQty Item Seatblocks ItemExt
0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60
1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300
#first define a function: given a Series of string, split each element into a new series
def split_series(ser,sep):
return pd.Series(ser.str.cat(sep=sep).split(sep=sep))
#test the function,
split_series(pd.Series(['a b','c']),sep=' ')
0 a
1 b
2 c
dtype: object
df2=(df.groupby(df.columns.drop('Seatblocks').tolist()) #group by all but one column
['Seatblocks'] #select the column to be split
.apply(split_series,sep=' ') # split 'Seatblocks' in each group
.reset_index(drop=True,level=-1).reset_index()) #remove extra index created
print(df2)
CustNum CustomerName ItemQty Item ItemExt Seatblocks
0 31316 Lennon, John 25 F01 300 1:13:36:1,12
1 31316 Lennon, John 25 F01 300 1:13:37:1,13
2 32363 McCartney, Paul 3 F04 60 2:218:10:4,6
In addition to the excellent examples and answers above, you can also do a "find" for two different elements using their classes. For example:
<div class="parent">
<div class="child1">Hello</div>
<div class="child2">World</div>
</div>
<script>
var x = jQuery('.parent').find('.child1, .child2').text();
console.log(x);
</script>
This should output "HelloWorld".
Don't forget the option "-o", which lets you download anywhere you want, although you have to create "archives", "lock" and "partial" first (the command prints what's needed).
apt-get install -d -o=dir::cache=/tmp whateveryouwant
^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.
So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"
Here's a quick reference: http://www.regular-expressions.info/reference.html
If you get this error in PowerShell, it's most likely because you're using Resolve-Path
to resolve a remote path, e.g.
Resolve-Path \\server\share\path
In this case, Resolve-Path
returns an object that, when converted to a string, doesn't return a valid path. It returns PowerShell's internal path:
> [string](Resolve-Path \\server\share\path)
Microsoft.PowerShell.Core\FileSystem::\\server\share\path
The solution is to use the ProviderPath
property on the object returned by Resolve-Path
:
> Resolve-Path \\server\share\path | Select-Object -ExpandProperty PRoviderPath
\\server\share\path
> (Resolve-Path \\server\share\path).ProviderPath
\\server\share\path
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
Since the original question was about the SerializableAttribute, it should be noted that this attribute only applies when using the BinaryFormatter or SoapFormatter.
It is a bit confusing, unless you really pay attention to the details, as to when to use it and what its actual purpose is.
It has NOTHING to do with XML or JSON serialization.
Used with the SerializableAttribute are the ISerializable Interface and SerializationInfo Class. These are also only used with the BinaryFormatter or SoapFormatter.
Unless you intend to serialize your class using Binary or Soap, do not bother marking your class as [Serializable]. XML and JSON serializers are not even aware of its existence.
I think this should point you towards the right direction:
import java.beans.*
for (PropertyDescriptor pd : Introspector.getBeanInfo(Foo.class).getPropertyDescriptors()) {
if (pd.getReadMethod() != null && !"class".equals(pd.getName()))
System.out.println(pd.getReadMethod().invoke(foo));
}
Note that you could create BeanInfo or PropertyDescriptor instances yourself, i.e. without using Introspector. However, Introspector does some caching internally which is normally a Good Thing (tm). If you're happy without a cache, you can even go for
// TODO check for non-existing readMethod
Object value = new PropertyDescriptor("name", Person.class).getReadMethod().invoke(person);
However, there are a lot of libraries that extend and simplify the java.beans API. Commons BeanUtils is a well known example. There, you'd simply do:
Object value = PropertyUtils.getProperty(person, "name");
BeanUtils comes with other handy stuff. i.e. on-the-fly value conversion (object to string, string to object) to simplify setting properties from user input.
I had this error message occur as I had set a Windows Environment Variable to an invalid certificate file.
Check if you have a CURL_CA_BUNDLE
variable by typing SET
at the command prompt.
You can override it for the current session with SET CURL_CA_BUNDLE=
The pip.log contained the following:
Getting page https://pypi.python.org/simple/pip/
Could not fetch URL https://pypi.python.org/simple/pip/: connection error: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib
With C++17 you can use std::filesystem::is_directory
function (https://en.cppreference.com/w/cpp/filesystem/is_directory). It accepts a std::filesystem::path
object which can be constructed with a unicode path.
Here is what I look at everytime I am writing a new crontab entry:
To start editing from terminal -type:
zee$ crontab -e
what you will add to crontab file:
0 22 * * 0 some-user /opt/somescript/to/run.sh
What it means:
[
+ user => 'some-user',
+ minute => ‘0’, <<= on top of the hour.
+ hour => '22', <<= at 10 PM. Military time.
+ monthday => '*', <<= Every day of the month*
+ month => '*', <<= Every month*
+ weekday => ‘0’, <<= Everyday (0 thru 6) = sunday thru saturday
]
Also, check what shell your machine is running and name the the file accordingly OR it wont execute.
Check the shell with either echo $SHELL
or echo $0
It can be "Bourne shell (sh)
, Bourne again shell (bash)
,Korn shell (ksh)
..etc"
Use a QR library like ZXing... I had very good experience with it, QrDroid is much buggier. If you must rely on an external reader, rely on a standard one like Google Goggles!
if its something you wish to switch, fading one out and fading another in the same place, you can place a {position:absolute} attribute on the divs, so both the animations play on top of one another, and you don't have to wait for one animation to be over before starting up the next.
pip install packageName -t pathOfDirectory
or
pip install packageName --target pathOfDirectorty
you can't change the DateTime object, it's immutable. However, you can set it to a new value, for example:
var newDate = oldDate.Date + new TimeSpan(11, 30, 55);
You did two mistakes . I think you misplace FROM and WHERE keywords.
SELECT DISTINCT Description, Date as treatmentDate
FROM doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I --Here you use "." operator to "I" alias
WHERE -- WHERE should be located here.
P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');
You can solve this by increasing the maximum request length and execution time out in your web.config:
-Please Clarify the maximum execution time out grater then 1200
<?xml version="1.0" encoding="utf-8"?> <configuration> <system.web> <httpRuntime maxRequestLength="102400" executionTimeout="1200" /> </system.web> </configuration>
I have created step by step instructions on how to do this as I also was very confused about how to get this working.
How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch
Here are the steps.
To make this easy create a folder c:\Install. This is where we will copy all the required files.
You need to download 7zSD.sfx
7zSD.sfx
in the bin
folder.I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.
Enter something like this:
;!@Install@!UTF-8!
Title="SOFTWARE v1.0.0.0"
BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
RunProgram="setup.exe"
;!@InstallEnd@!
Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.
You should now have a folder "c:\Install" with the following 3 files:
These instructions I found on the web but nowhere did it explain any of the 4 steps above.
In the command window type the following
cd \
cd Install
copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
Look in c:\Install and you will now see you have a MyInstaller.exe
Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.
Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.
copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.
myArray.sample
will return 1 random value.
myArray.shuffle.first
will also return 1 random value.
As the other comments suggest, you are confined to using pointers. But if it helps, here is one technique to avoid facing directly with pointers.
You can do something like the following:
vector<int*> iarray;
int default_item = 0; // for handling out-of-range exception
int& get_item_as_ref(unsigned int idx) {
// handling out-of-range exception
if(idx >= iarray.size())
return default_item;
return reinterpret_cast<int&>(*iarray[idx]);
}
As others said wc -l
is the best solution, but for future reference you can use Perl:
perl -lne 'END { print $. }'
$.
contains line number and END
block will execute at the end of script.
try
with open(f"{os.path.dirname(sys.argv[0])}/data/test.csv", newline='') as f:
I don't blame you for getting frustrated about this. The best way to look at is this. There are potentially three versions of every remote branch:
refs/heads/master
)refs/remotes/...
)refs/remotes/origin/master
)refs/heads/master
)Let's start with git prune
. This removes objects that are no longer being referenced, it does not remove references. In your case, you have a local branch. That means there's a ref named random_branch_I_want_deleted
that refers to some objects that represent the history of that branch. So, by definition, git prune
will not remove random_branch_I_want_deleted
. Really, git prune
is a way to delete data that has accumulated in Git but is not being referenced by anything. In general, it doesn't affect your view of any branches.
git remote prune origin
and git fetch --prune
both operate on references under refs/remotes/...
(I'll refer to these as remote references). It doesn't affect local branches. The git remote
version is useful if you only want to remove remote references under a particular remote. Otherwise, the two do exactly the same thing. So, in short, git remote prune
and git fetch --prune
operate on number 2 above. For example, if you deleted a branch using the git web GUI and don't want it to show up in your local branch list anymore (git branch -r
), then this is the command you should use.
To remove a local branch, you should use git branch -d
(or -D
if it's not merged anywhere). FWIW, there is no git command to automatically remove the local tracking branches if a remote branch disappears.
Ctrl + D
Ctrl + D
(edit) This feature is now built-in in VS2017: Ctrl + E, V duplicates a line if nothing is selected, or duplicates selection. You can assign it to a different key combination, or find it in the menu:
See this reference for more information.
As @cand mentioned, you can just do Ctrl + C ; Ctrl + V.
Ctrl + C will copy the line if nothing is selected.
If you'd like to implement a more complete solution, perhaps to create a simpler keyboard shortcut or you don't want to effect the clipboard, see this guide:
Duplicate line command for Visual Studio
Visual Basic:
Imports System Imports EnvDTE Imports EnvDTE80 Imports System.Diagnostics Public Module DuplicateLastLineModule Sub DuplicateLine() Dim line As String DTE.ActiveDocument.Selection.StartOfLine(0) DTE.ActiveDocument.Selection.EndOfLine(True) line = DTE.ActiveDocument.Selection.Text DTE.ActiveDocument.Selection.EndOfLine() DTE.ActiveDocument.Selection.NewLine() DTE.ActiveDocument.Selection.StartOfLine(0) DTE.ActiveDocument.Selection.Text = line End Sub End Module
To create the macro, just go to the macro explorer ("Tools->Macros->Macro Explorer" or Alt+F8) and copy paste the code in a new module. Now just assign a keyboard shortcut to it:
- go to Tools->Options...
- under Environment, click Keyboard
- in the "Show Commands Containing" textbox, enter "duplicate" (this according to the name you gave the module.)
- you should now see the macro in the list below
- choose "Text Editor" from the "Use new shortcut in" list
- set focus in the "Press shortcut keys" textbox and hit the combination on the keyboard you whish to use for it (Ctrl+Shift+D in my case)
- hit the "Assign" button
- you should now see the shortcut in the "Shortcuts for selected command" textbox
- hit the OK button
And that's it. Enjoy!
As Andrie said, system.time()
works fine. For short function I prefer to put replicate()
in it:
system.time( replicate(10000, myfunction(with,arguments) ) )
Use cell arrays. This has an advantage over 3D arrays in that it does not require a contiguous memory space to store all the matrices. In fact, each matrix can be stored in a different space in memory, which will save you from Out-of-Memory errors if your free memory is fragmented. Here is a sample function to create your matrices in a cell array:
function result = createArrays(nArrays, arraySize)
result = cell(1, nArrays);
for i = 1 : nArrays
result{i} = zeros(arraySize);
end
end
To use it:
myArray = createArrays(requiredNumberOfArrays, [500 800]);
And to access your elements:
myArray{1}(2,3) = 10;
If you can't know the number of matrices in advance, you could simply use MATLAB's dynamic indexing to make the array as large as you need. The performance overhead will be proportional to the size of the cell array, and is not affected by the size of the matrices themselves. For example:
myArray{1} = zeros(500, 800);
if twoRequired, myArray{2} = zeros(500, 800); end
Try git config core.fileMode false
From the git config
man page:
core.fileMode
If false, the executable bit differences between the index and the working copy are ignored; useful on broken filesystems like FAT. See git-update-index(1).
The default is true, except git-clone(1) or git-init(1) will probe and set core.fileMode false if appropriate when the repository is created.
After a bit of time (and more searching), I found this blog entry by Jomo Fisher.
One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:
Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.
[Snip]
The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:
<startup useLegacyV2RuntimeActivationPolicy="true"> <supportedRuntime version="v4.0"/> </startup>
So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy
attribute reverts back to CLR 2.0 loading.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
I created a simple extension that gives you an unsorted Array
as a property of Set
in Swift 4.0.
extension Set {
var array: [Element] {
return Array(self)
}
}
If you want a sorted array, you can either add an additional computed property, or modify the existing one to suit your needs.
To use this, just call
let array = set.array
I know this is an old post, but I just found this piece of gold. This is old (2006), but still works with IE9. I personnally added a bookmark with this.
Just copy paste this in your browser's address bar:
javascript:void(window.open("javascript:document.open(\"text/plain\");document.write(opener.document.body.parentNode.outerHTML)"))
As for firefox, web developper tool bar does the job. I usually use this, but sometimes, some dirty 3rd party asp.net controls generates differents markups based on the user agent...
EDIT
As Bryan pointed in the comment, some browser remove the javascript:
part when copy/pasting in url bar. I just tested and that's the case with IE10.
Replace the comma with a dot.
This will only return 554:
var value = parseFloat("554,20")
This will return 554.20:
var value = parseFloat("554.20")
So in the end, you can simply use:
var fValue = parseFloat(document.getElementById("textfield").value.replace(",","."))
Don't forget that parseInt()
should only be used to parse integers (no floating points). In your case it will only return 554. Additionally, calling parseInt() on a float will not round the number: it will take its floor (closest lower integer).
Extended example to answer Pedro Ferreira's question from the comments:
If the textfield contains thousands separator dots like in 1.234.567,99
those could be eliminated beforehand with another replace
:
var fValue = parseFloat(document.getElementById("textfield").value.replace(/\./g,"").replace(",","."))
1)your id should have sys dba access 2)
select sum(a.value) total_cur, avg(a.value) avg_cur, max(a.value) max_cur,
s.username, s.machine
from v$sesstat a, v$statname b, v$session s
where a.statistic# = b.statistic# and s.sid=a.sid
and b.name = 'opened cursors current'
group by s.username, s.machine
order by 1 desc;
It could be something as simple as setting a text field / label value or adding a subview inside a background thread, which may cause a field's layout to change. Make sure anything you do with the interface only happens in the main thread.
Check this link: https://forums.developer.apple.com/thread/7399
you can save the model in json and weights in a hdf5 file format.
# keras library import for Saving and loading model and weights
from keras.models import model_from_json
from keras.models import load_model
# serialize model to JSON
# the keras model which is trained is defined as 'model' in this example
model_json = model.to_json()
with open("model_num.json", "w") as json_file:
json_file.write(model_json)
# serialize weights to HDF5
model.save_weights("model_num.h5")
files "model_num.h5" and "model_num.json" are created which contain our model and weights
To use the same trained model for further testing you can simply load the hdf5 file and use it for the prediction of different data. here's how to load the model from saved files.
# load json and create model
json_file = open('model_num.json', 'r')
loaded_model_json = json_file.read()
json_file.close()
loaded_model = model_from_json(loaded_model_json)
# load weights into new model
loaded_model.load_weights("model_num.h5")
print("Loaded model from disk")
loaded_model.save('model_num.hdf5')
loaded_model=load_model('model_num.hdf5')
To predict for different data you can use this
loaded_model.predict_classes("your_test_data here")
Cpp-tool ex_diag - easyweight, multiplatform, minimal resource using, simple and flexible at trace.
If your input string doesn't contain forward slashes then you can use basename
and a subshell:
$ basename "$(echo 'maps.google.com' | tr '.' '/')"
This doesn't use sed
or awk
but it also doesn't use cut
either, so I'm not quite sure if it qualifies as an answer to the question as its worded.
This doesn't work well if processing input strings that can contain forward slashes. A workaround for that situation would be to replace forward slash with some other character that you know isn't part of a valid input string. For example, the pipe (|
) character is also not allowed in filenames, so this would work:
$ basename "$(echo 'maps.google.com/some/url/things' | tr '/' '|' | tr '.' '/')" | tr '|' '/'
document.getElementById('mybox').style.display = "block";
There is Array.filter()
:
var numbers = [1, 2, 3, 4, 5];
var filtered = numbers.filter(function(x) { return x > 3; });
// As a JavaScript 1.8 expression closure
filtered = numbers.filter(function(x) x > 3);
Note that Array.filter()
is not standard ECMAScript, and it does not appear in ECMAScript specs older than ES5 (thanks Yi Jiang and jAndy). As such, it may not be supported by other ECMAScript dialects like JScript (on MSIE).
Nov 2020 Update: Array.filter is now supported across all major browsers.
Use theme():
d <- data.frame(x=gl(10, 1, 10, labels=paste("long text label ", letters[1:10])), y=rnorm(10))
ggplot(d, aes(x=x, y=y)) + geom_point() +
theme(text = element_text(size=20))
I came across this looking for a way to format things better in an email to a co-worker. I ended up discovering that if you copy from Visual Studio Code (FREE) it retains the formatting, highlighting and everything else. This editor works with everything and has modules for every programming language I've ever encountered.
Looks beautiful in the email.
Here is bash script that can do it for you. It's modified version of http://snippets.freerobby.com/post/491644841/remove-merged-branches-in-git script. My modification enables it to support different remote locations.
#!/bin/bash
current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching merged branches...\n"
git remote update --prune
remote_branches=$(git branch -r --merged | grep -v '/master$' | grep -v "/$current_branch$")
local_branches=$(git branch --merged | grep -v 'master$' | grep -v "$current_branch$")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
echo "No existing branches have been merged into $current_branch."
else
echo "This will remove the following branches:"
if [ -n "$remote_branches" ]; then
echo "$remote_branches"
fi
if [ -n "$local_branches" ]; then
echo "$local_branches"
fi
read -p "Continue? (y/n): " -n 1 choice
echo
if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
remotes=`echo "$remote_branches" | sed 's/\(.*\)\/\(.*\)/\1/g' | sort -u`
# Remove remote branches
for remote in $remotes
do
branches=`echo "$remote_branches" | grep "$remote/" | sed 's/\(.*\)\/\(.*\)/:\2 /g' | tr -d '\n'`
git push $remote $branches
done
# Remove local branches
git branch -d `git branch --merged | grep -v 'master$' | grep -v "$current_branch$" | sed 's/origin\///g' | tr -d '\n'`
else
echo "No branches removed."
fi
fi
If you care about order, then just use the equals method:
list1.equals(list2)
If you don't care order then use this
Collections.sort(list1);
Collections.sort(list2);
list1.equals(list2)
For greater clarity, I want to add a clear example and running
openFileDialog1.FileName = "Select File";
openFileDialog1.DefaultExt = ".xls";
openFileDialog1.Filter = "Excel documents (.xls)|*.xls";
DialogResult result = openFileDialog1.ShowDialog();
if (result==DialogResult.OK)
{
string filename = openFileDialog1.FileName;
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.Visible = false;
xlApp.DisplayAlerts = false;
xlWorkBook = xlApp.Workbooks.Open(filename, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
var numRows = xlWorkSheet.Range["A1"].Offset[xlWorkSheet.Rows.Count - 1, 0].End[Excel.XlDirection.xlUp].Row;
MessageBox.Show("Number of max row is : "+ numRows.ToString());
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
}
Note that the NSString stringWithContentsOfURL will report a totally different user-agent string than the UIWebView making the same request. So if your server is user-agent aware, and sending back different html depending on who is asking for it, you may not get correct results this way.
Also note that the @"document.body.innerHTML"
mentioned above will only display what is in the body tag. If you use @"document.all[0].innerHTML"
you will get both head and body. Which is still not the complete contents of the UIWebView, since it will not get back the !doctype or html tags, but it is a lot closer.
This is the classroom problem called 'Longest sequence finder'. I have given some simple code that worked for me, also my inputs are lists of a sequence which can also be a string:
def longest_substring(list1,list2):
both=[]
if len(list1)>len(list2):
small=list2
big=list1
else:
small=list1
big=list2
removes=0
stop=0
for i in small:
for j in big:
if i!=j:
removes+=1
if stop==1:
break
elif i==j:
both.append(i)
for q in range(removes+1):
big.pop(0)
stop=1
break
removes=0
return both
You can achieve this with the background-size property, which is now supported by most browsers.
To scale the background image to fit inside the div:
background-size: contain;
To scale the background image to cover the whole div:
background-size: cover;
This can happen if you execute a query while iterating over the results from another query. It is not clear from your example where this happens because the example is not complete.
One thing that can cause this is lazy loading triggered when iterating over the results of some query.
This can be easily solved by allowing MARS in your connection string. Add MultipleActiveResultSets=true
to the provider part of your connection string (where Data Source, Initial Catalog, etc. are specified).
In case anyone landed here in search of "how to specify types of multiple return values?", use Tuple[type_value1, ..., type_valueN]
from typing import Tuple
def f() -> Tuple[dict, str]:
a = {1: 2}
b = "hello"
return a, b
Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.
When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.
An example of a DATE subtraction resulting in a positive integer difference:
select date '2009-08-07' - date '2008-08-08' from dual;
Results in:
DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
364
select dump(date '2009-08-07' - date '2008-08-08') from dual;
DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0
Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.
An example of a DATE subtraction resulting in a negative integer difference:
select date '1000-08-07' - date '2008-08-08' from dual;
Results in:
DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
-368160
select dump(date '1000-08-07' - date '2008-08-08') from dual;
DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0
Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.
An example of a DATE subtraction resulting in a decimal difference:
select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;
TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
.25
The difference between those 2 dates is 0.25 days or 6 hours.
select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
- to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;
DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0
Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.
Hope this helps anyone who was wondering how a DATE subtraction is actually stored.
You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:
SQL> SELECT DUMP(SYSDATE - start_date) from test;
DUMP(SYSDATE-START_DATE)
--------------------------------------
Typ=14 Len=8: 188,10,0,0,223,65,1,0
You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function
For example:
SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;
(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000
SQL> SELECT (SYSDATE - start_date) from test;
(SYSDATE-START_DATE)
--------------------
2748.9515
SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;
NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000
SQL>
Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.
Add the css styling text-align: center
to the control.
Ideally you would do this through a css class assigned to the control, but if you must do it directly, here is an example:
<asp:TextBox ID="myTextBox" runat="server" style="text-align: center"></asp:TextBox>
Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.
You can use an ALTER TABLE Statement to modify "START WITH" of the identity.
ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);
In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password
Update new Change code into Github
->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.
if ('function' === typeof callback) ...
Logic should be something like:
First step: For class MyData implements Comparable interface, override the compareTo method as per the per object requirement.
Second step: When it comes to list comparison (after checking for nulls), 2.1 Check the size of both lists, if equal returns true else return false, continue to object iteration 2.2 If step 2.1 returns true, iterate over elements from both lists and invoke something like,
listA.get(i).compareTo(listB.get(i))
This will be as per the code mentioned in step-1.
I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.
So here are steps.
Try this:
declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%'
You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _
"A picture is worth a thousand words".
I have a simple example here, it's similar to your case.
string s1 = "abc";
string s2 = s1;
s1 = "def";
Console.WriteLine(s2);
// Output: abc
This is what happened:
s1
and s2
variables reference to the same "abc"
string object."abc"
string object do not modify itself (to "def"
), but a new "def"
string object is created instead, and then s1
references to it.s2
still references to "abc"
string object, so that's the output.SEQUENCES like it works on firebird:
-- =======================================================
CREATE TABLE SEQUENCES
(
NM_SEQUENCE VARCHAR(32) NOT NULL UNIQUE,
VR_SEQUENCE BIGINT NOT NULL
);
-- =======================================================
-- Creates a sequence sSeqName and set its initial value.
-- =======================================================
DROP PROCEDURE IF EXISTS CreateSequence;
DELIMITER :)
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )
BEGIN
IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN
INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)
VALUES (sSeqName , iSeqValue );
END IF;
END :)
DELIMITER ;
-- CALL CreateSequence( 'MySequence', 0 );
-- =======================================================================
-- Increments the sequence value of sSeqName by iIncrement and returns it.
-- If iIncrement is zero, returns the current value of sSeqName.
-- =======================================================================
DROP FUNCTION IF EXISTS GetSequenceVal;
DELIMITER :)
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )
RETURNS BIGINT -- iIncrement can be negative
BEGIN
DECLARE iSeqValue BIGINT;
SELECT VR_SEQUENCE FROM SEQUENCES
WHERE ( NM_SEQUENCE = sSeqName )
INTO @iSeqValue;
IF ( iIncrement <> 0 ) THEN
SET @iSeqValue = @iSeqValue + iIncrement;
UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue
WHERE ( NM_SEQUENCE = sSeqName );
END IF;
RETURN @iSeqValue;
END :)
DELIMITER ;
-- SELECT GetSequenceVal('MySequence', 1); -- Adds 1 to MySequence value and returns it.
-- ===================================================================
If you are using React try this custom Image component:
import React, { useRef } from 'react';
import PropTypes from 'prop-types';
import defaultErrorImage from 'assets/images/default-placeholder-image.png';
const Image = ({ src, alt, className, onErrorImage }) => {
const imageEl = useRef(null);
return (
<img
src={src}
alt={alt}
className={className}
onError={() => {
imageEl.current.src = onErrorImage;
}}
ref={imageEl}
/>
);
};
Image.defaultProps = {
onErrorImage: defaultErrorImage,
};
Image.propTypes = {
src: PropTypes.string.isRequired,
alt: PropTypes.string.isRequired,
className: PropTypes.string.isRequired,
onErrorImage: PropTypes.string,
};
export default Image;
For a responsive design it is good to use a container having a relative layout and content (placed in container) having fixed layout as.
CSS Styles:
/*Centering element in a base container*/
.contianer-relative{
position: relative;
}
.content-center-text-absolute{
position: absolute;
text-align: center;
width: 100%;
height: 0%;
margin: auto;
top: 0;
left: 0;
bottom: 0;
right: 0;
z-index: 51;
}
HTML code:
<!-- Have used ionic classes -->
<div class="row">
<div class="col remove-padding contianer-relative"><!-- container with position relative -->
<div class="item item-image clear-border" ><a href="#"><img ng-src="img/engg-manl.png" alt="ENGINEERING MANUAL" title="ENGINEERING MANUAL" ></a></div> <!-- Image intended to work as a background -->
<h4 class="content-center-text-absolute white-text"><strong>ENGINEERING <br> MANUALS</strong></h4><!-- content div with position fixed -->
</div>
<div class="col remove-padding contianer-relative"><!-- container with position relative -->
<div class="item item-image clear-border"><a href="#"><img ng-src="img/contract-directory.png" alt="CONTRACTOR DIRECTORY" title="CONTRACTOR DIRECTORY"></a></div><!-- Image intended to work as a background -->
<h4 class="content-center-text-absolute white-text"><strong>CONTRACTOR <br> DIRECTORY</strong></h4><!-- content div with position fixed -->
</div>
</div>
For IONIC Grid layout, evenly spaced grid elements and the classes used in above HTML, please refer - Grid: Evenly Spaced Columns. Hope it helps you out... :)
Do you mean byte size or string length?
Byte size is measured with strlen()
, whereas string length is queried using mb_strlen()
. You can use substr()
to trim a string to X bytes (note that this will break the string if it has a multi-byte encoding - as pointed out by Darhazer in the comments) and mb_substr()
to trim it to X characters in the encoding of the string.
I got same error but this worked and solved my problem
If report is connected to Analysis server then give required permission to the user (who is accessing reporting server to view the the reports) in your model of analysis server. To do this add user in roles of model or cube and deploy the model to your analysis server.
You could do:
if [[ " ${arr[*]} " == *" d "* ]]; then
echo "arr contains d"
fi
This will give false positives for example if you look for "a b" -- that substring is in the joined string but not as an array element. This dilemma will occur for whatever delimiter you choose.
The safest way is to loop over the array until you find the element:
array_contains () {
local seeking=$1; shift
local in=1
for element; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
arr=(a b c "d e" f g)
array_contains "a b" "${arr[@]}" && echo yes || echo no # no
array_contains "d e" "${arr[@]}" && echo yes || echo no # yes
Here's a "cleaner" version where you just pass the array name, not all its elements
array_contains2 () {
local array="$1[@]"
local seeking=$2
local in=1
for element in "${!array}"; do
if [[ $element == "$seeking" ]]; then
in=0
break
fi
done
return $in
}
array_contains2 arr "a b" && echo yes || echo no # no
array_contains2 arr "d e" && echo yes || echo no # yes
For associative arrays, there's a very tidy way to test if the array contains a given key: The -v
operator
$ declare -A arr=( [foo]=bar [baz]=qux )
$ [[ -v arr[foo] ]] && echo yes || echo no
yes
$ [[ -v arr[bar] ]] && echo yes || echo no
no
See 6.4 Bash Conditional Expressions in the manual.
If you are on mac, Use rvm to install your specific version of ruby. See https://owanateamachree.medium.com/how-to-install-ruby-using-ruby-version-manager-rvm-on-macos-mojave-ab53f6d8d4ec
Make sure you follow all the steps. This worked for me.
Presuming every new branch in your tree is a div, I have implemented this solution with 2 functions:
function fillArray(vector1,vector2){
for (var i = 0; i < vector1.length; i++){
if (vector1[i].id.indexOf('q17_') == 0)
vector2.push(vector1[i]);
if(vector1[i].tagName == 'DIV')
fillArray (document.getElementById(vector1[i].id).children,vector2);
}
}
function selectAllElementsInsideDiv(divId){
var matches = new Array();
var searchEles = document.getElementById(divId).children;
fillArray(searchEles,matches);
return matches;
}
Now presuming your div's id is 'myDiv', all you have to do is create an array element and set its value to the function's return:
var ElementsInsideMyDiv = new Array();
ElementsInsideMyDiv = selectAllElementsInsideDiv('myDiv')
I have tested it and it worked for me. I hope it helps you.
Currently, ExplorerCanvas is the only option to emulate HTML5 canvas for IE6, 7, and 8. You're also right about its performance, which is pretty poor.
I found a particle simulatior that benchmarks the difference between true HTML5 canvas handling in Google Chrome, Safari, and Firefox, vs ExplorerCanvas in IE. The results show that the major browsers that do support the canvas tag run about 20 to 30 times faster than the emulated HTML5 in IE with ExplorerCanvas.
I doubt that anyone will go through the effort of creating an alternative because 1) excanvas.js is about as cleanly coded as it gets and 2) when IE9 is released all of the major browsers will finally support the canvas object. Hopefully, We'll get IE9 within a year
Eric @ www.webkrunk.com
I needed to set an additional option to allow SSO passthrough to our intranet site. I added some code to an example above.
pushd "%APPDATA%\Mozilla\Firefox\Profiles\*.default"
echo user_pref("network.proxy.type", 4);>>prefs.js
echo user_pref("network.automatic-ntlm-auth.trusted-uris","site.domain.com, sites.domain.com");>>prefs.js
popd
I think you are creating a project in the wrong way,I am going to post here in step by step
Step 1: File>>New>>Project>>Web>>Dynamic Web Project
Step 2: Enter Project Name>>Next>>Next>>
Step 3: Check the checkbox for Generate web.xml deployment descriptor
Step 4: Finish
Please follow this way you will get you web.xml file under WEB-INF folder
I had this problem minutes ago. It went away when I added 'extern "C"' to the main() definition.
Oddly, another simple program I wrote yesterday is almost identical, does not have the extern "C", yet compiled without this linker error.
This makes me think the problem is some subtle setting to be found deep in some configuration dialog, and that 'extern "C"' doesn't really solve the underlying problem, but superficially makes things work.
You can enter the following formula in the cell where you want to see the Overdue
or Not due
result:
=IF(ISBLANK(O10),"",IF(O10<TODAY(),"Overdue","Not due"))
This formula first tests if the source cell is blank. If it is, then the result cell will be filled with the empty string. If the source is not blank, then the formula tests if the date in the source cell is before the current day. If it is, then the value is set to Overdue
, otherwise it is set to Not due
.
This means that the folder/file that you are trying to put on svn already exists there. My advice is that before doing anything just right click on the folder/file and click on repo-browser. By doing this you will be able to see all the files/sub-folders etc that are already present on svn. If the required file/folder is not present on the svn then you just delete(after taking backup) the file that you you want to add and then run an update.
.navbar {
background-color: transparent;
background: transparent;
border-color: transparent;
}
.navbar li { color: #000 }
Arr1 becomes an array of 'Variant' by the first statement of your code:
Dim arr1() As Variant
Array of size zero is not empty, as like an empty box exists in real world.
If you define a variable of 'Variant', that will be empty when it is created.
Following code will display "Empty".
Dim a as Variant
If IsEmpty(a) then
MsgBox("Empty")
Else
MsgBox("Not Empty")
End If
I clone entire directory by SPL Directory Iterator.
function recursiveCopy($source, $destination)
{
if (!file_exists($destination)) {
mkdir($destination);
}
$splFileInfoArr = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);
foreach ($splFileInfoArr as $fullPath => $splFileinfo) {
//skip . ..
if (in_array($splFileinfo->getBasename(), [".", ".."])) {
continue;
}
//get relative path of source file or folder
$path = str_replace($source, "", $splFileinfo->getPathname());
if ($splFileinfo->isDir()) {
mkdir($destination . "/" . $path);
} else {
copy($fullPath, $destination . "/" . $path);
}
}
}
#calling the function
recursiveCopy(__DIR__ . "/source", __DIR__ . "/destination");
My problem is that I accidentally set the arguments for Main
static void Main(object value)
thanks to my refactoring tool. Took couple mins to figure out but should help someone along the way.
The better use you can specify the limit of your file size as it is shown in the given lines:
app.use(bodyParser.json({limit: '10mb', extended: true}))
app.use(bodyParser.urlencoded({limit: '10mb', extended: true}))
You can also change the default setting in node-modules body-parser then in the lib folder, there are JSON and text file. Then change limit here. Actually, this condition pass if you don't pass the limit parameter in the given line app.use(bodyParser.json({limit: '10mb', extended: true})).
For %appdata% take a look to
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Using $injector to call service methods in config
I had a similar issue and resolved it by using the $injector service as shown above. I tried injecting the service directly but ended up with a circular dependency on $http. The service displays a modal with the error and I am using ui-bootstrap modal which also has a dependency on $https.
$httpProvider.interceptors.push(function($injector) {
return {
"responseError": function(response) {
console.log("Error Response status: " + response.status);
if (response.status === 0) {
var myService= $injector.get("myService");
myService.showError("An unexpected error occurred. Please refresh the page.")
}
}
}
For me, changing the Start In location (of git-gui at least) did not affect where it looked for .gitconfig. My setup at work mounts U: for our home, but we do not have permission to write in U: directly, only subdirectories which were created for us inside, so this was a deal-breaker for me.
I solved the problem by making a batch script which would override the HOMEDRIVE and HOMEPATH env variables just for that application. Then changed my Start menu shortcut to point to that batch script instead.
find <directory_path> -type f -name "<wildcard-match>"
In the wildcard-match you can provide the string you wish to match e.g. *.c (for all c files)
In rails 4.2 the above methods didn't work.
To Run all the tasks in that file assign the following inside the same file and run rake all
task :all => [:iqmedier, :euroads, :mikkelsen, :orville ] do #This will print all the tasks o/p on the screen
end
I just wanted to post a demo using calc() for setting rows/height, since no one did.
body {_x000D_
/* page default */_x000D_
font-size: 15px;_x000D_
line-height: 1.5;_x000D_
}_x000D_
_x000D_
textarea {_x000D_
/* demo related */_x000D_
width: 300px;_x000D_
margin-bottom: 1em;_x000D_
display: block;_x000D_
_x000D_
/* rows related */_x000D_
font-size: inherit;_x000D_
line-height: inherit;_x000D_
padding: 3px;_x000D_
}_x000D_
_x000D_
textarea.border-box {_x000D_
box-sizing: border-box;_x000D_
}_x000D_
_x000D_
textarea.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows); */_x000D_
height: calc(1em * 1.5 * 5);_x000D_
}_x000D_
_x000D_
textarea.border-box.rows-5 {_x000D_
/* height: calc(font-size * line-height * rows + padding-top + padding-bottom + border-top-width + border-bottom-width); */_x000D_
height: calc(1em * 1.5 * 5 + 3px + 3px + 1px + 1px);_x000D_
}
_x000D_
<p>height is 2 rows by default</p>_x000D_
_x000D_
<textarea>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>height is 5 now</p>_x000D_
_x000D_
<textarea class="rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>_x000D_
_x000D_
<p>border-box height is 5 now</p>_x000D_
_x000D_
<textarea class="border-box rows-5">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
_x000D_
If you use large values for the paddings (e.g. greater than 0.5em), you'll start to see the text that overflows the content(-box) area, and that might lead you to think that the height is not exactly x rows (that you set), but it is. To understand what's going on, you might want to check out The box model and box-sizing pages.
Directly, you can't, and that's a good thing. The browser's alert is there for a reason. This thread should answer your question:
Prevent Back button from showing POST confirmation alert
Two key workarounds suggested were the PRG pattern, and an AJAX submit followed by a scripting relocation.
Note that if your method allows for a GET and not a POST submission method, then that would both solve the problem and better fit with convention. Those solutions are provided on the assumption you want/need to POST data.
Whenever you have a known pattern (i.e. you do not use a variable to build a RegExp), use literal regex notation where you only need to use single backslashes to escape special regex metacharacters:
var re = /I like your Apartment\. Could we schedule a viewing\?/g;
^^ ^^
Whenever you need to build a RegExp dynamically, use RegExp
constructor notation where you MUST double backslashes for them to denote a literal backslash:
var questionmark_block = "\\?"; // A literal ?
var initial_subpattern = "I like your Apartment\\. Could we schedule a viewing"; // Note the dot must also be escaped to match a literal dot
var re = new RegExp(initial_subpattern + questionmark_block, "g");
And if you use the String.raw
string literal you may use \
as is (see an example of using a template string literal where you may put variables into the regex pattern):
const questionmark_block = String.raw`\?`; // A literal ?
const initial_subpattern = "I like your Apartment\\. Could we schedule a viewing";
const re = new RegExp(`${initial_subpattern}${questionmark_block}`, 'g'); // Building pattern from two variables
console.log(re); // => /I like your Apartment\. Could we schedule a viewing\?/g
_x000D_
A must-read: RegExp: Description at MDN.
Also websocket scope is added:
Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the context of a web-aware Spring ApplicationContext.
As the per the content of the documentation, there is also thread scope, that is not registered by default.
These dependencies don't exist in Maven Central (see this).
I had this same issue going from e.g gcc to visual studio for C programming. Make sure your include file is actually in the directory -- not just shown in the VS project tree. For me in other languages copying into a folder in the project tree would indeed move the file in. With Visual Studio 2010, pasting into "Header Files" was NOT putting the .h file there.
Please check your actual directory for the presence of the include file. Putting it into the "header files" folder in project/solution explorer was not enough.
Just in case if you are using Telerik components and you have a reference in your javascript with <%= .... %> then wrap your script tag with a RadScriptBlock.
<telerik:RadScriptBlock ID="radSript1" runat="server">
<script type="text/javascript">
//Your javascript
</script>
</telerik>
Regards Örvar
I added a class to easily implement menu arguments. So you can customize and include in your function like this:
include_once get_template_directory() . DIRECTORY_SEPARATOR . "your-directory" . DIRECTORY_SEPARATOR . "Menu.php";
<?php $menu = (new Menu('your-theme-location'))
->setMenuClass('your-menu')
->setMenuID('your-menu-id')
->setListClass('your-menu-class')
->setLinkClass('your-menu-link anchor') ?>
// Print your menu
<?php $menu->showMenu() ?>
<?php
class Menu
{
private $args = [
'theme_location' => '',
'container' => '',
'menu_id' => '',
'menu_class' => '',
'add_li_class' => '',
'link_class' => ''
];
public function __construct($themeLocation)
{
add_filter('nav_menu_css_class', [$this,'add_additional_class_on_li'], 1, 3);
add_filter( 'nav_menu_link_attributes', [$this,'add_menu_link_class'], 1, 3 );
$this->args['theme_location'] = $themeLocation;
}
public function wrapWithTag($tagName){
$this->args['container'] = $tagName;
return $this;
}
public function setMenuID($id)
{
$this->args['menu_id'] = $id;
return $this;
}
public function setMenuClass($class)
{
$this->args['menu_class'] = $class;
return $this;
}
public function setListClass($class)
{
$this->args['add_li_class'] = $class;
return $this;
}
public function setLinkClass($class)
{
$this->args['link_class'] = $class;
return $this;
}
public function showMenu()
{
return wp_nav_menu($this->args);
}
function add_additional_class_on_li($classes, $item, $args) {
if(isset($args->add_li_class)) {
$classes[] = $args->add_li_class;
}
return $classes;
}
function add_menu_link_class( $atts, $item, $args ) {
if (property_exists($args, 'link_class')) {
$atts['class'] = $args->link_class;
}
return $atts;
}
}
I figured it out myself. I need
select extract(day from sysdate - to_date('2009-10-01', 'yyyy-mm-dd')) from dual
This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.
To clarify, using extern int x;
tells the compiler that an object of type int
called x
exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x
to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x
variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static
keyword.
#ifndef HEADER_H
#define HEADER_H
// any source file that includes this will be able to use "global_x"
extern int global_x;
void print_global_x();
#endif
#include "header.h"
// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;
int main()
{
//set global_x here:
global_x = 5;
print_global_x();
}
#include <iostream>
#include "header.h"
void print_global_x()
{
//print global_x here:
std::cout << global_x << std::endl;
}
Use this to check if a file is locked:
using System.IO;
using System.Runtime.InteropServices;
internal static class Helper
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;
private static bool IsFileLocked(Exception exception)
{
int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}
internal static bool CanReadFile(string filePath)
{
//Try-Catch so we dont crash the program and can check the exception
try {
//The "using" is important because FileStream implements IDisposable and
//"using" will avoid a heap exhaustion situation when too many handles
//are left undisposed.
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
if (fileStream != null) fileStream.Close(); //This line is me being overly cautious, fileStream will never be null unless an exception occurs... and I know the "using" does it but its helpful to be explicit - especially when we encounter errors - at least for me anyway!
}
}
catch (IOException ex) {
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex)) {
// do something, eg File.Copy or present the user with a MsgBox - I do not recommend Killing the process that is locking the file
return false;
}
}
finally
{ }
return true;
}
}
For performance reasons I recommend you read the file content in the same operation. Here are some examples:
public static byte[] ReadFileBytes(string filePath)
{
byte[] buffer = null;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
sum += count; // sum is a buffer offset for next reading
fileStream.Close(); //This is not needed, just me being paranoid and explicitly releasing resources ASAP
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{
}
return buffer;
}
public static string ReadFileTextWithEncoding(string filePath)
{
string fileContents = string.Empty;
byte[] buffer;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
{
sum += count; // sum is a buffer offset for next reading
}
fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP
//Depending on the encoding you wish to use - I'll leave that up to you
fileContents = System.Text.Encoding.Default.GetString(buffer);
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{ }
return fileContents;
}
public static string ReadFileTextNoEncoding(string filePath)
{
string fileContents = string.Empty;
byte[] buffer;
try
{
using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
int length = (int)fileStream.Length; // get file length
buffer = new byte[length]; // create buffer
int count; // actual number of bytes read
int sum = 0; // total number of bytes read
// read until Read method returns 0 (end of the stream has been reached)
while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
{
sum += count; // sum is a buffer offset for next reading
}
fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP
char[] chars = new char[buffer.Length / sizeof(char) + 1];
System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
fileContents = new string(chars);
}
}
catch (IOException ex)
{
//THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
if (IsFileLocked(ex))
{
// do something?
}
}
catch (Exception ex)
{
}
finally
{
}
return fileContents;
}
Try it out yourself:
byte[] output1 = Helper.ReadFileBytes(@"c:\temp\test.txt");
string output2 = Helper.ReadFileTextWithEncoding(@"c:\temp\test.txt");
string output3 = Helper.ReadFileTextNoEncoding(@"c:\temp\test.txt");
You could write a custom validation attribute:
public class CombinedMinLengthAttribute: ValidationAttribute
{
public CombinedMinLengthAttribute(int minLength, params string[] propertyNames)
{
this.PropertyNames = propertyNames;
this.MinLength = minLength;
}
public string[] PropertyNames { get; private set; }
public int MinLength { get; private set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var properties = this.PropertyNames.Select(validationContext.ObjectType.GetProperty);
var values = properties.Select(p => p.GetValue(validationContext.ObjectInstance, null)).OfType<string>();
var totalLength = values.Sum(x => x.Length) + Convert.ToString(value).Length;
if (totalLength < this.MinLength)
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
and then you might have a view model and decorate one of its properties with it:
public class MyViewModel
{
[CombinedMinLength(20, "Bar", "Baz", ErrorMessage = "The combined minimum length of the Foo, Bar and Baz properties should be longer than 20")]
public string Foo { get; set; }
public string Bar { get; set; }
public string Baz { get; set; }
}
select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )
I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.
Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:
select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )
Is it possible (work only online and load only your page or file): https://w3schools.com/xml/xml_http.asp Try my code:
function load_page(){
qr=new XMLHttpRequest();
qr.open('get','YOUR_file_or_page.htm');
qr.send();
qr.onload=function(){YOUR_div_id.innerHTML=qr.responseText}
};load_page();
qr.onreadystatechange instead qr.onload also use.
If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy
i tried to set default time for a picker and it worked:
$('#date2').datetimepicker({
format: 'DD-MM-YYYY 12:00:00'
});
this will save in database as : 2015-03-01 12:00:00
used for smalldatetime
type in sql server
Since people don't tend to read comments, here is an answer that mostly duplicates what I wrote here:
the root cause of the issue is the fact that android system does not call getItem
to obtain fragments that are actually displayed, but instantiateItem
. This method first tries to lookup and reuse a fragment instance for a given tab in FragmentManager
. Only if this lookup fails (which happens only the first time when FragmentManager
is newly created) then getItem
is called. It is for obvious reasons not to recreate fragments (that may be heavy) for example each time a user rotates his device.
To solve this, instead of creating fragments with Fragment.instantiate
in your activity, you should do it with pagerAdapter.instantiateItem
and all these calls should be surrounded by startUpdate/finishUpdate
method calls that start/commit fragment transaction respectively. getItem
should be the place where fragments are really created using their respective constructors.
List<Fragment> fragments = new Vector<Fragment>();
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myLayout);
ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
MyPagerAdapter adapter = new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
((TabLayout) findViewById(R.id.tabs)).setupWithViewPager(viewPager);
adapter.startUpdate(viewPager);
fragments.add(adapter.instantiateItem(viewPager, 0));
fragments.add(adapter.instantiateItem(viewPager, 1));
// and so on if you have more tabs...
adapter.finishUpdate(viewPager);
}
class MyPagerAdapter extends FragmentPagerAdapter {
public MyPagerAdapter(FragmentManager manager) {super(manager);}
@Override public int getCount() {return 2;}
@Override public Fragment getItem(int position) {
if (position == 0) return new Fragment0();
if (position == 1) return new Fragment1();
return null; // or throw some exception
}
@Override public CharSequence getPageTitle(int position) {
if (position == 0) return getString(R.string.tab0);
if (position == 1) return getString(R.string.tab1);
return null; // or throw some exception
}
}
This error might also occur when you have a large project with many modules. Make sure that the app (module) used in you angular file is the same that you use in your template, in this example "thisApp".
app.js
angular
.module('thisApp', [])
.controller('ContactController', ['$scope', function ContactController($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {
$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
};
}]);
index.html
<html>
<body ng-app='thisApp' ng-controller='ContactController>
...
<script type="text/javascript" src="assets/js/angular.js"></script>
<script src="app.js"></script>
</body>
</html>
Contents are shallow copied.
So if the original dict
contains a list
or another dictionary
, modifying one them in the original or its shallow copy will modify them (the list
or the dict
) in the other.
As per your request I have put this in an answer for you.
As Hieu Nguyen suggested in his answer, you can use the ajaxurl javascript variable to reference the admin-ajax.php file. However this variable is not declared on the frontend. It is simple to declare this on the front end, by putting the following in the header.php of your theme.
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
Everything else is described in the documentation linked above. Happy coding!
P.S. Here is an example that should work. (I have not tested)
Front end:
<script type="text/javascript">
jQuery.ajax({
url: ajaxurl,
data: {
action: 'my_action_name'
},
type: 'GET'
});
</script>
Back end:
<?php
function my_ajax_callback_function() {
// Implement ajax function here
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' ); // If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' ); // If called from front end
?>
UPDATE Even though this is an old answer, it seems to keep getting thumbs up from people - which is great! I think this may be of use to some people.
WordPress has a function wp_localize_script. This function takes an array of data as the third parameter, intended to be translations, like the following:
var translation = {
success: "Success!",
failure: "Failure!",
error: "Error!",
...
};
So this simply loads an object into the HTML head tag. This can be utilized in the following way:
Backend:
wp_localize_script( 'FrontEndAjax', 'ajax', array(
'url' => admin_url( 'admin-ajax.php' )
) );
The advantage of this method is that it may be used in both themes AND plugins, as you are not hard-coding the ajax URL variable into the theme.
On the front end, the URL is now accessible via ajax.url
, rather than simply ajaxurl
in the previous examples.
If the code in your question doesn't work, you probably have not implemented equals(Object)
on the Customer
class appropriately.
Presumably there is some key (let us call it customerId
) that uniquely identifies a customer; e.g.
class Customer {
private String customerId;
...
An appropriate definition of equals(Object)
would look like this:
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Customer)) {
return false;
}
Customer other = (Customer) obj;
return this.customerId.equals(other.customerId);
}
For completeness, you should also implement hashCode
so that two Customer
objects that are equal will return the same hash value. A matching hashCode
for the above definition of equals
would be:
public int hashCode() {
return customerId.hashCode();
}
It is also worth noting that this is not an efficient way to remove duplicates if the list is large. (For a list with N customers, you will need to perform N*(N-1)/2
comparisons in the worst case; i.e. when there are no duplicates.) For a more efficient solution you should use something like a HashSet
to do the duplicate checking.
in ie8 you can try
-ms-filter: "progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0')";
filter: progid:DXImageTransform.Microsoft.Shadow(Strength=5, Direction=135, Color='#c0c0c0');
caveat: in ie8 you loose smooth fonts for some reason, they will look ragged
Open $CATALINA_BASE/conf/web.xml
and find this
<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly -->
<!-- created sessions by modifying the value below. -->
<session-config>
<session-timeout>30</session-timeout>
</session-config>
all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.
This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different
Here is an even simpler solution using base graphics and alpha-blending (which does not work on all graphics devices):
set.seed(42)
p1 <- hist(rnorm(500,4)) # centered at 4
p2 <- hist(rnorm(500,6)) # centered at 6
plot( p1, col=rgb(0,0,1,1/4), xlim=c(0,10)) # first histogram
plot( p2, col=rgb(1,0,0,1/4), xlim=c(0,10), add=T) # second
The key is that the colours are semi-transparent.
Edit, more than two years later: As this just got an upvote, I figure I may as well add a visual of what the code produces as alpha-blending is so darn useful:
The @Context
annotation (see answers in this question :What does context annotation do in Spring?) will cause it to be injected for you.
I had to use
@Context
private HttpServletRequest request;
XmlWriterSettings settings = new XmlWriterSettings
{
OmitXmlDeclaration = true
};
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add("", "");
StringBuilder sb = new StringBuilder();
XmlSerializer xs = new XmlSerializer(typeof(BankingDetails));
using (XmlWriter xw = XmlWriter.Create(sb, settings))
{
xs.Serialize(xw, model, ns);
xw.Flush();
return sb.ToString();
}
@GavinSimpson: reorder
is a powerful and effective solution for this:
ggplot(theTable,
aes(x=reorder(Position,Position,
function(x)-length(x)))) +
geom_bar()
write it like this
p {
padding-bottom: 3cm;
}
or
p {
margin-bottom: 3cm;
}
Does this not work (assuming "ROUTERNAME" is the user name the router expects)?
net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"
Alternatively, you can use use a small VBScript:
Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")
l = "Z:"
s = "\\10.0.1.1\DRIVENAME"
u = "ROUTERNAME"
p = "PW"
Network.MapNetworkDrive l, s, False, u, p
I used
#content {
width: 100%;
height: 500px;
background-size: cover;
background-position: center top;
}
which worked really well.
I've just put together what you may be looking for: http://www.graphdracula.net
It's JavaScript with directed graph layouting, SVG and you can even drag the nodes around. Still needs some tweaking, but is totally usable. You create nodes and edges easily with JavaScript code like this:
var g = new Graph();
g.addEdge("strawberry", "cherry");
g.addEdge("cherry", "apple");
g.addEdge("id34", "cherry");
I used the previously mentioned Raphael JS library (the graffle example) plus some code for a force based graph layout algorithm I found on the net (everything open source, MIT license). If you have any remarks or need a certain feature, I may implement it, just ask!
You may want to have a look at other projects, too! Below are two meta-comparisons:
SocialCompare has an extensive list of libraries, and the "Node / edge graph" line will filter for graph visualization ones.
DataVisualization.ch has evaluated many libraries, including node/graph ones. Unfortunately there's no direct link so you'll have to filter for "graph":
Here's a list of similar projects (some have been already mentioned here):
vis.js supports many types of network/edge graphs, plus timelines and 2D/3D charts. Auto-layout, auto-clustering, springy physics engine, mobile-friendly, keyboard navigation, hierarchical layout, animation etc. MIT licensed and developed by a Dutch firm specializing in research on self-organizing networks.
Cytoscape.js - interactive graph analysis and visualization with mobile support, following jQuery conventions. Funded via NIH grants and developed by by @maxkfranz (see his answer below) with help from several universities and other organizations.
The JavaScript InfoVis Toolkit - Jit, an interactive, multi-purpose graph drawing and layout framework. See for example the Hyperbolic Tree. Built by Twitter dataviz architect Nicolas Garcia Belmonte and bought by Sencha in 2010.
D3.js Powerful multi-purpose JS visualization library, the successor of Protovis. See the force-directed graph example, and other graph examples in the gallery.
Plotly's JS visualization library uses D3.js with JS, Python, R, and MATLAB bindings. See a nexworkx example in IPython here, human interaction example here, and JS Embed API.
sigma.js Lightweight but powerful library for drawing graphs
jsPlumb jQuery plug-in for creating interactive connected graphs
Springy - a force-directed graph layout algorithm
Processing.js Javascript port of the Processing library by John Resig
JS Graph It - drag'n'drop boxes connected by straight lines. Minimal auto-layout of the lines.
RaphaelJS's Graffle - interactive graph example of a generic multi-purpose vector drawing library. RaphaelJS can't layout nodes automatically; you'll need another library for that.
JointJS Core - David Durman's MPL-licensed open source diagramming library. It can be used to create either static diagrams or fully interactive diagramming tools and application builders. Works in browsers supporting SVG. Layout algorithms not-included in the core package
mxGraph Previously commercial HTML 5 diagramming library, now available under Apache v2.0. mxGraph is the base library used in draw.io.
GoJS Interactive graph drawing and layout library
yFiles for HTML Commercial graph drawing and layout library
KeyLines Commercial JS network visualization toolkit
ZoomCharts Commercial multi-purpose visualization library
Syncfusion JavaScript Diagram Commercial diagram library for drawing and visualization.
Cytoscape Web Embeddable JS Network viewer (no new features planned; succeeded by Cytoscape.js)
Canviz JS renderer for Graphviz graphs. Abandoned in Sep 2013.
arbor.js Sophisticated graphing with nice physics and eye-candy. Abandoned in May 2012. Several semi-maintained forks exist.
jssvggraph "The simplest possible force directed graph layout algorithm implemented as a Javascript library that uses SVG objects". Abandoned in 2012.
jsdot Client side graph drawing application. Abandoned in 2011.
Protovis Graphical Toolkit for Visualization (JavaScript). Replaced by d3.
Moo Wheel Interactive JS representation for connections and relations (2008)
JSViz 2007-era graph visualization script
dagre Graph layout for JavaScript
Graphviz Sophisticated graph visualization language
Flare Beautiful and powerful Flash based graph drawing
NodeBox Python Graph Visualization
ddlCategory.DataSource = ds;
ddlCategory.DataTextField = "CatName";
ddlCategory.DataValueField = "CatID";
Cách 1:
ddlCategory.Items.Add(new ListItem("--please select--", "-1"));
ddlCategory.AppendDataBoundItems = true;
ddlCategory.SelectedIndex = -1;
ddlCategory.DataBind();
Cách 2:
ddlCategory.Items.Insert(0, new ListItem("-- please select --", "0"));
(Tested OK)
Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:
@Html.ActionLink("Edit", "edit", "markets",
new { id = 1 },
new {@class="ui-btn-right", data_icon="gear"})
becomes:
<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>
POSTMAN : A google chrome extension
Use postman to send message instead of server. Postman settings are as follows :
Request Type: POST
URL: https://android.googleapis.com/gcm/send
Header
Authorization : key=your key //Google API KEY
Content-Type : application/json
JSON (raw) :
{
"registration_ids":["yours"],
"data": {
"Hello" : "World"
}
}
on success you will get
Response :
{
"multicast_id": 6506103988515583000,
"success": 1,
"failure": 0,
"canonical_ids": 0,
"results": [
{
"message_id": "0:1432811719975865%54f79db3f9fd7ecd"
}
]
}
On Windows, you can also use the Win32 File Namespace prefixed with \\?\
to refer to your local directories:
\\?\C:\my_dir
Without any jQuery:
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
console.log(decodeEntities('1 & 2')); // '1 & 2'
_x000D_
This works similarly to the accepted answer, but is safe to use with untrusted user input.
As noted by Mike Samuel, doing this with a <div>
instead of a <textarea>
with untrusted user input is an XSS vulnerability, even if the <div>
is never added to the DOM:
function decodeEntities(encodedString) {_x000D_
var div = document.createElement('div');_x000D_
div.innerHTML = encodedString;_x000D_
return div.textContent;_x000D_
}_x000D_
_x000D_
// Shows an alert_x000D_
decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">')
_x000D_
However, this attack is not possible against a <textarea>
because there are no HTML elements that are permitted content of a <textarea>
. Consequently, any HTML tags still present in the 'encoded' string will be automatically entity-encoded by the browser.
function decodeEntities(encodedString) {_x000D_
var textArea = document.createElement('textarea');_x000D_
textArea.innerHTML = encodedString;_x000D_
return textArea.value;_x000D_
}_x000D_
_x000D_
// Safe, and returns the correct answer_x000D_
console.log(decodeEntities('<img src="nonexistent_image" onerror="alert(1337)">'))
_x000D_
Warning: Doing this using jQuery's
.html()
and.val()
methods instead of using.innerHTML
and.value
is also insecure* for some versions of jQuery, even when using atextarea
. This is because older versions of jQuery would deliberately and explicitly evaluate scripts contained in the string passed to.html()
. Hence code like this shows an alert in jQuery 1.8:
//<!-- CDATA_x000D_
// Shows alert_x000D_
$("<textarea>")_x000D_
.html("<script>alert(1337);</script>")_x000D_
.text();_x000D_
_x000D_
//-->
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
_x000D_
* Thanks to Eru Penkman for catching this vulnerability.
A UIImageView
is derived from a UIView
which is derived from UIResponder
so it's ready to handle touch events. You'll want to provide the touchesBegan
, touchesMoved
, and touchesEnded
methods and they'll get called if the user taps the image. If all you want is a tap event, it's easier to just use a custom button with the image set as the button image. But if you want finer-grain control over taps, moves, etc. this is the way to go.
You'll also want to look at a few more things:
Override canBecomeFirstResponder
and return YES to indicate that the view can become the focus of touch events (the default is NO).
Set the userInteractionEnabled
property to YES. The default for UIViews
is YES, but for UIImageViews
is NO so you have to explicitly turn it on.
If you want to respond to multi-touch events (i.e. pinch, zoom, etc) you'll want to set multipleTouchEnabled
to YES.
You may consider FluentFTP, previously known as System.Net.FtpClient.
It is released under The MIT License and available on NuGet (FluentFTP).
You can compile your code as Objective-C++ - the simplest way is to rename your .cpp as .mm. It will then compile properly if you include EAGLView.h
(you were getting so many errors because the C++ compiler didn't understand any of the Objective-C specific keywords), and you can (for the most part) mix Objective-C and C++ however you like.
Also, the best practice of moving your <script></script>
to the bottom of the html file fixes this too.
It could be due to below reasons: -
Either you dont have INTERNET permission in manifest file. If so then please use this statement <uses-permission android:name="android.permission.INTERNET" />
Or you are connected to a network but your internet connection is not working. Like you are connected to a Wi-Fi but it doesnt have internet connection or Mobile data on your phone is ON but you dont have data connectivity on your phone.
Point# 2 is interesting and its not assumption, I have tested the same at my end.
Hope this will help you
Summved
You should be able to continue the sequences directly in your existing -f
specification.
To skip both 5 and 7, try:
cut -d, -f-4,6-6,8-
As you're skipping a single sequential column, this can also be written as:
cut -d, -f-4,6,8-
To keep it going, if you wanted to skip 5, 7, and 11, you would use:
cut -d, -f-4,6-6,8-10,12-
To put it into a more-clear perspective, it is easier to visualize when you use starting/ending columns which go on the beginning/end of the sequence list, respectively. For instance, the following will print columns 2 through 20, skipping columns 5 and 11:
cut -d, -f2-4,6-10,12-20
So, this will print "2 through 4", skip 5, "6 through 10", skip 11, and then "12 through 20".
Although this is an old post, I thought that a simple function can make the code more readable and keeps with jQuery chaining code-style:
String.prototype.toNum = function(){
return parseInt(this, 10);
}
can be used with jQuery:
var padding_top = $('#some_div').css('padding-top'); //string: "10px"
var padding_top = $('#some_div').css('padding-top').toNum(); //number: 10`
or with any String
object:
"123".toNum(); //123 (number)`
You have to update it in your Credential Manager.
Go to Control Panel > User Accounts > Credential Manager > Windows Credentials. You will see Git credentials in the list (e.g. git:https://). Click on it, update the password, and execute git pull/push command from your Git bash and it won't throw any more error messages.
To make it easier add a custom function and call it when ever you want that changing the value also trigger change
$.fn.valAndTrigger = function (element) {
return $(this).val(element).trigger('change');
}
and
$("#sample").valAndTirgger("NewValue");
Or you can override the val function to always call the change when the val is called
(function ($) {
var originalVal = $.fn.val;
$.fn.val = function (value) {
this.trigger("change");
return originalVal.call(this, value);
};
})(jQuery);
Sample at http://jsfiddle.net/r60bfkub/
Use Lambda to find the index in the List and use this index to replace the list item.
List<string> listOfStrings = new List<string> {"abc", "123", "ghi"};
listOfStrings[listOfStrings.FindIndex(ind=>ind.Equals("123"))] = "def";
From MSDN
@@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that they return the last value inserted into the IDENTITY column of a table.
@@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in any table in the current session. However, SCOPE_IDENTITY returns the value only within the current scope; @@IDENTITY is not limited to a specific scope.
IDENT_CURRENT is not limited by scope and session; it is limited to a specified table. IDENT_CURRENT returns the identity value generated for a specific table in any session and any scope. For more information, see IDENT_CURRENT.
From a posting by Matz:
(1) ++ and -- are NOT reserved operator in Ruby.
(2) C's increment/decrement operators are in fact hidden assignment. They affect variables, not objects. You cannot accomplish assignment via method. Ruby uses +=/-= operator instead.
(3) self cannot be a target of assignment. In addition, altering the value of integer 1 might cause severe confusion throughout the program.
matz.
Run apt-get install build-essential
on your system.
This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.
See this page for more info.
try this :
@Html.DropDownList("Sortby", new SelectListItem[] { new SelectListItem()
{ Text = "Newest to Oldest", Value = "0" }, new SelectListItem()
{ Text = "Oldest to Newest", Value = "1" }},
new { onchange = "document.location.href = '/ControllerName/ActionName?id=' + this.options[this.selectedIndex].value;" })