A tuple consists of a number of values separated by commas. like
>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345
tuple are index based (and also immutable) in Python.
Here in this case x = rows[1][1] + " " + rows[1][2]
have only two index 0, 1 available but you are trying to access the 3rd index.
When you are dealing with objects, you want to ignore simple id's as much as convenient.
If you change the click line to this, I think you will be well on your way:
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">
Also, I think you may need to change
class="tutorial_title {{tutorial.active}}"
to something like
ng-class="tutorial_title {{tutorial.active}}"
See http://docs.angularjs.org/misc/faq and look for ng-class.
Sometimes, the minimal installation of Linux in Docker doesn't define the path and therefore it is necessary to call ping using ....
cd /usr/sbin
ping <ip>
There is a new annotation @Value
in Spring 3.0.0M3. @Value
support not only #{...}
expressions but ${...}
placeholders as well
Add the following dependency to your pom.xml
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency>
A better, easier, responsive approach is to set margin-top
in CSS to around 45%:
margin-top: 45%;
You might have to play with that number, but it will be in the center of the surrounding div.
Update: this answer works with both ,Visual Sudio 2017 and 2019
For me it worked by the following three steps:
Adding Report viewer control by:
Going to NuGet Package Manager.
Installing Microsoft.ReportingServices.ReportViewerControl.Winforms
For WebForms applications:
Adding Report viewer control by:
Going to NuGet Package Manager.
Installing Microsoft.ReportingServices.ReportViewerControl.WebForms
That's all!
Determine the data type of your data source column, "CreateDate". Make sure it is producing an actual datetime field and not something like a varchar. If your data source is a stored procedure, it is entirely possible that CreateDate is being processed to produce a varchar in order to format the date, like so:
SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate
FROM TableName ...
Using CONVERT like this is often done to make query results fill the requirements of whatever other code is going to be processing those results. Style 126 is ISO 8601 format, an international standard that works with any language setting. I don't know what your industry is, but that was probably intentional. You don't want to mess with it. This style (126) produces a string representation of a date in the form '2013-04-29T18:15:20.270' just like you reported! However, if CreateDate's been processed this way then there's no way you'll be able to get your bf1.DataFormatString to show "29/04/2013" instead. You must first start with a datetime type column in your original SQL data source first for bf1 to properly consume it. So just add it to the data source query, and call it by a different name like CreateDate2 so as not to disturb whatever other code already depends on CreateDate, like this:
SELECT CONVERT(varchar,TableName.CreateDate,126) AS CreateDate,
TableName.CreateDate AS CreateDate2
FROM TableName ...
Then, in your code, you'll have to bind bf1 to "CreateDate2" instead of the original "CreateDate", like so:
BoundField bf1 = new BoundField();
bf1.DataField = "CreateDate2";
bf1.DataFormatString = "{0:dd/MM/yyyy}";
bf1.HtmlEncode = false;
bf1.HeaderText = "Sample Header 2";
dv.Fields.Add(bf1);
Voila! Your date should now show "29/04/2013" instead!
You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:
import seaborn as sns
tips = sns.load_dataset("tips")
b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()
, which results in this:
To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.
NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.
If you are using sublime then this code may work if you add it in build as code for building system. You can use this link for more information.
{
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\"",
"file_regex": "^(..[^:]*):([0-9]+):?([0-9]+)?:? (.*)$",
"working_dir": "${file_path}",
"selector": "source.c, source.c++",
"variants":
[
{
"name": "Run",
"shell_cmd": "g++ \"${file}\" -std=c++1y -o \"${file_path}/${file_base_name}\" && \"${file_path}/${file_base_name}\""
}
]
}
You can also use Route::current()->getName()
to check your route name.
Example: routes.php
Route::get('test', ['as'=>'testing', function() {
return View::make('test');
}]);
View:
@if(Route::current()->getName() == 'testing')
Hello This is testing
@endif
Source: CodeSpeedy Click to know more Check if an ArrayList is empty or not
import java.util.ArrayList;
public class arraycheck {
public static void main(String args[]){
ArrayList<Integer> list=new ArrayList<Integer>();
if(list.size()==0){
System.out.println("Its Empty");
}
else
System.out.println("Not Empty");
}
}
Output:
run:
Its Empty
BUILD SUCCESSFUL (total time: 0 seconds)
I manged to set the MinDate & the MaxDate programmatically like this :
final Calendar c = Calendar.getInstance();
int maxYear = c.get(Calendar.YEAR) - 20; // this year ( 2011 ) - 20 = 1991
int maxMonth = c.get(Calendar.MONTH);
int maxDay = c.get(Calendar.DAY_OF_MONTH);
int minYear = 1960;
int minMonth = 0; // january
int minDay = 25;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.create_account);
BirthDateDP = (DatePicker) findViewById(R.id.create_account_BirthDate_DatePicker);
BirthDateDP.init(maxYear - 10, maxMonth, maxDay, new OnDateChangedListener()
{
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
if (year < minYear)
view.updateDate(minYear, minMonth, minDay);
if (monthOfYear < minMonth && year == minYear)
view.updateDate(minYear, minMonth, minDay);
if (dayOfMonth < minDay && year == minYear && monthOfYear == minMonth)
view.updateDate(minYear, minMonth, minDay);
if (year > maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (monthOfYear > maxMonth && year == maxYear)
view.updateDate(maxYear, maxMonth, maxDay);
if (dayOfMonth > maxDay && year == maxYear && monthOfYear == maxMonth)
view.updateDate(maxYear, maxMonth, maxDay);
}}); // BirthDateDP.init()
} // activity
it works fine for me, enjoy :)
If you want to execute that command, you should probably change:
PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'
to:
PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)
you need mail.jar and activation.jar to build javamail application
It makes it easier for static typed languages (CLR) to interoperate with dynamic ones (python, ruby ...) running on the DLR (dynamic language runtime), see MSDN:
For example, you might use the following code to increment a counter in XML in C#.
Scriptobj.SetProperty("Count", ((int)GetProperty("Count")) + 1);
By using the DLR, you could use the following code instead for the same operation.
scriptobj.Count += 1;
MSDN lists these advantages:
- Simplifies Porting Dynamic Languages to the .NET Framework
- Enables Dynamic Features in Statically Typed Languages
- Provides Future Benefits of the DLR and .NET Framework
- Enables Sharing of Libraries and Objects
- Provides Fast Dynamic Dispatch and Invocation
See MSDN for more details.
What browser are you testing in?
What DOCType have you set?
How exactly are you declaring your CSS?
Are you sure you haven't missed a ;
before/after the overflow-y: scroll
?
I've just tested the following in IE7 and Firefox and it works fine
<!-- Scroll bar present but disabled when less content -->_x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test_x000D_
</div>_x000D_
_x000D_
<!-- Scroll bar present and enabled when more contents --> _x000D_
<div style="width: 200px; height: 100px; overflow-y: scroll;">_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
test<br />_x000D_
</div>
_x000D_
keyCodes are different from the ASCII values. For a complete keyCode reference, see http://unixpapa.com/js/key.html
For example, Numpad numbers have keyCodes 96 - 105, which corresponds to the beginning of lowercase alphabet in ASCII. This could lead to problems in validating numeric input.
I am not sure what the problem is, but I am pretty sure this will fix it.
for (i=0; i<arrChecks.length; i++)
{
var attribute = arrChecks[i].getAttribute("xid")
if (attribute == elementName)
{
if (arrChecks[i].checked == 0)
{
arrChecks[i].checked = 1;
} else {
arrChecks[i].checked = 0;
}
} else {
arrChecks[i].checked = 0;
}
}
The best option is to clone them with clone() method.
You can use random.uniform
import random
random.uniform(0, 1)
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
Keith Elder nicely compares ASMX to WCF here. Check it out.
Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.
WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.
ASMX is:
WCF can be:
In short: WCF is here to replace ASMX fully.
Check out the WCF Developer Center on MSDN.
Update: link seems to be dead - try this: What Is Windows Communication Foundation?
Go and get the latest version of miniconda for Raspberry Pi - made for armv7l processor and bundled with Python 3 (eg.: uname -m
)
wget http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-armv7l.sh
md5sum Miniconda3-latest-Linux-armv7l.sh
bash Miniconda3-latest-Linux-armv7l.sh
After installation, source your updated .bashrc file with source ~/.bashrc
. Then enter the command python --version
, which should give you:
Python 3.4.3 :: Continuum Analytics, Inc.
Usually, you would do something like this:
$post_data = json_encode(array('item' => $post_data));
But, as it seems you want the output to be with "{}
", you better make sure to force json_encode()
to encode as object, by passing the JSON_FORCE_OBJECT
constant.
$post_data = json_encode(array('item' => $post_data), JSON_FORCE_OBJECT);
"{}
" brackets specify an object and "[]
" are used for arrays according to JSON specification.
The addition of relative dimensions to the source URL will be rendered in the majority of Markdown renderers.
We implemented this in Corilla as I think the pattern is one that follows expectations of existing workflows without pushing the user to rely on basic HTML. If your favourite tool doesn't follow a similar pattern it's worth raising a feature request.
Example of syntax:
![a-kitten.jpg](//corilla.com/a-kitten-2xU3C2.jpg =200x200)
Example of kitten:
NO, when you are using only one "=" you are assigning the variable.
You must use "==" : You must use "===" :
if (somevar === '836e3ef9-53d4-414b-a401-6eef16ac01d6'){
$("#code").text(data.DATA[0].ID);
}
You could use fonction like .toLowerCase()
to avoid case problem if you want
Note that you can escape a json array / dictionary by doing json.dumps twice and json.loads twice:
>>> a = {'x':1}
>>> b = json.dumps(json.dumps(a))
>>> b
'"{\\"x\\": 1}"'
>>> json.loads(json.loads(b))
{u'x': 1}
According to:
Fixing Node Mysql "Error: Cannot enqueue Handshake after invoking quit.":
http://codetheory.in/fixing-node-mysql-error-cannot-enqueue-handshake-after-invoking-quit/
TL;DR You need to establish a new connection by calling the
createConnection
method after every disconnection.
and
Note: If you're serving web requests, then you shouldn't be ending connections on every request. Just create a connection on server startup and use the connection/client object to query all the time. You can listen on the error event to handle server disconnection and for reconnecting purposes. Full code here.
From:
Readme.md - Server disconnects:
It says:
Server disconnects
You may lose the connection to a MySQL server due to network problems, the server timing you out, or the server crashing. All of these events are considered fatal errors, and will have the
err.code = 'PROTOCOL_CONNECTION_LOST'
. See the Error Handling section for more information.The best way to handle such unexpected disconnects is shown below:
function handleDisconnect(connection) { connection.on('error', function(err) { if (!err.fatal) { return; } if (err.code !== 'PROTOCOL_CONNECTION_LOST') { throw err; } console.log('Re-connecting lost connection: ' + err.stack); connection = mysql.createConnection(connection.config); handleDisconnect(connection); connection.connect(); }); } handleDisconnect(connection);
As you can see in the example above, re-connecting a connection is done by establishing a new connection. Once terminated, an existing connection object cannot be re-connected by design.
With Pool, disconnected connections will be removed from the pool freeing up space for a new connection to be created on the next getConnection call.
I have tweaked the function such that every time a connection is needed, an initializer function adds the handlers automatically:
function initializeConnection(config) {
function addDisconnectHandler(connection) {
connection.on("error", function (error) {
if (error instanceof Error) {
if (error.code === "PROTOCOL_CONNECTION_LOST") {
console.error(error.stack);
console.log("Lost connection. Reconnecting...");
initializeConnection(connection.config);
} else if (error.fatal) {
throw error;
}
}
});
}
var connection = mysql.createConnection(config);
// Add handlers.
addDisconnectHandler(connection);
connection.connect();
return connection;
}
Initializing a connection:
var connection = initializeConnection({
host: "localhost",
user: "user",
password: "password"
});
Minor suggestion: This may not apply to everyone but I did run into a minor issue relating to scope. If the OP feels this edit was unnecessary then he/she can choose to remove it. For me, I had to change a line in initializeConnection
, which was var connection = mysql.createConnection(config);
to simply just
connection = mysql.createConnection(config);
The reason being that if connection
is a global variable in your program, then the issue before was that you were making a new connection
variable when handling an error signal. But in my nodejs code, I kept using the same global connection
variable to run queries on, so the new connection
would be lost in the local scope of the initalizeConnection
method. But in the modification, it ensures that the global connection
variable is reset This may be relevant if you're experiencing an issue known as
Cannot enqueue Query after fatal error
after trying to perform a query after losing connection and then successfully reconnecting. This may have been a typo by the OP, but I just wanted to clarify.
You can also do what the "Service Reference" generated code does
public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
public ServiceXClient() { }
public ServiceXClient(string endpointConfigurationName) :
base(endpointConfigurationName) { }
public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) { }
public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
base(binding, remoteAddress) { }
public bool ServiceXWork(string data, string otherParam)
{
return base.Channel.ServiceXWork(data, otherParam);
}
}
Where IServiceX is your WCF Service Contract
Then your client code:
var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");
do url_raw.cast_to_raw()
support in oracle 6
For more info Configuring App Transport Security Exceptions in iOS 9 and OSX 10.11
Curiously, you’ll notice that the connection attempts to change the http protocol to https to protect against mistakes in your code where you may have accidentally misconfigured the URL. In some cases, this might actually work, but it’s also confusing.
This Shipping an App With App Transport Security covers some good debugging tips
ATS Failure
Most ATS failures will present as CFErrors with a code in the -9800 series. These are defined in the Security/SecureTransport.h header
2015-08-23 06:34:42.700 SelfSignedServerATSTest[3792:683731] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9813)
CFNETWORK_DIAGNOSTICS
Set the environment variable CFNETWORK_DIAGNOSTICS to 1 in order to get more information on the console about the failure
nscurl
The tool will run through several different combinations of ATS exceptions, trying a secure connection to the given host under each ATS configuration and reporting the result.
nscurl --ats-diagnostics https://example.com
You can net set it to view height
html, body
{
height: 100vh;
}
Here a bit easier:
@echo off
set /p var=Are You Sure?[Y/N]:
if %var%== Y goto ...
if not %var%== Y exit
or
@echo off
echo Are You Sure?[Y/N]
choice /c YN
if %errorlevel%==1 goto yes
if %errorlevel%==2 goto no
:yes
echo yes
goto :EOF
:no
echo no
Equal height columns is the default behaviour for Bootstrap 4 grids.
.col { background: red; }_x000D_
.col:nth-child(odd) { background: yellow; }
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
<br>_x000D_
Line 2_x000D_
<br>_x000D_
Line 3_x000D_
</div>_x000D_
<div class="col">_x000D_
1 of 3_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
impossible with javascript. Just as another alternative to suggestions from other answers: consider using jGrowl: http://archive.plugins.jquery.com/project/jGrowl
It is better if you don't kill a thread. A way could be to introduce a "try" block into the thread's cycle and to throw an exception when you want to stop the thread (for example a break/return/... that stops your for/while/...). I've used this on my app and it works...
Instead of doing this:
$(document).ready(function() { });
You should be doing this:
jQuery(document).ready(function($) {
// your code goes here
});
This is because WordPress may use $ for something other than jQuery, in the future, or now, and so you need to load jQuery in a way that the $ can be used only in a jQuery document ready callback.
The following is a solution extracted from Expert C Programming: Deep Secrets, which is supposed to work on SVr4. It uses stty and ioctl.
#include <sys/filio.h>
int kbhit()
{
int i;
ioctl(0, FIONREAD, &i);
return i; /* return a count of chars available to read */
}
main()
{
int i = 0;
intc='';
system("stty raw -echo");
printf("enter 'q' to quit \n");
for (;c!='q';i++) {
if (kbhit()) {
c=getchar();
printf("\n got %c, on iteration %d",c, i);
}
}
system("stty cooked echo");
}
Loading custom yml file with multiple profile config in Spring Boot.
1) Add the property bean with SpringBootApplication start up as follows
@SpringBootApplication
@ComponentScan({"com.example.as.*"})
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
@Bean
@Profile("dev")
public PropertySourcesPlaceholderConfigurer propertiesStage() {
return properties("dev");
}
@Bean
@Profile("stage")
public PropertySourcesPlaceholderConfigurer propertiesDev() {
return properties("stage");
}
@Bean
@Profile("default")
public PropertySourcesPlaceholderConfigurer propertiesDefault() {
return properties("default");
}
/**
* Update custom specific yml file with profile configuration.
* @param profile
* @return
*/
public static PropertySourcesPlaceholderConfigurer properties(String profile) {
PropertySourcesPlaceholderConfigurer propertyConfig = null;
YamlPropertiesFactoryBean yaml = null;
propertyConfig = new PropertySourcesPlaceholderConfigurer();
yaml = new YamlPropertiesFactoryBean();
yaml.setDocumentMatchers(new SpringProfileDocumentMatcher(profile));// load profile filter.
yaml.setResources(new ClassPathResource("env_config/test-service-config.yml"));
propertyConfig.setProperties(yaml.getObject());
return propertyConfig;
}
}
2) Config the Java pojo object as follows
@Component
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(Include.NON_NULL)
@ConfigurationProperties(prefix = "test-service")
public class TestConfig {
@JsonProperty("id")
private String id;
@JsonProperty("name")
private String name;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
3) Create the custom yml (and place it under resource path as follows, YML File name : test-service-config.yml
Eg Config in the yml file.
test-service:
id: default_id
name: Default application config
---
spring:
profiles: dev
test-service:
id: dev_id
name: dev application config
---
spring:
profiles: stage
test-service:
id: stage_id
name: stage application config
This code worked for me:
$(function(){
$('input:radio').change(function(){
alert('changed');
});
});
Try CONVERT instead of CAST.
CONVERT allows a third parameter indicating the date format.
List of formats is here: http://msdn.microsoft.com/en-us/library/ms187928.aspx
Update after another answer has been selected as the "correct" answer:
I don't really understand why an answer is selected that clearly depends on the NLS settings on your server, without indicating this restriction.
The <hr>
should be placed inside a <div>
for proper functioning.
Place it like this to get desired width `
<div class='row'>
<div class='col-lg-8 col-lg-offset-2'>
<hr>
</div>
</div>
`
Hope this helps a future reader!
Taken from the latest stable Oracle production version 12.2: Data Types
The major difference is that VARCHAR2
is an internal data type and VARCHAR
is an external data type. So we need to understand the difference between an internal and external data type...
Inside a database, values are stored in columns in tables. Internally, Oracle represents data in particular formats known as internal data types.
In general, OCI (Oracle Call Interface) applications do not work with internal data type representations of data, but with host language data types that are predefined by the language in which they are written. When data is transferred between an OCI client application and a database table, the OCI libraries convert the data between internal data types and external data types.
External types provide a convenience for the programmer by making it possible to work with host language types instead of proprietary data formats. OCI can perform a wide range of data type conversions when transferring data between an Oracle database and an OCI application. There are more OCI external data types than Oracle internal data types.
The VARCHAR2
data type is a variable-length string of characters with a maximum length of 4000 bytes. If the init.ora parameter max_string_size is default, the maximum length of a VARCHAR2
can be 4000 bytes. If the init.ora parameter max_string_size = extended, the maximum length of a VARCHAR2
can be 32767 bytes
The VARCHAR
data type stores character strings of varying length. The first 2 bytes contain the length of the character string, and the remaining bytes contain the string. The specified length of the string in a bind or a define call must include the two length bytes, so the largest VARCHAR
string that can be received or sent is 65533 bytes long, not 65535.
A quick test in a 12.2 database suggests that as an internal data type, Oracle still treats a VARCHAR
as a pseudotype for VARCHAR2
. It is NOT a SYNONYM
which is an actual object type in Oracle.
SQL> select substr(banner,1,80) from v$version where rownum=1;
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production
SQL> create table test (my_char varchar(20));
Table created.
SQL> desc test
Name Null? Type
MY_CHAR VARCHAR2(20)
There are also some implications of VARCHAR
for ProC/C++ Precompiler options. For programmers who are interested, the link is at: Pro*C/C++ Programmer's Guide
Since your object type is custom, I would tend to agree with your solution - break it down into smaller segments using an encoding method (like JSON or serializing the content), and on the other end have corresponding code to re-construct the object.
According to the book PHP and MySQL for Dynamic Web Sites (4th edition)
Example:
$r = mysqli_query($dbc, $q);
For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r
variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.
Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.
Then how to test?
While the mysqli_num_rows()
function will return the number of rows generated by a SELECT query, mysqli_affected_rows()
returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:
$num = mysqli_affected_rows($dbc);
Unlike mysqli_num_rows()
, the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).
Probably part of Open Graph Protocol for Facebook.
Edit: guess not only Facebook - that's only one example of using it.
Select the height constraint from the Interface builder and take an outlet of it. So, when you want to change the height of the view you can use the below code.
yourHeightConstraintOutlet.constant = someValue
yourView.layoutIfNeeded()
Method updateConstraints()
is an instance method of UIView
. It is helpful when you are setting the constraints programmatically. It updates constraints for the view. For more detail click here.
A table can have multiple candidate keys. Each candidate key is a column or set of columns that are UNIQUE, taken together, and also NOT NULL. Thus, specifying values for all the columns of any candidate key is enough to determine that there is one row that meets the criteria, or no rows at all.
Candidate keys are a fundamental concept in the relational data model.
It's common practice, if multiple keys are present in one table, to designate one of the candidate keys as the primary key. It's also common practice to cause any foreign keys to the table to reference the primary key, rather than any other candidate key.
I recommend these practices, but there is nothing in the relational model that requires selecting a primary key among the candidate keys.
I found it working after adding the dependency of Spring Data JPA -
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Add H2 DB configuration in application.yml -
spring:
datasource:
driverClassName: org.h2.Driver
initialization-mode: always
username: sa
password: ''
url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
h2:
console:
enabled: true
path: /h2
jpa:
database-platform: org.hibernate.dialect.H2Dialect
hibernate:
ddl-auto: none
Patch builtins.open
and use mock_open
, which is part of the mock
framework. patch
used as a context manager returns the object used to replace the patched one:
from unittest.mock import patch, mock_open
with patch("builtins.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
If you want to use patch
as a decorator, using mock_open()
's result as the new=
argument to patch
can be a little bit weird. Instead, use patch
's new_callable=
argument and remember that every extra argument that patch
doesn't use will be passed to the new_callable
function, as described in the patch
documentation:
patch()
takes arbitrary keyword arguments. These will be passed to theMock
(or new_callable) on construction.
@patch("builtins.open", new_callable=mock_open, read_data="data")
def test_patch(mock_file):
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
Remember that in this case patch
will pass the mocked object as an argument to your test function.
You need to patch __builtin__.open
instead of builtins.open
and mock
is not part of unittest
, you need to pip install
and import it separately:
from mock import patch, mock_open
with patch("__builtin__.open", mock_open(read_data="data")) as mock_file:
assert open("path/to/open").read() == "data"
mock_file.assert_called_with("path/to/open")
Not quite sure why it's not mentioned more online (or on this thread), but the Babel package (and Django utilities) from the Edgewall guys is awesome for currency formatting (and lots of other i18n tasks). It's nice because it doesn't suffer from the need to do everything globally like the core Python locale module.
The example the OP gave would simply be:
>>> import babel.numbers
>>> import decimal
>>> babel.numbers.format_currency( decimal.Decimal( "188518982.18" ), "GBP" )
£188,518,982.18
Expanding on Adis H's example to include the null case (got bit on this one)
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if (config.AppSettings.Settings["HostName"] != null)
config.AppSettings.Settings["HostName"].Value = hostName;
else
config.AppSettings.Settings.Add("HostName", hostName);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
It's just the required syntax:
void Func(int (&myArray)[100])
^ Pass array of 100 int
by reference the parameters name is myArray
;
void Func(int* myArray)
^ Pass an array. Array decays to a pointer. Thus you lose size information.
void Func(int (*myFunc)(double))
^ Pass a function pointer. The function returns an int
and takes a double
. The parameter name is myFunc
.
I have recently discovered that minidlna doesn't update the database if the media file is a hardlink. If you want these files to show up in the database, a full rescan is necessary.
ex: If you have a file /home/movies/foo.mkv and a hardlink in /home/minidlna/video/foo.mkv, where '/home/minidlna' is your minidlna share, you will have to do a rescan till that file appears in the db (and subsequently your dlna client).
I'm still trying to find a way around this. If anyone has any input, it's most welcome.
Ran into this exact problem.
What I ended up doing:
# starting with date string
sdt = "20190901"
std_format = '%Y%m%d'
# create naive datetime object
from datetime import datetime
dt = datetime.strptime(sdt, sdt_format)
# extract the relevant date time items
dt_formatters = ['%Y','%m','%d']
dt_vals = tuple(map(lambda formatter: int(datetime.strftime(dt,formatter)), dt_formatters))
# set timezone
import pendulum
tz = pendulum.timezone('utc')
dt_tz = datetime(*dt_vals,tzinfo=tz)
you can see this also in sockets ...
PrintWriter out = new PrintWriter(socket.getOutputStream());
out.println("hello");
If you don't have access to the classes to change the properties, or don't want to always use the same rename property, renaming can also be done by creating a custom resolver.
For example, if you have a class called MyCustomObject
, that has a property called LongPropertyName
, you can use a custom resolver like this…
public class CustomDataContractResolver : DefaultContractResolver
{
public static readonly CustomDataContractResolver Instance = new CustomDataContractResolver ();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(MyCustomObject))
{
if (property.PropertyName.Equals("LongPropertyName", StringComparison.OrdinalIgnoreCase))
{
property.PropertyName = "Short";
}
}
return property;
}
}
Then call for serialization and supply the resolver:
var result = JsonConvert.SerializeObject(myCustomObjectInstance,
new JsonSerializerSettings { ContractResolver = CustomDataContractResolver.Instance });
And the result will be shortened to {"Short":"prop value"} instead of {"LongPropertyName":"prop value"}
More info on custom resolvers here
I liked Arun's answer better but there is a tiny problem and I could not comment or edit the answer. sparkContext does not have createDeataFrame, sqlContext does (as Thiago mentioned). So:
from pyspark.sql import SQLContext
# assuming the spark environemnt is set and sc is spark.sparkContext
sqlContext = SQLContext(sc)
schemaPeople = sqlContext.createDataFrame(RDDName)
schemaPeople.createOrReplaceTempView("RDDName")
First things first :) reading books is an excellent approach to problem solving; it's the difference between band-aid fixes and long-term investments in solving problems. Never miss an opportunity to learn. :D
You might choose to interpret the 1
as a number, but environment variables don't care. They just pass around strings:
The argument envp is an array of character pointers to null-
terminated strings. These strings shall constitute the
environment for the new process image. The envp array is
terminated by a null pointer.
(From environ(3posix)
.)
You access environment variables in python using the os.environ
dictionary-like object:
>>> import os
>>> os.environ["HOME"]
'/home/sarnold'
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'
>>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/"
>>> os.environ["PATH"]
'/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/'
As user1511510 has identified, there's an unusual case when abc is at the end of the file name. We need to look for either /abc/
or /abc
followed by a string-terminator '\0'
. A naive way to do this would be to check if either /abc/
or /abc\0
are substrings:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "/user/desktop/abc";
const int exists = strstr(str, "/abc/") || strstr(str, "/abc\0");
printf("%d\n",exists);
return 0;
}
but exists
will be 1 even if abc is not followed by a null-terminator. This is because the string literal "/abc\0"
is equivalent to "/abc"
. A better approach is to test if /abc
is a substring, and then see if the character after this substring (indexed using the pointer returned by strstr()
) is either a /
or a '\0'
:
#include <stdio.h>
#include <string.h>
int main() {
const char *str = "/user/desktop/abc", *substr;
const int exists = (substr = strstr(str, "/abc")) && (substr[4] == '\0' || substr[4] == '/');
printf("%d\n",exists);
return 0;
}
This should work in all cases.
Since innerHeight
doesn't work in some old IE versions, clientHeight
can be used:
$(window).scroll(function (e){
var body = document.body;
//alert (body.clientHeight);
var scrollTop = this.pageYOffset || body.scrollTop;
if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) {
loadMoreNews();
}
});
Java 7+
It's possible to take advantage of the StandardCharsets
JDK class:
String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());
As I mentioned in your other question:
The problem to do with that fact, that you invented your own non-standard attributes (which you shouldn't have done in the first place), and now new standardized attributes (or attributes in the process of being standardized) are colliding with them.
The proper solution is to completely remove your invented attributes and replace them with
something sensible, for example classes (class="Montantetextfield fieldname-Montante required allow-decimal-values"
), or store them in JavaScript:
var validationData = {
"Montante": {fieldname: "Montante", required: true, allowDecimalValues: true}
}
If the proper solution isn't viable, you'll have to rename them. In that case you should use the prefix data-
... because that is reserved by HTML5 for such purposes, and it's less likely to collide with something - but it still could, so you should seriously consider the first solution - even it is more work to change.
You should see Sublime Column Selection:
Using the Mouse
Different mouse buttons are used on each platform:
OS X
- Left Mouse Button + ?
OR: Middle Mouse Button
Add to selection: ?
- Subtract from selection: ?+?
Windows
- Right Mouse Button + Shift
OR: Middle Mouse Button
Add to selection: Ctrl
- Subtract from selection: Alt
Linux
Right Mouse Button + Shift
Add to selection: Ctrl
- Subtract from selection: Alt
Using the Keyboard
OS X
- Ctrl + Shift + ?
- Ctrl + Shift + ?
Windows
- Ctrl + Alt + ?
- Ctrl + Alt + ?
Linux
- Ctrl + Alt + ?
- Ctrl + Alt + ?
With :after and :before you can do that.
HTML:
<div class="a"> </div>
<div class="b"> </div>
<div class="c"> </div>
CSS:
div {
height: 100px;
position: relative;
}
.a {
background: #9C9E9F;
}
.b {
background: linear-gradient(to right, #9c9e9f, #f6f6f6);
}
.a:after, .c:before, .c:after {
content: '';
width: 50%;
height: 100%;
top: 0;
right: 0;
display: block;
position: absolute;
}
.a:after {
background: #f6f6f6;
}
.c:before {
background: #9c9e9f;
left: 0;
}
.c:after {
background: #33CCFF;
right: 0;
height: 80%;
}
And a demo.
So I have ElementTree 1.2.6 on my box now, and ran the following code against the XML chunk you posted:
import elementtree.ElementTree as ET
tree = ET.parse("test.xml")
doc = tree.getroot()
thingy = doc.find('timeSeries')
print thingy.attrib
and got the following back:
{'name': 'NWIS Time Series Instantaneous Values'}
It appears to have found the timeSeries element without needing to use numerical indices.
What would be useful now is knowing what you mean when you say "it doesn't work." Since it works for me given the same input, it is unlikely that ElementTree is broken in some obvious way. Update your question with any error messages, backtraces, or anything you can provide to help us help you.
Or you can do it like as well:
<asp:DropDownList ID="ddl" runat="server" AutoPostBack="true" onchange="javascript:CalcTotalAmt();" OnSelectedIndexChanged="ddl_SelectedIndexChanged"></asp:DropDownList>
<pre lang="xml" >{{xmlString}}</pre>
This worked for me. Thanks to http://www.codeproject.com/Answers/998872/Display-XML-in-HTML-Div#answer1
Let's say you have a tar file and you want to uncompress it after placing it in your container, remove it, you can use the COPY command to do this. Butt he various commands would be 1) Copy the tar file to the destination, 2). Uncompress it, 3) Remove the tar file. If you did this in 3 steps then there will be a new image created after each step. You can do this in one step using & but it becomes a hassle.
But you used ADD, then Docker will take care of everything for you and only one intermediate image will be created.
I had the same issue (mysql 5.6 on mac) with 'can't rmdir..'-errors when dropping databases. Leaving an empty database directory not possible to get rid of. Thanks @Framework and @Beel for the solutions.
I first deleted the db directory from the Terminal in (/Applications/XAMPP/xamppfiles/var/mysql).
For further db drops, I also deleted the empty test file. In my case the file was called NOTEMPTY but still containing 0:
sudo ls -al test
total 0
drwxrwx--- 3 _mysql _mysql 102 Mar 26 16:50 .
drwxrwxr-x 18 _mysql _mysql 612 Apr 7 13:34 ..
-rw-rw---- 1 _mysql _mysql 0 Jun 26 2013 NOTEMPTY
Chmod first and then
sudo rm -rf test/NOTEMPTY
No problems dropping databases after that
You can use onclick
to run some JavaScript or jQuery code before submitting the form like this:
<script type="text/javascript">
beforeSubmit = function(){
if (1 == 1){
//your before submit logic
}
$("#formid").submit();
}
</script>
<input type="button" value="Click" onclick="beforeSubmit();" />
This is an additional way to find out the number of CPU cores (and a lot of other information), but this code requires an additional dependence:
Native Operating System and Hardware Information https://github.com/oshi/oshi
SystemInfo systemInfo = new SystemInfo();
HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
Get the number of logical CPUs available for processing:
centralProcessor.getLogicalProcessorCount();
I think you are misinterpreting the source of the error; rExternalTotal appears to be equal to a single cell.
rReportData.offset(0,0) is equal to rReportData
rReportData.offset(261,0).end(xlUp) is likely also equal to rReportData, as you offset by 261 rows and then use the .end(xlUp) function which selects the top of a contiguous data range.
If you are interested in the sum of just a column, you can just refer to the whole column:
dExternalTotal = Application.WorksheetFunction.Sum(columns("A:A"))
or
dExternalTotal = Application.WorksheetFunction.Sum(columns((rReportData.column))
The worksheet function sum will correctly ignore blank spaces.
Let me know if this helps!
Using the quite popular stream-buffers
package which you probably already have in your project dependencies, this is pretty straightforward:
// imports
const { WritableStreamBuffer } = require('stream-buffers');
const { promisify } = require('util');
const { createReadStream } = require('fs');
const pipeline = promisify(require('stream').pipeline);
// sample stream
let stream = createReadStream('/etc/hosts');
// pipeline the stream into a buffer, and print the contents when done
let buf = new WritableStreamBuffer();
pipeline(stream, buf).then(() => console.log(buf.getContents().toString()));
The ideal datatype for storing Lat Long values in SQL Server is decimal(9,6)
As others have said, this is at approximately 10cm precision, whilst only using 5 bytes of storage.
e.g. CAST(123.456789 as decimal(9,6)) as [LatOrLong]
You can get the managed bean by passing the name:
public static Object getBean(String beanName){
Object bean = null;
FacesContext fc = FacesContext.getCurrentInstance();
if(fc!=null){
ELContext elContext = fc.getELContext();
bean = elContext.getELResolver().getValue(elContext, null, beanName);
}
return bean;
}
In Jake's ViewPageIndicator he has implemented View pager to display a String array (i.e.
["this","is","a","text"]
) which you pass from YourAdapter.java (that extends FragmentPagerAdapter) to the YourFragment.java which returns a View to the viewpager.
In order to display something different, you simply have to change the context type your passing. In this case you want to pass images instead of text, as shown in the sample below:
This is how you setup your Viewpager:
public class PlaceDetailsFragment extends SherlockFragment {
PlaceSlidesFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
public static final String TAG = "detailsFragment";
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place_details,
container, false);
mAdapter = new PlaceSlidesFragmentAdapter(getActivity()
.getSupportFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
((CirclePageIndicator) mIndicator).setSnap(true);
mIndicator
.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
@Override
public void onPageSelected(int position) {
Toast.makeText(PlaceDetailsFragment.this.getActivity(),
"Changed to page " + position,
Toast.LENGTH_SHORT).show();
}
@Override
public void onPageScrolled(int position,
float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageScrollStateChanged(int state) {
}
});
return view;
}
}
your_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.viewpagerindicator.CirclePageIndicator
android:id="@+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip" />
</LinearLayout>
YourAdapter.java
public class PlaceSlidesFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter {
private int[] Images = new int[] { R.drawable.photo1, R.drawable.photo2,
R.drawable.photo3, R.drawable.photo4
};
protected static final int[] ICONS = new int[] { R.drawable.marker,
R.drawable.marker, R.drawable.marker, R.drawable.marker };
private int mCount = Images.length;
public PlaceSlidesFragmentAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
return new PlaceSlideFragment(Images[position]);
}
@Override
public int getCount() {
return mCount;
}
@Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
YourFragment.java
// you need to return image instaed of text from here.//
public final class PlaceSlideFragment extends Fragment {
int imageResourceId;
public PlaceSlideFragment(int i) {
imageResourceId = i;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ImageView image = new ImageView(getActivity());
image.setImageResource(imageResourceId);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams());
layout.setGravity(Gravity.CENTER);
layout.addView(image);
return layout;
}
}
You should get a View pager like this from the above code.
Don't try this, totally un-recommend, don't do this:
import string
s='ABCD'
print(''.join([string.ascii_lowercase[string.ascii_uppercase.index(i)] for i in s]))
Output:
abcd
Since no one wrote it yet you can use swapcase
(so uppercase letters will become lowercase, and vice versa) (and this one you should use in cases where i just mentioned (convert upper to lower, lower to upper)):
s='ABCD'
print(s.swapcase())
Output:
abcd
I asked one angle of this question here, and the answers will lead you to all the token-based timing-out cookie links you need.
Basically, you do not store the userId in the cookie. You store a one-time token (huge string) which the user uses to pick-up their old login session. Then to make it really secure, you ask for a password for heavy operations (like changing the password itself).
Every InvoiceItem
must have an Invoice
attached to it because of the not-null="true"
in the many-to-one mapping.
So the basic idea is you need to set up that explicit relationship in code. There are many ways to do that. On your class I see a setItems
method. I do NOT see an addInvoiceItem
method. When you set items, you need to loop through the set and call item.setInvoice(this)
on all of the items. If you implement an addItem
method, you need to do the same thing. Or you need to otherwise set the Invoice of every InvoiceItem
in the collection.
SMH, a lot of hours wasted on this due to lack of proper documentation and not everyone uses IIS... If anyone else is still stuck on this issue I hope this helps.
Solution: Trusted Self Signed SSL CERT for localhost on Windows 10
Note: If you only need the SSL cert follow the Certification Creation section
Stack: Azure Function App(Node.js), React.js - Windows 10
Step 1 - Create Certificate: OpenPowershell
and run the following:
New-SelfSignedCertificate -NotBefore (Get-Date) -NotAfter (Get-Date).AddYears(5) `
-Subject "CN=localhost" -KeyAlgorithm "RSA" -KeyLength 2048 `
-HashAlgorithm "SHA256" -CertStoreLocation "Cert:\CurrentUser\My" `
-FriendlyName "HTTPS Development Certificate" `
-TextExtension @("2.5.29.19={text}","2.5.29.17={text}DNS=localhost")
Step 2 - Copy Certificate: Open Certificate Manager
by pressing the windows key and search for "manage user certificates". Navigate to Personal -> Certificates
and copy the localhost cert to Trusted Root Certification Authorities -> Certificates
Trusted Root Certification Authorities -> Certificates
(Friendly Name will be HTTPS Development Certificate)
Step 3. Export Certificate right click cert -> All Tasks -> Export
which will launch the Certificate Export Wizard:
Certificate Export Wizard
Yes, export the private Key
Export private keyPersonal Information Exchange - PKCS #12
and leave the first and last checkboxes selected. Export formatStep 4. Restart Chrome
In this case we will run an Azure Function App with the SSL cert.
func start --useHttps --cert development.pfx --password 1111"
(If you used a different password and filename don't forget to update the values in this script)package.json
scripts to start your functions app:Install openssl locally, this will be used to convert the development.pfx
to a cert.pem
and server.key
. Source - Convert pfx to pem file
project-root/cert
)development.pfx
file in the cert folder. (project-root /cert/development.pfx
)openssl pkcs12 -in development.pfx -out cert.pem -nodes
openssl pkcs12 -in development.pfx -nocerts -out key.pem
openssl rsa -in key.pem -out server.key
.env.development.local
file by adding the following lines:SSL_CRT_FILE=cert.pem
SSL_KEY_FILE=server.key
npm start
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
Hope it helps. for more detail you can follow this Link
.parent{
display: flex;
flex-wrap: wrap;
}
.parent .child{
flex: 1 1 25%;
/*Start Run Code Snippet output CSS*/
padding: 5px;
box-sizing: border-box;
text-align: center;
border: 1px solid #000;
/*End Run Code Snippet output CSS*/
}
_x000D_
<div class="parent">
<div class="child">1</div>
<div class="child">2</div>
<div class="child">3</div>
<div class="child">4</div>
<div class="child">5</div>
<div class="child">6</div>
<div class="child">7</div>
<div class="child">8</div>
</div>
_x000D_
I faced the same issue in my scenario as follow:
I created textbook table first with
create table textbook(txtbk_isbn varchar2(13)
primary key,txtbk_title varchar2(40),
txtbk_author varchar2(40) );
Then chapter table:
create table chapter(txtbk_isbn varchar2(13),chapter_title varchar2(40),
constraint pk_chapter primary key(txtbk_isbn,chapter_title),
constraint chapter_txtbook foreign key (txtbk_isbn) references textbook (txtbk_isbn));
Then topic table:
create table topic(topic_id varchar2(20) primary key,topic_name varchar2(40));
Now when I wanted to create a relationship called chapter_topic between chapter (having composite primary key) and topic (having single column primary key), I faced issue with following query:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn) references textbook(txtbk_isbn),
foreign key (chapter_title) references chapter(chapter_title),
foreign key (topic_id) references topic (topic_id));
The solution was to refer to composite foreign key as below:
create table chapter_topic(txtbk_isbn varchar2(13),chapter_title varchar2(40),topic_id varchar2(20),
primary key (txtbk_isbn, chapter_title, topic_id),
foreign key (txtbk_isbn, chapter_title) references chapter(txtbk_isbn, chapter_title),
foreign key (topic_id) references topic (topic_id));
Thanks to APC post in which he mentioned in his post a statement that:
Common reasons for this are
- the parent lacks a constraint altogether
- the parent table's constraint is a compound key and we haven't referenced all the columns in the foreign key statement.
- the referenced PK constraint exists but is DISABLED
You can concat many kind of expression by sorrounding your simple/complex expression between ||
characters:
<p th:text="|${bean.field} ! ${bean.field}|">Static content</p>
You can't style a disabled checkbox directly because it's controlled by the browser / OS.
However you can be clever and replace the checkbox with a label that simulates a checkbox using pure CSS. You need to have an adjacent label that you can use to style a new "pseudo checkbox". Essentially you're completely redrawing the thing but it gives you complete control over how it looks in any state.
I've thrown up a basic example so that you can see it in action: http://jsfiddle.net/JohnSReid/pr9Lx5th/3/
Here's the sample:
input[type="checkbox"] {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
label:before {_x000D_
background: linear-gradient(to bottom, #fff 0px, #e6e6e6 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border: 1px solid #035f8f;_x000D_
height: 36px;_x000D_
width: 36px;_x000D_
display: block;_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
content: '';_x000D_
background: linear-gradient(to bottom, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
border-color: #3d9000;_x000D_
color: #96be0a;_x000D_
font-size: 38px;_x000D_
line-height: 35px;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:disabled + label:before {_x000D_
border-color: #eee;_x000D_
color: #ccc;_x000D_
background: linear-gradient(to top, #e6e6e6 0px, #fff 100%) repeat scroll 0 0 rgba(0, 0, 0, 0);_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
content: '?';_x000D_
}
_x000D_
<div><input id="cb1" type="checkbox" disabled checked /><label for="cb1"></label></div>_x000D_
<div><input id="cb2" type="checkbox" disabled /><label for="cb2"></label></div>_x000D_
<div><input id="cb3" type="checkbox" checked /><label for="cb3"></label></div>_x000D_
<div><input id="cb4" type="checkbox" /><label for="cb4"></label></div>
_x000D_
Depending on your level of browser compatibility and accessibility, some additional tweaks will need to be made.
Make Executable your jar and after that double click on it on Mac OS then it works successfully.
sudo chmod +x filename.jar
Try this, I hope this works.
This is easy with a flexbox:
#wrapper {_x000D_
display: flex;_x000D_
}_x000D_
_x000D_
#left {_x000D_
flex: 0 0 65%;_x000D_
}_x000D_
_x000D_
#right {_x000D_
flex: 1;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
<div id="left">Left side div</div>_x000D_
<div id="right">Right side div</div>_x000D_
</div>
_x000D_
The below regex will help to validate hh:mm format
^([0-1][0-9]|2[0-3]):[0-5][0-9]$
In addition to what was already posted you should know that since Java 8 we can shorten our code and write it like:
Collection.sort(yourList, Comparator.comparing(YourClass::getFieldToSortOn));
or since List now have sort
method
yourList.sort(Comparator.comparing(YourClass::getFieldToSortOn));
Since Java 8, functional interfaces (interfaces with only one abstract method - they can have more default or static methods) can be easily implemented using:
arguments -> body
source::method
.Since Comparator<T>
has only one abstract method int compare(T o1, T o2)
it is functional interface.
So instead of (example from @BalusC answer)
Collections.sort(contacts, new Comparator<Contact>() {
public int compare(Contact one, Contact other) {
return one.getAddress().compareTo(other.getAddress());
}
});
we can reduce this code to:
Collections.sort(contacts, (Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress());
});
We can simplify this (or any) lambda by skipping
{return
... }
So instead of
(Contact one, Contact other) -> {
return one.getAddress().compareTo(other.getAddress();
}
we can write
(one, other) -> one.getAddress().compareTo(other.getAddress())
Also now Comparator
has static methods like comparing(FunctionToComparableValue)
or comparing(FunctionToValue, ValueComparator)
which we could use to easily create Comparators which should compare some specific values from objects.
In other words we can rewrite above code as
Collections.sort(contacts, Comparator.comparing(Contact::getAddress));
//assuming that Address implements Comparable (provides default order).
The options object can be added to the chart when the new Chart object is created.
var chart1 = new Chart(canvas, {
type: "pie",
data: data,
options: {
legend: {
display: false
},
tooltips: {
enabled: false
}
}
});
DriverManager
is a fairly old way of doing things. The better way is to get a DataSource
, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
You could try
NumberUtils.isParsable(yourInput)
It is part of org/apache/commons/lang3/math/NumberUtils
and it checks whether the string can be parsed by Integer.parseInt(String)
, Long.parseLong(String)
, Float.parseFloat(String)
or Double.parseDouble(String)
.
See below:
The problem is database connection string, one of your MySQL database connection function parameter is not correct ,so there is an error message in the browser output, Just right click output webpage and view html source code you will see error line followed by correct XML output data(file). I had same problem and the above solution worked perfectly.
To Calculate days between 2 given dates you can use the following code.Dates I use here are Jan 01 2016 and Dec 31 2016
var day_start = new Date("Jan 01 2016");_x000D_
var day_end = new Date("Dec 31 2016");_x000D_
var total_days = (day_end - day_start) / (1000 * 60 * 60 * 24);_x000D_
document.getElementById("demo").innerHTML = Math.round(total_days);
_x000D_
<h3>DAYS BETWEEN GIVEN DATES</h3>_x000D_
<p id="demo"></p>
_x000D_
When you use lazy load you need to delete your component's module and routing module from app module. If you don't, it'll try to load them when app started and throws that error.
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpClientModule,
AppRoutingModule,
// YourComponentModule,
// YourComponentRoutingModule
],
bootstrap: [
AppComponent
]
})
export class AppModule { }
Scenario - 1
If you don't want selection for some specific cells on the tableview, you can set selection style in cellForRow function for those cells.
Objective-C
cell.selectionStyle = UITableViewCellSelectionStyleNone;
Swift 4.2
cell.selectionStyle = .none
Scenario - 2
For disabling selection on the whole table view :
Objective-C
self.tableView.allowsSelection = false;
Swift 4.2
self.tableView.allowsSelection = false
Looks like Firebug (Firefox add-on) has the answer:
Log Events
Closed
(manually)there will be something like this in Console tab:
...
mousemove clientX=1097, clientY=292
popupshowing
mousedown clientX=1097, clientY=292
focus
mouseup clientX=1097, clientY=292
click clientX=1097, clientY=292
mousemove clientX=1096, clientY=293
...
Source: Firebug Tip: Log Events
You want the CASE statement
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber)=1 THEN @OrderNumber ELSE '%' + @OrderNumber END
You won't be able to make an ajax call to http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml
from a file deployed at http://run.jsbin.com
due to the same-origin policy.
As the source (aka origin) page and the target URL are at different domains (run.jsbin.com
and www.ecb.europa.eu
), your code is actually attempting to make a Cross-domain (CORS) request, not an ordinary GET
.
In a few words, the same-origin policy says that browsers should only allow ajax calls to services at the same domain of the HTML page.
A page at http://www.example.com/myPage.html
can only directly request services that are at http://www.example.com
, like http://www.example.com/api/myService
. If the service is hosted at another domain (say http://www.ok.com/api/myService
), the browser won't make the call directly (as you'd expect). Instead, it will try to make a CORS request.
To put it shortly, to perform a (CORS) request* across different domains, your browser:
Origin
header in the original request (with the page's domain as value) and perform it as usual; and thenAccess-Control-Allow-Origin
is one of them) allowing the CORS request, the browse will complete the call (almost** exactly the way it would if the HTML page was at the same domain).
* The above depicts the steps in a simple request, such as a regular GET
with no fancy headers. If the request is not simple (like a POST
with application/json
as content type), the browser will hold it a moment, and, before fulfilling it, will first send an OPTIONS
request to the target URL. Like above, it only will continue if the response to this OPTIONS
request contains the CORS headers. This OPTIONS
call is known as preflight request.
** I'm saying almost because there are other differences between regular calls and CORS calls. An important one is that some headers, even if present in the response, will not be picked up by the browser if they aren't included in the Access-Control-Expose-Headers
header.
Was it just a typo? Sometimes the JavaScript code has just a typo in the target domain. Have you checked? If the page is at www.example.com
it will only make regular calls to www.example.com
! Other URLs, such as api.example.com
or even example.com
or www.example.com:8080
are considered different domains by the browser! Yes, if the port is different, then it is a different domain!
Add the headers. The simplest way to enable CORS is by adding the necessary headers (as Access-Control-Allow-Origin
) to the server's responses. (Each server/language has a way to do that - check some solutions here.)
Last resort: If you don't have server-side access to the service, you can also mirror it (through tools such as reverse proxies), and include all the necessary headers there.
The application/x-www-form-urlencoded
Content-type header is not needed. Unless the request handler expects the parameters coming from request body. Try it out:
curl -X DELETE "http://localhost:5000/locations?id=3"
or
curl -X GET "http://localhost:5000/locations?id=3"
just make sure how you are using image through css background use backgroud image position like background: url(your image path) no-repeat center center; automatically it wil align center to the screen.
Even though you've accepted an answer, I want to post this method. I use jQuery to center it vertically instead of css (although both of these methods work). Here is a fiddle, and I'll post the code here anyways.
HTML:
<h1>Hello world!</h1>
Javascript (jQuery):
$(document).ready(function(){
$('h1').css({ 'width':'100%', 'text-align':'center' });
var h1 = $('h1').height();
var h = h1/2;
var w1 = $(window).height();
var w = w1/2;
var m = w - h
$('h1').css("margin-top",m + "px")
});
This takes the height of the viewport, divides it by two, subtracts half the height of the h1, and sets that number to the margin-top
of the h1. The beauty of this method is that it works on multiple-line h1
s.
EDIT: I modified it so that it centered it every time the window is resized.
If you have Python 2.6 or newer, use format
:
'{0:.3g}'.format(num)
For Python 2.5 or older:
'%.3g'%(num)
Explanation:
{0}
tells format
to print the first argument -- in this case, num
.
Everything after the colon (:) specifies the format_spec
.
.3
sets the precision to 3.
g
removes insignificant zeros. See
http://en.wikipedia.org/wiki/Printf#fprintf
For example:
tests=[(1.00, '1'),
(1.2, '1.2'),
(1.23, '1.23'),
(1.234, '1.23'),
(1.2345, '1.23')]
for num, answer in tests:
result = '{0:.3g}'.format(num)
if result != answer:
print('Error: {0} --> {1} != {2}'.format(num, result, answer))
exit()
else:
print('{0} --> {1}'.format(num,result))
yields
1.0 --> 1
1.2 --> 1.2
1.23 --> 1.23
1.234 --> 1.23
1.2345 --> 1.23
Using Python 3.6 or newer, you could use f-strings
:
In [40]: num = 1.234; f'{num:.3g}'
Out[40]: '1.23'
To regain some single files or folders one may use the following
git reset -- path/to/file
git checkout -- path/to/file
This will first recreate the index entries for path/to/file
and recreate the file as it was in the last commit, i.e.HEAD
.
Hint: one may pass a commit hash to both commands to recreate files from an older commit. See git reset --help
and git checkout --help
for details.
In my projects, we usually call server side method like this:
in JavaScript:
document.getElementById("UploadButton").click();
Server side control:
<asp:Button runat="server" ID="UploadButton" Text="" style="display:none;" OnClick="UploadButton_Click" />
C#:
protected void Upload_Click(object sender, EventArgs e)
{
}
You will not write code into a static block that needs to be invoked anywhere in your program. If the purpose of the code is to be invoked then you must place it in a method.
You can write static initializer blocks to initialize static variables when the class is loaded but this code can be more complex..
A static initializer block looks like a method with no name, no arguments, and no return type. Since you never call it it doesn't need a name. The only time its called is when the virtual machine loads the class.
I'm not sure, what you mean as the 'mobile width'. But in each case, the CSS @media
can be used for hiding elements in the screen width basis. See some example:
<div id="my-content"></div>
...and:
@media screen and (min-width: 0px) and (max-width: 400px) {
#my-content { display: block; } /* show it on small screens */
}
@media screen and (min-width: 401px) and (max-width: 1024px) {
#my-content { display: none; } /* hide it elsewhere */
}
Some truly mobile detection is kind of hard programming and rather difficult. Eventually see the: http://detectmobilebrowsers.com/ or other similar sources.
Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.
Here would be the service:
import {Injectable} from '@angular/core';
@Injectable()
export class SharedService {
dataArray: string[] = [];
insertData(data: string){
this.dataArray.unshift(data);
}
}
Now, here would be the PARENT component
import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
selector: 'parent-component',
template: `
<h1>Parent</h1>
<div>
<child-component></child-component>
<child-sibling-component></child-sibling-component>
</div>
`,
providers: [SharedService],
directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{
}
and its two children
child 1
import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'
@Component({
selector: 'child-component',
template: `
<h1>I am a child</h1>
<div>
<ul *ngFor="#data in data">
<li>{{data}}</li>
</ul>
</div>
`
})
export class ChildComponent implements OnInit{
data: string[] = [];
constructor(
private _sharedService: SharedService) { }
ngOnInit():any {
this.data = this._sharedService.dataArray;
}
}
child 2 (It's sibling)
import {Component} from 'angular2/core';
import {SharedService} from './shared.service'
@Component({
selector: 'child-sibling-component',
template: `
<h1>I am a child</h1>
<input type="text" [(ngModel)]="data"/>
<button (click)="addData()"></button>
`
})
export class ChildSiblingComponent{
data: string = 'Testing data';
constructor(
private _sharedService: SharedService){}
addData(){
this._sharedService.insertData(this.data);
this.data = '';
}
}
NOW: Things to take note of when using this method.
If you want to do it by ClassName you could do:
<script type="text/javascript">
function hideTd(className){
var elements;
if (document.getElementsByClassName)
{
elements = document.getElementsByClassName(className);
}
else
{
var elArray = [];
var tmp = document.getElementsByTagName(elements);
var regex = new RegExp("(^|\\s)" + className+ "(\\s|$)");
for ( var i = 0; i < tmp.length; i++ ) {
if ( regex.test(tmp[i].className) ) {
elArray.push(tmp[i]);
}
}
elements = elArray;
}
for(var i = 0, i < elements.length; i++) {
if( elements[i].textContent == ''){
elements[i].style.display = 'none';
}
}
}
</script>
In Terminal type gradlew clean. it will automatically download and install gradle version 2.10(ie latest gradle verson available)
Eg : C:\android\workspace\projectname>gradlew clean
Yes, $_SERVER["HTTP_X_FORWARDED_FOR"]
is how I see my ip when under a proxy on my nginx server.
But your best bet is to run phpinfo()
on a page requested from under a proxy so you can look at all the availabe variables and see what is the one that carries your real ip.
The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:
The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?
This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.
In other words, the feature is missing to remove the temptation to use the feature insecurely.
It's worth noting that the QuerySet.values_list()
method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet
, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.
Somewhat irritatingly, though, this object has a custom __repr__
method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.
The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...
my_list = list(self.get_queryset().values_list('code', flat=True))
...then you can convert it to JSON with...
json_data = json.dumps(my_list)
You'll also have to place the resulting JSON data in an HttpResponse
object, which, apparently, should have a Content-Type
of application/json
, with...
response = HttpResponse(json_data, content_type='application/json')
...which you can then return from your function.
See this thread https://github.com/ivaynberg/select2/issues/489, you can hide the search box by setting minimumResultsForSearch to a negative value.
$('select').select2({
minimumResultsForSearch: -1
});
For this, what I did is
File f=new File("/data/data/your.app.package/databases/your_db.db3");
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
fis=new FileInputStream(f);
fos=new FileOutputStream("/mnt/sdcard/db_dump.db");
while(true)
{
int i=fis.read();
if(i!=-1)
{fos.write(i);}
else
{break;}
}
fos.flush();
Toast.makeText(this, "DB dump OK", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
e.printStackTrace();
Toast.makeText(this, "DB dump ERROR", Toast.LENGTH_LONG).show();
}
finally
{
try
{
fos.close();
fis.close();
}
catch(IOException ioe)
{}
}
And to do this, your app must have permission to access SD card, add following setting to your manifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Not a brilliant way, but works.
This is an addition to dmd733's answer. I fixed the bug with Day duration (well I hope I did, haven't been able to test every case).
I also quickly added a String property to the result that holds the general time passed (sorry for the bad nested ifs!!). For example if used for UI and indicating when something was updated (like a RSS feed). Kind of out of place but nice-to-have:
function getTimeDiffAndPrettyText(oDatePublished) {
var oResult = {};
var oToday = new Date();
var nDiff = oToday.getTime() - oDatePublished.getTime();
// Get diff in days
oResult.days = Math.floor(nDiff / 1000 / 60 / 60 / 24);
nDiff -= oResult.days * 1000 * 60 * 60 * 24;
// Get diff in hours
oResult.hours = Math.floor(nDiff / 1000 / 60 / 60);
nDiff -= oResult.hours * 1000 * 60 * 60;
// Get diff in minutes
oResult.minutes = Math.floor(nDiff / 1000 / 60);
nDiff -= oResult.minutes * 1000 * 60;
// Get diff in seconds
oResult.seconds = Math.floor(nDiff / 1000);
// Render the diffs into friendly duration string
// Days
var sDays = '00';
if (oResult.days > 0) {
sDays = String(oResult.days);
}
if (sDays.length === 1) {
sDays = '0' + sDays;
}
// Format Hours
var sHour = '00';
if (oResult.hours > 0) {
sHour = String(oResult.hours);
}
if (sHour.length === 1) {
sHour = '0' + sHour;
}
// Format Minutes
var sMins = '00';
if (oResult.minutes > 0) {
sMins = String(oResult.minutes);
}
if (sMins.length === 1) {
sMins = '0' + sMins;
}
// Format Seconds
var sSecs = '00';
if (oResult.seconds > 0) {
sSecs = String(oResult.seconds);
}
if (sSecs.length === 1) {
sSecs = '0' + sSecs;
}
// Set Duration
var sDuration = sDays + ':' + sHour + ':' + sMins + ':' + sSecs;
oResult.duration = sDuration;
// Set friendly text for printing
if(oResult.days === 0) {
if(oResult.hours === 0) {
if(oResult.minutes === 0) {
var sSecHolder = oResult.seconds > 1 ? 'Seconds' : 'Second';
oResult.friendlyNiceText = oResult.seconds + ' ' + sSecHolder + ' ago';
} else {
var sMinutesHolder = oResult.minutes > 1 ? 'Minutes' : 'Minute';
oResult.friendlyNiceText = oResult.minutes + ' ' + sMinutesHolder + ' ago';
}
} else {
var sHourHolder = oResult.hours > 1 ? 'Hours' : 'Hour';
oResult.friendlyNiceText = oResult.hours + ' ' + sHourHolder + ' ago';
}
} else {
var sDayHolder = oResult.days > 1 ? 'Days' : 'Day';
oResult.friendlyNiceText = oResult.days + ' ' + sDayHolder + ' ago';
}
return oResult;
}
As an explanation to Jonathan Fingland's answer:
[position()=1 and @location='US']
) must be true as a whole[position()=1][@location='US']
) must be true one after another[position()=1][@location='US']
!= [@location='US'][position()=1]
[position()=1 and @location='US']
== [@location='US' and position()=1]
[position()=1]
can be abbreviated to [1]
You can build complex expressions in predicates with the Boolean operators "and
" and "or
", and with the Boolean XPath functions not()
, true()
and false()
. Plus you can wrap sub-expressions in parentheses.
The only thing that solved it for me was to put the connection details in config/database.php instead of the .env file. Hope this helps
Use a language that doesn't come with a built-in switch statement. Perl 5 comes to mind.
Seriously though, why would you want to avoid it? And if you have good reason to avoid it, why not simply avoid it then?
Please try this line
getSupportActionBar().setHomeAsUpIndicator(R.drawable.back_arrow);
java.sql.Time timeValue = new java.sql.Time(formatter.parse(fajr_prayertime).getTime());
The error message seems self-explanatory. You can't instantiate an instance of an interface, and you've declared IUser
as an interface. (The same rule applies to abstract classes.) The whole point of an interface is that it doesn't do anything—there is no implementation provided for its methods.
However, you can instantiate an instance of a class that implements that interface (provides an implementation for its methods), which in your case is the User
class.
Thus, your code needs to look like this:
IUser user = new User();
This instantiates an instance of the User
class (which provides the implementation), and assigns it to an object variable for the interface type (IUser
, which provides the interface, the way in which you as the programmer can interact with the object).
Of course, you could also write:
User user = new User();
which creates an instance of the User
class and assigns it to an object variable of the same type, but that sort of defeats the purpose of a defining a separate interface in the first place.
An alternative I haven't seen as answer yet is the java.io.PrintWriter
.
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
writer.println("It was the best of times, it was the worst of times");
writer.println("it was the age of wisdom, it was the age of foolishness,");
writer.println("it was the epoch of belief, it was the epoch of incredulity,");
writer.println("it was the season of Light, it was the season of Darkness,");
writer.println("it was the spring of hope, it was the winter of despair,");
writer.println("we had everything before us, we had nothing before us");
String string = stringWriter.toString();
Also the fact that java.io.BufferedWriter
has a newLine()
method is unmentioned.
I know i am answering late. But this code may useful for some one. So i am attaching it here.
Use the following java code to download the videos from YouTube.
package com.mycompany.ytd;
import java.io.File;
import java.net.URL;
import com.github.axet.vget.VGet;
/**
*
* @author Manindar
*/
public class YTD {
public static void main(String[] args) {
try {
String url = "https://www.youtube.com/watch?v=s10ARdfQUOY";
String path = "D:\\Manindar\\YTD\\";
VGet v = new VGet(new URL(url), new File(path));
v.download();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Add the below Dependency in your POM.XML file
<dependency>
<groupId>com.github.axet</groupId>
<artifactId>vget</artifactId>
<version>1.1.33</version>
</dependency>
Hope this will be useful.
I saw a nice solution in this stackoverflow link that may help the readers of the defulat servlet handling issue by using the empty string URL pattern "" :
@WebServlet("")
or
<servlet-mapping>
<servlet-name>yourHomeServlet</servlet-name>
<url-pattern></url-pattern> <!-- Yes, empty string! -->
</servlet-mapping>
time1
is the key of the most outer dictionary, eg, feb2012
. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:
for info in courses[time1][course]:
As you're going through each dictionary, you must add another nest.
here's another version of the convertModelToFormData
since I needed it to also be able to send Files.
utility.js
const Utility = {
convertModelToFormData(val, formData = new FormData, namespace = '') {
if ((typeof val !== 'undefined') && val !== null) {
if (val instanceof Date) {
formData.append(namespace, val.toISOString());
} else if (val instanceof Array) {
for (let i = 0; i < val.length; i++) {
this.convertModelToFormData(val[i], formData, namespace + '[' + i + ']');
}
} else if (typeof val === 'object' && !(val instanceof File)) {
for (let propertyName in val) {
if (val.hasOwnProperty(propertyName)) {
this.convertModelToFormData(val[propertyName], formData, namespace ? `${namespace}[${propertyName}]` : propertyName);
}
}
} else if (val instanceof File) {
formData.append(namespace, val);
} else {
formData.append(namespace, val.toString());
}
}
return formData;
}
}
export default Utility;
my-client-code.js
import Utility from './utility'
...
someFunction(form_object) {
...
let formData = Utility.convertModelToFormData(form_object);
...
}
You can also use JFormattedTextField
, which is much simpler to use. Example:
public static void main(String[] args) {
NumberFormat format = NumberFormat.getInstance();
NumberFormatter formatter = new NumberFormatter(format);
formatter.setValueClass(Integer.class);
formatter.setMinimum(0);
formatter.setMaximum(Integer.MAX_VALUE);
formatter.setAllowsInvalid(false);
// If you want the value to be committed on each keystroke instead of focus lost
formatter.setCommitsOnValidEdit(true);
JFormattedTextField field = new JFormattedTextField(formatter);
JOptionPane.showMessageDialog(null, field);
// getValue() always returns something valid
System.out.println(field.getValue());
}
What types of files is not mentioned. If they're media files, go ahead with flat files. You probably just need a DB for tags and some way to associate the "external BLOBs" to the records in the DB. But if full text search is something you need, there's no other way to go but migrate to a full DB.
Another thing, your filesystem might provide the ceiling as far as number of physical files are concerned.
I'm not sure if this is 100% portable but the way the OS SHOULD parse the args is to scan through the console command string and insert a nil-term char at the end of each token, and int main(int,char**)
doesn't use const char**
so we can just iterate through the args starting from the third argument (@note the first arg is the working directory) and scan backward to the nil-term char and turn it into a space rather than start from beginning of the second argument and scanning forward to the nil-term char. Here is the function with test script, and if you do need to un-nil-ify more than one nil-term char then please comment so I can fix it; thanks.
#include <cstdio>
#include <iostream>
using namespace std;
namespace _ {
/* Converts int main(int,char**) arguments back into a string.
@return false if there are no args to convert.
@param arg_count The number of arguments.
@param args The arguments. */
bool ArgsToString(int args_count, char** args) {
if (args_count <= 1) return false;
if (args_count == 2) return true;
for (int i = 2; i < args_count; ++i) {
char* cursor = args[i];
while (*cursor) --cursor;
*cursor = ' ';
}
return true;
}
} // namespace _
int main(int args_count, char** args) {
cout << "\n\nTesting ArgsToString...\n";
if (args_count <= 1) return 1;
cout << "\nArguments:\n";
for (int i = 0; i < args_count; ++i) {
char* arg = args[i];
printf("\ni:%i\"%s\" 0x%p", i, arg, arg);
}
cout << "\n\nContiguous Args:\n";
char* end = args[args_count - 1];
while (*end) ++end;
cout << "\n\nContiguous Args:\n";
char* cursor = args[0];
while (cursor != end) {
char c = *cursor++;
if (c == 0)
cout << '`';
else if (c < ' ')
cout << '~';
else
cout << c;
}
cout << "\n\nPrinting argument string...\n";
_::ArgsToString(args_count, args);
cout << "\n" << args[1];
return 0;
}
The same happened for me with eslint
module. EsLinter throw Parsing error: Invalid left-hand side in assignment expression
for await in second if statement.
if (condition_one) {
let result = await myFunction()
}
if (condition_two) {
let result = await myFunction() // eslint parsing error
}
As strange as it sounds what fixed this error was to add ; semicolon at the end of line where await occurred.
if (condition_one) {
let result = await myFunction();
}
if (condition_two) {
let result = await myFunction();
}
I just got this working on my own website, so I figured it would be worth posting my solution here.
<a [routerLink]="baseUrlGoesHere" fragment="nameOfYourAnchorGoesHere">Link Text!</a>
<a name="nameOfYourAnchorGoesHere"></a>
<div>They're trying to anchor to me!</div>
And then in your component, make sure you include this:
import { ActivatedRoute } from '@angular/router';
constructor(private route: ActivatedRoute) {
this.route.fragment.subscribe ( f => {
const element = document.querySelector ( "#" + f )
if ( element ) element.scrollIntoView ( element )
});
}
Check out strptime in the time module. It is the inverse of strftime.
$ python
>>> import time
>>> my_time = time.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
time.struct_time(tm_year=2005, tm_mon=6, tm_mday=1,
tm_hour=13, tm_min=33, tm_sec=0,
tm_wday=2, tm_yday=152, tm_isdst=-1)
timestamp = time.mktime(my_time)
# convert time object to datetime
from datetime import datetime
my_datetime = datetime.fromtimestamp(timestamp)
# convert time object to date
from datetime import date
my_date = date.fromtimestamp(timestamp)
Try this:
#!/usr/bin/env python
import os
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username="username", password="password")
sftp = ssh.open_sftp()
localpath = '/home/e100075/python/ss.txt'
remotepath = '/home/developers/screenshots/ss.txt'
sftp.put(localpath, remotepath)
sftp.close()
ssh.close()
I used this more concisely :
var sys = require('sys')
var exec = require('child_process').exec;
function puts(error, stdout, stderr) { sys.puts(stdout) }
exec("ls -la", puts);
it works perfectly. :)
Use the Array#join
method (the argument to join
is what to insert between the strings - in this case a space):
@arr.join(" ")
JPA specification contains a very precise description of semantics of these operations, better than in javadoc:
The semantics of the persist operation, applied to an entity X are as follows:
If X is a new entity, it becomes managed. The entity X will be entered into the database at or before transaction commit or as a result of the flush operation.
If X is a preexisting managed entity, it is ignored by the persist operation. However, the persist operation is cascaded to entities referenced by X, if the relationships from X to these other entities are annotated with the
cascade=PERSIST
orcascade=ALL
annotation element value or specified with the equivalent XML descriptor element.If X is a removed entity, it becomes managed.
If X is a detached object, the
EntityExistsException
may be thrown when the persist operation is invoked, or theEntityExistsException
or anotherPersistenceException
may be thrown at flush or commit time.For all entities Y referenced by a relationship from X, if the relationship to Y has been annotated with the cascade element value
cascade=PERSIST
orcascade=ALL
, the persist operation is applied to Y.
The semantics of the merge operation applied to an entity X are as follows:
If X is a detached entity, the state of X is copied onto a pre-existing managed entity instance X' of the same identity or a new managed copy X' of X is created.
If X is a new entity instance, a new managed entity instance X' is created and the state of X is copied into the new managed entity instance X'.
If X is a removed entity instance, an
IllegalArgumentException
will be thrown by the merge operation (or the transaction commit will fail).If X is a managed entity, it is ignored by the merge operation, however, the merge operation is cascaded to entities referenced by relationships from X if these relationships have been annotated with the cascade element value
cascade=MERGE
orcascade=ALL
annotation.For all entities Y referenced by relationships from X having the cascade element value
cascade=MERGE
orcascade=ALL
, Y is merged recursively as Y'. For all such Y referenced by X, X' is set to reference Y'. (Note that if X is managed then X is the same object as X'.)If X is an entity merged to X', with a reference to another entity Y, where
cascade=MERGE
orcascade=ALL
is not specified, then navigation of the same association from X' yields a reference to a managed object Y' with the same persistent identity as Y.
If you set up your file system differently or looking for a different way of setting up a file system and then checking if a file exists in the documents folder heres an another example. also show dynamic checking
for (int i = 0; i < numberHere; ++i){
NSFileManager* fileMgr = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString* imageName = [NSString stringWithFormat:@"image-%@.png", i];
NSString* currentFile = [documentsDirectory stringByAppendingPathComponent:imageName];
BOOL fileExists = [fileMgr fileExistsAtPath:currentFile];
if (fileExists == NO){
cout << "DOESNT Exist!" << endl;
} else {
cout << "DOES Exist!" << endl;
}
}
There is collection of Func<...>
classes - Func that is probably what you are looking for:
void MyMethod(Func<int> param1 = null)
This defines method that have parameter param1
with default value null
(similar to AS), and a function that returns int
. Unlike AS in C# you need to specify type of the function's arguments.
So if you AS usage was
MyMethod(function(intArg, stringArg) { return true; })
Than in C# it would require param1
to be of type Func<int, siring, bool>
and usage like
MyMethod( (intArg, stringArg) => { return true;} );
header_remove("X-Powered-By");
I go to build.gradle
and click sync now. Then it worked.
Update :
File
-> Sync Project with Gradle Files
(Android Studio 3.1.1)
Tools
-> Android
-> Sync Project with Gradle Files
(Android Studio 3.0.1)
Or You can click on the icon from the toolbar.
This answer may not help works for later version as Android studio Team work on making the tool more better, the way to sync may be different in the next version of Android Studio.
COMMON WAY that may helps is try to sync project and then Invalidate Caches and Restart Android Studio.
Solution for Android Studio 3.1.2
[See below answer]
Since Dave asked for me to repeat my answer to Omitting all xsi and xsd namespaces when serializing an object in .NET, I have updated this post and repeated my answer here from the afore-mentioned link. The example used in this answer is the same example used for the other question. What follows is copied, verbatim.
After reading Microsoft's documentation and several solutions online, I have discovered the solution to this problem. It works with both the built-in XmlSerializer
and custom XML serialization via IXmlSerialiazble
.
To whit, I'll use the same MyTypeWithNamespaces
XML sample that's been used in the answers to this question so far.
[XmlRoot("MyTypeWithNamespaces", Namespace="urn:Abracadabra", IsNullable=false)]
public class MyTypeWithNamespaces
{
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
// Don't do this!! Microsoft's documentation explicitly says it's not supported.
// It doesn't throw any exceptions, but in my testing, it didn't always work.
// new XmlQualifiedName(string.Empty, string.Empty), // And don't do this:
// new XmlQualifiedName("", "")
// DO THIS:
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
// Add any other namespaces, with prefixes, here.
});
}
// If you have other constructors, make sure to call the default constructor.
public MyTypeWithNamespaces(string label, int epoch) : this( )
{
this._label = label;
this._epoch = epoch;
}
// An element with a declared namespace different than the namespace
// of the enclosing type.
[XmlElement(Namespace="urn:Whoohoo")]
public string Label
{
get { return this._label; }
set { this._label = value; }
}
private string _label;
// An element whose tag will be the same name as the property name.
// Also, this element will inherit the namespace of the enclosing type.
public int Epoch
{
get { return this._epoch; }
set { this._epoch = value; }
}
private int _epoch;
// Per Microsoft's documentation, you can add some public member that
// returns a XmlSerializerNamespaces object. They use a public field,
// but that's sloppy. So I'll use a private backed-field with a public
// getter property. Also, per the documentation, for this to work with
// the XmlSerializer, decorate it with the XmlNamespaceDeclarations
// attribute.
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
}
That's all to this class. Now, some objected to having an XmlSerializerNamespaces
object somewhere within their classes; but as you can see, I neatly tucked it away in the default constructor and exposed a public property to return the namespaces.
Now, when it comes time to serialize the class, you would use the following code:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
/******
OK, I just figured I could do this to make the code shorter, so I commented out the
below and replaced it with what follows:
// You have to use this constructor in order for the root element to have the right namespaces.
// If you need to do custom serialization of inner objects, you can use a shortened constructor.
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces), new XmlAttributeOverrides(),
new Type[]{}, new XmlRootAttribute("MyTypeWithNamespaces"), "urn:Abracadabra");
******/
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
// I'll use a MemoryStream as my backing store.
MemoryStream ms = new MemoryStream();
// This is extra! If you want to change the settings for the XmlSerializer, you have to create
// a separate XmlWriterSettings object and use the XmlTextWriter.Create(...) factory method.
// So, in this case, I want to omit the XML declaration.
XmlWriterSettings xws = new XmlWriterSettings();
xws.OmitXmlDeclaration = true;
xws.Encoding = Encoding.UTF8; // This is probably the default
// You could use the XmlWriterSetting to set indenting and new line options, but the
// XmlTextWriter class has a much easier method to accomplish that.
// The factory method returns a XmlWriter, not a XmlTextWriter, so cast it.
XmlTextWriter xtw = (XmlTextWriter)XmlTextWriter.Create(ms, xws);
// Then we can set our indenting options (this is, of course, optional).
xtw.Formatting = Formatting.Indented;
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
Once you have done this, you should get the following output:
<MyTypeWithNamespaces>
<Label xmlns="urn:Whoohoo">myLabel</Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
I have successfully used this method in a recent project with a deep hierachy of classes that are serialized to XML for web service calls. Microsoft's documentation is not very clear about what to do with the publicly accesible XmlSerializerNamespaces
member once you've created it, and so many think it's useless. But by following their documentation and using it in the manner shown above, you can customize how the XmlSerializer generates XML for your classes without resorting to unsupported behavior or "rolling your own" serialization by implementing IXmlSerializable
.
It is my hope that this answer will put to rest, once and for all, how to get rid of the standard xsi
and xsd
namespaces generated by the XmlSerializer
.
UPDATE: I just want to make sure I answered the OP's question about removing all namespaces. My code above will work for this; let me show you how. Now, in the example above, you really can't get rid of all namespaces (because there are two namespaces in use). Somewhere in your XML document, you're going to need to have something like xmlns="urn:Abracadabra" xmlns:w="urn:Whoohoo
. If the class in the example is part of a larger document, then somewhere above a namespace must be declared for either one of (or both) Abracadbra
and Whoohoo
. If not, then the element in one or both of the namespaces must be decorated with a prefix of some sort (you can't have two default namespaces, right?). So, for this example, Abracadabra
is the default namespace. I could inside my MyTypeWithNamespaces
class add a namespace prefix for the Whoohoo
namespace like so:
public MyTypeWithNamespaces
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra"), // Default Namespace
new XmlQualifiedName("w", "urn:Whoohoo")
});
}
Now, in my class definition, I indicated that the <Label/>
element is in the namespace "urn:Whoohoo"
, so I don't need to do anything further. When I now serialize the class using my above serialization code unchanged, this is the output:
<MyTypeWithNamespaces xmlns:w="urn:Whoohoo">
<w:Label>myLabel</w:Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Because <Label>
is in a different namespace from the rest of the document, it must, in someway, be "decorated" with a namespace. Notice that there are still no xsi
and xsd
namespaces.
This ends my answer to the other question. But I wanted to make sure I answered the OP's question about using no namespaces, as I feel I didn't really address it yet. Assume that <Label>
is part of the same namespace as the rest of the document, in this case urn:Abracadabra
:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Your constructor would look as it would in my very first code example, along with the public property to retrieve the default namespace:
// As noted below, per Microsoft's documentation, if the class exposes a public
// member of type XmlSerializerNamespaces decorated with the
// XmlNamespacesDeclarationAttribute, then the XmlSerializer will utilize those
// namespaces during serialization.
public MyTypeWithNamespaces( )
{
this._namespaces = new XmlSerializerNamespaces(new XmlQualifiedName[] {
new XmlQualifiedName(string.Empty, "urn:Abracadabra") // Default Namespace
});
}
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces Namespaces
{
get { return this._namespaces; }
}
private XmlSerializerNamespaces _namespaces;
Then, later, in your code that uses the MyTypeWithNamespaces
object to serialize it, you would call it as I did above:
MyTypeWithNamespaces myType = new MyTypeWithNamespaces("myLabel", 42);
XmlSerializer xs = new XmlSerializer(typeof(MyTypeWithNamespaces),
new XmlRootAttribute("MyTypeWithNamespaces") { Namespace="urn:Abracadabra" });
...
// Above, you'd setup your XmlTextWriter.
// Now serialize our object.
xs.Serialize(xtw, myType, myType.Namespaces);
And the XmlSerializer
would spit back out the same XML as shown immediately above with no additional namespaces in the output:
<MyTypeWithNamespaces>
<Label>myLabel<Label>
<Epoch>42</Epoch>
</MyTypeWithNamespaces>
Replace this :
$('#subscription_order_form').submit(function(e){
e.preventDefault();
});
with this:
$('#subscription_order_form').on('keydown', function(e){
if (e.which===13) e.preventDefault();
});
That will prevent the form from submitting when Enter key is pressed as it prevents the default action of the key, but the form will submit normally on click.
This is really more of a serverfault-type question, but you can use netstat.
something like:
# netstat -lpnt | grep 6000 | grep ssh
This will tell you if there's an ssh process listening on the specified port. it will also tell you the PID of the process.
If you really want to double-check that the ssh process was started with the right options, you can then look up the process by PID in something like
# ps aux | grep PID
With MoQ, you can mock concrete classes:
var mocked = new Mock<MyConcreteClass>();
but this allows you to override virtual
code (methods and properties).
You will need wrapper classes:
public class SomeIntInfo
{
[XmlAttribute]
public int Value { get; set; }
}
public class SomeStringInfo
{
[XmlAttribute]
public string Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeStringInfo SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeIntInfo SomeInfo { get; set; }
}
or a more generic approach if you prefer:
public class SomeInfo<T>
{
[XmlAttribute]
public T Value { get; set; }
}
public class SomeModel
{
[XmlElement("SomeStringElementName")]
public SomeInfo<string> SomeString { get; set; }
[XmlElement("SomeInfoElementName")]
public SomeInfo<int> SomeInfo { get; set; }
}
And then:
class Program
{
static void Main()
{
var model = new SomeModel
{
SomeString = new SomeInfo<string> { Value = "testData" },
SomeInfo = new SomeInfo<int> { Value = 5 }
};
var serializer = new XmlSerializer(model.GetType());
serializer.Serialize(Console.Out, model);
}
}
will produce:
<?xml version="1.0" encoding="ibm850"?>
<SomeModel xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SomeStringElementName Value="testData" />
<SomeInfoElementName Value="5" />
</SomeModel>
To scroll an element into view of a div, only if needed, you can use this scrollIfNeeded
function:
function scrollIfNeeded(element, container) {_x000D_
if (element.offsetTop < container.scrollTop) {_x000D_
container.scrollTop = element.offsetTop;_x000D_
} else {_x000D_
const offsetBottom = element.offsetTop + element.offsetHeight;_x000D_
const scrollBottom = container.scrollTop + container.offsetHeight;_x000D_
if (offsetBottom > scrollBottom) {_x000D_
container.scrollTop = offsetBottom - container.offsetHeight;_x000D_
}_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('btn').addEventListener('click', ev => {_x000D_
ev.preventDefault();_x000D_
scrollIfNeeded(document.getElementById('goose'), document.getElementById('container'));_x000D_
});
_x000D_
.scrollContainer {_x000D_
overflow-y: auto;_x000D_
max-height: 100px;_x000D_
position: relative;_x000D_
border: 1px solid red;_x000D_
width: 120px;_x000D_
}_x000D_
_x000D_
body {_x000D_
padding: 10px;_x000D_
}_x000D_
_x000D_
.box {_x000D_
margin: 5px;_x000D_
background-color: yellow;_x000D_
height: 25px;_x000D_
display: flex;_x000D_
align-items: center;_x000D_
justify-content: center;_x000D_
}_x000D_
_x000D_
#goose {_x000D_
background-color: lime;_x000D_
}
_x000D_
<div id="container" class="scrollContainer">_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div id="goose" class="box">goose</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
<div class="box">duck</div>_x000D_
</div>_x000D_
_x000D_
<button id="btn">scroll to goose</button>
_x000D_
I would use the readonly attribute
<input type="checkbox" readonly>
Then use CSS to disable interactions:
input[type='checkbox'][readonly]{
pointer-events: none;
}
Note that using the pseudo-class :read-only doesn't work here.
input[type='checkbox']:read-only{ /*not working*/
pointer-events: none;
}
Say if you have
/**
*
*/
public KKSSocket(final KKSApp app, final String name) {
this.app = app;
this.name = name;
...
}
then a sub-class named KKSUDPSocket extending KKSSocket could have:
/**
* @param app
* @param path
* @param remoteAddr
*/
public KKSUDPSocket(KKSApp app, String path, KKSAddress remoteAddr) {
super(app, path, remoteAddr);
}
and
/**
* @param app
* @param path
*/
public KKSUDPSocket(KKSApp app, String path) {
super(app, path);
}
You simply pass the arguments up the constructor chain, like method calls to super classes, but using super(...) which references the super-class constructor and passes in the given args.
DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:
DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;
Changing Command Execute Timeout in Management Studio:
Click on Tools -> Options
Select Query Execution from tree on left side and enter command timeout in "Execute Timeout" control.
Changing Command Timeout in Server:
In the object browser tree right click on the server which give you timeout and select "Properties" from context menu.
Now in "Server Properties -....." dialog click on "Connections" page in "Select a Page" list (on left side). On the right side you will get property
Remote query timeout (in seconds, 0 = no timeout):
[up/down control]
you can set the value in up/down control.
Try this ...
StringRequest sr = new StringRequest(type,url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
// valid response
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
// error
}
}){
@Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
params.put("grant_type", "password");
return params;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String,String> params = new HashMap<String, String>();
// Removed this line if you dont need it or Use application/json
// params.put("Content-Type", "application/x-www-form-urlencoded");
return params;
}
I had same error and the mistake was that I had added list and dictionary into the same list (object) and when I used to iterate over the list of dictionaries and use to hit a list (type) object then I used to get this error.
Its was a code error and made sure that I only added dictionary objects to that list and list typed object into the list, this solved my issue as well.
You can either have the newly inserted ID being output to the SSMS console like this:
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar()
(instead of .ExecuteNonQuery()
) to read the resulting ID
back.
Or if you need to capture the newly inserted ID
inside T-SQL (e.g. for later further processing), you need to create a table variable:
DECLARE @OutputTbl TABLE (ID INT)
INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')
This way, you can put multiple values into @OutputTbl
and do further processing on those. You could also use a "regular" temporary table (#temp
) or even a "real" persistent table as your "output target" here.
Use insert
:
In [1]: ls = [1,2,3]
In [2]: ls.insert(0, "new")
In [3]: ls
Out[3]: ['new', 1, 2, 3]
I have always found it difficult to remember all the keys; so I keep the below notes handy, hope they help someone! Let me know if it can be improved.
Key: An attribute or combination of attributes that uniquely identify an entity/record in a relational table.
PK: A single key that is unique and not-null. It is one of the candidate keys.
Foreign Key: FK is a key in one table (child) that uniquely identifies a row of another table (parent). A FK is not-unique in the child table. It is a candidate key in the parent table. Referential integrity is maintained as the value in FK is present as a value in PK in parent table else it is NULL.
Unique Key: A unique key that may or may not be NULL
Natural key: PK in OLTP. It may be a PK in OLAP.
Surrogate Key: It is the Surrogate PK in OLAP acting as the substitute of the PK in OLTP. Artificial key generated internally in OLAP.
Composite Key: PK made up of multiple attributes
SuperKey: A key that can be uniquely used to identify a database record, that may contain extra attributes that are not necessary to uniquely identify records.
Candidate Key: A candidate key can be uniquely used to identify a database record without any extraneous data. They are Not Null and unique. It is a minimal super-key.
Alternate Key: A candidate key that is not the primary key is called an alternate key.
Candidate Key/s with Extraneous data: Consider that can be used to identify a record in the Employee table but candidate key alone is sufficient for this task. So becomes the extraneous data.
Note that the PK, Foreign Key, Unique Key, Natural key, Surrogate Key, Composite Key are defined as Database objects; where the Natural key is a PK in the OLTP and could be a PK in the target OLAP. For the rest of the keys, it's up to the DB designer/architect to decide whether unique/not-null/referential integrity constraints need to enforced or not.
Below I have tried to use set theory to simplify the representation of the membership of the keys w.r.t. each other.
key = { All of the below keys }
PK = { PK }
Foreign Key = { Key with Not Null constraint }
Unique Key = { {Candidate Key/s}, {attributes containing NULL} }
Natural key = { PK }
Surrogate Key = { PK }
Composite Key = { PK }
Super Key = { {Candidate Key/s}, {Candidate Key/s with Extraneous data} }
Candidate Key = { PK, {Alternate Key/s} }
Alternate Key = { {Candidate Keys} - PK }
Candidate Key/s with Extraneous data = { }
I have summarized it below:
Notes: an-overview-of-the-database-keys-primary-key-composite-key-surrogate-key-et-al
Here is how I solved it, based on the answers here:
Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.
String sql = "INSERT INTO \"TableName\"" +
"(\"Column1\", \"Column2\",\"Column3\",\"Column4\")" +
"VALUES ('value1',value2, 'value3', 'value4') RETURNING
\"TableName\".\"TableId\"";
PreparedStatement prpState = conn.prepareStatement(sql);
ResultSet rs = prpState.executeQuery();
if(rs.next()){
System.out.println(rs.getInt(1));
}
Have you googled about it - insert update delete access vb.net, there are lots of reference about this.
Insert Update Delete Navigation & Searching In Access Database Using VB.NET
what could be the easier way to connect and manipulate the DB?
Use OleDBConnection class to make connection with DB
is it by using MS ACCESS 2003 or MS ACCESS 2007?
you can use any you want to use or your client will use on their machine.
it seems that you want to find some example of opereations fo the database. Here is an example of Access 2010 for your reference:
Example code snippet:
Imports System
Imports System.Data
Imports System.Data.OleDb
Public Class DBUtil
Private connectionString As String
Public Sub New()
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=d:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
End Sub
Public Function GetCategories() As DataSet
Dim query As String = "SELECT * FROM Categories"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Categories")
End Function
Public SubUpdateCategories(ByVal name As String)
Dim query As String = "update Categories set name = 'new2' where name = ?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("Name", name)
Return FillDataSet(cmd, "Categories")
End Sub
Public Function GetItems() As DataSet
Dim query As String = "SELECT * FROM Items"
Dim cmd As New OleDbCommand(query)
Return FillDataSet(cmd, "Items")
End Function
Public Function GetItems(ByVal categoryID As Integer) As DataSet
'Create the command.
Dim query As String = "SELECT * FROM Items WHERE Category_ID=?"
Dim cmd As New OleDbCommand(query)
cmd.Parameters.AddWithValue("category_ID", categoryID)
'Fill the dataset.
Return FillDataSet(cmd, "Items")
End Function
Public Sub AddCategory(ByVal name As String)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Categories "
insertSQL &= "VALUES(?)"
Dim cmd As New OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Name", name)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Public Sub AddItem(ByVal title As String, ByVal description As String, _
ByVal price As Decimal, ByVal categoryID As Integer)
Dim con As New OleDbConnection(connectionString)
'Create the command.
Dim insertSQL As String = "INSERT INTO Items "
insertSQL &= "(Title, Description, Price, Category_ID)"
insertSQL &= "VALUES (?, ?, ?, ?)"
Dim cmd As New OleDb.OleDbCommand(insertSQL, con)
cmd.Parameters.AddWithValue("Title", title)
cmd.Parameters.AddWithValue("Description", description)
cmd.Parameters.AddWithValue("Price", price)
cmd.Parameters.AddWithValue("CategoryID", categoryID)
Try
con.Open()
cmd.ExecuteNonQuery()
Finally
con.Close()
End Try
End Sub
Private Function FillDataSet(ByVal cmd As OleDbCommand, ByVal tableName As String) As DataSet
Dim con As New OleDb.OleDbConnection
Dim dbProvider As String = "Provider=Microsoft.ace.oledb.12.0;"
Dim dbSource = "Data Source=D:\DB\Database11.accdb"
connectionString = dbProvider & dbSource
con.ConnectionString = connectionString
cmd.Connection = con
Dim adapter As New OleDbDataAdapter(cmd)
Dim ds As New DataSet()
Try
con.Open()
adapter.Fill(ds, tableName)
Finally
con.Close()
End Try
Return ds
End Function
End Class
Refer these links:
Insert, Update, Delete & Search Values in MS Access 2003 with VB.NET 2005
INSERT, DELETE, UPDATE AND SELECT Data in MS-Access with VB 2008
How Add new record ,Update record,Delete Records using Vb.net Forms when Access as a back
Possible alternative from the source code of Integer.compare
method which requires API Version 19
is :
public int compareTo(Animal other) {
return Integer.valueOf(this.year_discovered).compareTo(other.year_discovered);
}
This alternative does not require you to use API version 19
.
This approach can be used to automate this (the following exemplary solution is in python, although obviously it can be ported to any language):
you can strip the whitespace beforehand AND save the positions of non-whitespace characters so you can use them later to find out the matched string boundary positions in the original string like the following:
def regex_search_ignore_space(regex, string):
no_spaces = ''
char_positions = []
for pos, char in enumerate(string):
if re.match(r'\S', char): # upper \S matches non-whitespace chars
no_spaces += char
char_positions.append(pos)
match = re.search(regex, no_spaces)
if not match:
return match
# match.start() and match.end() are indices of start and end
# of the found string in the spaceless string
# (as we have searched in it).
start = char_positions[match.start()] # in the original string
end = char_positions[match.end()] # in the original string
matched_string = string[start:end] # see
# the match WITH spaces is returned.
return matched_string
with_spaces = 'a li on and a cat'
print(regex_search_ignore_space('lion', with_spaces))
# prints 'li on'
If you want to go further you can construct the match object and return it instead, so the use of this helper will be more handy.
And the performance of this function can of course also be optimized, this example is just to show the path to a solution.
Disclaim: the following suggestion could be an overhead depending on the situation. The function is only tested with MSSQL 2008 R2 but seams be compatible to other versions
if you wane do this with many Id's you may could use a function which creates a temp table where you will be able to DELETE FROM the selection
how the query could look like:
-- not tested
-- @ids will contain a varchar with your ids e.g.'9 12 27 37'
DELETE FROM table WHERE id IN (SELECT i.number FROM iter_intlist_to_tbl(@ids))
here is the function:
ALTER FUNCTION iter_intlist_to_tbl (@list nvarchar(MAX))
RETURNS @tbl TABLE (listpos int IDENTITY(1, 1) NOT NULL,
number int NOT NULL) AS
-- funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer liste von elementen
BEGIN
-- Deklaration der Variablen
DECLARE @startpos int,
@endpos int,
@textpos int,
@chunklen smallint,
@str nvarchar(4000),
@tmpstr nvarchar(4000),
@leftover nvarchar(4000)
-- Startwerte festlegen
SET @textpos = 1
SET @leftover = ''
-- Loop 1
WHILE @textpos <= datalength(@list) / 2
BEGIN
--
SET @chunklen = 4000 - datalength(@leftover) / 2 --datalength() gibt die anzahl der bytes zurück (mit Leerzeichen)
--
SET @tmpstr = ltrim(@leftover + substring(@list, @textpos, @chunklen))--SUBSTRING ( @string ,start , length ) | ltrim(@string) abschneiden aller Leerzeichen am Begin des Strings
--hochzählen der TestPosition
SET @textpos = @textpos + @chunklen
--start position 0 setzen
SET @startpos = 0
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr)--charindex(searchChar,Wo,Startposition)
-- Loop 2
WHILE @endpos > 0
BEGIN
--str ist der string welcher zwischen den [LEERZEICHEN] steht
SET @str = substring(@tmpstr, @startpos + 1, @endpos - @startpos - 1)
--wenn @str nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF @str <> ''
INSERT @tbl (number) VALUES(convert(int, @str))-- convert(Ziel-Type,Value)
-- start wird auf das letzte bekannte end gesetzt
SET @startpos = @endpos
-- end position bekommt den charindex wo ein [LEERZEICHEN] gefunden wird
SET @endpos = charindex(' ' COLLATE Slovenian_BIN2, @tmpstr, @startpos + 1)
END
-- Loop 2
-- dient dafür den letzten teil des strings zu selektieren
SET @leftover = right(@tmpstr, datalength(@tmpstr) / 2 - @startpos)--right(@string,anzahl der Zeichen) bsp.: right("abcdef",3) => "def"
END
-- Loop 1
--wenn @leftover nach dem entfernen aller [LEERZEICHEN] nicht leer ist wird er zu int Convertiert und @tbl unter der Spalte 'number' hinzugefügt
IF ltrim(rtrim(@leftover)) <> ''
INSERT @tbl (number) VALUES(convert(int, @leftover))
RETURN
END
-- ############################ WICHTIG ############################
-- das is ein Beispiel wie man die Funktion benutzt
--
--CREATE PROCEDURE get_product_names_iter
-- @ids varchar(50) AS
--SELECT P.ProductName, P.ProductID
--FROM Northwind.Products P
--JOIN iter_intlist_to_tbl(@ids) i ON P.ProductID = i.number
--go
--EXEC get_product_names_iter '9 12 27 37'
--
-- Funktion gefunden auf http://www.sommarskog.se/arrays-in-sql-2005.html
-- dient zum übergeben einer Liste von Id's
-- ############################ WICHTIG ############################
In case anyone is still looking for Helvetica Neue Condensed Bold, you essentially have two options.
A very cheap compromise is to buy Franklin from fontspring and then use "HelveticaNeue-CondensedBold" as the preferred font in your CSS.
h2 {"HelveticaNeue-CondensedBold", "FranklinGothicFSDemiCondensed", Arial, sans-serif;}
Then if a Mac user loads your site they see Helvetica Neue, but if they're on another platform they see Franklin.
UPDATE: I discovered a much closer match to Helvetica Neue Condensed Bold is Nimbus Sans Novus D Condensed bold. In fact, it is also derived from Helvetica. You can get it at MyFonts.com for $20 (desktop) and $20 (web, 10k pageviews). Web with unlimited pageviews is $160. I have used this font throughout (i.e. NOT exploiting the Mac's built in "NimbusSansNovusDBoldCondensed" at all) because it leads to a design that is more uniform across browsers. Built in HN and Nimbus Sans are very similar in all respects but point size. Nimbus needs a few extra points to get an identical size match.
By default, a batch file will display its command as it runs. The purpose of this first command which @echo off is to turn off this display. The command "echo off" turns off the display for the whole script, except for the "echo off" command itself. The "at" sign "@" in front makes the command apply to itself as well.
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
There are three options to get rid of this warning:
Below pattern perfectly works in case of leap year and as well as with normal dates. The date format is : YYYY-MM-DD
<input type="text" placeholder="YYYY-MM-DD" pattern="(?:19|20)(?:(?:[13579][26]|[02468][048])-(?:(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-9])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:30))|(?:(?:0[13578]|1[02])-31))|(?:[0-9]{2}-(?:0[1-9]|1[0-2])-(?:0[1-9]|1[0-9]|2[0-8])|(?:(?!02)(?:0[1-9]|1[0-2])-(?:29|30))|(?:(?:0[13578]|1[02])-31)))" class="form-control " name="eventDate" id="" required autofocus autocomplete="nope">
I got this solution from http://html5pattern.com/Dates. Hope it may help someone.
Just in case someone stumbles upon this like I did and doesn't realise, the two variations above are for different use cases.
The following:
.blue-border, .background {
border: 1px solid #00f;
background: #fff;
}
is for when you want to add styles to elements that have either the blue-border or background class, for example:
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
would all get a blue border and white background applied to them.
However, the accepted answer is different.
.blue-border.background {
border: 1px solid #00f;
background: #fff;
}
This applies the styles to elements that have both classes so in this example only the <div>
with both classes should get the styles applied (in browsers that interpret the CSS properly):
<div class="blue-border">Hello</div>
<div class="background">World</div>
<div class="blue-border background">!</div>
So basically think of it like this, comma separating applies to elements with one class OR another class and dot separating applies to elements with one class AND another class.
Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.
Discord supports Markdown and uses highlight.js to highlight code-blocks.
Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.
To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).
```language
message
```
Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).
Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.
Use the CSS function from jQuery to set styles to your items :
$('#buttonId').css({ "background-color": 'brown'});
Yes, on a 32bit machine the maximum amount of memory usable is around 4GB. Actually, depending on the OS it might be less due to parts of the address space being reserved: On Windows you can only use 3.5GB for example.
On 64bit you can indeed address 2^64 bytes of memory. Not that you'll ever have those - but then again, a long time ago the same thing was said about ever needing more than 640kb of memory...
Just want to share another option:
# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)
# commit (or flush)
session.commit()
http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting
In this example, the following codes shall works fine:
obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()
As per Wikipedia: runtime library/run-time system.
In computer programming, a runtime library is a special program library used by a compiler, to implement functions built into a programming language, during the runtime (execution) of a computer program. This often includes functions for input and output, or for memory management.
A run-time system (also called runtime system or just runtime) is software designed to support the execution of computer programs written in some computer language. The run-time system contains implementations of basic low-level commands and may also implement higher-level commands and may support type checking, debugging, and even code generation and optimization. Some services of the run-time system are accessible to the programmer through an application programming interface, but other services (such as task scheduling and resource management) may be inaccessible.
Re: your edit, "runtime" and "runtime library" are two different names for the same thing.
Hopefully, this will help...
interface Param {
title: string;
callback: (error: Error, data: string) => void;
}
Or in a Function
let myfunction = (title: string, callback: (error: Error, data: string) => void): string => {
callback(new Error(`Error Message Here.`), "This is callback data.");
return title;
}
How about this one using BlueBird?
function fetchUserDetails(arr) {
return Promise.each(arr, function(email) {
return db.getUser(email).done(function(res) {
logger.log(res);
});
});
}
For my responsive design, my drop-box down-arrow on the right side of the box (vertical accordion), accepted percentage as position. Initially the down-arrow was "position: absolute; right: 13px;". With the 97% positioning it worked like charm as follows:
> background: #ffffff;
> background-image: url(PATH-TO-arrow_down.png); /*fall back - IE */
> background-position: 97% center; /*fall back - IE */
> background-repeat: no-repeat; /*fall back - IE */
> background-image: url(PATH-TO-arrow_down.png) no-repeat 97% center;
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -moz-linear-gradient(top, #ffffff 1%, #eaeaea 100%);
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -webkit-gradient(linear, left top, left bottom, color-stop(1%,#ffffff), color-stop(100%,#eaeaea));
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -webkit-linear-gradient(top, #ffffff 1%,#eaeaea 100%);
> background: url(PATH-TO-arrow_down.png) no-repeat 97% center, -o-linear-gradient(top, #ffffff 1%,#eaeaea 100%);<br />
> filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#ffffff', endColorstr='#eaeaea',GradientType=0 );
P.S. Sorry, don't know how to handle the filters.
I use the Publish Subscribe pattern for complicated class-dependencies:
ViewModel:
public class ViewModel : ViewModelBase
{
public ViewModel()
{
CloseComand = new DelegateCommand((obj) =>
{
MessageBus.Instance.Publish(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, null);
});
}
}
Window:
public partial class SomeWindow : Window
{
Subscription _subscription = new Subscription();
public SomeWindow()
{
InitializeComponent();
_subscription.Subscribe(Messages.REQUEST_DEPLOYMENT_SETTINGS_CLOSED, obj =>
{
this.Close();
});
}
}
You can leverage Bizmonger.Patterns to get the MessageBus.
MessageBus
public class MessageBus
{
#region Singleton
static MessageBus _messageBus = null;
private MessageBus() { }
public static MessageBus Instance
{
get
{
if (_messageBus == null)
{
_messageBus = new MessageBus();
}
return _messageBus;
}
}
#endregion
#region Members
List<Observer> _observers = new List<Observer>();
List<Observer> _oneTimeObservers = new List<Observer>();
List<Observer> _waitingSubscribers = new List<Observer>();
List<Observer> _waitingUnsubscribers = new List<Observer>();
int _publishingCount = 0;
#endregion
public void Subscribe(string message, Action<object> response)
{
Subscribe(message, response, _observers);
}
public void SubscribeFirstPublication(string message, Action<object> response)
{
Subscribe(message, response, _oneTimeObservers);
}
public int Unsubscribe(string message, Action<object> response)
{
var observers = new List<Observer>(_observers.Where(o => o.Respond == response).ToList());
observers.AddRange(_waitingSubscribers.Where(o => o.Respond == response));
observers.AddRange(_oneTimeObservers.Where(o => o.Respond == response));
if (_publishingCount == 0)
{
observers.ForEach(o => _observers.Remove(o));
}
else
{
_waitingUnsubscribers.AddRange(observers);
}
return observers.Count;
}
public int Unsubscribe(string subscription)
{
var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription).ToList());
observers.AddRange(_waitingSubscribers.Where(o => o.Subscription == subscription));
observers.AddRange(_oneTimeObservers.Where(o => o.Subscription == subscription));
if (_publishingCount == 0)
{
observers.ForEach(o => _observers.Remove(o));
}
else
{
_waitingUnsubscribers.AddRange(observers);
}
return observers.Count;
}
public void Publish(string message, object payload)
{
_publishingCount++;
Publish(_observers, message, payload);
Publish(_oneTimeObservers, message, payload);
Publish(_waitingSubscribers, message, payload);
_oneTimeObservers.RemoveAll(o => o.Subscription == message);
_waitingUnsubscribers.Clear();
_publishingCount--;
}
private void Publish(List<Observer> observers, string message, object payload)
{
Debug.Assert(_publishingCount >= 0);
var subscribers = observers.Where(o => o.Subscription.ToLower() == message.ToLower());
foreach (var subscriber in subscribers)
{
subscriber.Respond(payload);
}
}
public IEnumerable<Observer> GetObservers(string subscription)
{
var observers = new List<Observer>(_observers.Where(o => o.Subscription == subscription));
return observers;
}
public void Clear()
{
_observers.Clear();
_oneTimeObservers.Clear();
}
#region Helpers
private void Subscribe(string message, Action<object> response, List<Observer> observers)
{
Debug.Assert(_publishingCount >= 0);
var observer = new Observer() { Subscription = message, Respond = response };
if (_publishingCount == 0)
{
observers.Add(observer);
}
else
{
_waitingSubscribers.Add(observer);
}
}
#endregion
}
}
Subscription
public class Subscription
{
#region Members
List<Observer> _observerList = new List<Observer>();
#endregion
public void Unsubscribe(string subscription)
{
var observers = _observerList.Where(o => o.Subscription == subscription);
foreach (var observer in observers)
{
MessageBus.Instance.Unsubscribe(observer.Subscription, observer.Respond);
}
_observerList.Where(o => o.Subscription == subscription).ToList().ForEach(o => _observerList.Remove(o));
}
public void Subscribe(string subscription, Action<object> response)
{
MessageBus.Instance.Subscribe(subscription, response);
_observerList.Add(new Observer() { Subscription = subscription, Respond = response });
}
public void SubscribeFirstPublication(string subscription, Action<object> response)
{
MessageBus.Instance.SubscribeFirstPublication(subscription, response);
}
}
if anyone is interested to use the cURL for validation. You can use the following code.
<?php
public function validationUrl($Url){
if ($Url == NULL){
return $false;
}
$ch = curl_init($Url);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return ($httpcode >= 200 && $httpcode < 300) ? true : false;
}
Had the same problem where I specified data
but the browser was sending requests to URL ending with [Object object]
.
You should have processData
set to true
.
processData: true, // You should comment this out if is false or set to true
I think the question was asking for a solution without the use of the Collections API. One uses arrays either for low level details, where performance matters, or for a loosely coupled SOA integration. In the later, it is OK to convert them to Collections and pass them to the business logic as that.
For the low level performance stuff, it is usually already obfuscated by the quick-and-dirty imperative state-mingling by for loops, etc. In that case converting back and forth between Collections and arrays is cumbersome, unreadable, and even resource intensive.
By the way, TopCoder, anyone? Always those array parameters! So be prepared to be able to handle them when in the Arena.
Below is my interpretation of the problem, and a solution. It is different in functionality from both of the one given by Bill K and jelovirt. Also, it handles gracefully the case when the element is not in the array.
Hope that helps!
public char[] remove(char[] symbols, char c)
{
for (int i = 0; i < symbols.length; i++)
{
if (symbols[i] == c)
{
char[] copy = new char[symbols.length-1];
System.arraycopy(symbols, 0, copy, 0, i);
System.arraycopy(symbols, i+1, copy, i, symbols.length-i-1);
return copy;
}
}
return symbols;
}
You may use os.stat()
function, which is a wrapper of system call stat()
:
import os
def getSize(filename):
st = os.stat(filename)
return st.st_size
You can use a $where. Just be aware it will be fairly slow (has to execute Javascript code on every record) so combine with indexed queries if you can.
db.T.find( { $where: function() { return this.Grade1 > this.Grade2 } } );
or more compact:
db.T.find( { $where : "this.Grade1 > this.Grade2" } );
you can use $expr
as described in recent answer
Well, Pavel was close, but there's even a more simple and elegant solution to initialize a sequential container from a c style array.
In your case:
w_ (array, std::end(array))
load_weights
only sets the weights of your network. You still need to define its architecture before calling load_weights
:
def create_model():
model = Sequential()
model.add(Dense(64, input_dim=14, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))
model.add(Dense(64, init='uniform'))
model.add(LeakyReLU(alpha=0.3))
model.add(BatchNormalization(epsilon=1e-06, mode=0, momentum=0.9, weights=None))
model.add(Dropout(0.5))
model.add(Dense(2, init='uniform'))
model.add(Activation('softmax'))
return model
def train():
model = create_model()
sgd = SGD(lr=0.1, decay=1e-6, momentum=0.9, nesterov=True)
model.compile(loss='binary_crossentropy', optimizer=sgd)
checkpointer = ModelCheckpoint(filepath="/tmp/weights.hdf5", verbose=1, save_best_only=True)
model.fit(X_train, y_train, nb_epoch=20, batch_size=16, show_accuracy=True, validation_split=0.2, verbose=2, callbacks=[checkpointer])
def load_trained_model(weights_path):
model = create_model()
model.load_weights(weights_path)
Try this one dude if you're using windows:
1.) Search environment variables at your start menu's search box.
2.) Click it then go to Environment Variables...
3.) Click PATH, click Edit
4.) Click New and try to copy and paste this: C:\Program Files\nodejs\node_modules\npm\bin
If you got an error. Do the number 4.) Click New, then browse the bin folder
You can use minimalist UML state machine framework in c. https://github.com/kiishor/UML-State-Machine-in-C
It supports both finite and hierarchical state machine. It has only 3 API's, 2 structures and 1 enumeration.
The State machine is represented by state_machine_t
structure. It is an abstract structure that can be inherited to create a state machine.
//! Abstract state machine structure
struct state_machine_t
{
uint32_t Event; //!< Pending Event for state machine
const state_t* State; //!< State of state machine.
};
State is represented by pointer to state_t
structure in the framework.
If framework is configured for finite state machine then state_t
contains,
typedef struct finite_state_t state_t;
// finite state structure
typedef struct finite_state_t{
state_handler Handler; //!< State handler function (function pointer)
state_handler Entry; //!< Entry action for state (function pointer)
state_handler Exit; //!< Exit action for state (function pointer)
}finite_state_t;
The framework provides an API dispatch_event
to dispatch the event to the state machine and two API's for the state traversal.
state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);
state_machine_result_t switch_state(state_machine_t* const, const state_t*);
state_machine_result_t traverse_state(state_machine_t* const, const state_t*);
For further details on how to implement hierarchical state machine refer the GitHub repository.
code examples
https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine/readme.md
https://github.com/kiishor/UML-State-Machine-in-C/blob/master/demo/simple_state_machine_enhanced/readme.md
Usually I would say it is overkill, but there are occasionally reasons for writing unit tests for enums.
Sometimes the values assigned to enumeration members must never change or the loading of legacy persisted data will fail. Similarly, apparently unused members must not be deleted. Unit tests can be used to guard against a developer making changes without realising the implications.
webDriver.FindElement(By.CssSelector("--cssSelector--")).Click();
webDriver.SwitchTo().ActiveElement().SendKeys(fileName);
worked well for me. Taking another approach provided in answer above by Matt in C# .net could also work with Class name #32770 for upload box.
Here's how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.
in_file = open("in-file", "rb") # opening for [r]eading as [b]inary
data = in_file.read() # if you only wanted to read 512 bytes, do .read(512)
in_file.close()
out_file = open("out-file", "wb") # open for [w]riting as [b]inary
out_file.write(data)
out_file.close()
We can do this more succinctly by using the with
keyboard to handle closing the file.
with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
out_file.write(in_file.read())
If you don't want to store the entire file in memory, you can transfer it in pieces.
piece_size = 4096 # 4 KiB
with open("in-file", "rb") as in_file, open("out-file", "wb") as out_file:
while True:
piece = in_file.read(piece_size)
if piece == "":
break # end of file
out_file.write(piece)
You could try this
SELECT RIGHT( '0' + convert( varchar(2) , '0' ), 2 ) -- OUTPUTS : 00
SELECT RIGHT( '0' + convert( varchar(2) , '8' ), 2 ) -- OUTPUTS : 08
SELECT RIGHT( '0' + convert( varchar(2) , '9' ), 2 ) -- OUTPUTS : 09
SELECT RIGHT( '0' + convert( varchar(2) , '10' ), 2 ) -- OUTPUTS : 10
SELECT RIGHT( '0' + convert( varchar(2) , '11' ), 2 ) -- OUTPUTS : 11
this should help
Try using
$("#mydialog").closest(".ui-dialog-titlebar").hide();
This will hide all dialogs titles
$(".ui-dialog-titlebar").hide();
I found this code works:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy MMM dd HH:mm:ss");
Calendar calendar = new GregorianCalendar(2013,0,31);
System.out.println(sdf.format(calendar.getTime()));
you can find the rest in this tutorial:
http://www.mkyong.com/java/java-date-and-calendar-examples/
application/force-download
is not a standard MIME type. It's a hack supported by some browsers, added fairly recently.
Your question doesn't really make any sense. It's like asking why Internet Explorer 4 doesn't support the latest CSS 3 functionality.
If you want the editor to work with git operations, setting the $EDITOR
environment variable may not be enough, at least not in the case of Sublime - e.g. if you want to rebase, it will just say that the rebase was successful, but you won't have a chance to edit the file in any way, git will just close it straight away:
git rebase -i HEAD~
Successfully rebased and updated refs/heads/master.
If you want Sublime to work correctly with git, you should configure it using:
git config --global core.editor "sublime -n -w"
I came here looking for this and found the solution in this gist on github.