Do not put a space after the Driver
keyword in the connection string.
This fails on Windows ...
conn_str = (
r'DRIVER = {SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
... but this works:
conn_str = (
r'DRIVER={SQL Server};'
r'SERVER=(local)\SQLEXPRESS;'
r'DATABASE=myDb;'
r'Trusted_Connection=yes;'
)
cnxn = pyodbc.connect(conn_str)
Previously, you configured the seed data in the Configure method in Startup.cs. It is now recommended that you use the Configure method only to set up the request pipeline. Application startup code belongs in the Main method.
The refactored Main method. Add the following references to the Program.cs:
using Microsoft.Extensions.DependencyInjection;
using MyProject.MyDbContextFolder;
public static void Main(string[] args)_x000D_
{_x000D_
var host = BuildWebHost(args);_x000D_
_x000D_
using (var scope = host.Services.CreateScope())_x000D_
{_x000D_
var services = scope.ServiceProvider;_x000D_
try_x000D_
{_x000D_
var context = services.GetRequiredService<MyDbConext>();_x000D_
DbInitializer.Initialize(context);_x000D_
}_x000D_
catch (Exception ex)_x000D_
{_x000D_
var logger = services.GetRequiredService<ILogger<Program>>();_x000D_
logger.LogError(ex, "An error occurred while seeding the database.");_x000D_
}_x000D_
}_x000D_
_x000D_
host.Run();_x000D_
}
_x000D_
I've been struggling with this for 3 days now while attempting to connect to a local API running Laravel valet. I finally figured it out. In my case I had to drag and drop over the LaravelValetCASelfSigned.pem file from ~/.config/valet/CA/LaravelValetCASelfSigned.pem
After verifying the installing within the simulator I had to go to Settings > About > Certificate Trust Settings > and Enable the Laravel Valet VA Self Signed CN
Finally working!!!
Yet another reason may be that your entity class has several properties named somhow /.*id/i
- so ending with ID case insensitive AND elementary type AND there is no [Key]
attribute.
EF will namely try to figure out the PK by itself by looking for elementary typed properties ending in ID.
See my case:
public class MyTest, IMustHaveTenant
{
public long Id { get; set; }
public int TenantId { get; set; }
[MaxLength(32)]
public virtual string Signum{ get; set; }
public virtual string ID { get; set; }
public virtual string ID_Other { get; set; }
}
don't ask - lecacy code. The Id
was even inherited, so I could not use [Key]
(just simplifying the code here)
But here EF is totally confused.
What helped was using modelbuilder this in DBContext class.
modelBuilder.Entity<MyTest>(f =>
{
f.HasKey(e => e.Id);
f.HasIndex(e => new { e.TenantId });
f.HasIndex(e => new { e.TenantId, e.ID_Other });
});
the index on PK is implicit.
This worked for me and also worked with bootstrap tables
<style>
.table td, .table th {
font-size: 10px;
}
</style>
In my case I was trying to do dependency injection for an object which required constructor arguments. In this case, during Startup I just provided the arguments from the configuration file, for example:
var config = Configuration.GetSection("subservice").Get<SubServiceConfig>();
services.AddScoped<ISubService>(provider => new SubService(config.value1, config.value2));
this.form.disable()
this.form.enable()
For one formcontrol makes disable
this.form.get('first').disable()
this.form.get('first').enable()
Or initial set method.
first: new FormControl({disabled: true}, Validators.required)
If you have OS(64bit) and SSMS(64bit) and already install the AccessDatabaseEngine(64bit) and you still received an error, try this following solutions:
1: direct opening the sql server import and export wizard.
if you able to connect using direct sql server import and export wizard, then importing from SSMS is the issue, it's like activating 32bit if you import data from SSMS.
Instead of installing AccessDatabaseEngine(64bit) , try to use the AccessDatabaseEngine(32bit) , upon installation, windows will stop you for continuing the installation if you already have another app installed , if so , then use the following steps. This is from the MICROSOFT. The Quiet Installation.
If Office 365 is already installed, side by side detection will prevent the installation from proceeding. Instead perform a /quiet install of these components from command line. To do so, download the desired AccessDatabaseEngine.exe or AccessDatabaeEngine_x64.exe to your PC, open an administrative command prompt, and provide the installation path and switch Ex: C:\Files\AccessDatabaseEngine.exe /quiet
or check in the Addition Information content from the link below,
https://www.microsoft.com/en-us/download/details.aspx?id=54920
C++ programs are translated to assembly programs during the generation of machine code from the source code. It would be virtually wrong to say assembly is slower than C++. Moreover, the binary code generated differs from compiler to compiler. So a smart C++ compiler may produce binary code more optimal and efficient than a dumb assembler's code.
However I believe your profiling methodology has certain flaws. The following are general guidelines for profiling:
The posted answer is fine but didn't directly answer the same question I had about reading in a connection string. Through much searching I found a slightly simpler way of doing this.
In Startup.cs
public void ConfigureServices(IServiceCollection services)
{
...
// Add the whole configuration object here.
services.AddSingleton<IConfiguration>(Configuration);
}
In your controller add a field for the configuration and a parameter for it on a constructor
private readonly IConfiguration configuration;
public HomeController(IConfiguration config)
{
configuration = config;
}
Now later in your view code you can access it like:
connectionString = configuration.GetConnectionString("DefaultConnection");
You have two options here, 1. Use for
instead for foreach
for iteration.But in your case the collection is IEnumerable and the upper limit of the collection is unknown so foreach will be the best option. so i prefer to use another integer variable to hold the iteration count: here is the code for that:
int i = 0; // for index
foreach (var row in list)
{
bool IsChecked;// assign value to this variable
if (IsChecked)
{
// use i value here
}
i++; // will increment i in each iteration
}
There are various ways to achieve this. Here are three.
Map<String, String> map = new HashMap<String, String>();
map.put("key1", "value1");
map.put("key2", "value2");
map.put("key3", "value3");
System.out.println("using entrySet and toString");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry);
}
System.out.println();
System.out.println("using entrySet and manual string creation");
for (Entry<String, String> entry : map.entrySet()) {
System.out.println(entry.getKey() + "=" + entry.getValue());
}
System.out.println();
System.out.println("using keySet");
for (String key : map.keySet()) {
System.out.println(key + "=" + map.get(key));
}
System.out.println();
using entrySet and toString
key1=value1
key2=value2
key3=value3
using entrySet and manual string creation
key1=value1
key2=value2
key3=value3
using keySet
key1=value1
key2=value2
key3=value3
In my case, I stopped my docker hive container and run it again and finally, it worked. Hope it will be useful for someone.
Note: This might be caused because there might be an instance running in the background so stopping the container will stop all background instances.
I had to do 2 things: Do what Joseph Wu said and change the authentication to be SQL and Windows. But I also had to go to Server Properties > Advanced and change "Enable Contained Databases" to True.
I got the same error but it was due to me not creating a default constructor. If you haven't already tried that, create the default constructor like this:
public TestClass() {
}
To check if LocalDb is installed or not:
cmd
and type in sqllocaldb i
this should give you the installed sqllocaldb instances if found.(localdb)\V11.0
using windows authentication.If an error is raised Cannot connect to (localdb)\V11.0.
change the instance name to (localdb)\MSSQLLocalDB
and try again to connect, if you still get the same error.
Follow these steps to install LocalDb:
Start Menu
and type in search sqlLocalDb
.sqlLocalDb.msi
and click it.after finishing the installation re-run SSMS
and try connecting to either of the instances (localdb)\V11.0
or (localdb)\MSSQLLocalDB
, one of it should work depending on what Visual Studio version you have.
You can also verify that localdb
is installed using Visual Studio by simply creating new sql file and go to the connect icon on the top header of the file which by default lists all the servers you can connect to including localdb
if installed.
In addition to the above mentioned ways of finding if localdb is installed, you can also use the MS windows power shell
or windows command processor CMD
or even NuGet package manager console
on your server machine and run these commands sqllocaldb i
and sqllocaldb v
that will show you the localdb name if it is installed and the MSSQL server version installed and running on your machine.
In my case, the problem was setting up DNS on the wifi. I removed the settings, and left them empty, and worked.
The URI to open a specific channel in Slack app is:
slack://channel?id=<CHANNEL-ID>&team=<TEAM-ID>
You will probably need these resources of the Slack API to get IDs of your team and channel:
Here's the full documentation from Slack
Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:
SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc,
pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
ON pe.grantee_principal_id = pr.principal_id;
Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.
As above the question was originally about MySQL
Use REGEXP
, not LIKE
:
SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')
make sure that you have specified user in Security-> Logins, if no - add it and try again.
This is for my reference, as I encountered a variety of SQL error messages while trying to connect with provider. Other answers prescribe "try this, then this, then this". I appreciate the other answers, but I like to pair specific solutions with specific problems
Error
...provider did not give information...Cannot initialize data source object...
Error Numbers
7399, 7303
Error Detail
Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error.
The provider did not give any information about the error.
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object
of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
Solution
File was open. Close it.
Credit
Error
Access denied...Cannot get the column information...
Error Numbers
7399, 7350
Error Detail
Msg 7399, Level 16, State 1, Line 2 The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" reported an error.
Access denied.
Msg 7350, Level 16, State 2, Line 2 Cannot get the column information
from OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
Solution
Give access
Credit
Error
No value given for one or more required parameters....Cannot execute the query ...
Error Numbers
???, 7320
Error Detail
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "No value given for one or more required parameters.".
Msg 7320, Level 16, State 2, Line 2
Cannot execute the query "select [Col A], [Col A] FROM $Sheet" against OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
Solution
Column names might be wrong. Do [Col A]
and [Col B]
actually exist in your spreadsheet?
Error
"Unspecified error"...Cannot initialize data source object...
Error Numbers
???, 7303
Error Detail
OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "Unspecified error".
Msg 7303, Level 16, State 1, Line 2 Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)".
Solution
Run SSMS as admin. See this question.
Other References
Other answers which suggest modifying properties. Not sure how modifying these two properties (checking them or unchecking them) would help.
In Windows 8 PC with Laragon 3.4.0 180809, I faced the same issue. It happened in my case because I updated Laragon and it added a new version of PHP. So in laragon/bin/php/
I actually had two directories:
php-7.1.20-Win32-VC14-x64
php-7.1.7-Win32-VC14-x64
I added 7.1.20
into my PATH
variable. But in my Command Console, running php --ini
was showing that the path actually was fetching from the older one: php-7.1.7-Win32-VC14-x64
. So I deleted the old one (for safety, I put it in Recycle Bin). But Laragon failed to start after that.
So, in laragaon/etc/apache2/mod_php.conf
, I changed the path to the latest PHP version. Then restarted Laragon and the issue is resolved.
downloaded Sql server management 2008 r2 and got it installed. Its getting installed but when I try to connect it via .\SQLEXPRESS it shows error. DO I need to install any SQL service on my system?
You installed management studio which is just a management interface to SQL Server. If you didn't (which is what it seems like) already have SQL Server installed, you'll need to install it in order to have it on your system and use it.
http://www.microsoft.com/en-us/download/details.aspx?id=1695
also this works too
SELECT replace(replace(replace(convert(varchar, getdate(), 120),':',''),'-',''),' ','')
I'd like to share a pattern that I've been using to solve these kinds of problems. It works rather well I think. Of course, it only works if you have control over what calls the constructor. Example below
public class MyClass
{
public static async Task<MyClass> Create()
{
var myClass = new MyClass();
await myClass.Initialize();
return myClass;
}
private MyClass()
{
}
private async Task Initialize()
{
await Task.Delay(1000); // Do whatever asynchronous work you need to do
}
}
Basicly what we do is we make the constructor private and make our own public static async method that is responsible for creating an instance of MyClass. By making the constructor private and keeping the static method within the same class we have made sure that noone could "accidently" create an instance of this class without calling the proper initialization methods. All the logic around the creation of the object is still contained within the class (just within a static method).
var myClass1 = new MyClass() // Cannot be done, the constructor is private
var myClass2 = MyClass.Create() // Returns a Task that promises an instance of MyClass once it's finished
var myClass3 = await MyClass.Create() // asynchronously creates and initializes an instance of MyClass
Implemented on the current scenario it would look something like:
public partial class Page2 : PhoneApplicationPage
{
public static async Task<Page2> Create()
{
var page = new Page2();
await page.getWritings();
return page;
}
List<Writing> writings;
private Page2()
{
InitializeComponent();
}
private async Task getWritings()
{
string jsonData = await JsonDataManager.GetJsonAsync("1");
JObject obj = JObject.Parse(jsonData);
JArray array = (JArray)obj["posts"];
for (int i = 0; i < array.Count; i++)
{
Writing writing = new Writing();
writing.content = JsonDataManager.JsonParse(array, i, "content");
writing.date = JsonDataManager.JsonParse(array, i, "date");
writing.image = JsonDataManager.JsonParse(array, i, "url");
writing.summary = JsonDataManager.JsonParse(array, i, "excerpt");
writing.title = JsonDataManager.JsonParse(array, i, "title");
writings.Add(writing);
}
myLongList.ItemsSource = writings;
}
}
And instead of doing
var page = new Page2();
You would be doing
var page = await Page2.Create();
taking original db to offline worked for me
I arranged a little. This works great.
@SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MM yyyy");
Date date = new Date();
String dateOfDay = simpleDateFormat.format(date);
String timeofday = android.text.format.DateFormat.format("HH:mm:ss", new Date().getTime()).toString();
@SuppressLint("SimpleDateFormat") SimpleDateFormat dateFormat = new SimpleDateFormat("dd MM yyyy hh:mm:ss");
try {
Date date1 = dateFormat.parse(06 09 2018 + " " + 10:12:56);
Date date2 = dateFormat.parse(dateOfDay + " " + timeofday);
printDifference(date1, date2);
} catch (ParseException e) {
e.printStackTrace();
}
@SuppressLint("SetTextI18n")
private void printDifference(Date startDate, Date endDate) {
//milliseconds
long different = endDate.getTime() - startDate.getTime();
long secondsInMilli = 1000;
long minutesInMilli = secondsInMilli * 60;
long hoursInMilli = minutesInMilli * 60;
long daysInMilli = hoursInMilli * 24;
long elapsedDays = different / daysInMilli;
different = different % daysInMilli;
long elapsedHours = different / hoursInMilli;
different = different % hoursInMilli;
long elapsedMinutes = different / minutesInMilli;
different = different % minutesInMilli;
long elapsedSeconds = different / secondsInMilli;
Toast.makeText(context, elapsedDays + " " + elapsedHours + " " + elapsedMinutes + " " + elapsedSeconds, Toast.LENGTH_SHORT).show();
}
internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
return ConvertedUnixTime.ToString(ConvertFormat);
}
int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;
Usage:
UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172
In cs file:
private DataTable _dataTable;
public DataTable DataTable
{
get { return _dataTable; }
set { _dataTable = value; }
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
this._dataTable = new DataTable("table");
this._dataTable.Columns.Add("col0");
this._dataTable.Columns.Add("col1");
this._dataTable.Columns.Add("col2");
this._dataTable.Rows.Add("data00", "data01", "data02");
this._dataTable.Rows.Add("data10", "data11", "data22");
this._dataTable.Rows.Add("data20", "data21", "data22");
this.grid1.DataContext = this;
}
In Xaml file:
<DataGrid x:Name="grid1"
Margin="10"
AutoGenerateColumns="True"
ItemsSource="{Binding Path=DataTable, Mode=TwoWay}" />
A simple example in shell script
#!/bin/bash
current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;
With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S
This question comes in top of Google search when you find "golang current time format" so, for all the people that want to use another format, remember that you can always call to:
t := time.Now()
t.Year()
t.Month()
t.Day()
t.Hour()
t.Minute()
t.Second()
For example, to get current date time as "YYYY-MM-DDTHH:MM:SS" (for example 2019-01-22T12:40:55) you can use these methods with fmt.Sprintf:
t := time.Now()
formatted := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
As always, remember that docs are the best source of learning: https://golang.org/pkg/time/
<!-- xaml code-->
<Grid>
<ComboBox Name="cmbData" SelectedItem="{Binding SelectedstudentInfo, Mode=OneWayToSource}" HorizontalAlignment="Left" Margin="225,150,0,0" VerticalAlignment="Top" Width="120" DisplayMemberPath="name" SelectedValuePath="id" SelectedIndex="0" />
<Button VerticalAlignment="Center" Margin="0,0,150,0" Height="40" Width="70" Click="Button_Click">OK</Button>
</Grid>
//student Class
public class Student
{
public int Id { set; get; }
public string name { set; get; }
}
//set 2 properties in MainWindow.xaml.cs Class
public ObservableCollection<Student> studentInfo { set; get; }
public Student SelectedstudentInfo { set; get; }
//MainWindow.xaml.cs Constructor
public MainWindow()
{
InitializeComponent();
bindCombo();
this.DataContext = this;
cmbData.ItemsSource = studentInfo;
}
//method to bind cobobox or you can fetch data from database in MainWindow.xaml.cs
public void bindCombo()
{
ObservableCollection<Student> studentList = new ObservableCollection<Student>();
studentList.Add(new Student { Id=0 ,name="==Select=="});
studentList.Add(new Student { Id = 1, name = "zoyeb" });
studentList.Add(new Student { Id = 2, name = "siddiq" });
studentList.Add(new Student { Id = 3, name = "James" });
studentInfo=studentList;
}
//button click to get selected student MainWindow.xaml.cs
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student = SelectedstudentInfo;
if(student.Id ==0)
{
MessageBox.Show("select name from dropdown");
}
else
{
MessageBox.Show("Name :"+student.name + "Id :"+student.Id);
}
}
The main thread here seems to be a corrupted user account profile for the account that is used to start the DB engine. This is the account that was specified for the "SQL Server Database" engine during installation. In the setup event log, it's also indicated by the following entry:
SQLSVCACCOUNT: NT AUTHORITY\SYSTEM
According to the link provided by @royki:
The root cause of this issue, in most cases, is that the profile of the user being used for the service account (in my case it was local system) is corrupted.
This would explain why other respondents had success after changing to different accounts:
To fix the user profile that's causing the error, follow the steps listed KB947215.
The main steps from KB947215 are summarized as follows:-
regedit
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList
Navigate to the SID for the corrupted profile
To find the SID, click on each SID GUID, review the value for the ProfileImagePath
value, and see if it's the correct account. For system accounts, there's a different way to know the SID for the account that failed:
The main system account SIDs of interest are:
SID Name Also Known As
S-1-5-18 Local System NT AUTHORITY\SYSTEM
S-1-5-19 LocalService NT AUTHORITY\LOCAL SERVICE
S-1-5-20 NetworkService NT AUTHORITY\NETWORK SERVICE
For information on additional SIDs, see Well-known security identifiers in Windows operating systems.
RefCount
and State
to be 0
.Clearly HttpContext.Current
is not null
only if you access it in a thread that handles incoming requests. That's why it works "when i use this code in another class of a page".
It won't work in the scheduling related class because relevant code is not executed on a valid thread, but a background thread, which has no HTTP context associated with.
Overall, don't use Application["Setting"]
to store global stuffs, as they are not global as you discovered.
If you need to pass certain information down to business logic layer, pass as arguments to the related methods. Don't let your business logic layer access things like HttpContext
or Application["Settings"]
, as that violates the principles of isolation and decoupling.
Update:
Due to the introduction of async/await
it is more often that such issues happen, so you might consider the following tip,
In general, you should only call HttpContext.Current
in only a few scenarios (within an HTTP module for example). In all other cases, you should use
Page.Context
https://docs.microsoft.com/en-us/dotnet/api/system.web.ui.page.context?view=netframework-4.7.2 Controller.HttpContext
https://docs.microsoft.com/en-us/dotnet/api/system.web.mvc.controller.httpcontext?view=aspnet-mvc-5.2instead of HttpContext.Current
.
Configuration that worked for me:
In settings, only 2 checkboxes marked:
use value
instead of query
(must specify index of node to return in the XQuery as well as passing the sql data type to return as the second parameter):
select
xt.Id
, x.m.value( '@id[1]', 'varchar(max)' ) MetricId
from
XmlTest xt
cross apply xt.XmlData.nodes( '/Sqm/Metrics/Metric' ) x(m)
for further investigation: print out the mssql error message:
$dbhandle = mssql_connect($myServer, $myUser, $myPass) or die("Could not connect to database: ".mssql_get_last_message());
It is also important to specify the port: On MS SQL Server 2000, separate it with a comma:
$myServer = "10.85.80.229:1443";
or
$myServer = "10.85.80.229,1443";
You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)
$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property
Or just this, xpath is case sensitive. Both have the same output:
$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml
Name Type #text
---- ---- -----
DisplayName System.String SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName System.String SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped
In my case the issue was resolved by installing Oracle's official JDK 10 as opposed to using the default OpenJDK that came with my Ubuntu. This is the guide I followed: https://www.linuxuprising.com/2018/04/install-oracle-java-10-in-ubuntu-or.html
From a script (one that works):
CREATE DATABASE Northwind
ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
GO
obviously update the path:
C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA
To where your .mdf and .ldf reside.
The same can be done without DataTrigger
too:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="Background" >
<Setter.Value>
<Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
<Binding.ConverterParameter>
<x:Array Type="SolidColorBrush">
<SolidColorBrush Color="{StaticResource RedColor}"/>
<SolidColorBrush Color="{StaticResource TransparentColor}"/>
</x:Array>
</Binding.ConverterParameter>
</Binding>
</Setter.Value>
</Setter>
</Style>
</DataGrid.RowStyle>
Where BooleanToBrushConverter
is the following class:
public class BooleanToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return Brushes.Transparent;
Brush[] brushes = parameter as Brush[];
if (brushes == null)
return Brushes.Transparent;
bool isTrue;
bool.TryParse(value.ToString(), out isTrue);
if (isTrue)
{
var brush = (SolidColorBrush)brushes[0];
return brush ?? Brushes.Transparent;
}
else
{
var brush = (SolidColorBrush)brushes[1];
return brush ?? Brushes.Transparent;
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
SELECT
DB_NAME (database_id) as [Database Name],
name as [Database File Name],
[Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
WHEN Type_Desc = 'LOG' THEN 'Log File(s)'
ELSE Type_Desc END,
size*8/1024 as 'Size (MB)',
physical_name as [Database_File_Location]
FROM sys.master_files
ORDER BY 1,3
Output
Database Name Database File Name Type Size (MB) Database_File_Location
--------------------------- ------------------------------- ------------------- ----------- ---------------------------------------------------------------
AdventureWorksDW2017 AdventureWorksDW2017 Data File(s) 136 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017.mdf
AdventureWorksDW2017 AdventureWorksDW2017_log Log File(s) 72 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017_log.ldf
DBA_Admin DBA_Admin Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin.mdf
DBA_Admin DBA_Admin_log Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin_log.ldf
EventNotifications EventNotifications Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications.mdf
EventNotifications EventNotifications_log Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications_log.ldf
master master Data File(s) 4 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\master.mdf
master mastlog Log File(s) 2 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
model modeldev Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\model.mdf
model modellog Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\modellog.ldf
msdb MSDBData Data File(s) 19 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
msdb MSDBLog Log File(s) 13 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf
tempdb temp2 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_2.ndf
tempdb temp3 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_3.ndf
tempdb temp4 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_4.ndf
tempdb tempdev Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
tempdb templog Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\templog.ldf
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE 0 END AS YOUR_QUERY_ANSWERED
above will return values
however below query wont work
DECLARE @INPUT VARCHAR(5) = '0.12',@INPUT_1 VARCHAR(5)='0.12x';
select CONVERT(float, @INPUT) YOUR_QUERY ,
case when isnumeric(@INPUT_1)=1 THEN CONVERT(float, @INPUT_1) ELSE **@INPUT_1** END AS YOUR_QUERY_ANSWERED
as @INPUT_1 actually has varchar in it.
So your output column must have a varchar in it.
The php mysql api is deprecated. It's kaput --- going away -- not to be used, finito.
If you have a modern version of PHP (> 5.6) then Wordpress should automatically switch to make use of mysqli. That should be your first attempt.
If you can not update your php, rather than attempting to resurrect something that php no longer supports, just patch your wordpress: http://wordpress.org/plugins/mysqli/
A few times now, I've experienced various instances MS SQL Server to fail with this error after a Windows update. Most of the quick fixes above did not work for me.
What did:
For me, this was the fastest solution. Trying to find the cause of the error and fixing it is an afternoon of googling misty error messages. But YMMV.
Try:
$result = curl_exec($cURL);
$result = json_decode($result,true);
Now you can access MessageID
from $result['MessageID']
.
As for the database, it's simply using a query like so:
INSERT INTO `tableName`(`Cancelled`,`Queued`,`SMSError`,`SMSIncommingMessage`,`Sent`,`SentDateTime`) VALUES('?','?','?','?','?');
Prepared.
Use the CREATE TABLE SELECT syntax.
http://dev.mysql.com/doc/refman/5.0/en/create-table-select.html
CREATE TABLE new_tbl SELECT * FROM orig_tbl;
You should be using DATEADD
is Sql server so if try this simple select you will see the affect
Select DATEADD(Month, -1, getdate())
Result
2013-04-20 14:08:07.177
in your case try this query
SELECT name
FROM (
SELECT name FROM
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name
i was getting error as "This driver is not configured for integrated authentication" while authenticating windows users by following jdbc string
jdbc:sqlserver://host:1433;integratedSecurity=true;domain=myDomain
So the updated connection string to make it work is as below.
jdbc:sqlserver://host:1433;authenticationScheme=NTLM;integratedSecurity=true;domain=myDomain
note: username entered was without domain.
Just simply use this Style
of DataGridRow
:
<DataGrid.RowStyle>
<Style TargetType="DataGridRow">
<Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
</Style>
</DataGrid.RowStyle>
Your question is a little unclear...as the part that you indicate you want to bold in Excel is a DataGridView in the import from word method. Do you maybe want to bold the first row in the excel document?
using xl = Microsoft.Office.Interop.Excel;
xl.Range rng = (xl.Range)xlWorkSheet.Rows[0];
rng.Font.Bold = true;
Simple as that!
HTH, Z
You can use date_parse_from_format()
function ...
Check this link..you will get clear idea
I think your expectations and reality don't match (but when do they ever ;))
Basically, where you think the file is written and where the file is actually written are not equal (hmmm, perhaps I should write an if
statement ;))
public class TestWriteFile {
public static void main(String[] args) {
BufferedWriter writer = null;
try {
//create a temporary file
String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
File logFile = new File(timeLog);
// This will output the full path where the file will be written to...
System.out.println(logFile.getCanonicalPath());
writer = new BufferedWriter(new FileWriter(logFile));
writer.write("Hello world!");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close the writer regardless of what happens...
writer.close();
} catch (Exception e) {
}
}
}
}
Also note that your example will overwrite any existing files. If you want to append the text to the file you should do the following instead:
writer = new BufferedWriter(new FileWriter(logFile, true));
$(document).ready(function () {
toggleFields(); // call this first so we start out with the correct visibility depending on the selected form values
// this will call our toggleFields function every time the selection value of our other field changes
$("#dbType").change(function () {
toggleFields();
});
});
// this toggles the visibility of other server
function toggleFields() {
if ($("#dbType").val() === "other")
$("#otherServer").show();
else
$("#otherServer").hide();
}
HTML:
<p>Choose type</p>
<p>Server:
<select id="dbType" name="dbType">
<option>Choose Database Type</option>
<option value="oracle">Oracle</option>
<option value="mssql">MS SQL</option>
<option value="mysql">MySQL</option>
<option value="other">Other</option>
</select>
</p>
<div id="otherServer">
<p>Server:
<input type="text" name="server_name" />
</p>
<p>Port:
<input type="text" name="port_no" />
</p>
</div>
<p align="center">
<input type="submit" value="Submit!" />
</p>
Here is another method, much simple, lets say your dataframe name is daat
and column name is YEARMONTH
daat.YEARMONTH.value_counts()
SQL Server doesn't allow you to pass parameters to a procedure that you haven't defined. I think the closest you can get to this sort of design is to use optional parameters like so:
CREATE PROCEDURE GetTaskEvents
@TaskName varchar(50),
@ID int = NULL
AS
BEGIN
-- SP Logic
END;
You would need to include every possible parameter that you might use in the definition. Then you'd be free to call the procedure either way:
EXEC GetTaskEvents @TaskName = 'TESTTASK', @ID = 2;
EXEC GetTaskEvents @TaskName = 'TESTTASK'; -- @ID gets NULL here
Here is a rough explanation of the concepts.
[ACK]
is the acknowledgement that the previously sent data packet was received.
[FIN]
is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN
).
So, suppose
[FIN,ACK]
indicating that it received the sent packet and wants to close the session.[FIN,ACK]
indicating that it received the termination request (the ACK
part) and that it too will close the connection (the FIN
part).However, if host A wants to close the session after sending the packet, it would only send a [FIN]
packet (nothing to acknowledge) but host B would respond with [FIN,ACK]
(acknowledges the request and responds with FIN
).
Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST]
instead of the usual [FIN,ACK]
. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.
You can find a more detailed and comprehensive explanation here.
You can easy change collation in Microsoft SQL Server Management studio.
Downloading Wget is not necessary; the .NET Framework has web client classes built in.
$wc = New-Object system.Net.WebClient;
$sms = Read-Host "Enter SMS text";
$sms = [System.Web.HttpUtility]::UrlEncode($sms);
$smsResult = $wc.downloadString("http://smsserver/SNSManager/msgSend.jsp?uid&to=smartsms:*+001XXXXXX&msg=$sms&encoding=windows-1255")
The answer is in the error message itself:
Error Locating Server/Instance Specified
Basically, you've got the wrong server\instance in the connection string, i.e. this bit:
Data Source=MSSQL2008-1
is wrong and not pointing to the server, or the servername doesn't resolve to an IP address. Two other posibilities: (1) the SQL Browser Service on the box running SQL Server isn't running or (2) Windows Firewall (or some other firewall) on the SQL box is denying incoming connections.
Ultimately, if the servername is correct, then it turns into a networking problem, and you need to find out why the client cannot connect to the server (and this will be more likely to be a basic networking problem than a SQL Server configuration problem).
Could be because of restoring SQL Server 2012 version backup file into SQL Server 2008 R2 or even less.
There is also EntityFunctions.TruncateTime
or DbFunctions.TruncateTime
in EF 6.0
This may help you.
public MyContext() : base("name=MyContext")
{
Database.SetInitializer(new MyContextDataInitializer());
this.Configuration.LazyLoadingEnabled = false;
this.Configuration.ProxyCreationEnabled = false;
}
http://code.msdn.microsoft.com/Loop-Reference-handling-in-caaffaf7
An alternative if you sometimes do not have spaces do not want to use the CASE statement
select REVERSE(RIGHT(REVERSE(YourColumn), LEN(YourColumn) - CHARINDEX(' ', REVERSE(YourColumn))))
This works in SQL Server, and according to my searching MySQL has the same functions
If you have android, you can install free app on phone (Wifi file Transfer) and enable ssl, port and other options for access and send data in both directions just start application and write in pc browser phone ip and port. enjoy!
$servername = "";
$username = "";
$password = "";
$database = "";
$port = "1433";
try {
$conn = new PDO("sqlsrv:server=$servername,$port;Database=$database;ConnectionPooling=0", $username, $password,
array(
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
)
);
} catch (PDOException $e) {
echo ("Error connecting to SQL Server: " . $e->getMessage());
}
by default -
you can also log in to sql express using server name as:
./SQLEXPRESS
or log in to sql server simply as
.
I had a similar issue that was resolved with the following:
If the user is a domain user use Domain username and password
In my case, Run as Administrator does not help. I solved the problem by changing the Build-in Account to Local System in Configuration Manager.
Just to add to the other answers, the documentation gives this explanation:
KEY
is normally a synonym forINDEX
. The key attributePRIMARY KEY
can also be specified as justKEY
when given in a column definition. This was implemented for compatibility with other database systems.A
UNIQUE
index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. For all engines, aUNIQUE
index permits multipleNULL
values for columns that can containNULL
.A
PRIMARY KEY
is a unique index where all key columns must be defined asNOT NULL
. If they are not explicitly declared asNOT NULL
, MySQL declares them so implicitly (and silently). A table can have only onePRIMARY KEY
. The name of aPRIMARY KEY
is alwaysPRIMARY
, which thus cannot be used as the name for any other kind of index.
This worked for me.
Single-clicking a row triggers the code-behind.
XAML:
<ListView x:Name="MyListView" MouseLeftButtonUp="MyListView_MouseLeftButtonUp">
<GridView>
<!-- Declare GridViewColumns. -->
</GridView>
</ListView.View>
Code-behind:
private void MyListView_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
System.Windows.Controls.ListView list = (System.Windows.Controls.ListView)sender;
MyClass selectedObject = (MyClass)list.SelectedItem;
// Do stuff with the selectedObject.
}
I have just tried to install that extension on my dev server.
First, make sure that the extension is correctly enabled. Your phpinfo()
output doesn't seem complete.
If it is indeed installed properly, your phpinfo()
should have a section that looks like this:
If you do not get that section in your phpinfo()
. Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.
Finally, check your extension_dir
setting. By default it's this: extension_dir = "ext"
, for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext"
.
===========================================================================
EDIT given new info:
You are using the wrong function. mssql_connect()
is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect()
, for the API for the microsoft driver, look at SQLSRV_Help.chm
which should be extracted to your ext
directory when you extracted the extension.
To add my 2 cents, the exception can occur even if you call your code through System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke()
.
The point is that you have to call Invoke()
of the Dispatcher
of the control that you're trying to access, which in some cases may not be the same as System.Windows.Threading.Dispatcher.CurrentDispatcher
. So instead you should use YourControl.Dispatcher.Invoke()
to be safe. I was banging my head for a couple of hours before I realized this.
For future readers, it looks like this has changed in the newer versions of .NET (4.0 and above). Now you no longer have to worry about the correct dispatcher when updating UI-backing properties in your VM. WPF engine will marshal cross-thread calls on the correct UI thread. See more details here. Thanks to @aaronburro for the info and link. You may also want to read our conversation below in comments.
Sorry for only commenting in the first place, but i'm posting almost every day a similar comment since many people think that it would be smart to encapsulate ADO.NET functionality into a DB-Class(me too 10 years ago). Mostly they decide to use static/shared objects since it seems to be faster than to create a new object for any action.
That is neither a good idea in terms of peformance nor in terms of fail-safety.
There's a good reason why ADO.NET internally manages the underlying Connections to the DBMS in the ADO-NET Connection-Pool:
In practice, most applications use only one or a few different configurations for connections. This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.
Connection pooling reduces the number of times that new connections must be opened. The pooler maintains ownership of the physical connection. It manages connections by keeping alive a set of active connections for each given connection configuration. Whenever a user calls Open on a connection, the pooler looks for an available connection in the pool. If a pooled connection is available, it returns it to the caller instead of opening a new connection. When the application calls Close on the connection, the pooler returns it to the pooled set of active connections instead of closing it. Once the connection is returned to the pool, it is ready to be reused on the next Open call.
So obviously there's no reason to avoid creating,opening or closing connections since actually they aren't created,opened and closed at all. This is "only" a flag for the connection pool to know when a connection can be reused or not. But it's a very important flag, because if a connection is "in use"(the connection pool assumes), a new physical connection must be openend to the DBMS what is very expensive.
So you're gaining no performance improvement but the opposite. If the maximum pool size specified (100 is the default) is reached, you would even get exceptions(too many open connections ...). So this will not only impact the performance tremendously but also be a source for nasty errors and (without using Transactions) a data-dumping-area.
If you're even using static connections you're creating a lock for every thread trying to access this object. ASP.NET is a multithreading environment by nature. So theres a great chance for these locks which causes performance issues at best. Actually sooner or later you'll get many different exceptions(like your ExecuteReader requires an open and available Connection).
Conclusion:
using-statement
to dispose and close(in case of Connections) implicitelyThat's true not only for Connections(although most noticable). Every object implementing IDisposable
should be disposed(simplest by using-statement
), all the more in the System.Data.SqlClient
namespace.
All the above speaks against a custom DB-Class which encapsulates and reuse all objects. That's the reason why i commented to trash it. That's only a problem source.
Edit: Here's a possible implementation of your retrievePromotion
-method:
public Promotion retrievePromotion(int promotionID)
{
Promotion promo = null;
var connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MainConnStr"].ConnectionString;
using (SqlConnection connection = new SqlConnection(connectionString))
{
var queryString = "SELECT PromotionID, PromotionTitle, PromotionURL FROM Promotion WHERE PromotionID=@PromotionID";
using (var da = new SqlDataAdapter(queryString, connection))
{
// you could also use a SqlDataReader instead
// note that a DataTable does not need to be disposed since it does not implement IDisposable
var tblPromotion = new DataTable();
// avoid SQL-Injection
da.SelectCommand.Parameters.Add("@PromotionID", SqlDbType.Int);
da.SelectCommand.Parameters["@PromotionID"].Value = promotionID;
try
{
connection.Open(); // not necessarily needed in this case because DataAdapter.Fill does it otherwise
da.Fill(tblPromotion);
if (tblPromotion.Rows.Count != 0)
{
var promoRow = tblPromotion.Rows[0];
promo = new Promotion()
{
promotionID = promotionID,
promotionTitle = promoRow.Field<String>("PromotionTitle"),
promotionUrl = promoRow.Field<String>("PromotionURL")
};
}
}
catch (Exception ex)
{
// log this exception or throw it up the StackTrace
// we do not need a finally-block to close the connection since it will be closed implicitely in an using-statement
throw;
}
}
}
return promo;
}
This function handels "HH:MM:SS" as well as "MM:SS" or "SS".
function hmsToSecondsOnly(str) {
var p = str.split(':'),
s = 0, m = 1;
while (p.length > 0) {
s += m * parseInt(p.pop(), 10);
m *= 60;
}
return s;
}
REST doesn't have a recommended date format. Really it boils down to what works best for your end user and your system. Personally, I would want to stick to a standard like you have for ISO 8601 (url encoded).
If not having ugly URI is a concern (e.g. not including the url encoded version of :
, -
, in you URI) and (human) addressability is not as important, you could also consider epoch time (e.g.
http://example.com/start/1331162374
). The URL looks a little cleaner, but you certainly lose readability.
The /2012/03/07
is another format you see a lot. You could expand upon that I suppose. If you go this route, just make sure you're either always in GMT time (and make that clear in your documentation) or you might also want to include some sort of timezone indicator.
Ultimately it boils down to what works for your API and your end user. Your API should work for you, not you for it ;-).
In MySql, you can get 10 rows starting from row 20 using:
SELECT * FROM Reflow
WHERE ReflowProcessID = somenumber
ORDER BY ID DESC
LIMIT 10 OFFSET 20 --Equivalent to LIMIT 20, 10
It is not too surprising: the execution plan for the tiny insert is computed once, and then reused 1000 times. Parsing and preparing the plan is quick, because it has only four values to del with. A 1000-row plan, on the other hand, needs to deal with 4000 values (or 4000 parameters if you parameterized your C# tests). This could easily eat up the time savings you gain by eliminating 999 roundtrips to SQL Server, especially if your network is not overly slow.
Just to add my TSQL-scripted solution:
First of all; add a new database named backup_lookup
.
Then just run this script, inserting your own databases' root path and backup filepath
USE [master]
GO
RESTORE DATABASE backup_lookup
FROM DISK = 'C:\backup.bak'
WITH REPLACE,
MOVE 'Old Database Name' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup.mdf',
MOVE 'Old Database Name_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\backup_lookup_log.ldf'
GO
I know it's late, but maybe this helps others. I have created a class NotifyObservableCollection
, that solves the problem of missing notification to item itself, when a property of the item changes. The usage is as simple as ObservableCollection
.
public class NotifyObservableCollection<T> : ObservableCollection<T> where T : INotifyPropertyChanged
{
private void Handle(object sender, PropertyChangedEventArgs args)
{
OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset, null));
}
protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null) {
foreach (object t in e.NewItems) {
((T) t).PropertyChanged += Handle;
}
}
if (e.OldItems != null) {
foreach (object t in e.OldItems) {
((T) t).PropertyChanged -= Handle;
}
}
base.OnCollectionChanged(e);
}
While Items are added or removed the class forwards the items PropertyChanged
event to the collections PropertyChanged
event.
usage:
public abstract class ParameterBase : INotifyPropertyChanged
{
protected readonly CultureInfo Ci = new CultureInfo("en-US");
private string _value;
public string Value {
get { return _value; }
set {
if (value == _value) return;
_value = value;
OnPropertyChanged();
}
}
}
public class AItem {
public NotifyObservableCollection<ParameterBase> Parameters {
get { return _parameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_parameters != null) _parameters.CollectionChanged -= cceh;
_parameters = value;
//needed for Binding to AItem at xaml directly
_parameters.CollectionChanged += cceh;
}
}
public NotifyObservableCollection<ParameterBase> DefaultParameters {
get { return _defaultParameters; }
set {
NotifyCollectionChangedEventHandler cceh = (sender, args) => OnPropertyChanged();
if (_defaultParameters != null) _defaultParameters.CollectionChanged -= cceh;
_defaultParameters = value;
//needed for Binding to AItem at xaml directly
_defaultParameters.CollectionChanged += cceh;
}
}
public class MyViewModel {
public NotifyObservableCollection<AItem> DataItems { get; set; }
}
If now a property of an item in DataItems
changes, the following xaml will get a notification, though it binds to Parameters[0]
or to the item itself except to the changing property Value
of the item (Converters at Triggers are called reliable on every change).
<DataGrid CanUserAddRows="False" AutoGenerateColumns="False" ItemsSource="{Binding DataItems}">
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Parameters[0].Value}" Header="P1">
<DataGridTextColumn.CellStyle>
<Style TargetType="DataGridCell">
<Setter Property="Background" Value="Aqua" />
<Style.Triggers>
<DataTrigger Value="False">
<!-- Bind to Items with changing properties -->
<DataTrigger.Binding>
<MultiBinding Converter="{StaticResource ParameterCompareConverter}">
<Binding Path="DefaultParameters[0]" />
<Binding Path="Parameters[0]" />
</MultiBinding>
</DataTrigger.Binding>
<Setter Property="Background" Value="DeepPink" />
</DataTrigger>
<!-- Binds to AItem directly -->
<DataTrigger Value="True" Binding="{Binding Converter={StaticResource CheckParametersConverter}}">
<Setter Property="FontWeight" Value="ExtraBold" />
</DataTrigger>
</Style.Triggers>
</Style>
</DataGridTextColumn.CellStyle>
</DataGridTextColumn>
In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.
If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.
255 is a good baseline definition unless you particularly wish to curtail excessive input.
Up to Postgres 11 generated columns are not supported - as defined in the SQL standard and implemented by some RDBMS including DB2, MySQL and Oracle. Nor the similar "computed columns" of SQL Server.
STORED
generated columns are introduced with Postgres 12. Trivial example:
CREATE TABLE tbl (
int1 int
, int2 int
, product bigint GENERATED ALWAYS AS (int1 * int2) STORED
);
db<>fiddle here
VIRTUAL
generated columns may come with one of the next iterations. (Not in Postgres 13, yet) .
Related:
Until then, you can emulate VIRTUAL
generated columns with a function using attribute notation (tbl.col
) that looks and works much like a virtual generated column. That's a bit of a syntax oddity which exists in Postgres for historic reasons and happens to fit the case. This related answer has code examples:
The expression (looking like a column) is not included in a SELECT * FROM tbl
, though. You always have to list it explicitly.
Can also be supported with a matching expression index - provided the function is IMMUTABLE
. Like:
CREATE FUNCTION col(tbl) ... AS ... -- your computed expression here
CREATE INDEX ON tbl(col(tbl));
Alternatively, you can implement similar functionality with a VIEW
, optionally coupled with expression indexes. Then SELECT *
can include the generated column.
"Persisted" (STORED
) computed columns can be implemented with triggers in a functionally identical way.
Materialized views are a closely related concept, implemented since Postgres 9.3.
In earlier versions one can manage MVs manually.
The following lines are used to control the listen-port of a server, both are necessary:
<listen-port>7002</listen-port>
<listen-port-enabled>true</listen-port-enabled>
Don`t forget to use DataGrid.Columns, all columns must be inside that collection. In my project I format date a little bit differently:
<tk:DataGrid>
<tk:DataGrid.Columns>
<tk:DataGridTextColumn Binding="{Binding StartDate, StringFormat=\{0:dd.MM.yy HH:mm:ss\}}" />
</tk:DataGrid.Columns>
</tk:DataGrid>
With AutoGenerateColumns you won`t be able to contol formatting as DataGird will add its own columns.
How about:
(Updated)
$("#column_select").change(function () {
$("#layout_select")
.find("option")
.show()
.not("option[value*='" + this.value + "']").hide();
$("#layout_select").val(
$("#layout_select").find("option:visible:first").val());
}).change();
(assuming the third option
should have a value col3
)
Example: http://jsfiddle.net/cL2tt/
Notes:
.change()
event to define an event handler that executes when the value of select#column_select
changes..show()
all option
s in the second select
..hide()
all option
s in the second select
whose value
does not contain the value
of the selected option in select#column_select
, using the attribute contains selector.Apart from the security settings, I had to open some ports on both servers for the transaction to run. I had to open port 59640 but according to the following suggestion, port 135 has to be open. http://support.microsoft.com/kb/839279
I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.
You should almost always use a Collator for dictionary based sorting.
For case insensitive collator searching for the English language you do the following:
Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);
Quoting http://php.net/manual/en/intro.mssql.php:
The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.
Once you downloaded that, follow the instructions at this page:
In a nutshell:
Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:extension=php_sqlsrv_53_nts_vc9.dll
Restart the Web server.
See Also (copied from that page)
The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:
The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.
The drivers can also be used with PDO.
You'll have to write the SQL DML yourself explicitly. i.e.
UPDATE <table>
SET <column> = NULL;
Once it has completed you'll need to commit your updates
commit;
If you only want to set certain records to NULL use a WHERE clause in your UPDATE statement.
As your original question is pretty vague I hope this covers what you want.
The best way is Mikael Eriksson, if ROW_NUMBER()
is available to you.
The next best is to join on a query, as per Cularis' answer.
Alternatively, the most simple and straight forward way is a correlated-sub-query in the WHERE clause.
SELECT
*
FROM
yourTable AS [data]
WHERE
DateEntered = (SELECT MAX(DateEntered) FROM yourTable WHERE orderNo = [data].orderNo)
Or...
WHERE
ID = (SELECT TOP 1 ID FROM yourTable WHERE orderNo = [data].orderNo ORDER BY DateEntered DESC)
Got problem like this. Error caused by enabled compression on SQL Server folders.
Some notes to complement the ALTER DATABASE process:
1) You can obtain a full list of databases with logical names and full paths of MDF and LDF files:
USE master SELECT name, physical_name FROM sys.master_files
2) You can move manually the files with CMD move command:
Move "Source" "Destination"
Example:
md "D:\MSSQLData"
Move "C:\test\SYSADMIT-DB.mdf" "D:\MSSQLData\SYSADMIT-DB_Data.mdf"
Move "C:\test\SYSADMIT-DB_log.ldf" "D:\MSSQLData\SYSADMIT-DB_log.ldf"
3) You should change the default database path for new databases creation. The default path is obtained from the Windows registry.
You can also change with T-SQL, for example, to set default destination to: D:\MSSQLData
USE [master]
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', REG_SZ, N'D:\MSSQLData'
GO
EXEC xp_instance_regwrite N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', REG_SZ, N'D:\MSSQLData'
GO
Extracted from: http://www.sysadmit.com/2016/08/mover-base-de-datos-sql-server-a-otro-disco.html
I would not have expected this case to be optimized at all. It can't be very often where an expression contains subexpressions that can be regrouped to remove entire operations. I would expect compiler writers to invest their time in areas which would be more likely to result in noticeable improvements, rather than covering a rarely encountered edge case.
I was surprised to learn from the other answers that this expression could indeed be optimized with the proper compiler switches. Either the optimization is trivial, or it is an edge case of a much more common optimization, or the compiler writers were extremely thorough.
There's nothing wrong with providing hints to the compiler as you've done here. It's a normal and expected part of the micro-optimization process to rearrange statements and expressions to see what differences they will bring.
While the compiler may be justified in considering the two expressions to deliver inconsistent results (without the proper switches), there's no need for you to be bound by that restriction. The difference will be incredibly tiny - so much so that if the difference matters to you, you should not be using standard floating point arithmetic in the first place.
Add below code in your client code :
static {
Security.insertProviderAt(new BouncyCastleProvider(),1);
}
with this there is no need to add any entry in java.security file.
SELECT number, COUNT(*)
FROM YourTable
GROUP BY number
ORDER BY number
You can do it from code by placing the following code in Window Loaded
event handler, for example:
yourComboBox.ItemsSource = Enum.GetValues(typeof(EffectStyle)).Cast<EffectStyle>();
If you need to bind it in XAML you need to use ObjectDataProvider
to create object available as binding source:
<Window x:Class="YourNamespace.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects">
<Window.Resources>
<ObjectDataProvider x:Key="dataFromEnum" MethodName="GetValues"
ObjectType="{x:Type System:Enum}">
<ObjectDataProvider.MethodParameters>
<x:Type TypeName="StyleAlias:EffectStyle"/>
</ObjectDataProvider.MethodParameters>
</ObjectDataProvider>
</Window.Resources>
<Grid>
<ComboBox ItemsSource="{Binding Source={StaticResource dataFromEnum}}"
SelectedItem="{Binding Path=CurrentEffectStyle}" />
</Grid>
</Window>
Draw attention on the next code:
xmlns:System="clr-namespace:System;assembly=mscorlib"
xmlns:StyleAlias="clr-namespace:Motion.VideoEffects"
Guide how to map namespace and assembly you can read on MSDN.
A little bit simpler using regex and toJSON()
.
var now = new Date();
var timeRegex = /^.*T(\d{2}):(\d{2}):(\d{2}).*$/
var dateRegex = /^(\d{4})-(\d{2})-(\d{2})T.*$/
var dateData = dateRegex.exec(now.toJSON());
var timeData = timeRegex.exec(now.toJSON());
var myFormat = dateData[1]+dateData[2]+dateData[3]+timeData[1]+timeData[2]+timeData[3]
Which at the time of writing gives you "20151111180924"
.
The good thing of using toJSON()
is that everything comes already padded.
Use the time.Now() and time.Format() functions (as time.LocalTime() doesn't exist anymore as of Go 1.0.3)
t := time.Now()
fmt.Println(t.Format("20060102150405"))
Online demo (with date fixed in the past in the playground, never mind)
You want to convert mdb to mysql (direct transfer to mysql or mysql dump)?
Try a software called Access to MySQL.
Access to MySQL is a small program that will convert Microsoft Access Databases to MySQL.
- Wizard interface.
- Transfer data directly from one server to another.
- Create a dump file.
- Select tables to transfer.
- Select fields to transfer.
- Transfer password protected databases.
- Supports both shared security and user-level security.
- Optional transfer of indexes.
- Optional transfer of records.
- Optional transfer of default values in field definitions.
- Identifies and transfers auto number field types.
- Command line interface.
- Easy install, uninstall and upgrade.
See the aforementioned link for a step-by-step tutorial with screenshots.
A 2016/2017 update will show you the bad value and column.
A new trace flag will swap the old error for a new 2628 error and will print out the column and offending value. Traceflag 460 is available in the latest cumulative update for 2016 and 2017:
Just make sure that after you've installed the CU that you enable the trace flag, either globally/permanently on the server:
...or with DBCC TRACEON:
The correct solution seems to be:
<Window.Resources>
<CollectionViewSource x:Key="ItemsCVS" Source="{Binding MyItems}" />
</Window.Resources>
<!-- ... -->
<DataGrid ItemsSource="{Binding MyRecords}">
<DataGridComboBoxColumn Header="Column With Predefined Values"
ItemsSource="{Binding Source={StaticResource ItemsCVS}}"
SelectedValueBinding="{Binding MyItemId}"
SelectedValuePath="Id"
DisplayMemberPath="StatusCode" />
</DataGrid>
The layout above works perfectly fine for me, and should work for others. This design choice also makes sense, though it isn't very well explained anywhere. But if you have a data column with predefined values, those values typically don't change during run-time. So creating a CollectionViewSource
and initializing the data once makes sense. It also gets rid of the longer bindings to find an ancestor and bind on it's data context (which always felt wrong to me).
I am leaving this here for anyone else who struggled with this binding, and wondered if there was a better way (As this page is obviously still coming up in search results, that's how I got here).
In package specs you can do all you mentioned but not sure about INDEX BY BINARY_INTEGER;
In package body:
initialize the table in declarations:
exch_rt exch_tbl := exch_tbl();
in order to add record to the local collection, in begin - end block you can do:
exch_rt.extend;
one_row.exch_rt_usd := 2;
one_row.exch_rt_eur := 1;
one_row.currency_cd := 'dollar';
exch_rt(1) := one_row; -- 1 - number of row in the table - you can put a variable which will be incremented inside a loop
in order to get data from this table , inside package body you can use:
select exch_rt_usd, exch_rt_eur, currency_cd from table(exch_rt)
enjoy!
P.S. sorry for a late answer :D
Since the SERVICE_USER table is not a pure join table, but has additional functional fields (blocked), you must map it as an entity, and decompose the many to many association between User and Service into two OneToMany associations : One User has many UserServices, and one Service has many UserServices.
You haven't shown us the most important part : the mapping and initialization of the relationships between your entities (i.e. the part you have problems with). So I'll show you how it should look like.
If you make the relationships bidirectional, you should thus have
class User {
@OneToMany(mappedBy = "user")
private Set<UserService> userServices = new HashSet<UserService>();
}
class UserService {
@ManyToOne
@JoinColumn(name = "user_id")
private User user;
@ManyToOne
@JoinColumn(name = "service_code")
private Service service;
@Column(name = "blocked")
private boolean blocked;
}
class Service {
@OneToMany(mappedBy = "service")
private Set<UserService> userServices = new HashSet<UserService>();
}
If you don't put any cascade on your relationships, then you must persist/save all the entities. Although only the owning side of the relationship (here, the UserService side) must be initialized, it's also a good practice to make sure both sides are in coherence.
User user = new User();
Service service = new Service();
UserService userService = new UserService();
user.addUserService(userService);
userService.setUser(user);
service.addUserService(userService);
userService.setService(service);
session.save(user);
session.save(service);
session.save(userService);
It sets how the database server sorts (compares pieces of text). in this case:
SQL_Latin1_General_CP1_CI_AS
breaks up into interesting parts:
latin1
makes the server treat strings using charset latin 1, basically asciiCP1
stands for Code Page 1252CI
case insensitive comparisons so 'ABC' would equal 'abc'AS
accent sensitive, so 'ü' does not equal 'u'P.S. For more detailed information be sure to read @solomon-rutzky's answer.
It's database specific. You haven't specified what database engine you are using.
e.g. in PostgreSQL you do cast(myvalue as date).
have you tried:
C:\Program Files\Microsoft SQL Server\MSSQL10.SQL2008\MSSQL\Backup
Script to get all backups in the last week can be found at:
http://wraithnath.blogspot.com/2010/12/how-to-find-all-database-backups-in.html
I have plenty more backup SQL scripts there also at
Use the script: sp_blocker_pss08 or SQL Trace/Profiler and the Blocked Process Report event class.
If you're on windows you probably want the pywin32
library, which includes pythoncom
and a whole lot of other stuff that is pretty standard.
I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:
CREATE FUNCTION nomen_tree() RETURNS trigger
LANGUAGE plpgsql
AS $_$
DECLARE
old_parent INTEGER;
new_parent INTEGER;
id_nom INTEGER;
txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
IF TG_OP = 'INSERT' THEN
EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT $1.id,$1.id,0 UNION ALL
SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
ELSE
-- EXECUTE does not support conditional statements inside
EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
EXECUTE '
-- prevent cycles in the tree
UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
|| ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
|| TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
-- first remove edges between all old parents of node and its descendants
DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
(SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
AND ancestor_id IN
(SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
-- then add edges for all new parents ...
INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth)
SELECT child_id,ancestor_id,d_c+d_a FROM
(SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
CROSS JOIN
(SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.'
|| TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
END IF;
END IF;
RETURN NULL;
END;
$_$;
Then for each table where I have a hierarchy, I create a trigger
CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');
For populating a closure table from existing hierarchy I use this stored procedure:
CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
LANGUAGE plpgsql
AS $$
BEGIN
EXECUTE 'TRUNCATE ' || tbl_closure || ';
INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth)
WITH RECURSIVE tree AS
(
SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
UNION ALL
SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
JOIN tree ON child_id = ' || fld_parent || '
)
SELECT * FROM tree;';
END;
$$;
Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:
-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;
I also encountered a similar error when trying to generate the client for a web service from an ASP .Net MVC 4.0 project using Visual Studio 2012.
The root of the problem seems to be that fact that the project from where I was trying to generate the client was referencing an assembly which in turn was dependent on another assembly that was not being referenced as well.
When "Reuse types in referenced assemblies" is enabled in the service configuration, the service generator is probably inspecting all the referenced assemblies to get a list of types that can be reused. The fact that one of the referenced assemblies is referencing another assembly which is not available is probably causing the generator to fail.
Unchecking "Reuse types in referenced assemblies" from the service configurations will solve the above problem, but there is a side effect to it. The reuse types option is there for a reason and in some cases it avoids unnecessary casting in the code consuming the service.
For example, if the service itself is built using WCF and some methods parameters inside it are of type System.Guid, they will be translated to strings in the generated client if the reuse types option is disabled.
An alternative that I prefer to disabling reusing types is to add the service reference from Class Library project specifically created for that purpose. The one thing to keep in mind is to copy all the service related configurations from the class library's app.config to the configuration file of the startup project.
If there are types defined in local assemblies that need to be reused in the service client, those assemblies simply need to be referenced from the above mentioned class library project, along with all their dependencies.
Gentil Kiwi's answer is correct. He developed this mimikatz tool that is able to retrieve non-exportable private keys.
However, his instructions are outdated. You need:
Download the lastest release from https://github.com/gentilkiwi/mimikatz/releases
Run the cmd with admin rights in the same machine where the certificate was requested
Change to the mimikatz bin directory (Win32 or x64 version)
Run mimikatz
Follow the wiki instructions and the .pfx file (protected with password mimikatz) will be placed in the same folder of the mimikatz bin
mimikatz # crypto::capi
Local CryptoAPI patchedmimikatz # privilege::debug
Privilege '20' OKmimikatz # crypto::cng
"KeyIso" service patchedmimikatz # crypto::certificates /systemstore:local_machine /store:my /export
* System Store : 'local_machine' (0x00020000)
* Store : 'my'
- example.domain.local
Key Container : example.domain.local
Provider : Microsoft Software Key Storage Provider
Type : CNG Key (0xffffffff)
Exportable key : NO
Key size : 2048
Public export : OK - 'local_machine_my_0_example.domain.local.der'
Private export : OK - 'local_machine_my_0_example.domain.local.pfx'
Yes, there is Oracle SQL Developer, which is maintained by Oracle.
Oracle SQL Developer is a free graphical tool for database development. With SQL Developer, you can browse database objects, run SQL statements and SQL scripts, and edit and debug PL/SQL statements. You can also run any number of provided reports, as well as create and save your own. SQL Developer enhances productivity and simplifies your database development tasks.
SQL Developer can connect to any Oracle Database version 10g and later and runs on Windows, Linux and Mac OSX.
I found this, and it worked for me:
CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO
Try the to_date function.
Ok - my case was not strictly related to this question, but I ended up on this page when Googling for the same exception; I queried an SQL database with LINQ when I got this exception.
private Table<SubscriptionModel> m_subscriptionsSql;
var query = from SubscriptionModel subscription in m_subscriptionsSql ...
Turned out I forgot to initialize my Table instance variable, that I used in the LINQ query.
m_subscriptionsSql = GetTable<SubscriptionModel>();
try to upgrade each of those modules using pecl command
# pecl upgrade fileinfo
# pecl upgrade memcache
# pecl upgrade mhash
# pecl upgrade readline
etc...
Cannot open backup device 'c:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Backup\ C:\HostingSpaces\dbname_jun14_2010_new.bak'
The error is quite self-explanatory. The file C:\program files\...\Backup \c:\Hosting...\
is incorrectly formatted. This is quite obvious if you inspect the file name. Perhaps ommit the extra space in your backup statement?
BACKUP DATABASE go4sharepoint_1384_8481
TO DISK='C:\HostingSpaces\dbname_jun14_2010_new.bak' with FORMAT
Note there is no space between '
and C:
Define your own parse format string to use.
string formatString = "yyyyMMddHHmmss";
string sample = "20100611221912";
DateTime dt = DateTime.ParseExact(sample,formatString,null);
In case you got a datetime having milliseconds, use the following formatString
string format = "yyyyMMddHHmmssfff"
string dateTime = "20140123205803252";
DateTime.ParseExact(dateTime ,format,CultureInfo.InvariantCulture);
Thanks
You can use a custom format string:
DateTime d = DateTime.Now;
string dateString = d.ToString("yyyyMMddHHmmss");
Substitute "hh" for "HH" if you do not want 24-hour clock time.
Dependencies that are not referenced in an interfaces methods should be regarded as implementation details, not something that the interface enforces. Of course there can be exceptions, but as a rule, you should define your interface as what the behavior is expected to be. Internal state of a given implementation shouldn't be a design concern of the interface.
It prevents disclosure of the response through JSON hijacking.
In theory, the content of HTTP responses are protected by the Same Origin Policy: pages from one domain cannot get any pieces of information from pages on the other domain (unless explicitly allowed).
An attacker can request pages on other domains on your behalf, e.g. by using a <script src=...>
or <img>
tag, but it can't get any information about the result (headers, contents).
Thus, if you visit an attacker's page, it couldn't read your email from gmail.com.
Except that when using a script tag to request JSON content, the JSON is executed as JavaScript in an attacker's controlled environment. If the attacker can replace the Array or Object constructor or some other method used during object construction, anything in the JSON would pass through the attacker's code, and be disclosed.
Note that this happens at the time the JSON is executed as JavaScript, not at the time it's parsed.
There are multiple countermeasures:
By placing a while(1);
statement before the JSON data, Google makes sure that the JSON data is never executed as JavaScript.
Only a legitimate page could actually get the whole content, strip the while(1);
, and parse the remainder as JSON.
Things like for(;;);
have been seen at Facebook for instance, with the same results.
Similarly, adding invalid tokens before the JSON, like &&&START&&&
, makes sure that it is never executed.
This is OWASP recommended way to protect from JSON hijacking and is the less intrusive one.
Similarly to the previous counter-measures, it makes sure that the JSON is never executed as JavaScript.
A valid JSON object, when not enclosed by anything, is not valid in JavaScript:
eval('{"foo":"bar"}')
// SyntaxError: Unexpected token :
This is however valid JSON:
JSON.parse('{"foo":"bar"}')
// Object {foo: "bar"}
So, making sure you always return an Object at the top level of the response makes sure that the JSON is not valid JavaScript, while still being valid JSON.
As noted by @hvd in the comments, the empty object {}
is valid JavaScript, and knowing the object is empty may itself be valuable information.
The OWASP way is less intrusive, as it needs no client library changes, and transfers valid JSON. It is unsure whether past or future browser bugs could defeat this, however. As noted by @oriadam, it is unclear whether data could be leaked in a parse error through an error handling or not (e.g. window.onerror).
Google's way requires a client library in order for it to support automatic de-serialization and can be considered to be safer with regard to browser bugs.
Both methods require server side changes in order to avoid developers accidentally sending vulnerable JSON.
update Hotels set Discount=30 where Hotelid >= 1 and Hotelid <= 5504
The problem with toISOString is that it gives datetime only as "Z".
ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).
I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.
var timezone_offset_min = new Date().getTimezoneOffset(),
offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
offset_min = Math.abs(timezone_offset_min%60),
timezone_standard;
if(offset_hrs < 10)
offset_hrs = '0' + offset_hrs;
if(offset_min > 10)
offset_min = '0' + offset_min;
// getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
// So add an opposite sign to the offset
// If offset is 0, it means timezone is UTC
if(timezone_offset_min < 0)
timezone_standard = '+' + offset_hrs + ':' + offset_min;
else if(timezone_offset_min > 0)
timezone_standard = '-' + offset_hrs + ':' + offset_min;
else if(timezone_offset_min == 0)
timezone_standard = 'Z';
// Timezone difference in hours and minutes
// String such as +5:30 or -6:00 or Z
console.log(timezone_standard);
Once you have the timezone offset in hours and minutes, you can append to a datetime string.
I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes
Please follow the below steps :
1) Locate php.ini in your apache bin folder, I.e Apache/bin/php.ini
2) Remove the ; from the beginning of extension=php_soap.dll
3) Restart your Apache server (by using :
# /etc/init.d/apache2 restart OR
$ sudo /etc/init.d/apache2 restart OR
$ sudo service apache2 restart)
4) Look up your phpinfo();
you may check here as well,if this does not solve your issue:
https://www.php.net/manual/en/soap.requirements.php
I had this error and found a few solutions:
Looking at your connection string, it looks valid. I found this blog post, the problem here is that they were using Integrated Security. If you are running on IIS, your IIS user needs access to the database.
If you are using Entity Framework with Transactions, Entity Framework automatically opens and closes a connection with each database call. So when using transactions, you are attempting to spread a transaction out over multiple connections. This elevates to MSDTC.
(See this reference for more information.)
Changing my code to the following fixed it:
using (DatabaseEntities context = new DatabaseEntities())
{
context.Connection.Open();
// the rest
}
If your having trouble connecting, most likely the problem is that you haven't yet enabled the TCP/IP listener on port 1433. A quick "netstat -an" command will tell you if its listening. By default, SQL server doesn't enable this after installation.
Also, you need to set a password on the "sa" account and also ENABLE the "sa" account (if you plan to use that account to connect with).
Obviously, this also means you need to enable "mixed mode authentication" on your MSSQL node.
This should do the trick:
date.Subtract(new DateTime(1970, 1,1)).TotalMilliseconds
Here's a snippet I used - with plain SimpleDateFormat
. Hope somebody else may benefit from it:
public static void main(String[] args) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ") {
public StringBuffer format(Date date, StringBuffer toAppendTo, java.text.FieldPosition pos) {
StringBuffer toFix = super.format(date, toAppendTo, pos);
return toFix.insert(toFix.length()-2, ':');
};
};
// Usage:
System.out.println(dateFormat.format(new Date()));
}
Output:
- Usual Output.........: 2013-06-14T10:54:07-0200
- This snippet's Output: 2013-06-14T10:54:07-02:00
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
// Usage:
System.out.println(dateFormat2.format(new Date()));
Output:
- This pattern's output: 2013-06-14T10:54:07-02:00
See the docs for that.
This setting needs to be set:
SET SERVEROUTPUT ON
<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
</Style>
</UserControl.Resources>
and
<ListBox ItemsSource="{Binding Path=FirstNames}"
ItemContainerStyle="{StaticResource myLBStyle}">
You just override the style of the listboxitem (see the: TargetType is ListBoxItem)
I want to complete the answer from tchester.
(1) Enable the xp_cmdshell procedure:
-- To allow advanced options to be changed.
EXEC sp_configure 'show advanced options', 1
RECONFIGURE
GO
-- Enable the xp_cmdshell procedure
EXEC sp_configure 'xp_cmdshell', 1
RECONFIGURE
GO
(2) Create a login 'Domain\TestUser' (windows user) for the non-sysadmin user that has public access to the master database
(3) Grant EXEC permission on the xp_cmdshell stored procedure:
GRANT EXECUTE ON xp_cmdshell TO [Domain\TestUser]
(4) Create a proxy account that xp_cmdshell will be run under using sp_xp_cmdshell_proxy_account
EXEC sp_xp_cmdshell_proxy_account 'Domain\TestUser', 'pwd'
-- Note: pwd means windows password for [Domain\TestUser] account id on the box.
-- Don't include square brackets around Domain\TestUser.
(5) Grant control server permission to user
USE master;
GRANT CONTROL SERVER TO [Domain\TestUser]
GO
For me, I usually use DataContext
together in order to bind two-depth property such as this question.
<TextBlock DataContext="{Binding SelectedRule}" Text="{Binding Name}" />
Or, I prefer to use ElementName
because it achieves bindings only with view controls.
<TextBlock DataContext="{Binding ElementName=lbRules, Path=SelectedItem}" Text="{Binding Name}" />
Ctrl+3 in SQL Server 2012. Might work in 2008 too
Simply put, you are doing this completely backward.
You should not be approaching this from what URLs you should be using. The URLs will effectively come "for free" once you've decided upon what resources are necessary for your system AND how you will represent those resources, and the interactions between the resources and application state.
To quote Roy Fielding
A REST API should spend almost all of its descriptive effort in defining the media type(s) used for representing resources and driving application state, or in defining extended relation names and/or hypertext-enabled mark-up for existing standard media types. Any effort spent describing what methods to use on what URIs of interest should be entirely defined within the scope of the processing rules for a media type (and, in most cases, already defined by existing media types). [Failure here implies that out-of-band information is driving interaction instead of hypertext.]
Folks always start with the URIs and think this is the solution, and then they tend to miss a key concept in REST architecture, notably, as quoted above, "Failure here implies that out-of-band information is driving interaction instead of hypertext."
To be honest, many see a bunch of URIs and some GETs and PUTs and POSTs and think REST is easy. REST is not easy. RPC over HTTP is easy, moving blobs of data back and forth proxied through HTTP payloads is easy. REST, however, goes beyond that. REST is protocol agnostic. HTTP is just very popular and apt for REST systems.
REST lives in the media types, their definitions, and how the application drives the actions available to those resources via hypertext (links, effectively).
There are different view about media types in REST systems. Some favor application specific payloads, while others like uplifting existing media types in to roles that are appropriate for the application. For example, on the one hand you have specific XML schemas designed suited to your application versus using something like XHTML as your representation, perhaps through microformats and other mechanisms.
Both approaches have their place, I think, the XHTML working very well in scenarios that overlap both the human driven and machine driven web, whereas the former, more specific data types I feel better facilitate machine to machine interactions. I find the uplifting of commodity formats can make content negotiation potentially difficult. "application/xml+yourresource" is much more specific as a media type than "application/xhtml+xml", as the latter can apply to many payloads which may or may not be something a machine client is actually interested in, nor can it determine without introspection.
However, XHTML works very well (obviously) in the human web where web browsers and rendering is very important.
You application will guide you in those kinds of decisions.
Part of the process of designing a REST system is discovering the first class resources in your system, along with the derivative, support resources necessary to support the operations on the primary resources. Once the resources are discovered, then the representation of those resources, as well as the state diagrams showing resource flow via hypertext within the representations because the next challenge.
Recall that each representation of a resource, in a hypertext system, combines both the actual resource representation along with the state transitions available to the resource. Consider each resource a node in a graph, with the links being the lines leaving that node to other states. These links inform clients not only what can be done, but what is required for them to be done (as a good link combines the URI and the media type required).
For example, you may have:
<link href="http://example.com/users" rel="users" type="application/xml+usercollection"/>
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
Your documentation will talk about the rel field named "users", and the media type of "application/xml+youruser".
These links may seem redundant, they're all talking to the same URI, pretty much. But they're not.
This is because for the "users" relation, that link is talking about the collection of users, and you can use the uniform interface to work with the collection (GET to retrieve all of them, DELETE to delete all of them, etc.)
If you POST to this URL, you will need to pass a "application/xml+usercollection" document, which will probably only contain a single user instance within the document so you can add the user, or not, perhaps, to add several at once. Perhaps your documentation will suggest that you can simply pass a single user type, instead of the collection.
You can see what the application requires in order to perform a search, as defined by the "search" link and it's mediatype. The documentation for the search media type will tell you how this behaves, and what to expect as results.
The takeaway here, though, is the URIs themselves are basically unimportant. The application is in control of the URIs, not the clients. Beyond a few 'entry points', your clients should rely on the URIs provided by the application for its work.
The client needs to know how to manipulate and interpret the media types, but doesn't much need to care where it goes.
These two links are semantically identical in a clients eyes:
<link href="http://example.com/users?search" rel="search" type="application/xml+usersearchcriteria"/>
<link href="http://example.com/AW163FH87SGV" rel="search" type="application/xml+usersearchcriteria"/>
So, focus on your resources. Focus on their state transitions in the application and how that's best achieved.
In App.config:
<add key="YOURKEY" value="a,b,c"/>
In C#:
string[] InFormOfStringArray = ConfigurationManager.AppSettings["YOURKEY"].Split(',').Select(s => s.Trim()).ToArray();
List<string> list = new List<string>(InFormOfStringArray);
You can use Microsoft's row_number() function to decide which rows to return. That means that you aren't limited to just the top X results, you can take pages.
SELECT *
FROM (SELECT row_number() over (order by UserID) AS line_no, *
FROM dbo.User) as users
WHERE users.line_no < 10
OR users.line_no BETWEEN 34 and 67
You have to nest the original query though, because otherwise you'll get an error message telling you that you can't do what you want to in the way you probably should be able to in an ideal world.
Msg 4108, Level 15, State 1, Line 3
Windowed functions can only appear in the SELECT or ORDER BY clauses.
I had the same error and SOLVED by removing the DB roles db_denydatawriter
and db_denydatreader
of the DB user. For that, select the appropriate DB user on logins >> properties >> user mappings >> find out DB and select it >> uncheck the mentioned Db user roles. Thats it !!
i suggest using phpmyadmin
it’s definitely the best free tool out there and it works on every system with php+mysql
If you are use sqljdbc4.jar, use the following code
ResultSet objResultSet = objPreparedStatement.getResultSet();
if (objResultSet == null) {
boolean bResult = false;
while (!bResult){
if (objPreparedStatement.getMoreResults()){
objResultSet = objPreparedStatement.getResultSet();
bResult = true;
}
}
}
objCachedRowSet = new CachedRowSetImpl();
objCachedRowSet.populate(objResultSet);
if (CommonUtility.isValidObject(objResultSet)) objResultSet.close();
objResultSet = null;
A interesting writeup on the logical differences: SQL Server: JOIN vs IN vs EXISTS - the logical difference
I am pretty sure that assuming that the relations and indexes are maintained a Join will perform better overall (more effort goes into working with that operation then others). If you think about it conceptually then its the difference between 2 queries and 1 query.
You need to hook it up to the Query Analyzer and try it and see the difference. Also look at the Query Execution Plan and try to minimize steps.
UPDATE MyTable SET MyDate = CONVERT(datetime, '2009/07/16 08:28:01', 120)
For a full discussion of CAST and CONVERT, including the different date formatting options, see the MSDN Library Link below:
https://docs.microsoft.com/en-us/sql/t-sql/functions/cast-and-convert-transact-sql
You could try something like this:
...Binding="{Binding RelativeSource={RelativeSource FindAncestor,
AncestorType={x:Type Window}}, Path=DataContext.AllowItemCommand}" ...
check this image link for all steps https://drive.google.com/open?id=0B0-Ll2y6vo_sQ29hYndnbGZVZms
STEP1: I created a field of type varbinary in table
STEP2: I created a stored procedure to accept a parameter of type sql_variant
STEP3: In my front end asp.net page, I created a sql data source parameter of object type
<tr>
<td>
UPLOAD DOCUMENT</td>
<td>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" runat="server" Text="Upload" />
<asp:SqlDataSource ID="sqldsFileUploadConn" runat="server"
ConnectionString="<%$ ConnectionStrings: %>"
InsertCommand="ph_SaveDocument"
InsertCommandType="StoredProcedure">
<InsertParameters>
<asp:Parameter Name="DocBinaryForm" Type="Object" />
</InsertParameters>
</asp:SqlDataSource>
</td>
<td>
</td>
</tr>
STEP 4: In my code behind, I try to upload the FileBytes from FileUpload Control via this stored procedure call using a sql data source control
Dim filebytes As Object
filebytes = FileUpload1.FileBytes()
sqldsFileUploadConn.InsertParameters("DocBinaryForm").DefaultValue = filebytes.ToString
Dim uploadstatus As Int16 = sqldsFileUploadConn.Insert()
' ... code continues ... '
Given an object which I suspect to be some kind of IList<>
, how can I determine of what it's an IList<>
?
Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.
/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
Contract.Requires(type != null);
var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);
innerType = interfaceTest(type);
if (innerType != null)
{
return true;
}
foreach (var i in type.GetInterfaces())
{
innerType = interfaceTest(i);
if (innerType != null)
{
return true;
}
}
return false;
}
Example usage:
object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();
Returns
True
typeof(Int32)
In MySQL, @variable
indicates a user-defined variable. You can define your own.
SET @a = 'test';
SELECT @a;
Outside of stored programs, a variable
, without @
, is a system variable, which you cannot define yourself.
The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.
This is in contrast with MSSQL, where the variable will only be available in the current batch of queries (stored procedure, script, or otherwise). It will not be available in a different batch in the same session.
For Oracle, I highly recommend the free Oracle SQL Developer
http://www.oracle.com/technology/products/database/sql_developer/index.html
The doucmentation states it also works with non-oracle databases - i've never tried that feature myself, but I do know that it works really well with Oracle
After studying the Internet for a day I found my own solution for selecting an item after create a normal treeview in a normal WPF/C# environment
private void BuildSortTree(int sel)
{
MergeSort.Items.Clear();
TreeViewItem itTemp = new TreeViewItem();
itTemp.Header = SortList[0];
MergeSort.Items.Add(itTemp);
TreeViewItem prev;
itTemp.IsExpanded = true;
if (0 == sel) itTemp.IsSelected= true;
prev = itTemp;
for(int i = 1; i<SortList.Count; i++)
{
TreeViewItem itTempNEW = new TreeViewItem();
itTempNEW.Header = SortList[i];
prev.Items.Add(itTempNEW);
itTempNEW.IsExpanded = true;
if (i == sel) itTempNEW.IsSelected = true;
prev = itTempNEW ;
}
}
We worked around this limitation by adding a simple IF statement in the stored procedure. Practically we pass an empty string whenever we want to save the default value in the DB.
CREATE DEFINER=`test`@`%` PROCEDURE `myProc`(IN myVarParam VARCHAR(40))
BEGIN
IF myVarParam = '' THEN SET myVarParam = 'default-value'; END IF;
...your code here...
END
I think this should work...
var query = from m in context.MyTable
where m.MyContainerId == '1' // or what ever the foreign key name is...
select m;
var count = query.Count();
For all those recommending using table variables, be cautious in doing so. Table variable cannot be indexed whereas a temp table can be. A table variable is best when working with small amounts of data but if you are working on larger sets of data (e.g. 50k records) a temp table will be much faster than a table variable.
Also keep in mind that you can't rely on a try/catch to force a cleanup within the stored procedure. certain types of failures cannot be caught within a try/catch (e.g. compile failures due to delayed name resolution) if you want to be really certain you may need to create a wrapper stored procedure that can do a try/catch of the worker stored procedure and do the cleanup there.
e.g. create proc worker AS BEGIN -- do something here END
create proc wrapper AS
BEGIN
Create table #...
BEGIN TRY
exec worker
exec worker2 -- using same temp table
-- etc
END TRY
END CATCH
-- handle transaction cleanup here
drop table #...
END CATCH
END
One place where table variables are always useful is they do not get rolled back when a transaction is rolled back. This can be useful for capturing debug data that you want to commit outside the primary transaction.
I'm sure this is a duplicate, but I can't find a question with the same answer.
Add HorizontalContentAlignment="Stretch"
to your ListBox. That should do the trick. Just be careful with auto-complete because it is so easy to get HorizontalAlignment
by mistake.
For what it is worth, an additional consideration when using .NET 4.0 is that if a valid endpoint is not found in your configuration, a default endpoint will be automatically created and used.
The default endpoint will use all default values so if you think you have a valid service configuration with a large value for maxReceivedMessageSize etc., but there is something wrong with the configuration, you would still get the 400 Bad Request since a default endpoint would be created and used.
This is done silently so it is hard to detect. You will see messages to this effect (e.g. 'No Endpoint found for Service, creating Default Endpoint' or similar) if you turn on tracing on the server but there is no other indication (to my knowledge).
I encountered this error in another situation. I tried to defined a style for TreeViewItems directly within the <TreeView>
, but instead should have embedded that within <TreeView.ItemContainerStyle>
.
Wrong:
<TreeView ItemsSource="{Binding ExampleListView}">
<Style TargetType="{x:Type TreeViewItem}">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
...
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Correct:
<TreeView ItemsSource="{Binding ExampleListView}">
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}"/>
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}"/>
</Style>
</TreeView.ItemContainerStyle>
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding SubItemListList}">
...
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
Put the DataGrid
in a Grid
, DockPanel
, ContentControl
or directly in the Window
. A vertically-oriented StackPanel
will give its children whatever vertical space they ask for - even if that means it is rendered out of view.
I solved the problem by adding dispatcher in UserControl_Loaded event
Dispatcher.BeginInvoke(DispatcherPriority.Loaded, new Action(() =>
{
combobox.SelectedIndex = 0;
}));
SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()
That said, everybody seems to come to this page for the more general answer to your question:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
SELECT TOP 1 column FROM table
ORDER BY NEWID()
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
SELECT column FROM table
ORDER BY RANDOM() LIMIT 1
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.
Have you set the DataContext to your ConnectionViewModel object?
I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.
Here is my XAML content:
<Window x:Class="WpfApplication6.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel>
<Button Click="Button_Click">asdf</Button>
<ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
DisplayMemberPath="Name"
SelectedValuePath="Name"
SelectedValue="{Binding Path=PhonebookEntry}" />
</StackPanel>
</Grid>
</Window>
And here is my code-behind:
namespace WpfApplication6
{
/// <summary>
/// Interaction logic for Window1.xaml
/// </summary>
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
ConnectionViewModel vm = new ConnectionViewModel();
DataContext = vm;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
((ConnectionViewModel)DataContext).PhonebookEntry = "test";
}
}
public class PhoneBookEntry
{
public string Name { get; set; }
public PhoneBookEntry(string name)
{
Name = name;
}
public override string ToString()
{
return Name;
}
}
public class ConnectionViewModel : INotifyPropertyChanged
{
public ConnectionViewModel()
{
IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
list.Add(new PhoneBookEntry("test"));
list.Add(new PhoneBookEntry("test2"));
_phonebookEntries = new CollectionView(list);
}
private readonly CollectionView _phonebookEntries;
private string _phonebookEntry;
public CollectionView PhonebookEntries
{
get { return _phonebookEntries; }
}
public string PhonebookEntry
{
get { return _phonebookEntry; }
set
{
if (_phonebookEntry == value) return;
_phonebookEntry = value;
OnPropertyChanged("PhonebookEntry");
}
}
private void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.
Maybe there is an issue with the CollectionView? I noticed a warning in the output console:
System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.
Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.
I liked user1333423's solution except that it always re-sized every column; i needed to allow some columns to be fixed width. So in this version columns with a width set to "Auto" will be auto-sized and those set to a fixed amount will not be auto-sized.
public class AutoSizedGridView : GridView
{
HashSet<int> _autoWidthColumns;
protected override void PrepareItem(ListViewItem item)
{
if (_autoWidthColumns == null)
{
_autoWidthColumns = new HashSet<int>();
foreach (var column in Columns)
{
if(double.IsNaN(column.Width))
_autoWidthColumns.Add(column.GetHashCode());
}
}
foreach (GridViewColumn column in Columns)
{
if (_autoWidthColumns.Contains(column.GetHashCode()))
{
if (double.IsNaN(column.Width))
column.Width = column.ActualWidth;
column.Width = double.NaN;
}
}
base.PrepareItem(item);
}
}
You can start with a custom number and increment from there, for example you want to add a cheque number for each payment you can do:
select @StartChequeNumber = 3446;
SELECT
((ROW_NUMBER() OVER(ORDER BY AnyColumn)) + @StartChequeNumber ) AS 'ChequeNumber'
,* FROM YourTable
will give the correct cheque number for each row.
I had a similar incident with stopping a log shipping secondary server. After the command to remove the server from log shipping and stopped the log shipping from primary server the database on secondary server got stuck in restoring status after the command
RESTORE DATABASE <database name> WITH RECOVERY
The database messages:
RESTORE DATABASE successfully processed 0 pages in 18.530 seconds (0.000 MB/sec).
The database was usable again after those 18 seconds.
I was having the same problem, I had a ComboBox followed by a ListBox in a StackPanel and the scroll bar for the ListBox was not showing up. I solved this by putting the two in a DockPanel instead. I set the ComboBox DockPanel.Dock="Top" and let the ListBox fill the remaining space.
"Therefore it's reasonable to assume much space should now be retrievable."
Apologies if I misunderstood the question, but are you sure it's the database and not the log files that are using up the space? Check to see what recovery model the database is in. Chances are it's in Full, which means the log file is never truncated. If you don't need a complete record of every transaction, you should be able to change to Simple, which will truncate the logs. You can shrink the database during the process. Assuming things go right, the process looks like:
If that doesn't work (or you get a message saying "log file is full" when you try to switch recovery modes), try this:
etc.
This works for me on the Northwind sample DB, note that SearchLetter has 2 characters to it and SearchLetter also has to be declared for this to run:
declare @SearchLetter2 char(2)
declare @SearchLetter char(1)
Set @SearchLetter = 'A'
Set @SearchLetter2 = @SearchLetter+'%'
select * from Customers where ContactName like @SearchLetter2 and Region='WY'
var.connectionstring = "server=localhost; database=dbname; integrated security=yes"
or
var.connectionstring = "server=localhost; database=dbname; login=yourlogin; pwd=yourpass"
IIRC the tables you need are DBA_TABLES, DBA_EXTENTS or DBA_SEGMENTS and DBA_DATA_FILES. There are also USER_ and ALL_ versions of these for tables you can see if you don't have administration permissions on the machine.
I write the following ways and tried to parameterized them, so you can Run them in a Query document
Or Make a useful SP
with them easily.
If your table has not millions of records this works good and hasn't any Alter commands:
---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb' --< Db Name
DECLARE @Schema AS NVARCHAR(30) = 'dbo' --< Schema
DECLARE @TableName AS NVARCHAR(30) = 'Book' --< Table Name
------------------ /Just Fill Parameters Value ----------------
DECLARE @Query AS NVARCHAR(500) = 'Delete FROM ' + @TableName
EXECUTE sp_executesql @Query
SET @Query=@DbName+'.'+@Schema+'.'+@TableName
DBCC CHECKIDENT (@Query,RESEED, 0)
- In above answer of mine the method of resolve the mentioned problem in the question is based on @s15199d answer.
If your table has millions of records or you hasn't any problem with Alter command in your codes, then use this one:
-- Book Student
--
-- | BookId | Field1 | | StudentId | BookId |
-- --------------------- ------------------------
-- | 1 | A | | 2 | 1 |
-- | 2 | B | | 1 | 1 |
-- | 3 | C | | 2 | 3 |
---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb'
DECLARE @Schema AS NVARCHAR(30) = 'dbo'
DECLARE @TableName_ToTruncate AS NVARCHAR(30) = 'Book'
DECLARE @TableName_OfOwnerOfConstraint AS NVARCHAR(30) = 'Student' --< Decelations About FK_Book_Constraint
DECLARE @Ref_ColumnName_In_TableName_ToTruncate AS NVARCHAR(30) = 'BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ColumnName_In_TableOfOwnerOfConstraint AS NVARCHAR(30) = 'Fk_BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ConstraintName AS NVARCHAR(30) = 'FK_Book_Constraint' --< Decelations About FK_Book_Constraint
------------------ /Just Fill Parameters Value ----------------
DECLARE @Query AS NVARCHAR(2000)
SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' DROP CONSTRAINT '+@FK_ConstraintName
EXECUTE sp_executesql @Query
SET @Query= 'Truncate Table '+ @TableName_ToTruncate
EXECUTE sp_executesql @Query
SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' ADD CONSTRAINT '+@FK_ConstraintName+' FOREIGN KEY('+@FK_ColumnName_In_TableOfOwnerOfConstraint+') REFERENCES '+@TableName_ToTruncate+'('+@Ref_ColumnName_In_TableName_ToTruncate+')'
EXECUTE sp_executesql @Query
In above answer of mine the method of resolve the mentioned problem in the question is based on @LauroWolffValenteSobrinho answer.
If you have more than one CONSTRAINT then you should append its codes like me to the above query
Also you can change the above code base @SerjSagan answer to disable an enable the constraint
For reference from SQL Server 2016 SP1+
you could use CREATE OR ALTER VIEW
syntax.
CREATE [ OR ALTER ] VIEW [ schema_name . ] view_name [ (column [ ,...n ] ) ] [ WITH <view_attribute> [ ,...n ] ] AS select_statement [ WITH CHECK OPTION ] [ ; ]
OR ALTER
Conditionally alters the view only if it already exists.
being a newbie here i can't yet directly comment but here is a small correction i'd like to add to the following part of ??O?????'s answer :
If you prefer full pathnames, then use this function:
def listdirs(folder): return [ d for d in (os.path.join(folder, d1) for d1 in os.listdir(folder)) if os.path.isdir(d) ]
for those still on python < 2.4: the inner construct needs to be a list instead of a tuple and therefore should read like this:
def listdirs(folder):
return [
d for d in [os.path.join(folder, d1) for d1 in os.listdir(folder)]
if os.path.isdir(d)
]
otherwise one gets a syntax error.
If you are working with SQL Server 2005 or later there is also a CLR library available at http://www.sqlsharp.com/ that provides .NET implementations of string and RegEx functions which, depending on your volume and type of data may be easier to use and in some cases the .NET string manipulation functions can be more efficient than T-SQL ones.
you can consider something like that:
define a style for textblock, or any other control you want to use to display your enum:
<Style x:Key="enumStyle" TargetType="{x:Type TextBlock}">
<Setter Property="Text" Value="<NULL>"/>
<Style.Triggers>
<Trigger Property="Tag">
<Trigger.Value>
<proj:YourEnum>Value1<proj:YourEnum>
</Trigger.Value>
<Setter Property="Text" Value="{DynamicResource yourFriendlyValue1}"/>
</Trigger>
<!-- add more triggers here to reflect your enum -->
</Style.Triggers>
</Style>
define your style for ComboBoxItem
<Style TargetType="{x:Type ComboBoxItem}">
<Setter Property="ContentTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Tag="{Binding}" Style="{StaticResource enumStyle}"/>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
add a combobox and load it with your enum values:
<ComboBox SelectedValue="{Binding Path=your property goes here}" SelectedValuePath="Content">
<ComboBox.Items>
<ComboBoxItem>
<proj:YourEnum>Value1</proj:YourEnum>
</ComboBoxItem>
</ComboBox.Items>
</ComboBox>
if your enum is large, you can of course do the same in code, sparing a lot of typing. i like that approach, since it makes localization easy - you define all the templates once, and then, you only update your string resource files.
EXEC sp_helplogins
You can also pass an "@LoginNamePattern" parameter to get information about a specific login:
EXEC sp_helplogins @LoginNamePattern='fred'
Just compare the year, month and day values.
Declare @DateToSearch DateTime
Set @DateToSearch = '14 AUG 2008'
SELECT *
FROM table1
WHERE Year(column_datetime) = Year(@DateToSearch)
AND Month(column_datetime) = Month(@DateToSearch)
AND Day(column_datetime) = Day(@DateToSearch)
If you can move to SQL Server 2008, you can take advantage of the FILESTREAM support which gives you the best of both - the files are stored in the filesystem, but the database integration is much better than just storing a filepath in a varchar field. Your query can return a standard .NET file stream, which makes the integration a lot simpler.
As also noted in the docs here.
Go to Python X.X/Lib
and add these lines to the site.py
there,
import sys
sys.path.append("yourpathstring")
This changes your sys.path
so that on every load, it will have that value in it..
As stated here about site.py
,
This module is automatically imported during initialization. Importing this module will append site-specific paths to the module search path and add a few builtins.
For other possible methods of adding some path to sys.path
see these docs
If you want to add a query parameter after you have created the request, try casting the HttpRequest
to a HttpBaseRequest
. Then you can change the URI of the casted request:
HttpGet someHttpGet = new HttpGet("http://google.de");
URI uri = new URIBuilder(someHttpGet.getURI()).addParameter("q",
"That was easy!").build();
((HttpRequestBase) someHttpGet).setURI(uri);
Problem is that while runtime generic type is erased so new E[10]
would be equivalent to new Object[10]
.
This would be dangerous because it would be possible to put in array other data than of E
type. That is why you need to explicitly say that type you want by either
E[]
array, or componentType
argiment.Easier with inline coding
<button type="button" ng-click="showmore = (showmore !=null && showmore) ? false : true;" class="btn float-right" data-toggle="collapse" data-target="#moreoptions">
<span class="glyphicon" ng-class="showmore ? 'glyphicon-collapse-up': 'glyphicon-collapse-down'"></span>
{{ showmore !=null && showmore ? "Hide More Options" : "Show More Options" }}
</button>
<div id="moreoptions" class="collapse">Your Panel</div>
It depends on what function you want to run. If you need something done on server side, like querying a database or setting something in the session or anything that can not be done on client side, you need AJAX, else you can do it on client-side with JavaScript. Don't make the server work when you can do what you need to do on client side.
jQuery provides an easy way to do ajax : http://api.jquery.com/jQuery.ajax/
I had a similar problem last week. I received a number of CSV files with varying encodings. Before importing into the database I then used the chardet libary to automatically sniff out the correct encoding.
Chardet is a port from Mozillas character detection engine and if the sample size is large enough (one accentuated character will not do) works really well.
That directory is part of your user data and you can delete any user data without affecting Xcode seriously. You can delete the whole CoreSimulator/ directory. Xcode will recreate fresh instances there for you when you do your next simulator run. If you can afford losing any previous simulator data of your apps this is the easy way to get space.
Update: A related useful app is "DevCleaner for Xcode" https://apps.apple.com/app/devcleaner-for-xcode/id1388020431
I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:
SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;
Thanks for answering, it helped my train of thought.
I made a little change on the script.
DECLARE @collate nvarchar(100);
DECLARE @table sysname;
DECLARE @schema sysname;
DECLARE @objectId int;
DECLARE @column_name nvarchar(255);
DECLARE @column_id int;
DECLARE @data_type nvarchar(255);
DECLARE @max_length int;
DECLARE @row_id int;
DECLARE @sql nvarchar(max);
DECLARE @sql_column nvarchar(max);
DECLARE @is_Nullable bit;
DECLARE @null nvarchar(25);
SET @collate = 'Latin1_General_CI_AS';
DECLARE local_table_cursor CURSOR FOR
SELECT tbl.TABLE_SCHEMA,[name],obj.id
FROM sysobjects as obj
inner join INFORMATION_SCHEMA.TABLES as tbl
on obj.name = tbl.TABLE_NAME
WHERE OBJECTPROPERTY(obj.id, N'IsUserTable') = 1
OPEN local_table_cursor
FETCH NEXT FROM local_table_cursor
INTO @schema, @table, @objectId;
WHILE @@FETCH_STATUS = 0
BEGIN
DECLARE local_change_cursor CURSOR FOR
SELECT ROW_NUMBER() OVER (ORDER BY c.column_id) AS row_id
, c.name column_name
, t.Name data_type
, c.max_length
, c.column_id
, c.is_nullable
FROM sys.columns c
JOIN sys.types t ON c.system_type_id = t.system_type_id
LEFT OUTER JOIN sys.index_columns ic ON ic.object_id = c.object_id AND ic.column_id = c.column_id
LEFT OUTER JOIN sys.indexes i ON ic.object_id = i.object_id AND ic.index_id = i.index_id
WHERE c.object_id = @objectId
ORDER BY c.column_id
OPEN local_change_cursor
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_nullable
WHILE @@FETCH_STATUS = 0
BEGIN
IF (@max_length = -1) SET @max_length = 4000;
set @null=' NOT NULL'
if (@is_nullable = 1) Set @null=' NULL'
if (@Data_type='nvarchar') set @max_length=cast(@max_length/2 as bigint)
IF (@data_type LIKE '%char%')
BEGIN TRY
SET @sql = 'ALTER TABLE ' + @schema + '.' + @table + ' ALTER COLUMN [' + rtrim(@column_name) + '] ' + @data_type + '(' + CAST(@max_length AS nvarchar(100)) + ') COLLATE ' + @collate + @null
PRINT @sql
EXEC sp_executesql @sql
END TRY
BEGIN CATCH
PRINT 'ERROR: Some index or contraint rely on the column ' + @column_name + '. No conversion possible.'
PRINT @sql
END CATCH
FETCH NEXT FROM local_change_cursor
INTO @row_id, @column_name, @data_type, @max_length, @column_id, @is_Nullable
END
CLOSE local_change_cursor
DEALLOCATE local_change_cursor
FETCH NEXT FROM local_table_cursor
INTO @schema,@table,@objectId
END
CLOSE local_table_cursor
DEALLOCATE local_table_cursor
GO
To convert a Decimal to scientific notation without needing to specify the precision in the format string, and without including trailing zeros, I'm currently using
def sci_str(dec):
return ('{:.' + str(len(dec.normalize().as_tuple().digits) - 1) + 'E}').format(dec)
print( sci_str( Decimal('123.456000') ) ) # 1.23456E+2
To keep any trailing zeros, just remove the normalize()
.
If the IUSR user is already specified in Authentication and you're still getting this issue, it could be that your Directory Listing isn't enabled. Be sure to check that. That was the case for me.
In IE11 we can change user agent to IE10, IE9 and even as windows phone. It is really good
The DateTime.Now
property returns the current date and time, for example 2011-07-01 10:09.45310
.
The DateTime.Today
property returns the current date with the time compnents set to zero, for example 2011-07-01 00:00.00000
.
The DateTime.Today
property actually is implemented to return DateTime.Now.Date
:
public static DateTime Today {
get {
DateTime now = DateTime.Now;
return now.Date;
}
}
Scroll down on that page and you'll see:
Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.
That's the SQLEXPRWT_x64_ENU.exe
download.... (WT = with tools)
Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.
That's the SQLEXPRADV_x64_ENU.exe
download ... (ADV = Advanced Services)
The SQLEXPR_x64_ENU.exe
file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.
In matrix multiplication there are 3 for loop, we are using since execution of each for loop requires time complexity O(n)
. So for three loops it becomes O(n^3)
Download source code from here (Open Pdf from url in Android Programmatically)
MainActivity.java
package com.deepshikha.openpdf;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
WebView webview;
ProgressBar progressbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView)findViewById(R.id.webview);
progressbar = (ProgressBar) findViewById(R.id.progressbar);
webview.getSettings().setJavaScriptEnabled(true);
String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);
webview.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
progressbar.setVisibility(View.GONE);
}
});
}
}
Thanks!
I resolve the problem. It's very simple . if do you checking care the problem may be because the auxiliar variable has whitespace. Why ? I don't know but yus must use the trim() method and will resolve the problem
Give the div a fixed height and srcoll:hidden; and on hover change the scroll to auto;
#test_scroll{ height:300px; overflow:hidden;}
#test_scroll:hover{overflow-y:auto;}
Here is an example. http://jsfiddle.net/Lywpk/
Ok it's very easy actually to solve this...most of you who are presented with this problem probably don't even realize you don't have the full software yet installed :) I tried looking online with little success except some1 mentioned you need to look for those services running already. Forexample problem with filezilla you look in task manager for filezilla and you stop the process then you click the X in the xampp control pannel to install filezilla and then click run and it should start the service normally showing you a green lite with a check mark.
Same goes for mysql issues.
As for the apache problem, it usualy is a problem with the port being overtaken by skype or some other program, but you can find info how to solve that on the net easily :)
I had the same error while copying and pasting a comment from the web
For me it was a single quote (') in the word
I just erased it and re-typed it.
HTML:
<div class="foo">
/* whatever is required */
</div>
CSS:
.foo {
top: 0;
transition: top ease 0.5s;
}
.foo:hover{
top: -10px;
}
This is just a basic transition to ease the div tag up by 10px when it is hovered on. The transition property's values can be edited along with the class.hover properties to determine how the transition works.
You need the change those double quotation marks into singles.
ie. if (answer == 'y')
returns true
;
Here is some info on String Literals in C++: http://msdn.microsoft.com/en-us/library/69ze775t%28VS.80%29.aspx
The !important rule is a way to make your CSS cascade but also have the rules you feel are most crucial always be applied. A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.
So, if you have the following:
.class {
color: red !important;
}
.outerClass .class {
color: blue;
}
the rule with the important will be the one applied (not counting specificity)
I believe !important
appeared in CSS1 so every browser supports it (IE4 to IE6 with a partial implementation, IE7+ full)
Also, it's something that you don't want to use pretty often, because if you're working with other people you can override other properties.
None of these answers worked for me. This is how I did it.
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
see Doug Crockford's page on this. You have to do it indirectly with something that can access the scope of the private variable.
another example:
Incrementer = function(init) {
var counter = init || 0; // "counter" is a private variable
this._increment = function() { return counter++; }
this._set = function(x) { counter = x; }
}
Incrementer.prototype.increment = function() { return this._increment(); }
Incrementer.prototype.set = function(x) { return this._set(x); }
use case:
js>i = new Incrementer(100);
[object Object]
js>i.increment()
100
js>i.increment()
101
js>i.increment()
102
js>i.increment()
103
js>i.set(-44)
js>i.increment()
-44
js>i.increment()
-43
js>i.increment()
-42
You don't mention a few important details like:
Here's one possibility:
body,_x000D_
div {_x000D_
margin: 0;_x000D_
border: 0 none;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body,_x000D_
#wrapper,_x000D_
#left,_x000D_
#right {_x000D_
height: 100%;_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#wrapper {_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
width: 960px; // width optional_x000D_
}_x000D_
_x000D_
#left {_x000D_
background: yellow;_x000D_
float: left;_x000D_
width: 360px; // width optional but recommended _x000D_
}_x000D_
_x000D_
#right {_x000D_
background: grey;_x000D_
margin-left: 360px; // must agree with previous width _x000D_
}
_x000D_
<html>_x000D_
<head>_x000D_
<title>Example</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<div id="wrapper">_x000D_
<div id="left">_x000D_
Left_x000D_
</div>_x000D_
_x000D_
<div id="right"></div>_x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
There are many variations on this depending on which columns need to be fixed and which are liquid. You can do this with absolute positioning too but I've generally found better results (particularly in terms of cross-browser) using floats instead.
I found the answer.
Cast integer to string:
myOldIntValue|string
Cast string to integer:
myOldStrValue|int
Also, bear in mind that if you need to export multiple functions at once, like actions you can use
export * from './XThingActions';
New Database Inspector introduced in Android 4.1 Canary 5 Preview where you can now Inspect, query, modify, and debug SQLite databases in your running app directly from the IDE - https://developer.android.com/studio/preview/features?linkId=86173020#database-inspector
Supports database live query as well - https://developer.android.com/studio/preview/features?linkId=86173020#query
If you don't want to change the value of the original variable after passing it into a function, the function should be constructed with a "pass by value" parameter.
Then the function will have ONLY the value but not the address of the passed in variable. Without the variable's address, the code inside the function cannot change the variable value as seen from the outside of the function.
But if you want to give the function the ability to change the value of the variable as seen from the outside, you need to use pass by reference. As both the value and the address (reference) are passed in and available inside the function.
If they are not exactly same (100% same codec, same resolution, same type) MP4 files, then you have to trans-code them into intermediate streams at first:
ffmpeg -i myfile1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp1.ts
ffmpeg -i myfile2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp2.ts
// now join
ffmpeg -i "concat:temp1.ts|temp2.ts" -c copy -bsf:a aac_adtstoasc output.mp4
NOTE!: Output will be like first file ( and not a second one)
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
Throws:
create or replace procedure delete_duplicate_enq as
cursor c1 is
select *
from enquiry;
begin
for z in c1 loop
delete enquiry
where enquiry.enquiryno = z.enquiryno
and rowid > any
(select rowid
from enquiry
where enquiry.enquiryno = z.enquiryno);
end loop;
end delete_duplicate_enq;
Another php solution, but with PDO:
<?php
try {
$pdo = new PDO('mysql:host=localhost;dbname=dbname', 'root', 'password');
echo 'table dbname exists...';
}
catch (PDOException $e) {
die('dbname not found...');
}
I ended up with this slightly different version:
var dirty = false;
window.onbeforeunload = function() {
return dirty ? "If you leave this page you will lose your unsaved changes." : null;
}
Elsewhere I set the dirty flag to true when the form gets dirtied (or I otherwise want to prevent navigating away). This allows me to easily control whether or not the user gets the Confirm Navigation prompt.
With the text in the selected answer you see redundant prompts:
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
I came here from google so it might be relevant to others:
for yarn
you could use:
yarn --cwd /path/to/your/app run start
You may have to perform a diff and put document.getElementById('name')
code inside a condition, in case your component is something like this:
// using the new hooks API
function Comp(props) {
const { isLoading, data } = props;
useEffect(() => {
if (data) {
var name = document.getElementById('name').value;
}
}, [data]) // this diff is necessary
if (isLoading) return <div>isLoading</div>
return (
<div id='name'>Comp</div>
);
}
If diff is not performed then, you will get null
.
If you want to add you custom Overlay screen on Layout, you can create a Custom Linear Layout and get control of drawing and key events. You can my tutorial- Overlay on Android Layout- http://prasanta-paul.blogspot.com/2010/08/overlay-on-android-layout.html
It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:
openssl sha1 [put the full path to the file here without brackets]
For example:
openssl sha1 /Users/me/Desktop/myFile.dmg
If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.
I made an autocomplete directive and uploaded it to GitHub. It should also be able to handle data from an HTTP-Request.
Here's the demo: http://justgoscha.github.io/allmighty-autocomplete/ And here the documentation and repository: https://github.com/JustGoscha/allmighty-autocomplete
So basically you have to return a promise
when you want to get data from an HTTP request, that gets resolved when the data is loaded. Therefore you have to inject the $q
service/directive/controller where you issue your HTTP Request.
Example:
function getMyHttpData(){
var deferred = $q.defer();
$http.jsonp(request).success(function(data){
// the promise gets resolved with the data from HTTP
deferred.resolve(data);
});
// return the promise
return deferred.promise;
}
I hope this helps.
set its position:fixed and bottom:0 so that it will always reside at bottom of your browser windows
Interpreted string literals are character sequences between double quotes "" using the (possibly multi-byte) UTF-8 encoding of individual characters. In UTF-8, ASCII characters are single-byte corresponding to the first 128 Unicode characters. Strings behave like slices of bytes. A rune is an integer value identifying a Unicode code point. Therefore,
package main
import "fmt"
func main() {
fmt.Println(string("Hello"[1])) // ASCII only
fmt.Println(string([]rune("Hello, ??")[1])) // UTF-8
fmt.Println(string([]rune("Hello, ??")[8])) // UTF-8
}
Output:
e
e
?
Read:
Go Programming Language Specification section on Conversions.
Create a linked server to your document
http://www.excel-sql-server.com/excel-import-to-sql-server-using-linked-servers.htm
Then use ordinary INSERT or SELECT INTO. If you want to get fancy, you can use ADO.NET's SqlBulkCopy, which takes just about any data source that you can get a DataReader from and is pretty quick on insert, although the reading of the data won't be esp fast.
You could also take the time to transform an excel spreadsheet into a text delimited file or other bcp supported format and then use BCP.
strings = ("string1", "string2", "string3")
for line in file:
if any(s in line for s in strings):
print "yay!"
From the Rails api on PartialRender:
Rendering the default case
If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.
Examples:
# Instead of <%= render partial: "account" %>
<%= render "account" %>
# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>
# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>
# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>
So, you can use pass a local variable size
to render as follows:
<%= render @users, size: 50 %>
and then use it in the _user.html.erb
partial:
<li>
<%= gravatar_for user, size: size %>
<%= link_to user.name, user %>
</li>
Note that size: size
is equivalent to :size => size
.
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
_x000D_
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
_x000D_
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
_x000D_
The answers here work to open the page in the same browser window/tab.
However, I wanted the page to open in a new window/tab when they click a button. (tab/window decision depends on the user's browser setting)
So here is how it worked to open the page in new tab/window:
<button type="button" onclick="window.open('http://www.example.com/', '_blank');">View Example Page</button>
It doesn't have to be a button, you can use anywhere. Notice the _blank that is used to open in new tab/window.
It couldn't be simpler than this:
public SomeClass Clone () {
var clonedJson = JsonConvert.SerializeObject (this);
return JsonConvert.DeserializeObject<SomeClass> (clonedJson);
}
Just serialize any object to a JSON string and then deserialize it. This will do a deep copy...
I'm facing same problem and so far I found:
new Uri(Request.Url,Request.ApplicationPath)
or
Request.Url.GetLeftPart(UriPartial.Authority)+Request.ApplicationPath
I would suggest using inline CSS styling.
<table border="1" style="padding-right: 10px;">
<tr>
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr style="padding-right: 10px;">
<td>Content</td>
</tr>
</table>
or
<table border="1">
<tr>
<td style="padding-right: 10px;">Content</td>
</tr>
</table>
I don't quite follow what you need, but this is what I would do, assuming I understand you needs.
Nope. No way to do that natively. You're going to have to subclass UIImageView, and add an imageFileName property (which you set when you set the image).
As of 16/9/2020 most of these answers are not too much consistent any way! Try this new npm package
Sequelize-mig
It completed most known problems in sequelize-auto-migrations and its forks and its maintained and documented!
Its used in a way similar to the known one
Install:
npm install sequelize-mig -g / yarn global add sequelize-mig
then use it like this
sequelize-mig migration:make -n <migration name>
I had some difficulty following the most popular answer for my circumstances. For example, my validation was failing with characters such as ;
or [
. I was not interested in white-listing my special characters, so I instead leveraged [^\w\s]
as a test - simply put - match non word characters (including numeric) and non white space characters. To summarize, here is what worked for me...
8
characters1
numeric character1
lowercase letter 1
uppercase letter 1
special character/^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[^\w\s]).{8,}$/
JSFiddle Link - simple demo covering various cases
The following example highlights various advantages of using interpolated strings over string.Format()
as far as cleanliness and readability goes. It also shows that code within {}
gets evaluated like any other function argument, just as it would if string.Format()
we're being called.
using System;
public class Example
{
public static void Main()
{
var name = "Horace";
var age = 34;
// replaces {name} with the value of name, "Horace"
var s1 = $"He asked, \"Is your name {name}?\", but didn't wait for a reply.";
Console.WriteLine(s1);
// as age is an integer, we can use ":D3" to denote that
// it should have leading zeroes and be 3 characters long
// see https://docs.microsoft.com/en-us/dotnet/standard/base-types/how-to-pad-a-number-with-leading-zeros
//
// (age == 1 ? "" : "s") uses the ternary operator to
// decide the value used in the placeholder, the same
// as if it had been placed as an argument of string.Format
//
// finally, it shows that you can actually have quoted strings within strings
// e.g. $"outer { "inner" } string"
var s2 = $"{name} is {age:D3} year{(age == 1 ? "" : "s")} old.";
Console.WriteLine(s2);
}
}
// The example displays the following output:
// He asked, "Is your name Horace?", but didn't wait for a reply.
// Horace is 034 years old.
You need to #include <stdlib.h>
. Otherwise it's defined as int malloc()
which is incompatible with the built-in type void *malloc(size_t)
.
// Prefs.h
extern NSString * const RAHUL;
// Prefs.m
NSString * const RAHUL = @"rahul";
'vb.net
'Extended file stributes
'visual basic .net sample
Dim sFile As Object
Dim oShell = CreateObject("Shell.Application")
Dim oDir = oShell.Namespace("c:\temp")
For i = 0 To 34
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(oDir, i) & vbCrLf
For Each sFile In oDir.Items
TextBox1.Text = TextBox1.Text & oDir.GetDetailsOf(sFile, i) & vbCrLf
Next
TextBox1.Text = TextBox1.Text & vbCrLf
Next
Or you could simply do this:
@foreach(var myItem in Model.Members)
{
<span>@Model.Members.IndexOf(myItem)</span>
}
char * Source = "Hello, world.";
char * ShallowCopy = Source;
char * DeepCopy = new char(strlen(Source)+1);
strcpy(DeepCopy,Source);
'ShallowCopy' points to the same location in memory as 'Source' does. 'DeepCopy' points to a different location in memory, but the contents are the same.
I agree with Charles Duffy that a proper XML parser is the right way to go.
But as to what's wrong with your sed
command (or did you do it on purpose?).
$data
was not quoted, so $data
is subject to shell's word splitting, filename expansion among other things. One of the consequences being that the spacing in the XML snippet is not preserved.So given your specific XML structure, this modified sed
command should work
title=$(sed -ne '/title/{s/.*<title>\(.*\)<\/title>.*/\1/p;q;}' <<< "$data")
Basically for the line that contains title
, extract the text between the tags, then quit (so you don't extract the 2nd <title>
)
You just have to replace the break
with a return
statement.
Think of the code inside the Foreach-Object
as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue
, break
, ...).
Configuring JDKs
Maven
BUT IF you are using maven, provided that you have your latest JRE (Windows/Preferences/Installed JREs) -for example JDK 1.8
You can select the level 1.6, 1.7, 1.8 by configuring the maven-compiler-plugin source and target attributes, like this
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
And ideally, if you have a parent pom, you can do it for all the modules (Eclipse projects) in the parent pom, in one single place.
Source and Target If we want to use the Java 8 language features the –source should be set to 1.8. Also, for the compiled classes to be compatible with JVM 1.8, the –target value should be 1.8.
Updating JRE library that is broken in many projects at once (with Maven)
Rather than updating one by one the JRE library, let Maven do it for you.
Selecting the projects and right-clicking for Maven -> Update Project, will set the system library to the path of the installed JDK, in case the paths are broken (because you installed a new JDK or imported from another computer, etc.) and set the JDK compliance according to the maven source and target setting in the pom.
You can update your Bitbucket credentials from the OSX Keychain.
Updating your cached credentials via the command line:
$ git credential-osxkeychain erase
host=bitbucket.org
protocol=https
[press return]
If it's successful, nothing will print out. To test that it works, try and clone a repository from Bitbucket. If you are prompted for a password, the keychain entry was deleted.
C++11 added alias declarations, which are generalization of typedef
, allowing templates:
template <size_t N>
using Vector = Matrix<N, 1>;
The type Vector<3>
is equivalent to Matrix<3, 1>
.
In C++03, the closest approximation was:
template <size_t N>
struct Vector
{
typedef Matrix<N, 1> type;
};
Here, the type Vector<3>::type
is equivalent to Matrix<3, 1>
.
As ping
works, but telnet
to port 80
does not, the HTTP port 80
is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?).
You need to add some code to your python program, that handles the proxy, like described here:
setVisible(false); //you can't see me!
dispose(); //Destroy the JFrame object
Not too tricky.
To set the font by program, write...
TextView tv7 = new TextView(this);
tv7.setText(" TIME ");
tv7.setTypeface(Typeface.create("sans-serif-condensed",Typeface.BOLD));
tv7.setTextSize(12);
tbrow.addView(tv7);
The name "sans-serif-condensed" is referenced from fonts.xml file which should be created in app--> res--> values folder and it holds the fonts in it.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="font_family_light">sans-serif-light</string>
<string name="font_family_medium">sans-serif-medium</string>
<string name="font_family_regular">sans-serif</string>
<string name="font_family_condensed">sans-serif-condensed</string>
<string name="font_family_black">sans-serif-black</string>
<string name="font_family_thin">sans-serif-thin</string>
</resources>
Hope this is clear!
I m agree with @ReNjITh.R answer but If you want to display error message just beside textbox. Just like below
<html>
<head>
<script type="text/javascript">
function validate()
{
if(myform.fname.value.length==0)
{
document.getElementById('errfn').innerHTML="this is invalid name";
}
}
</script>
</head>
<body>
<form name="myform">
First_Name
<input type=text id=fname name=fname onblur="validate()" /><span id="errfn"></span>
<br> <br>
Last_Name
<input type=text id=lname name=lname onblur="validate()"/><br>
<input type=button value=check />
</form>
</body>
git stash show -p | git apply --reverse
Warning, that would not in every case: "git apply -R
"(man) did not handle patches that touch the same path twice correctly, which has been corrected with Git 2.30 (Q1 2021).
This is most relevant in a patch that changes a path from a regular file to a symbolic link (and vice versa).
See commit b0f266d (20 Oct 2020) by Jonathan Tan (jhowtan
).
(Merged by Junio C Hamano -- gitster
-- in commit c23cd78, 02 Nov 2020)
apply
: when-R
, also reverse list of sectionsHelped-by: Junio C Hamano
Signed-off-by: Jonathan Tan
A patch changing a symlink into a file is written with 2 sections (in the code, represented as "struct patch"): firstly, the deletion of the symlink, and secondly, the creation of the file.
When applying that patch with
-R
, the sections are reversed, so we get: (1) creation of a symlink, then (2) deletion of a file.This causes an issue when the "deletion of a file" section is checked, because Git observes that the so-called file is not a file but a symlink, resulting in a "wrong type" error message.
What we want is: (1) deletion of a file, then (2) creation of a symlink.
In the code, this is reflected in the behavior of
previous_patch()
when invoked fromcheck_preimage()
when the deletion is checked.
Creation then deletion means that when the deletion is checked,previous_patch()
returns the creation section, triggering a mode conflict resulting in the "wrong type" error message.But deletion then creation means that when the deletion is checked,
previous_patch()
returnsNULL
, so the deletion mode is checked against lstat, which is what we want.There are also other ways a patch can contain 2 sections referencing the same file, for example, in 7a07841c0b ("
git-apply
: handle a patch that touches the same path more than once better", 2008-06-27, Git v1.6.0-rc0 -- merge). "git apply -R
"(man) fails in the same way, and this commit makes this case succeed.Therefore, when building the list of sections, build them in reverse order (by adding to the front of the list instead of the back) when
-R
is passed.
I am going to blow everyone's mind right now . . .
Delete all the <assemblyBinding>
references from your .config file, and then run this command from the NuGet Package Manager console:
Get-Project -All | Add-BindingRedirect
IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.
Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.
You need to close all your connexions for example: If you make an INSERT INTO statement you need to close the statement and your connexion in this way:
statement.close();
Connexion.close():
And if you make a SELECT statement you need to close the statement, the connexion and the resultset in this way:
resultset.close();
statement.close();
Connexion.close();
I did this and it worked
I found a way to do it without replacing the slashes
select CONVERT(VARCHAR(10), GETDATE(), 112)
This would return: "YYYYMMDD"
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
About prototype bean(s) :
The client code must clean up prototype-scoped objects and release expensive resources that the prototype bean(s) are holding. To get the Spring container to release resources held by prototype-scoped beans, try using a custom bean post-processor, which holds a reference to beans that need to be cleaned up.
When in trouble what means what:
?%timeit
or ??timeit
To get the details:
Usage, in line mode:
%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
code
code...
Time execution of a Python statement or expression using the timeit
module. This function can be used both as a line and cell magic:
- In line mode you can time a single-line statement (though multiple
ones can be chained with using semicolons).
- In cell mode, the statement in the first line is used as setup code
(executed but not timed) and the body of the cell is timed. The cell
body has access to any variables created in the setup code.
install homebrew via terminal
brew install mysql
I also found that in some cases the reason for 502/400 in case of many headers could be because of a large number of headers without regard to size. from the docs
tune.http.maxhdr Sets the maximum number of headers in a request. When a request comes with a number of headers greater than this value (including the first line), it is rejected with a "400 Bad Request" status code. Similarly, too large responses are blocked with "502 Bad Gateway". The default value is 101, which is enough for all usages, considering that the widely deployed Apache server uses the same limit. It can be useful to push this limit further to temporarily allow a buggy application to work by the time it gets fixed. Keep in mind that each new header consumes 32bits of memory for each session, so don't push this limit too high.
https://cbonte.github.io/haproxy-dconv/configuration-1.5.html#3.2-tune.http.maxhdr
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use different proxy settings to the current user then you would need to code
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
or
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set webRequest.Proxy
or WebRequest.DefaultWebProxy = null
to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy()
with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.
The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.
Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:
Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True
Now it works fine.
Your code returns 0
if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.
>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret
Use the @RequestParam to pass a parameter to the controller handler method.
In the jsp your form should have an input field with name = "id"
like the following:
<input type="text" name="id" />
<input type="submit" />
Then in your controller, your handler method should be like the following:
@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
Person person = personService.getCurrentlyAuthenticatedUser();
model.addAttribute("person", new Person());
model.addAttribute("listPersons", this.personService.listPersons());
model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
return "note";
}
Please also refer to these answers and tutorial:
I was able to quickly fix it by going into Design View of the Form and putting [] around any field names that had spaces. I am now able to use the built in filters without the annoying popup about syntax problems.
it should work fine:
var Something = $(this).children("td:nth-child(n)").text();
Removing an option
$("#val option[value='A']").remove();
this is a mysql function example. I hope it helps. (I have not tested it yet, but should work)
DROP FUNCTION IF EXISTS F_TEST //
CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR
BEGIN
/*DECLARE VALUES YOU MAY NEED, EXAMPLE:
DECLARE NOM_VAR1 DATATYPE [DEFAULT] VALUE;
*/
DECLARE NAME_FOUND VARCHAR DEFAULT "";
SELECT EMPLOYEE_NAME INTO NAME_FOUND FROM TABLE_NAME WHERE ID = PID;
RETURN NAME_FOUND;
END;//
If you wish to use es6 arrow functions you can add a .timeout(ms)
to the end of your it
definition:
it('should not timeout', (done) => {
doLongThing().then(() => {
done();
});
}).timeout(5000);
At least this works in Typescript.
The Fill function uses a DataReader internally. If your consideration is "Which one is more efficient?", then using a DataReader in a tight loop that populates a collection record-by-record, is likely to be the same load on the system as using DataAdapter.Fill.
(System.Data.dll, System.Data.Common.DbDataAdapter, FillInternal.)
A few points:
1) "DataBind()" is only for web apps (not windows apps).
2) Your code looks very 'JAVAish' (not a bad thing, just an observation).
Try this:
mnuActionLanguage.ComboBox.DataSource = languages;
If that doesn't work... then I'm assuming that your datasource is being stepped on somewhere else in the code.
Use this
SELECT *
INTO new_table_name
FROM current_table_name
There are two simplest ways if one does not work please try the other one.
OR
I was going to use clipboard.js, but it doesn't have any mobile solution in place (yet) ... so I wrote a super small library:
This will either copy the text (desktop, Android, and Safari 10+), or at the very least, select the text (older versions of iOS). Minified it is just over 1 kB. In desktop Safari (before version 10) it tells the user to "Press Command + C to copy". You also don't need to write any JavaScript to use it.
The only character that needs escaping is <
. (>
is meaningless outside of a tag).
Therefore, your "magic" code is:
safestring = unsafestring.replace(/</g,'<');
Aircoded (but tested on this fiddle)
(function($) {
function startTrigger(e) {
var $elem = $(this);
$elem.data('mouseheld_timeout', setTimeout(function() {
$elem.trigger('mouseheld');
}, e.data));
}
function stopTrigger() {
var $elem = $(this);
clearTimeout($elem.data('mouseheld_timeout'));
}
var mouseheld = $.event.special.mouseheld = {
setup: function(data) {
// the first binding of a mouseheld event on an element will trigger this
// lets bind our event handlers
var $this = $(this);
$this.bind('mousedown', +data || mouseheld.time, startTrigger);
$this.bind('mouseleave mouseup', stopTrigger);
},
teardown: function() {
var $this = $(this);
$this.unbind('mousedown', startTrigger);
$this.unbind('mouseleave mouseup', stopTrigger);
},
time: 750 // default to 750ms
};
})(jQuery);
// usage
$("div").bind('mouseheld', function(e) {
console.log('Held', e);
})
I have encountered the same problem today and found that beyond that 4000 character limit, I had to split the dynamic query into two strings and concatenate them when executing the query.
DECLARE @Query NVARCHAR(max);
DECLARE @Query2 NVARCHAR(max);
SET @Query = 'SELECT...' -- some of the query gets set here
SET @Query2 = '...' -- more query gets added on, etc.
EXEC (@Query + @Query2)
The easiest way to solve this in pure HTML is to use the <base href="…">
element like so:
<base href="http://localhost/mywebsite/" />
Then all of the URLs in your HTML can just be this:
<a href="images/example.png">Link To Image</a>
Just change the <base href="…">
to match your server. The rest of the HTML paths will just fall in line and will be appended to that.
Mun's answer didn't work for me so I made some changes to that answer to get it to work. Hope this helps someone. Using SQL Server 2012:
SELECT [VehicleID]
, [Name]
, STUFF((SELECT DISTINCT ',' + CONVERT(VARCHAR,City)
FROM [Location]
WHERE (VehicleID = Vehicle.VehicleID)
FOR XML PATH ('')), 1, 2, '') AS Locations
FROM [Vehicle]
Should work.
Here's a working example:
Excerpt:
function loadIframe(iframeName, url) {
var $iframe = $('#' + iframeName);
if ($iframe.length) {
$iframe.attr('src',url);
return false;
}
return true;
}
return (input - 0) == input && input.length > 0;
didn't work for me. When I put in an alert and tested, input.length
was undefined
. I think there is no property to check integer length. So what I did was
var temp = '' + input;
return (input - 0) == input && temp.length > 0;
It worked fine.
Using JavaScript and jQuery:
<script src="js/jquery.js"></script>
...
<video id="vid" width="1280" height="720" src="v/myvideo01.mp4" controls autoplay></video>
...
function chVid(vid) {
$("#vid").attr("src",vid);
}
...
<div onclick="chVid('v/myvideo02.mp4')">See my video #2!</div>
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
def prepare_table_row(row):
lst = [i.text for i in row if i != u'\n']
return dict(rank = int(lst[0]),
grade = str(lst[1]),
channel=str(lst[2])),
videos = float(lst[3].replace(",", " ")),
subscribers = float(lst[4].replace(",", "")),
views = float(lst[5].replace(",", "")))
here is a workable sample cod, considering the image orientation:
#define rad(angle) ((angle) / 180.0 * M_PI)
- (CGAffineTransform)orientationTransformedRectOfImage:(UIImage *)img
{
CGAffineTransform rectTransform;
switch (img.imageOrientation)
{
case UIImageOrientationLeft:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(90)), 0, -img.size.height);
break;
case UIImageOrientationRight:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-90)), -img.size.width, 0);
break;
case UIImageOrientationDown:
rectTransform = CGAffineTransformTranslate(CGAffineTransformMakeRotation(rad(-180)), -img.size.width, -img.size.height);
break;
default:
rectTransform = CGAffineTransformIdentity;
};
return CGAffineTransformScale(rectTransform, img.scale, img.scale);
}
- (UIImage *)croppedImage:(UIImage*)orignialImage InRect:(CGRect)visibleRect{
//transform visible rect to image orientation
CGAffineTransform rectTransform = [self orientationTransformedRectOfImage:orignialImage];
visibleRect = CGRectApplyAffineTransform(visibleRect, rectTransform);
//crop image
CGImageRef imageRef = CGImageCreateWithImageInRect([orignialImage CGImage], visibleRect);
UIImage *result = [UIImage imageWithCGImage:imageRef scale:orignialImage.scale orientation:orignialImage.imageOrientation];
CGImageRelease(imageRef);
return result;
}
they're the same thing with different defaults (private by default for class
, and public by default for struct
), so in theory they're totally interchangeable.
so, if I just want to package some info to move around, I use a struct, even if i put a few methods there (but not many). If it's a mostly-opaque thing, where the main use would be via methods, and not directly to the data members, i use a full class.
Add the Library file in project.. Project->right click->Properties->android->Library-> click Add and select the Library Project and give apply and ok.. then, clean the project and run again.. if you want restart the eclipse..
And also, sometimes, need to update Android SDK build tools..
For someone from internet, there was a similar question https://stackoverflow.com/a/35848666/906265 I do provide the modified answer from it here as well:
// build.gradle
<...>
bootRun {}
// make sure bootRun is executed when this task runs
task runDev(dependsOn:bootRun) {
// TaskExecutionGraph is populated only after
// all the projects in the build have been evaulated https://docs.gradle.org/current/javadoc/org/gradle/api/execution/TaskExecutionGraph.html#whenReady-groovy.lang.Closure-
gradle.taskGraph.whenReady { graph ->
logger.lifecycle('>>> Setting spring.profiles.active to dev')
if (graph.hasTask(runDev)) {
// configure task before it is executed
bootRun {
args = ["--spring.profiles.active=dev"]
}
}
}
}
<...>
then in terminal:
gradle runDev
Have used gradle 3.4.1
and spring boot 1.5.10.RELEASE
Found a very hacky solution to this problem, but it works. I added a class to the link that is used to open the modal (With the data-target), then using Jquery, added a click event to that class that gets the data-target, finds the modal it is supposed to open, and then opens it via Javascript. Works just fine for me. I also added a mobile check on mine so that it only runs on mobile, but that's not required.
$('.forceOpen').click(function() {
var id = $(this).attr('data-target');
$('.modal').modal('hide');
$(id).modal('show');
});
The well-described answer is already there, but I went through this SHORTER recipe:
$ brew install glfw
cd /home/linuxbrew/.linuxbrew/Cellar/glfw/X.X/include
sudo cp -R GLFW /usr/include
Explanation: We manage to build GLFW by CMAKE which is done by Linuxbrew (Linux port of beloved Homebrew). Then copy the header files to where Linux reads from (/usr/include
).
For me it works like this:
options : {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'probability'
}
}]
}
}
The way I do this is to create a remote (bare) repository (on a separate drive, USB Key, backup server or even github) and then use push --mirror
to make that remote repo look exactly like my local one (except the remote is a bare repository).
This will push all refs (branches and tags) including non-fast-forward updates. I use this for creating backups of my local repository.
The man page describes it like this:
Instead of naming each ref to push, specifies that all refs under
$GIT_DIR/refs/
(which includes but is not limited torefs/heads/
,refs/remotes/
, andrefs/tags/
) be mirrored to the remote repository. Newly created local refs will be pushed to the remote end, locally updated refs will be force updated on the remote end, and deleted refs will be removed from the remote end. This is the default if the configuration optionremote.<remote>.mirror
is set.
I made an alias to do the push:
git config --add alias.bak "push --mirror github"
Then, I just run git bak
whenever I want to do a backup.
for this, I have noticed that it far better to show and hide the tags instead of adding and removing them for the DOM. It performs better that way.
Quick summary, you can do either:
Include the JavaFX modules via --module-path
and --add-modules
like in José's answer.
OR
Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java
file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java
file).
This answer is a supplement to Jose's answer.
The situation is this:
IllegalAccessError
involving an "unnamed module" when trying to launch the app.Excerpt for a stack trace generating an IllegalAccessError
when trying to run a JavaFX app from Intellij Idea:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:567)
at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main
OK, now you are kind of stuck and have no clue what is going on.
What has actually happened is this:
So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError
. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).
This is where some of the other answers to this question, which reference module-info.java
, come into the picture.
So let's take a crash course in Java modules:
The key part is this:
4.9. Opens
If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.
But remember, this will open the package up to the entire world, so make sure that is what you want:
module my.module { opens com.my.package; }
So, perhaps you don't want to open your package to the entire world, then you can do:
4.10. Opens … To
Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:
module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }
So, you end up creating a src/main/java/module-info.java class which looks like this:
module org.jewelsea.demo.javafx.springboot {
requires javafx.fxml;
requires javafx.controls;
requires javafx.graphics;
opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}
Where, org.jewelsea.demo.javafx.springboot
is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics
and javafx.fxml
to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot
package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError
generated by JavaFX's use of reflection will no longer occur.
But what if you don't want to create a module-info.java file
If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:
javafx.run
.Run Maven Build
or Debug...
.Then the app will run without the module-info.java
file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java
file, though I don't know how this is accomplished.
To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run
Maven target and choose the option to Create Run/Debug Configuration
for the target. Then you can just choose Run from the top toolbar to execute the Maven target.
$('input[name="mygroup"]').val([5])
I admit that my approach escapes the whole "Code First" concept. But if you have the ability to just change the default value in the table itself... it's much simpler than the lengths that you have to go through above... I'm just too lazy to do all that work!
It almost seems as if the posters original idea would work:
[DefaultValue(true)]
public bool IsAdmin { get; set; }
I thought they just made the mistake of adding quotes... but alas no such intuitiveness. The other suggestions were just too much for me (granted I have the privileges needed to go into the table and make the changes... where not every developer will in every situation). In the end I just did it the old fashioned way. I set the default value in the SQL Server table... I mean really, enough already! NOTE: I further tested doing an add-migration and update-database and the changes stuck.
Everyone who answered before me is correct. You use it kind of as an alias shortcut name for a table when you have long queries or queries that have joins. Here's a couple examples.
Example 1
SELECT P.ProductName,
P.ProductGroup,
P.ProductRetailPrice
FROM Products AS P
Example 2
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products AS P
LEFT OUTER JOIN Orders AS O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Example 3 It's a good practice to use the AS keyword, and very recommended, but it is possible to perform the same query without one (and I do often).
SELECT P.ProductName,
P.ProductRetailPrice,
O.Quantity
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
As you can tell, I left out the AS keyword in the last example. And it can be used as an alias.
Example 4
SELECT P.ProductName AS "Product",
P.ProductRetailPrice AS "Retail Price",
O.Quantity AS "Quantity Ordered"
FROM Products P
LEFT OUTER JOIN Orders O ON O.ProductID = P.ProductID
WHERE O.OrderID = 123456
Output of Example 4
Product Retail Price Quantity Ordered
Blue Raspberry Gum $10 pk/$50 Case 2 Cases
Twizzler $5 pk/$25 Case 10 Cases
Its not really possible to perform a 'mouse hover' action, instead you need to chain all of the actions that you want to achieve in one go. So move to the element that reveals the others, then during the same chain, move to the now revealed element and click on it.
When using Action Chains you have to remember to 'do it like a user would'.
Actions action = new Actions(webdriver);
WebElement we = webdriver.findElement(By.xpath("html/body/div[13]/ul/li[4]/a"));
action.moveToElement(we).moveToElement(webdriver.findElement(By.xpath("/expression-here"))).click().build().perform();
I follwed the same tutorial but after some months I strangely got the error "403 Access Denied" while tryed to use Manager App. In this case I was using the ipaddress:8080 in the address bar and Tomcat Manager App didin't prompting for user/password. In case of localhost:8080 the error was "401", the dialogbox asking for username and password was displayed but the user not recognized.
I tried all the previous suggestions / solutions without lucky. The only way I found is been to repeat again the entire tutorial overwriting also the files. When finished, I found again the old deployed project into the webapps directory. Now Apache Tomcat/8.5.16 Manager App are working again. I do not know what happened I didn't understand also because I'm a newbie in Tomcat user
I've found out that GPS does not need Internet, BUT of course if you need to download maps, you will need a data connection or wifi.
http://androidforums.com/samsung-fascinate/288871-gps-independent-3g-wi-fi.html http://www.droidforums.net/forum/droid-applications/63145-does-google-navigation-gps-requires-3g-work.html
var student = [];
var obj = {
'first_name': name,
'last_name': name,
'age': age,
}
student.push(obj);
Yes, this is related to new updates in safari that are breaking your layout now if you use overflow: hidden to take care of clearing divs.
I don't know if it's the same with other OS, but in OpenBSD, the mail command has this syntax:
mail to-addr ... -sendmail-options ...
sendmail has -f option where you indicate the email address for the FROM: field. The following command works for me.
mail [email protected] -f [email protected]
# Hide grid lines
ax.grid(False)
# Hide axes ticks
ax.set_xticks([])
ax.set_yticks([])
ax.set_zticks([])
Note, you need matplotlib>=1.2 for set_zticks()
to work.
first of all;
a Fragment
must be inside a FragmentActivity
, that's the first rule,
a FragmentActivity
is quite similar to a standart Activity
that you already know, besides having some Fragment oriented methods
second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView
, where you inflate your layout, think of it as the setContentLayout
here is an example:
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mView = inflater.inflate(R.layout.fragment_layout, container, false); return mView; }
and continu your work based on that mView, so to find a View
by id, call mView.findViewById(..);
for the FragmentActivity
part:
the xml part "must" have a FrameLayout
in order to inflate a fragment in it
<FrameLayout android:id="@+id/content_frame" android:layout_width="match_parent" android:layout_height="match_parent" > </FrameLayout>
as for the inflation part
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();
begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site
Ems is a typography term, it controls text size, etc. Check here
string_list = ['A', 'B', 'C', 'B', 'D', 'B']
pos_list = []
for i in range(len(string_list)):
if string_list[i] = ='B':
pos_list.append(i)
print pos_list
What worked for me (with JDK7) was the following:
Alternatively, if you don't want to write to your JDK folder, you could also attach src.zip to (at least) rt.jar in eclipse in the Window | Preferences menu in Java | Installed JREs.
If you're not comfortable with downloading the sources from GrepCode, you could also get them from openJDK directly. This requires requires a bit more effort, though. Replace step one above by the following steps:
A third alternative to acquire src.zip is to download the unofficial OpenJDK builds from here. The src.zip is contained within the downloaded zip.
Best way to solve this as per my opinion is Using "ignoreReadonly".
First make the input field readonly then add ignoreReadonly:true. This will make sure that even if the text field is readonly , popup will show.
$('#txtStartDate').datetimepicker({
locale: "da",
format: "DD/MM/YYYY",
ignoreReadonly: true
});
$('#txtEndDate').datetimepicker({
locale: "da",
useCurrent: false,
format: "DD/MM/YYYY",
ignoreReadonly: true
});
});
maybe I'd go by this.
SQL = SELECT REPLACE(myColumn, '""', '\'') FROM myTable
I used singlequotes because that's the one that registers string expressions in MySQL, or so I believe.
Hope that helps.
suppose ROM is string variable which equals "strval" you can simply do
String value= " \" "+ROM+" \" ";
it will be stored as
value= " "strval" ";
I just went throught same issue and I solved it the following way. 1 - found the .err file which logs all mysql issues, in win7, located under programData\MySQL\MySQL Server 5.6\data\ 2 - Check the last entries from the file and, in my case, I found the error was coming from a flag (audit-log) that I set to "true" from the workbench interface the day before! 3 - went into the my.ini file, and removed audit-log=ON. 4 - launched mysql service and it worked!!
This happened to me. If you are using cocoapods do this:
You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType
value. If I have two rows with the same FruitType
value but different Fruit_Id
values for example, what should the system do?
Select Min(tblFruit_id) As tblFruit_id
, tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType
Using keySet-
id1.keySet().stream()
.filter(x -> x == 1)
.map(x -> id1.get(x))
.collect(Collectors.toList())
Data-dismiss completely removes the element. Use jQuery's .hide() method instead.
The fix-it-quick method:
Using inline javascript to hide the element onclick like this:
<div class="alert" style="display: none">
<a class="close" onclick="$('.alert').hide()">×</a>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
<a href="#" onclick="$('alert').show()">show</a>
This should however only be used if you are lazy (which is no good thing if you want an maintainable app).
The do-it-right method:
Create a new data attribute for hiding an element.
Javascript:
$(function(){
$("[data-hide]").on("click", function(){
$("." + $(this).attr("data-hide")).hide()
// -or-, see below
// $(this).closest("." + $(this).attr("data-hide")).hide()
})
})
and then change data-dismiss to data-hide in the markup. Example at jsfiddle.
$("." + $(this).attr("data-hide")).hide()
This will hide all elements with the class specified in data-hide, i.e: data-hide="alert"
will hide all elements with the alert class.
Xeon06 provided an alternative solution:
$(this).closest("." + $(this).attr("data-hide")).hide()
This will only hide the closest parent element. This is very useful if you don't want to give each alert a unique class. Please note that, however, you need to place the close button within the alert.
Definition of .closest from jquery doc:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
A Context
is:
Try curl -v http://localhost:8080/
instead of 127.0.0.1
Not exactly what you were asking, but you can make action a template member function:
template<typename Subclass>
class A {
public:
//Why doesn't it like this?
template<class V> void action(V var) {
(static_cast<Subclass*>(this))->do_action();
}
};
class B : public A<B> {
public:
typedef int mytype;
B() {}
void do_action(mytype var) {
// Do stuff
}
};
int main(int argc, char** argv) {
B myInstance;
return 0;
}
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
http://php.net/manual/en/language.types.string.php says:
Note: As of PHP 7.0.0, there are no particular restrictions regarding the length of a string on 64-bit builds. On 32-bit builds and in earlier versions, a string can be as large as up to 2GB (2147483647 bytes maximum)
In PHP 5.x, strings were limited to 231-1 bytes, because internal code recorded the length in a signed 32-bit integer.
You can slurp in the contents of an entire file, for instance using file_get_contents()
However, a PHP script has a limit on the total memory it can allocate for all variables in a given script execution, so this effectively places a limit on the length of a single string variable too.
This limit is the memory_limit
directive in the php.ini configuration file. The memory limit defaults to 128MB in PHP 5.2, and 8MB in earlier releases.
If you don't specify a memory limit in your php.ini file, it uses the default, which is compiled into the PHP binary. In theory you can modify the source and rebuild PHP to change this default value.
If you specify -1
as the memory limit in your php.ini file, it stop checking and permits your script to use as much memory as the operating system will allocate. This is still a practical limit, but depends on system resources and architecture.
Re comment from @c2:
Here's a test:
<?php
// limit memory usage to 1MB
ini_set('memory_limit', 1024*1024);
// initially, PHP seems to allocate 768KB for basic operation
printf("memory: %d\n", memory_get_usage(true));
$str = str_repeat('a', 255*1024);
echo "Allocated string of 255KB\n";
// now we have allocated all of the 1MB of memory allowed
printf("memory: %d\n", memory_get_usage(true));
// going over the limit causes a fatal error, so no output follows
$str = str_repeat('a', 256*1024);
echo "Allocated string of 256KB\n";
printf("memory: %d\n", memory_get_usage(true));
Anticipating that I already had the answer, which is that there is no built-in worksheet function that returns the background color of a cell, I decided to review this article, in case I was wrong. I was amused to notice a citation to the very same MVP article that I used in the course of my ongoing research into colors in Microsoft Excel.
While I agree that, in the purest sense, color is not data, it is meta-data, and it has uses as such. To that end, I shall attempt to develop a function that returns the color of a cell. If I succeed, I plan to put it into an add-in, so that I can use it in any workbook, where it will join a growing legion of other functions that I think Microsoft left out of the product.
Regardless, IMO, the ColorIndex property is virtually useless, since there is essentially no connection between color indexes and the colors that can be selected in the standard foreground and background color pickers. See Color Combinations: Working with Colors in Microsoft Office and the associated binary workbook, Color_Combinations Workbook.
I encountered issues where Safari wasn't firing "onchange" events on a text input field. I used a jQuery 1.7.2 "change" event and it didn't work either. I ended up using ZURB's textchange event. It works with mouseevents and can fire without leaving the field:
http://www.zurb.com/playground/jquery-text-change-custom-event
$('.inputClassToBind').bind('textchange', function (event, previousText) {
alert($(this).attr('id'));
});
There is issues with the precision of the accepted answer.
the round(value, decimals) function in this test works. unlike the simple toFixed example.
http://www.jacklmoore.com/notes/rounding-in-javascript/
Number.prototype.format = function(n) {_x000D_
return this.toFixed(Math.max(0, ~~n));_x000D_
};_x000D_
function round(value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);_x000D_
}_x000D_
_x000D_
// can anyone tell me why these are equivalent for 50.005, and 1050.005 through 8150.005 (increments of 50)_x000D_
_x000D_
var round_to = 2;_x000D_
var maxInt = 1500000;_x000D_
var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';_x000D_
var increment = 50;_x000D_
var round_from = 0.005;_x000D_
var expected = 0.01;_x000D_
var lastWasMatch = true;_x000D_
_x000D_
for( var n = 0; n < maxInt; n=n+increment){_x000D_
var data = {};_x000D_
var numberCheck = parseFloat(n + round_from);_x000D_
data.original = numberCheck * 1;_x000D_
data.expected = Number(n + expected) * 1;_x000D_
data.formatIt = Number(numberCheck).format(round_to) * 1;_x000D_
data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;_x000D_
data.numberIt = Number(numberCheck).toFixed(round_to) * 1;_x000D_
//console.log(data);_x000D_
_x000D_
if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||_x000D_
data.roundIt !== data.numberIt || data.roundIt != data.expected_x000D_
){_x000D_
if(lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;_x000D_
document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');_x000D_
document.write('expected: '+data.expected + ' :: ' + (typeof data.expected) + '<br />');_x000D_
document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt) + '<br />');_x000D_
document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt) + '<br />');_x000D_
document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt) + '<br />');_x000D_
lastWasMatch=false;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
} else {_x000D_
if(!lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;_x000D_
} {_x000D_
lastWasMatch=true;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
}_x000D_
}_x000D_
document.write('equalRound: '+equalRound + '</div><br />');
_x000D_
export default {_x000D_
methods: {_x000D_
roundFormat: function (value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);_x000D_
},_x000D_
currencyFormat: function (value, decimals, symbol='$') {_x000D_
return symbol + this.roundFormat(value,2);_x000D_
}_x000D_
}_x000D_
}
_x000D_
BULK INSERT dbo.temp
FROM 'c:\temp\file.txt' --- path file in db server
WITH
(
ROWTERMINATOR ='\n'
)
it work for me but save as by editplus to ansi encoding for multilanguage
If you don't want duplicates in a Collection
, you should consider why you're using a Collection
that allows duplicates. The easiest way to remove repeated elements is to add the contents to a Set
(which will not allow duplicates) and then add the Set
back to the ArrayList
:
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
Of course, this destroys the ordering of the elements in the ArrayList
.
I tried the following; it helped me. I hope it help you also.
cd /c/xampp/your-project
"Slicing" is where you assign an object of a derived class to an instance of a base class, thereby losing part of the information - some of it is "sliced" away.
For example,
class A {
int foo;
};
class B : public A {
int bar;
};
So an object of type B
has two data members, foo
and bar
.
Then if you were to write this:
B b;
A a = b;
Then the information in b
about member bar
is lost in a
.
For the record, to force angular to re-render the current page, you can use:
$route.reload();
According to AngularJS documentation:
Causes $route service to reload the current route even if $location hasn't changed.
As a result of that, ngView creates new scope, reinstantiates the controller.
As other mentioned JSX
is not a standard Javascript extension. It's better to name your entry point of Application based on .js
and for the rest components, you can use .jsx
.
I have an important reason for why I'm using .JSX
for all component's file names.
Actually, In a large scale project with huge bunch of code, if we set all React's component with .jsx
extension, It'll be easier while navigating to different javascript files across the project(like helpers, middleware, etc.) and you know this is a React Component and not other types of the javascript file.
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
You don't need a function for it - simply use the bracket notation:
var side = columns['right'];
This is equal to dot notation, var side = columns.right;
, except the fact that right
could also come from a variable, function return value, etc., when using bracket notation.
If you NEED a function for it, here it is:
function read_prop(obj, prop) {
return obj[prop];
}
To answer some of the comments below that aren't directly related to the original question, nested objects can be referenced through multiple brackets. If you have a nested object like so:
var foo = { a: 1, b: 2, c: {x: 999, y:998, z: 997}};
you can access property x
of c
as follows:
var cx = foo['c']['x']
If a property is undefined, an attempt to reference it will return undefined
(not null
or false
):
foo['c']['q'] === null
// returns false
foo['c']['q'] === false
// returns false
foo['c']['q'] === undefined
// returns true
Try this:
var alphaExp = /^[a-zA-Z]+$/;
if(document.myForm.name.match(alphaExp))
{
//Your logice will be here.
}
else{
alert("Please enter only alphabets");
}
Thanks.
To make it simpler
SELECT *,MIN(price) FROM prod LIMIT 1
You are just initing in the wrong order.
class Shape2 {
var numberOfSides = 0
var name: String
init(name:String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
class Square2: Shape2 {
var sideLength: Double
init(sideLength:Double, name:String) {
self.sideLength = sideLength
super.init(name:name) // It should be behind "self.sideLength = sideLength"
numberOfSides = 4
}
func area () -> Double {
return sideLength * sideLength
}
}
According to Apple documentation of NSDate compare:
Returns an NSComparisonResult value that indicates the temporal ordering of the receiver and another given date.
- (NSComparisonResult)compare:(NSDate *)anotherDate
Parameters
anotherDate
The date with which to compare the receiver. This value must not be nil. If the value is nil, the behavior is undefined and may change in future versions of Mac OS X.
Return Value
If:
The receiver and anotherDate are exactly equal to each other,
NSOrderedSame
The receiver is later in time than anotherDate,
NSOrderedDescending
The receiver is earlier in time than anotherDate,
NSOrderedAscending
In other words:
if ([date1 compare:date2] == NSOrderedSame) ...
Note that it might be easier in your particular case to read and write this :
if ([date2 isEqualToDate:date2]) ...
Depending on your needs, *ngIf
or [ngClass]="{hide_element: item.hidden}"
where CSS class hide_element
is { display: none; }
*ngIf
can cause issues if you're changing state variables *ngIf
is removing, in those cases using CSS display: none;
is required.
another solution , you can add <br>
tag to your table
|Method name| Behavior |
|--|--|
| OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|
We can use Jquery methods $.each()/$.grep()
var data= [];
$.each(array,function(i){if(n !== 5 && i > 4){data.push(item)}}
or
var data = $.grep(array, function( n, i ) {
return ( n !== 5 && i > 4 );
});
use ES6 syntax:
Array.find, Array.filter, Array.forEach, Array.map
Or use Lodash https://lodash.com/docs/4.17.10#filter, Underscore https://underscorejs.org/#filter
Python long
can be arbitrarily large. If you need a value that's greater than any other value, you can use float('inf')
, since Python has no trouble comparing numeric values of different types. Similarly, for a value lesser than any other value, you can use float('-inf')
.
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
In my network, Ubuntu works behind a corporate ISA proxy server. And it requires authentication. I tried all the solutions mentioned above and nothing helped. What really helped was to write a proxy line in file /etc/systemd/system/docker.service.d/https-proxy.conf
without a domain name.
Instead of
Environment="HTTP_PROXY=http://user@domain:password@proxy:8080"
or
Environment="HTTP_PROXY=http://domain\user:password@proxy:8080"
and some other replacement such as @ -> %40
or \ -> \\
I tried to use
Environment="HTTP_PROXY=http://user:password@proxy:8080"
And it works now.
The methods provide different layers of abstraction.
$.ajax()
gives you full control over the Ajax request. You should use it if the other methods don't fullfil your needs.
$.get()
executes an Ajax GET
request. The returned data (which can be any data) will be passed to your callback handler.
$(selector).load()
will execute an Ajax GET
request and will set the content of the selected returned data (which should be either text or HTML).
It depends on the situation which method you should use. If you want to do simple stuff, there is no need to bother with $.ajax()
.
E.g. you won't use $.load()
, if the returned data will be JSON which needs to be processed further. Here you would either use $.ajax()
or $.get()
.
If you are using PHP you can use this, and I'm sure it's almost similar in other languages as well
$WebsiteURL = "https://api.telegram.org/bot".$BotToken;
$text = "<b>This</b> <i>is some Text</i>";
$Update = file_get_contents($WebsiteURL."/sendMessage?chat_id=$chat_id&text=$text&parse_mode=html);
echo $Update;
Here is the list of all tags that you can use
<b>bold</b>, <strong>bold</strong>
<i>italic</i>, <em>italic</em>
<a href="http://www.example.com/">inline URL</a>
<code>inline fixed-width code</code>
<pre>pre-formatted fixed-width code block</pre>
As described by Gideon, this is a known issue.
For use window.onunload = function() { debugger; }
instead.
But you can add a breakpoint in Source tab, then can solve your problem.
like this:
You can get access token using FB.getAuthResponse()['accessToken']
:
FB.login(function(response) {
if (response.authResponse) {
var access_token = FB.getAuthResponse()['accessToken'];
console.log('Access Token = '+ access_token);
FB.api('/me', function(response) {
console.log('Good to see you, ' + response.name + '.');
});
} else {
console.log('User cancelled login or did not fully authorize.');
}
}, {scope: ''});
Edit:
Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse();
If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log
lines or use a log-failsafe script such as:
if (typeof(console) == "undefined") { console = {}; }
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }
Here is a php4/php5 class that will sort one or more fields:
// a sorter class
// php4 and php5 compatible
class Sorter {
var $sort_fields;
var $backwards = false;
var $numeric = false;
function sort() {
$args = func_get_args();
$array = $args[0];
if (!$array) return array();
$this->sort_fields = array_slice($args, 1);
if (!$this->sort_fields) return $array();
if ($this->numeric) {
usort($array, array($this, 'numericCompare'));
} else {
usort($array, array($this, 'stringCompare'));
}
return $array;
}
function numericCompare($a, $b) {
foreach($this->sort_fields as $sort_field) {
if ($a[$sort_field] == $b[$sort_field]) {
continue;
}
return ($a[$sort_field] < $b[$sort_field]) ? ($this->backwards ? 1 : -1) : ($this->backwards ? -1 : 1);
}
return 0;
}
function stringCompare($a, $b) {
foreach($this->sort_fields as $sort_field) {
$cmp_result = strcasecmp($a[$sort_field], $b[$sort_field]);
if ($cmp_result == 0) continue;
return ($this->backwards ? -$cmp_result : $cmp_result);
}
return 0;
}
}
/////////////////////
// usage examples
// some starting data
$start_data = array(
array('first_name' => 'John', 'last_name' => 'Smith', 'age' => 10),
array('first_name' => 'Joe', 'last_name' => 'Smith', 'age' => 11),
array('first_name' => 'Jake', 'last_name' => 'Xample', 'age' => 9),
);
// sort by last_name, then first_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'last_name', 'first_name'));
// sort by first_name, then last_name
$sorter = new Sorter();
print_r($sorter->sort($start_data, 'first_name', 'last_name'));
// sort by last_name, then first_name (backwards)
$sorter = new Sorter();
$sorter->backwards = true;
print_r($sorter->sort($start_data, 'last_name', 'first_name'));
// sort numerically by age
$sorter = new Sorter();
$sorter->numeric = true;
print_r($sorter->sort($start_data, 'age'));
in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:
copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.
since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.
Try to change type of ScoreIfNoMatch, like this:
public class MatrixModel
{
public string S1 { get; set; }
public string S2 { get; set; }
public string S3 { get; set; }
public string S4 { get; set; }
public string S5 { get; set; }
public string S6 { get; set; }
public string S7 { get; set; }
public string S8 { get; set; }
public string S9 { get; set; }
public string S10 { get; set; }
// the type should be string
public string ScoreIfNoMatch { get; set; }
}
The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:
/**
* The "booting" method of the model.
*
* @return void
*/
protected static function boot()
{
parent::boot();
// auto-sets values on creation
static::creating(function ($query) {
$query->is_voicemail = $query->is_voicemail ?? true;
});
}
Using only print:
>>> l = ['x', 3, 'b']
>>> print(*l, sep='\n')
x
3
b
>>> print(*l, sep=', ')
x, 3, b
If your date column is a string of the format '2017-01-01' you can use pandas astype to convert it to datetime.
df['date'] = df['date'].astype('datetime64[ns]')
or use datetime64[D] if you want Day precision and not nanoseconds
print(type(df_launath['date'].iloc[0]))
yields
<class 'pandas._libs.tslib.Timestamp'>
the same as when you use pandas.to_datetime
You can try it with other formats then '%Y-%m-%d' but at least this works.
@echo off
color 1F
@sc query >%COMPUTERNAME%_START.TXT
find /I "AcPrfMgrSvc" %COMPUTERNAME%_START.TXT >nul
IF ERRORLEVEL 0 EXIT
IF ERRORLEVEL 1 NET START "AcPrfMgrSvc"
Another way:
if (s.size > 5) s.reverse.substring(5).reverse
BTW, this is Scala code. May need brackets to work in Java.
IMO the main difference is that Textbox is not strongly typed. TextboxFor take a lambda as a parameter that tell the helper the with element of the model to use in a typed view.
You can do the same things with both, but you should use typed views and TextboxFor when possible.
Since this answer got very much attention, here is a nice configurable snippet I came up with:
/**
* @author ComFreek <https://stackoverflow.com/users/603003/comfreek>
* @link https://stackoverflow.com/a/16069817/603003
* @license MIT 2013-2015 ComFreek
* @license[dual licensed] CC BY-SA 3.0 2013-2015 ComFreek
* You MUST retain this license header!
*/
(function (exports) {
function valOrFunction(val, ctx, args) {
if (typeof val == "function") {
return val.apply(ctx, args);
} else {
return val;
}
}
function InvalidInputHelper(input, options) {
input.setCustomValidity(valOrFunction(options.defaultText, window, [input]));
function changeOrInput() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity("");
}
}
function invalid() {
if (input.value == "") {
input.setCustomValidity(valOrFunction(options.emptyText, window, [input]));
} else {
input.setCustomValidity(valOrFunction(options.invalidText, window, [input]));
}
}
input.addEventListener("change", changeOrInput);
input.addEventListener("input", changeOrInput);
input.addEventListener("invalid", invalid);
}
exports.InvalidInputHelper = InvalidInputHelper;
})(window);
→ jsFiddle
<input id="email" type="email" required="required" />
InvalidInputHelper(document.getElementById("email"), {
defaultText: "Please enter an email address!",
emptyText: "Please enter an email address!",
invalidText: function (input) {
return 'The email address "' + input.value + '" is invalid!';
}
});
defaultText
is displayed initiallyemptyText
is displayed when the input is empty (was cleared)invalidText
is displayed when the input is marked as invalid by the browser (for example when it's not a valid email address)You can either assign a string or a function to each of the three properties.
If you assign a function, it can accept a reference to the input element (DOM node) and it must return a string which is then displayed as the error message.
Tested in:
You can see the old revision here: https://stackoverflow.com/revisions/16069817/6
This should fit the bill. Sounds like a super-annoying thing to have going on, but there you have it:
@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F
for %%x in (%NUM%) do (
for %%y in (%NUM%) do (
color %%x%%y
timeout 1 >nul
)
)
According to this article on sqlserverstudymaterial;
Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).
If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.
If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including
In your case you need to
android:scaleType
to fitXY
Below is an example:
<ImageView
android:id="@+id/photo"
android:layout_width="200dp"
android:layout_height="100dp"
android:src="@drawable/iclauncher"
android:scaleType="fitXY"/>
For more information regarding ImageView scaleType please refer to the developer website.
With Spring Boot 1.4+ new cool classes for easier exception handling were added that helps in removing the boilerplate code.
A new @RestControllerAdvice
is provided for exception handling, it is combination of @ControllerAdvice
and @ResponseBody
. You can remove the @ResponseBody
on the @ExceptionHandler
method when use this new annotation.
i.e.
@RestControllerAdvice
public class GlobalControllerExceptionHandler {
@ExceptionHandler(value = { Exception.class })
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ApiErrorResponse unknownException(Exception ex, WebRequest req) {
return new ApiErrorResponse(...);
}
}
For handling 404 errors adding @EnableWebMvc
annotation and the following to application.properties was enough:
spring.mvc.throw-exception-if-no-handler-found=true
You can find and play with the sources here:
https://github.com/magiccrafter/spring-boot-exception-handling
Embedded Emmet could do the trick:
Emmet: Wrap with Abbreviation
div
(or an abbreviation .wrapper>p
)Command can be assigned to a keybinding.
This thing even supports passing arguments:
{
"key": "ctrl+shift+9",
"command": "editor.emmet.action.wrapWithAbbreviation",
"when": "editorHasSelection",
"args": {
"abbreviation": "span"
}
},
Use it like this:
span.myCssClass
span#myCssId
b
b.myCssClass
Though you can use First()
, Dictionaries do not have order per se. Please use OrderedDictionary instead. And then you can do FirstOrDefault
. This way it will be meaningful.
If double backslash looks weird to you, C# also allows verbatim string literals where the escaping is not required.
Console.WriteLine(@"Mango \ Nightangle");
Don't you just wish Java had something like this ;-)
If you want to display the menu up, just add the class "dropup"
and remove the class "dropdown" if exists from the same div.
<div class="btn-group dropup">
You could also use this existing solution. The demo is here. It looks like youtube loading bar. I just found it and added it to my own project.
you can do it by two simple point and change in your code
1.In your xml in anim folder of your project, Set the fade in and fade out duration time not equal
2.In you java class before the start of fade out animation, set second imageView visibility Gone then after fade out animation started set second imageView visibility which you want to fade in visible
fadeout.xml
<alpha
android:duration="4000"
android:fromAlpha="1.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="0.0" />
fadein.xml
<alpha
android:duration="6000"
android:fromAlpha="0.0"
android:interpolator="@android:anim/accelerate_interpolator"
android:toAlpha="1.0" />
In you java class
Animation animFadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
ImageView iv2 = (ImageView) findViewById(R.id.imageView2);
iv.setVisibility(View.VISIBLE);
iv2.setVisibility(View.GONE);
animFadeOut.reset();
iv.clearAnimation();
iv.startAnimation(animFadeOut);
Animation animFadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
iv2.setVisibility(View.VISIBLE);
animFadeIn.reset();
iv2.clearAnimation();
iv2.startAnimation(animFadeIn);
body
{
width:80%;
margin-left:auto;
margin-right:auto;
}
This will work on most browsers, including IE.
I found an easy way using the new callback refs. You can just pass a callback as a prop to the child component. Like this:
class Container extends React.Component {
constructor(props) {
super(props)
this.setRef = this.setRef.bind(this)
}
setRef(node) {
this.childRef = node
}
render() {
return <Child setRef={ this.setRef }/>
}
}
const Child = ({ setRef }) => (
<div ref={ setRef }>
</div>
)
Here's an example of doing this with a modal:
class Container extends React.Component {
constructor(props) {
super(props)
this.state = {
modalOpen: false
}
this.open = this.open.bind(this)
this.close = this.close.bind(this)
this.setModal = this.setModal.bind(this)
}
open() {
this.setState({ open: true })
}
close(event) {
if (!this.modal.contains(event.target)) {
this.setState({ open: false })
}
}
setModal(node) {
this.modal = node
}
render() {
let { modalOpen } = this.state
return (
<div>
<button onClick={ this.open }>Open</button>
{
modalOpen ? <Modal close={ this.close } setModal={ this.setModal }/> : null
}
</div>
)
}
}
const Modal = ({ close, setModal }) => (
<div className='modal' onClick={ close }>
<div className='modal-window' ref={ setModal }>
</div>
</div>
)
After some serious searching it seems i've found the answer to my question:
from: http://www.brunildo.org/test/Overflowxy2.html
In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.
also the W3C spec says:
The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.
Short Version:
If you are using visible
for either overflow-x
or overflow-y
and something other than visible
for the other, the visible
value is interpreted as auto
.
Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)
Code:
include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf');
$a->decodePDF();
echo $a->output();
class.pdf2text.php
Project Home
pdf2textclass
doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser
When you use spring then you can use
boolean isNullOrEmpty = org.springframework.util.ObjectUtils.isEmpty(obj);
where obj is any [map,collection,array,aything...]
otherwise: the code is:
public static boolean isEmpty(Object[] array) {
return (array == null || array.length == 0);
}
public static boolean isEmpty(Object obj) {
if (obj == null) {
return true;
}
if (obj.getClass().isArray()) {
return Array.getLength(obj) == 0;
}
if (obj instanceof CharSequence) {
return ((CharSequence) obj).length() == 0;
}
if (obj instanceof Collection) {
return ((Collection) obj).isEmpty();
}
if (obj instanceof Map) {
return ((Map) obj).isEmpty();
}
// else
return false;
}
for String best is:
boolean isNullOrEmpty = (str==null || str.trim().isEmpty());
I found 5 main ways to iterate over a Linked List in Java (including the Java 8 way):
For loop
LinkedList<String> linkedList = new LinkedList<>();
System.out.println("==> For Loop Example.");
for (int i = 0; i < linkedList.size(); i++) {
System.out.println(linkedList.get(i));
}
Enhanced for loop
for (String temp : linkedList) {
System.out.println(temp);
}
While loop
int i = 0;
while (i < linkedList.size()) {
System.out.println(linkedList.get(i));
i++;
}
Iterator
Iterator<String> iterator = linkedList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
collection stream() util (Java 8)
linkedList.forEach((temp) -> {
System.out.println(temp);
});
One thing should be pointed out is that the running time of For Loop or While Loop is O(n square) because get(i)
operation takes O(n) time(see this for details). The other 3 ways take linear time and performs better.
Updating and placing, somewhere it will be easier for others to find, ling's comment upon jur's response above.
df_diff = pd.concat([df1,df2]).drop_duplicates(keep=False)
Testing with these DataFrames:
# with import pandas as pd
df1 = pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24'],
'Fruit':['Banana','Orange','Apple','Celery'],
'Num':[22.1,8.6,7.6,10.2],
'Color':['Yellow','Orange','Green','Green'],
})
df2 = pd.DataFrame({
'Date':['2013-11-24','2013-11-24','2013-11-24','2013-11-24','2013-11-25','2013-11-25'],
'Fruit':['Banana','Orange','Apple','Celery','Apple','Orange'],
'Num':[22.1,8.6,7.6,10.2,22.1,8.6],
'Color':['Yellow','Orange','Green','Green','Red','Orange'],
})
Results in this:
# for df1
Date Fruit Num Color
0 2013-11-24 Banana 22.1 Yellow
1 2013-11-24 Orange 8.6 Orange
2 2013-11-24 Apple 7.6 Green
3 2013-11-24 Celery 10.2 Green
# for df2
Date Fruit Num Color
0 2013-11-24 Banana 22.1 Yellow
1 2013-11-24 Orange 8.6 Orange
2 2013-11-24 Apple 7.6 Green
3 2013-11-24 Celery 10.2 Green
4 2013-11-25 Apple 22.1 Red
5 2013-11-25 Orange 8.6 Orange
# for df_diff
Date Fruit Num Color
4 2013-11-25 Apple 22.1 Red
5 2013-11-25 Orange 8.6 Orange
Just add addToBackStack
while you are transitioning between your fragments like below:
fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();
if you write addToBackStack(null)
, it will handle it by itself but if you give a tag , you should handle it manually.
One way would be to first flatten the list with a SelectMany
:
subList.SelectMany(m => m).Where(k => k.Key.Equals("valueTitle"));
I was having a similar error, it seems that the compiler misunderstand the call to the constructor without arguments. I made it work by removing the parenthesis from the variable declaration, in your code something like this:
class Foo
{
public:
Foo() {};
Foo(int a) {};
void bar() {};
};
int main()
{
// this works...
Foo foo1(1);
foo1.bar();
// this does not...
Foo foo2; // Without "()"
foo2.bar();
return 0;
}
your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.
Both should work.
/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2
/node/text()[1] - should return Text1
/node/text()[2] - should return text2
In a comment you wrote
i want to show that there is a difference in local and github repo
As already mentioned in another answer, you should do a git fetch origin
first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with
git log master..origin/master --stat
If your local branch is ahead:
git log origin/master..master --stat
--stat
shows a list of changed files as well.
If you want to explicitly list the additions and deletions, use git diff
:
git diff master origin/master
You can't run 16-bit applications (or components) on 64-bit versions of Windows. That emulation layer no longer exists. The 64-bit versions already have to provide a compatibility layer for 32-bit applications.
Support for 16-bit had to be dropped eventually, even in a culture where backwards-compatibility is of sacred import. The transition to 64-bit seemed like as good a time as any. It's hard to imagine anyone out there in the wild that is still using 16-bit applications and seeking to upgrade to 64-bit OSes.
What would be the best way to get round this problem?
If the component itself is 16-bit, then using a virtual machine running a 32-bit version of Windows is your only real choice. Oracle's VirtualBox is free, and a perennial favorite.
If only the installer is 16-bit (and it installs a 32-bit component), then you might be able to use a program like 7-Zip to extract the contents of the installer and install them manually. Let's just say this "solution" is high-risk and you should have few, if any, expectations.
It's high time to upgrade away from 16-bit stuff, like Turbo C++ and Sheridan controls. I've yet to come across anything that the Sheridan controls can do that the built-in controls can't do and haven't been able to do since Windows 95.
You can validate point a and b compactly by doing something like the following:
#!/bin/sh
MYVAL=$(echo ${1} | awk '/^[0-9]+$/')
MYVAL=${MYVAL:?"Usage - testparms <number>"}
echo ${MYVAL}
Which gives us ...
$ ./testparams.sh
Usage - testparms <number>
$ ./testparams.sh 1234
1234
$ ./testparams.sh abcd
Usage - testparms <number>
This method should work fine in sh.
For Unix users, mail() is actually using Sendmail command to send email. Instead of modifying the application, you can change the environment. msmtp is an SMTP client with Sendmail compatible CLI syntax which means it can be used in place of Sendmail. It only requires a small change to your php.ini.
sendmail_path = "/usr/bin/msmtp -C /path/to/your/config -t"
Then even the lowly mail() function can work with SMTP goodness. It is super useful if you're trying to connect an existing application to mail services like sendgrid or mandrill without modifying the application.