Some ideas in the following answer:
Steps in creating a web service using Axis2 - The client code
Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.
There are lots of web service frameworks out there...
In the case you are sure that you should be able to access given class, than this can mean you added several jars to your project containing classes with identical names (or paths) but different content and they are overshadowing each other (typically an old custom build jar contains built-in older version of a 3rd party library).
For example when you add a jar implementing:
a.b.c.d1
a.b.c.d2
but also an older version implementing only:
a.b.c.d1
(d2 is missing altogether or has restricted access)
Everything works fine in the code editor but fails during the compilation if the "old" library overshadows the new one - d2 suddenly turns out "missing or inaccessible" even when it is there.
The solution is a to check the order of compile-time libraries and make sure that the one with correct implementation goes first.
I was able to generate
static {
WSDL_LOCATION = null;
}
by configuring pom file to have a null for wsdlurl:
<plugin>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-codegen-plugin</artifactId>
<executions>
<execution>
<id>generate-sources</id>
<phase>generate-sources</phase>
<configuration>
<sourceRoot>${basedir}/target/generated/src/main/java</sourceRoot>
<wsdlOptions>
<wsdlOption>
<wsdl>${basedir}/src/main/resources/service.wsdl</wsdl>
<extraargs>
<extraarg>-client</extraarg>
<extraarg>-wsdlLocation</extraarg>
<wsdlurl />
</extraargs>
</wsdlOption>
</wsdlOptions>
</configuration>
<goals>
<goal>wsdl2java</goal>
</goals>
</execution>
</executions>
</plugin>
import vs. include
The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import
statement with an include
statement).
Another area of confusion is how to specify the location or path of the included .xsd
file: An XSD import statement has an optional attribute named schemaLocation
but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.
When you do chose to use an external .xsd
file for your WSDL, the schemaLocation
attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:
WSDL:
xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>
XSD:
<xsd:schema targetNamespace="urn:listing3"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>xmlbeans-maven-plugin</artifactId>
<executions>
<execution>
<id>generate-sources-xmlbeans</id>
<phase>generate-sources</phase>
<goals>
<goal>xmlbeans</goal>
</goals>
</execution>
</executions>
<version>2.3.3</version>
<inherited>true</inherited>
<configuration>
<schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
</configuration>
</plugin>
You can read more on this in this great IBM article. It has typos such as xsd:import
instead of xs:import
but otherwise it's fine.
It is possible to check it with the help of window.closed in an event handler on 'unload' event like this, but timeout usage is required (so result cannot be guaranteed if smth delay or prevent window from closure):
Example of JSFiddle (Tested on lates Safari, FF, Chrome, Edge and IE11 )
var win = window.open('', '', 'width=200,height=50,left=200,top=50');
win.document.write(`<html>
<head><title>CHILD WINDOW/TAB</title></head>
<body><h2>CHILD WINDOW/TAB</h2></body>
</html>`);
win.addEventListener('load',() => {
document.querySelector('.status').innerHTML += '<p>Child was loaded!</p>';
});
win.addEventListener('unload',() => {
document.querySelector('.status').innerHTML += '<p>Child was unloaded!</p>';
setTimeout(()=>{
document.querySelector('.status').innerHTML += getChildWindowStatus();
},1000);
});
win.document.close()
document.querySelector('.check-child-window').onclick = ()=> {
alert(getChildWindowStatus());
}
function getChildWindowStatus() {
if (win.closed) {
return 'Child window has been closed!';
} else {
return 'Child window has not been closed!';
}
}
If you revise your regular expression like this:
drupal-6.14/(?=sites(?!/all|/default)).*
^^
...then it will match all inputs that contain drupal-6.14/
followed by sites
followed by anything other than /all
or /default
. For example:
drupal-6.14/sites/foo
drupal-6.14/sites/bar
drupal-6.14/sitesfoo42
drupal-6.14/sitesall
Changing ?=
to ?!
to match your original regex simply negates those matches:
drupal-6.14/(?!sites(?!/all|/default)).*
^^
So, this simply means that drupal-6.14/
now cannot be followed by sites
followed by anything other than /all
or /default
. So now, these inputs will satisfy the regex:
drupal-6.14/sites/all
drupal-6.14/sites/default
drupal-6.14/sites/all42
But, what may not be obvious from some of the other answers (and possibly your question) is that your regex will also permit other inputs where drupal-6.14/
is followed by anything other than sites
as well. For example:
drupal-6.14/foo
drupal-6.14/xsites
Conclusion: So, your regex basically says to include all subdirectories of drupal-6.14
except those subdirectories of sites
whose name begins with anything other than all
or default
.
Why not use this
unbind()
before bind()
$('#myButton').unbind().bind('click', onButtonClicked);
MS-Access doesn't support ROW_NUMBER(). Use TOP 1:
SELECT TOP 1 *
FROM [MyTable]
ORDER BY [MyIdentityCOlumn]
If you need the 15th row - MS-Access has no simple, built-in, way to do this. You can simulate the rownumber by using reverse nested ordering to get this:
SELECT TOP 1 *
FROM (
SELECT TOP 15 *
FROM [MyTable]
ORDER BY [MyIdentityColumn] ) t
ORDER BY [MyIdentityColumn] DESC
If accepted answer doesn't work for you, make sure you didn't define in manifest file:
android:screenOrientation="portrait"
Which is my case.
First, let's make some test data:
create table client (client_id integer not null primary key auto_increment,
name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
client_id integer references client.id,
cash decimal(10,2),
stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
(1, 10.11, 23.22),
(2, 30.30, 40.40),
(2, 40.40, 50.50);
If you didn't need the portfolio ID, it would be easy:
select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id
+-----------+----------+--------------------+
| client_id | name | max(cash + stocks) |
+-----------+----------+--------------------+
| 1 | John Doe | 33.33 |
| 2 | Jane Doe | 90.90 |
+-----------+----------+--------------------+
Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:
select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id
+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
| 1 | 33.33 |
| 2 | 90.90 |
+-----------+----------+
Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:
select portfolio_id, cash + stocks from portfolio
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
| 5 | 33.33 |
| 6 | 33.33 |
| 8 | 90.90 |
+--------------+---------------+
Finally, we can join to the client table (as you did) in order to include the name of each client:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 1 | John Doe | 6 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:
select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks
+-----------+----------+--------------+---------------+
| client_id | name | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
| 1 | John Doe | 5 | 33.33 |
| 2 | Jane Doe | 8 | 90.90 |
+-----------+----------+--------------+---------------+
SharePoint lists V: Techniques for managing large lists :
Tutorial By Microsoft
Level: Advanced
Length: 40 - 50 minutes
When a SharePoint list gets large, you might see warnings such as, “This list exceeds the list view threshold,” or “Displaying the newest results below.” Find out why these warnings occur, and learn ways to configure your large list so that it still provides useful information.
After completing this course you will be able to:
A query's projection can only have one instance of a given name. As your WHERE clause shows, you have several tables with a column called ID. Because you are selecting *
your projection will have several columns called ID. Or it would have were it not for the compiler hurling ORA-00918.
The solution is quite simple: you will have to expand the projection to explicitly select named columns. Then you can either leave out the duplicate columns, retaining just (say) COACHES.ID or use column aliases: coaches.id as COACHES_ID
.
Perhaps that strikes you as a lot of typing, but it is the only way. If it is any comfort, SELECT *
is regarded as bad practice in production code: explicitly named columns are much safer.
The JAXB APIs are considered to be Java EE APIs and therefore are no longer contained on the default classpath in Java SE 9. In Java 11, they are completely removed from the JDK.
Java 9 introduces the concepts of modules, and by default, the java.se
aggregate module is available on the classpath (or rather, module-path). As the name implies, the java.se
aggregate module does not include the Java EE APIs that have been traditionally bundled with Java 6/7/8.
Fortunately, these Java EE APIs that were provided in JDK 6/7/8 are still in the JDK, but they just aren't on the classpath by default. The extra Java EE APIs are provided in the following modules:
java.activation
java.corba
java.transaction
java.xml.bind << This one contains the JAXB APIs
java.xml.ws
java.xml.ws.annotation
Quick and dirty solution: (JDK 9/10 only)
To make the JAXB APIs available at runtime, specify the following command-line option:
--add-modules java.xml.bind
But I still need this to work with Java 8!!!
If you try specifying --add-modules
with an older JDK, it will blow up because it's an unrecognized option. I suggest one of two options:
JDK_JAVA_OPTIONS
environment variable. This environment variable is automatically read by the java
launcher for Java 9+.-XX:+IgnoreUnrecognizedVMOptions
to make the JVM silently ignore unrecognized options, instead of blowing up. But beware! Any other command-line arguments you use will no longer be validated for you by the JVM. This option works with Oracle/OpenJDK as well as IBM JDK (as of JDK 8sr4).Alternate quick solution: (JDK 9/10 only)
Note that you can make all of the above Java EE modules available at run time by specifying the --add-modules java.se.ee
option. The java.se.ee
module is an aggregate module that includes java.se.ee
as well as the above Java EE API modules. Note, this doesn't work on Java 11 because java.se.ee
was removed in Java 11.
The Java EE API modules listed above are all marked @Deprecated(forRemoval=true)
because they are scheduled for removal in Java 11. So the --add-module
approach will no longer work in Java 11 out-of-the-box.
What you will need to do in Java 11 and forward is include your own copy of the Java EE APIs on the classpath or module path. For example, you can add the JAX-B APIs as a Maven dependency like this:
<!-- API, java.xml.bind module -->
<dependency>
<groupId>jakarta.xml.bind</groupId>
<artifactId>jakarta.xml.bind-api</artifactId>
<version>2.3.2</version>
</dependency>
<!-- Runtime, com.sun.xml.bind module -->
<dependency>
<groupId>org.glassfish.jaxb</groupId>
<artifactId>jaxb-runtime</artifactId>
<version>2.3.2</version>
</dependency>
See the JAXB Reference Implementation page for more details on JAXB.
For full details on Java modularity, see JEP 261: Module System
For Gradle or Android Studio developer: (JDK 9 and beyond)
Add the following dependencies to your build.gradle
file:
dependencies {
// JAX-B dependencies for JDK 9+
implementation "jakarta.xml.bind:jakarta.xml.bind-api:2.3.2"
implementation "org.glassfish.jaxb:jaxb-runtime:2.3.2"
}
Report Manager has been around for quite a few years. It's written in Delphi (at least it was originally) and has components that can be used in Delphi, but is usable via ActiveX or dll from just about any language. Now has a native .NET library too. Has a nifty report-serving webserver you can set up too. The designer gui looks and feels a little rough around the edges but it works. http://reportman.sourceforge.net/
::-webkit-input-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
:-moz-placeholder {
font-size:14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
::-moz-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
:-ms-input-placeholder {
font-size: 14px;
color: #d0cdfa;
text-transform: uppercase;
text-align: center;
font-weight: bold;
}
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password
Update new Change code into Github
->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.
Make sure you have SQLCMD enabled by clicking on the Query > SQLCMD mode option in the management studio.
Suppose you have four .sql files (script1.sql,script2.sql,script3.sql,script4.sql
) in a folder c:\scripts
.
Create a main script file (Main.sql) with the following:
:r c:\Scripts\script1.sql
:r c:\Scripts\script2.sql
:r c:\Scripts\script3.sql
:r c:\Scripts\script4.sql
Save the Main.sql in c:\scripts itself.
Create a batch file named ExecuteScripts.bat
with the following:
SQLCMD -E -d<YourDatabaseName> -ic:\Scripts\Main.sql
PAUSE
Remember to replace <YourDatabaseName>
with the database you want to execute your scripts. For example, if the database is "Employee", the command would be the following:
SQLCMD -E -dEmployee -ic:\Scripts\Main.sql
PAUSE
Execute the batch file by double clicking the same.
For Oracle use:
Select * from v$version;
For SQL server use:
Select @@VERSION as Version
and for MySQL use:
Show variables LIKE "%version%";
Hi! In order to use percentage(%), you must define the % of it parent element. If you use body{height: 100%} it will not work because it parent have no percentage in height. In that case in order to work that body height you must add this in html{height:100%}
In other case to get rid of that defining parent percentage you can use
body{height:100vh}
vh stands for viewport height
I think it help
Remove last 3 characters of a string
var str = '1437203995000';
str = str.substring(0, str.length-3);
// '1437203995'
Remove last 3 digits of a number
var a = 1437203995000;
a = (a-(a%1000))/1000;
// a = 1437203995
The real problem: How to get the difference of two sets?
The fastest way I've found is to convert the sets to dictionaries first, then diff 'em. Here's a generic approach:
static IEnumerable<T> DictionaryDiff<K, T>(Dictionary<K, T> d1, Dictionary<K, T> d2)
{
return from x in d1 where !d2.ContainsKey(x.Key) select x.Value;
}
Then you can do something like this:
static public IEnumerable<PropertyInfo> PropertyDiff(Type t1, Type t2)
{
var d1 = t1.GetProperties().ToDictionary(x => x.Name);
var d2 = t2.GetProperties().ToDictionary(x => x.Name);
return DictionaryDiff(d1, d2);
}
As of Django 1.2, you can use exists()
:
https://docs.djangoproject.com/en/dev/ref/models/querysets/#exists
if some_queryset.filter(pk=entity_id).exists():
print("Entry contained in queryset")
OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.
First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?
I had previously touched this subject in this article:
Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.
tutorial to draw line use Bitmap, Canvas, and Paint class. draw-line-on-finger-touch and androiddraw
here one simple class to draw line using canvas as show below.
public class TestLineView extends View {
private Paint paint;
private PointF startPoint, endPoint;
private boolean isDrawing;
public TestLineView(Context context)
{
super(context);
init();
}
private void init()
{
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Style.STROKE);
paint.setStrokeWidth(2);
paint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas)
{
if(isDrawing)
{
canvas.drawLine(startPoint.x, startPoint.y, endPoint.x, endPoint.y, paint);
}
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
startPoint = new PointF(event.getX(), event.getY());
endPoint = new PointF();
isDrawing = true;
break;
case MotionEvent.ACTION_MOVE:
if(isDrawing)
{
endPoint.x = event.getX();
endPoint.y = event.getY();
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if(isDrawing)
{
endPoint.x = event.getX();
endPoint.y = event.getY();
isDrawing = false;
invalidate();
}
break;
default:
break;
}
return true;
}
}
// Used In TypeScript For Angular 4+
const viewArray = [
{id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
{id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
{id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
{id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
{id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
{id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
{id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
{id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
{id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
{id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
{id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
{id: 12, question: "Do you feel a sense of peace and contentment in your home? ", category: "Home Environment", subs: []},
{id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
{id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
{id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];
const arrayObj = any;
const objectData = any;
for (let index = 0; index < this.viewArray.length; index++) {
this.arrayObj = this.viewArray[index];
this.arrayObj.filter((x) => {
if (x.id === id) {
this.objectData = x;
}
});
console.log('Json Object Data by ID ==> ', this.objectData);
}
};
If you're using pretty permalinks, get_query_var('page_id')
won't work.
Instead, get the queried object ID from the global :$wp_query
// Since 3.1 - recommended!
$page_object = get_queried_object();
$page_id = get_queried_object_id();
// "Dirty" pre 3.1
global $wp_query;
$page_object = $wp_query->get_queried_object();
$page_id = $wp_query->get_queried_object_id();
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
With PostgreSQL there are a number of date/time functions available, see here.
In your example, you could use:
SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';
If you are running this query regularly, it is possible to create an index using the date_trunc
function as well:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );
One advantage of this is there is some more flexibility with timezones if required, for example:
CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';
You can use simple form:
@using(Html.BeginForm("Update", "Shopping"))
{
<input type="text" id="ss" name="qty" value="@item.Quantity"/>
...
<input type="submit" value="Update" />
}
And add here attribute:
[HttpPost]
public ActionResult Update(string id, string productid, int qty, decimal unitrate)
I think you would want to add an 'onSelect' event handler to the initialization of your datepicker so your code gets triggered when the user selects a date. Try it out on jsFiddle
$(document).ready(function(){
// Datepicker
$('#datepicker').datepicker({
dateFormat: 'yy-mm-dd',
inline: true,
minDate: new Date(2010, 1 - 1, 1),
maxDate:new Date(2010, 12 - 1, 31),
altField: '#datepicker_value',
onSelect: function(){
var day1 = $("#datepicker").datepicker('getDate').getDate();
var month1 = $("#datepicker").datepicker('getDate').getMonth() + 1;
var year1 = $("#datepicker").datepicker('getDate').getFullYear();
var fullDate = year1 + "-" + month1 + "-" + day1;
var str_output = "<h1><center><img src=\"/images/a" + fullDate +".png\"></center></h1><br/><br>";
$('#page_output').html(str_output);
}
});
});
/^$|\s+/
This matches when empty or white spaces
/(?!^$)([^\s])/
This matches when its not empty or white spaces
Probably "new f-strings in Python 3.6" is the most efficient way of concatenating strings.
Using %s
>>> timeit.timeit("""name = "Some"
... age = 100
... '%s is %s.' % (name, age)""", number = 10000)
0.0029734770068898797
Using .format
>>> timeit.timeit("""name = "Some"
... age = 100
... '{} is {}.'.format(name, age)""", number = 10000)
0.004015227983472869
Using f
>>> timeit.timeit("""name = "Some"
... age = 100
... f'{name} is {age}.'""", number = 10000)
0.0019175919878762215
I got this error in R Studio, and was simply fixed by making the sidebar bigger by clicking and dragging on its edge from right to left.
Picture here: https://janac.medium.com/error-in-plot-new-figure-margins-too-large-in-r-214621b4b2af
Your CA file must have been in a binary X.509 format instead of Base64 encoding; it needs to be a regular DER or PEM in order for it to be added successfully to the list of trusted CAs on your server.
To proceed, do place your CA file inside your /usr/share/pki/ca-trust-source/anchors/
directory, then run the command line below (you might need sudo privileges based on your settings);
# CentOS 7, Red Hat 7, Oracle Linux 7
update-ca-trust
Please note that all trust settings available in the /usr/share/pki/ca-trust-source/anchors/
directory are interpreted with a lower priority compared to the ones placed under the /etc/pki/ca-trust/source/anchors/
directory which may be in the extended BEGIN TRUSTED file format.
For Ubuntu and Debian systems, /usr/local/share/ca-certificates/
is the preferred directory for that purpose.
As such, you need to place your CA file within the /usr/local/share/ca-certificates/
directory, then update the of trusted CAs by running, with sudo privileges where required, the command line below;
update-ca-certificates
I know this is an old question, but I wrote this function with tests for extracting file extension, and her available with NPM, Yarn, Bit.
Maybe it will help someone.
https://bit.dev/joshk/jotils/get-file-extension
function getFileExtension(path: string): string {
var regexp = /\.([0-9a-z]+)(?:[\?#]|$)/i
var extension = path.match(regexp)
return extension && extension[1]
}
You can see the tests I wrote here.
The most likely reason for use of single vs. double in different libraries is programmer preference and/or API consistency. Other than being consistent, use whichever best suits the string.
Using the other type of quote as a literal:
alert('Say "Hello"');
alert("Say 'Hello'");
This can get complicated:
alert("It's \"game\" time.");
alert('It\'s "game" time.');
Another option, new in ECMAScript 6, is template literals which use the backtick character:
alert(`Use "double" and 'single' quotes in the same string`);
alert(`Escape the \` back-tick character and the \${ dollar-brace sequence in a string`);
Template literals offer a clean syntax for: variable interpolation, multi-line strings, and more.
Note that JSON is formally specified to use double quotes, which may be worth considering depending on system requirements.
Combination of @[macbirdie] and @[Adrian Borchardt] answer. Which proves to be very useful in production environment (not messing up previously existing warning, especially during cross-platform compile)
#if (_MSC_VER >= 1400) // Check MSC version
#pragma warning(push)
#pragma warning(disable: 4996) // Disable deprecation
#endif
//... // ...
strcat(base, cat); // Sample depreciated code
//... // ...
#if (_MSC_VER >= 1400) // Check MSC version
#pragma warning(pop) // Renable previous depreciations
#endif
I use __get
(and public properties) as much as possible, because they make code much more readable. Compare:
this code unequivocally says what i'm doing:
echo $user->name;
this code makes me feel stupid, which i don't enjoy:
function getName() { return $this->_name; }
....
echo $user->getName();
The difference between the two is particularly obvious when you access multiple properties at once.
echo "
Dear $user->firstName $user->lastName!
Your purchase:
$product->name $product->count x $product->price
"
and
echo "
Dear " . $user->getFirstName() . " " . $user->getLastName() . "
Your purchase:
" . $product->getName() . " " . $product->getCount() . " x " . $product->getPrice() . " ";
Whether $a->b
should really do something or just return a value is the responsibility of the callee. For the caller, $user->name
and $user->accountBalance
should look the same, although the latter may involve complicated calculations. In my data classes i use the following small method:
function __get($p) {
$m = "get_$p";
if(method_exists($this, $m)) return $this->$m();
user_error("undefined property $p");
}
when someone calls $obj->xxx
and the class has get_xxx
defined, this method will be implicitly called. So you can define a getter if you need it, while keeping your interface uniform and transparent. As an additional bonus this provides an elegant way to memorize calculations:
function get_accountBalance() {
$result = <...complex stuff...>
// since we cache the result in a public property, the getter will be called only once
$this->accountBalance = $result;
}
....
echo $user->accountBalance; // calculate the value
....
echo $user->accountBalance; // use the cached value
Bottom line: php is a dynamic scripting language, use it that way, don't pretend you're doing Java or C#.
We had the Broken Pipe error after a new network was put into place. After ensuring that port 9100 was open and could connect to the printer over telnet port 9100, we changed the printer driver from "HP" to "Generic PDF", the broken pipe error went away and were able to print successfully.
(RHEL 7, Printers were Ricoh brand, the HP configuration was pre-existing and functional on the previous network)
Hmmm -- since this is handled by the JVM, I delved into the OpenJDK VM source code a little bit, thinking that maybe what's done by OpenJDK mimics what's done by Java 6 and prior. It isn't reassuring that there's a way to do this other than on Windows.
On Windows, OpenJDK's get_temp_directory()
function makes a Win32 API call to GetTempPath()
; this is how on Windows, Java reflects the value of the TMP
environment variable.
On Linux and Solaris, the same get_temp_directory()
functions return a static value of /tmp/
.
I don't know if the actual JDK6 follows these exact conventions, but by the behavior on each of the listed platforms, it seems like they do.
.contentWrapper {
float: left;
clear: both;
margin-left: 10%;
margin-right: 10%;
}
.repeater {
height: 9em;
width: 9em;
float: left;
margin: 0.2em;
position: relative;
text-align: center;
cursor: pointer;
}
Try with this :
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<gradient
android:angle="90"
android:centerColor="#555994"
android:endColor="#b5b6d2"
android:startColor="#555994"
android:type="linear" />
<corners
android:radius="0dp"/>
</shape>
From Mac OS Catalina .bash_profile is replaced with .zprofile
Step 1: Create a .zprofile
touch .zprofile
Step 2:
nano .zprofile
type below line in this
source ~/.bash_profile
and save(ctrl+o return ctrl+x)
Step 3: Restart your terminal
To Add Git Branch Name Now you can add below lines in .bash_profile
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
export PS1="\u@\h \[\033[32m\]\w - \$(parse_git_branch)\[\033[00m\] $ "
Restart your terminal this will work.
Note: Even you can rename .bash_profile to .zprofile that also works.
SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO
to indicate the end of a batch and to retrieve the results:
PRINT '1'
GO
WAITFOR DELAY '00:00:05'
PRINT '2'
GO
WAITFOR DELAY '00:00:05'
PRINT '3'
GO
In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT
, which gbn has provided as an answer as I type this.
Only because there's a more base point to point out I'll add that you can simply test your string is null:
if [ "$1" ]; then
echo yes
else
echo no
fi
Likewise if you're expecting arg count just test your last:
if [ "$3" ]; then
echo has args correct or not
else
echo fixme
fi
and so on with any arg or var
Here's a more concise approach...
df['a_bsum'] = df.groupby('A')['B'].transform(sum)
df.sort(['a_bsum','C'], ascending=[True, False]).drop('a_bsum', axis=1)
The first line adds a column to the data frame with the groupwise sum. The second line performs the sort and then removes the extra column.
Result:
A B C
5 baz -2.301539 True
2 baz -0.528172 False
1 bar -0.611756 True
4 bar 0.865408 False
3 foo -1.072969 True
0 foo 1.624345 False
NOTE: sort
is deprecated, use sort_values
instead
Use the DecimalFormat class to format the double
The solution is this:
<input (click)="focusOut()" type="text" matInput [formControl]="inputControl"
[matAutocomplete]="auto">
<mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn" >
<mat-option (onSelectionChange)="submitValue($event)" *ngFor="let option of
options | async" [value]="option">
{{option.name | translate}}
</mat-option>
</mat-autocomplete>
TS
focusOut() {
this.inputControl.disable();
this.inputControl.enable();
}
First add a column in child table Cid
as int
then alter table
with the code below. This way you can add the foreign key Cid
as the primary key of parent table and use it as the foreign key in child table ... hope it will help you as it is good for me:
ALTER TABLE [child]
ADD CONSTRAINT [CId]
FOREIGN KEY ([CId])
REFERENCES [Parent]([CId])
ON DELETE CASCADE ON UPDATE NO ACTION;
GO
I have a label on my form receiving the sum of numbers from Column D in Sheet1. I am only interested in rows 2 to 50, you can use a row counter if your row count is dynamic. I have some blank entries as well in column D and they are ignored.
Me.lblRangeTotal = Application.WorksheetFunction.Sum(ThisWorkbook.Sheets("Sheet1").Range("D2:D50"))
/***Your Code***/
public void paintComponent(Graphics g){
/***Your Code***/
g.setColor(Color.RED);
g.fillOval(50,50,20,20);
}
g.fillOval(x-axis,y-axis,width,height);
info frame
to show the stack frame info
To read the memory at given addresses you should take a look at x
x/x $esp
for hex x/d $esp
for signed x/u $esp
for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip
etc.
The answer by Nick Mitchinson is for Bootstrap version 2.
If you are using Bootstrap version 3, then forms have changed a bit. For bootstrap 3, use the following instead:
<div class="form-horizontal">
<div class="form-group">
<div class="col-md-6">
<textarea class="form-control" rows="3" placeholder="What's up?" required></textarea>
</div>
</div>
</div>
Where, col-md-6 will target medium sized devices. You can add col-xs-6 etc to target smaller devices.
// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates
I have written on this property framework for the last year. It will provide of multiple ways to load properties, and have them strongly typed as well.
Have a look at http://sourceforge.net/projects/jhpropertiestyp/
JHPropertiesTyped will give the developer strongly typed properties. Easy to integrate in existing projects. Handled by a large series for property types. Gives the ability to one-line initialize properties via property IO implementations. Gives the developer the ability to create own property types and property io's. Web demo is also available, screenshots shown above. Also have a standard implementation for a web front end to manage properties, if you choose to use it.
Complete documentation, tutorial, javadoc, faq etc is a available on the project webpage.
If you're worried about performance, check out the Boost::lexical_cast library.
You are getting that error because you are posting to a GET
route.
I would split your routing for validate
into a separate GET
and POST
routes.
New Routes:
Route::post('validate', 'MemberController@validateCredentials');
Route::get('validate', function () {
return View::make('members/login');
});
Then your controller method could just be
public function validateCredentials()
{
$email = Input::post('email');
$password = Input::post('password');
return "Email: " . $email . " and Password: " . $password;
}
with location - in new GoogleMaps SDK:
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(chLocation,14));
It's as simple as:
irb(main):001:0> hash = {:item1 => 1}
=> {:item1=>1}
irb(main):002:0> hash[:item2] = 2
=> 2
irb(main):003:0> hash
=> {:item1=>1, :item2=>2}
for Python 2.7+ the idiomatic answer is to use subprocess.check_output()
You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....
If args is just single command with no args of its own (or you have shell=True
set), it can be a string. Otherwise it must be a list.
for example... to invoke the ls
command, this is fine:
from subprocess import check_call
check_call('ls')
so is this:
from subprocess import check_call
check_call(['ls',])
however, if you want to pass some args to the shell command, you can't do this:
from subprocess import check_call
check_call('ls -al')
instead, you must pass it as a list:
from subprocess import check_call
check_call(['ls', '-al'])
the shlex.split()
function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses...
like this:
from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))
How about a one-liner in JS ES10 / ES2019 ?
Making use of Object.entries()
and Object.fromEntries()
:
let newObj = Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, v * v]));
The same thing written as a function:
function objMap(obj, func) {
return Object.fromEntries(Object.entries(obj).map(([k, v]) => [k, func(v)]));
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
This function uses recursion to square nested objects as well:
function objMap(obj, func) {
return Object.fromEntries(
Object.entries(obj).map(([k, v]) =>
[k, v === Object(v) ? objMap(v, func) : func(v)]
)
);
}
// To square each value you can call it like this:
let mappedObj = objMap(obj, (x) => x * x);
With ES7 / ES2016 you cant' use Objects.fromEntries
, but you can achieve the same using Object.assign
in combination with spread operators and computed key names syntax:
let newObj = Object.assign(...Object.entries(obj).map(([k, v]) => ({[k]: v * v})));
ES6 / ES2015 Doesn't allow Object.entires
, but you could use Object.keys
instead:
let newObj = Object.assign(...Object.keys(obj).map(k => ({[k]: obj[k] * obj[k]})));
ES6 also introduced for...of
loops, which allow a more imperative style:
let newObj = {}
for (let [k, v] of Object.entries(obj)) {
newObj[k] = v * v;
}
Instead of Object.fromEntries
and Object.assign
you can also use reduce for this:
let newObj = Object.entries(obj).reduce((p, [k, v]) => ({ ...p, [k]: v * v }), {});
In some rare situation you may need to map a class-like object which holds properties of an inherited object on its prototype-chain. In such cases Object.keys()
and Object.entries()
won't work, because these functions do not include the prototype chain.
If you need to map inherited properties, you can use for (key in myObj) {...}
.
Here is an example of such situation:
const obj1 = { 'a': 1, 'b': 2, 'c': 3}
const obj2 = Object.create(obj1); // One of multiple ways to inherit an object in JS.
// Here you see how the properties of obj1 sit on the 'prototype' of obj2
console.log(obj2) // Prints: obj2.__proto__ = { 'a': 1, 'b': 2, 'c': 3}
console.log(Object.keys(obj2)); // Prints: an empty Array.
console.log(Object.entries(obj2)); // Prints: an empty Array.
for (let key in obj2) {
console.log(key); // Prints: 'a', 'b', 'c'
}
However, please do me a favor and avoid inheritance. :-)
Someone with more reputation can copy this into the main answer:
MonthRepository monthRepository = new MonthRepository();
IQueryable<MonthEntity> entities = monthRepository.GetAllMonth();
List<MonthEntity> monthEntities = new List<MonthEntity>();
foreach(var r in entities)
{
monthEntities.Add(r);
}
ViewData["Month"] = new SelectList(monthEntities, "MonthID", "Month", "Mars");
This is something you solve in the "controller", which is the point of logicless templating.
// some function that retreived data through ajax
function( view ){
if ( !view.avatar ) {
// DEFAULTS can be a global settings object you define elsewhere
// so that you don't have to maintain these values all over the place
// in your code.
view.avatar = DEFAULTS.AVATAR;
}
// do template stuff here
}
This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)
Another option is to do the following:
// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;
And in the template:
{{#hasAvatar}}
SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
SHOW DEFAULT
{{/noAvatar}}
But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)
XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();
xmlw.Close();
XmlDocument doc = new XmlDocument();
doc.Load(@"C:\WINDOWS\Temp\exm.xml");
XmlNode root = doc.DocumentElement["Starttime"];
root.FirstChild.InnerText = "First";
XmlNode root1 = doc.DocumentElement["Changetime"];
root1.FirstChild.InnerText = "Second";
doc.Save(@"C:\WINDOWS\Temp\exm.xml");
Try this. It's C# code.
If you want to make transformation your app setting from web config file to web.Release.config,you have to do the following steps. Let your web.config app setting file is this-
<appSettings>
<add key ="K1" value="Debendra Dash"/>
</appSettings>
Now here is the web.Release.config for the transformation.
<appSettings>
<add key="K1" value="value dynamicly from Realease"
xdt:Transform="SetAttributes"
xdt:Locator="Match(key)"
/>
</appSettings>
This will transform the value of K1 to the new value in realese Mode.
I was brought here by a different problem. Whenever I tried to login, i got that message because instead of authenticating correctly I logged in as anonymous user. The solution to my problem was:
To see which user you are, and whose permissions you have:
select user(), current_user();
To delete the pesky anonymous user:
drop user ''@'localhost';
For API level 23 (Marshmallow) and later, additional to uses-permission in manifest, pop up permission should also be implemented, and user needs to grant it while using the app in run-time.
Below, there is an example to save hello world!
as content of myFile.txt
file in Test
directory inside picture directory.
In the manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Where you want to create the file:
int permission = ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
String[] PERMISSIONS_STORAGE = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (permission != PackageManager.PERMISSION_GRANTED)
{
ActivityCompat.requestPermissions(MainActivity.this,PERMISSIONS_STORAGE, 1);
}
File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "Test");
myDir.mkdirs();
try
{
String FILENAME = "myFile.txt";
File file = new File (myDir, FILENAME);
String string = "hello world!";
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();
}
catch (IOException e) {
e.printStackTrace();
}
For images in td, use this for images:
display: block;
That removes unwanted space for me
Some of it is possible, specifically accessing subtotals:
"In Excel 2010+, you can right-click on the values and select Show Values As –> % of Parent Row Total." (or % of Parent Column Total)
Source: http://datapigtechnologies.com/blog/index.php/excel-2010-pivottable-subtotals/
try doing this
<div style="position: absolute;top: 32px; left: 430px;" id="outerFilterDiv">
<input name="filterTextField" type="text" id="filterTextField" tabindex="2" style="width: 140px;
position: absolute; top: 1px; left: 1px; z-index: 2;border:none;" />
<div style="position: absolute;" id="filterDropdownDiv">
<select name="filterDropDown" id="filterDropDown" tabindex="1000"
onchange="DropDownTextToBox(this,'filterTextField');" style="position: absolute;
top: 0px; left: 0px; z-index: 1; width: 165px;">
<option value="-1" selected="selected" disabled="disabled">-- Select Column Name --</option>
</select>
please look at following example fiddle
A node is defined as:
the smallest unit of a valid, complete structure in a document.
or as:
An object in the tree view that serves as a container to hold related objects.
Now their are many different kinds of nodes as an elements node, an attribute node etc.
You have to open that file with a text editor and then save it.
touch ~/.bash_profile; open ~/.bash_profile
It will open the file with TextEdit, paste your things and then save it. If you open it again you'll find your edits.
You can use other editors:
nano ~/.bash_profile
mate ~/.bash_profile
vim ~/.bash_profile
But if you don't know how to use them, it's easier to use the open
approach.
Alternatively, you can rely on pbpaste
. Copy
export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools
in the system clipboard and then in a shell run
pbpaste > ~/.bash_profile
Or alternatively you can also use cat
cat > ~/.bash_profile
(now cat
waits for input: paste the two export definitions and then hit ctrl-D).
Factory Method patter: BeanFactory for creating instance of an object Singleton : instance type can be singleton for a context Prototype : instance type can be prototype. Builder pattern: you can also define a method in a class who will be responsible for creating complex instance.
I removed bin
from the CLASSPATH
. I found out that I was executing the java
command from the directory where the HelloWorld.java
is located, i.e.:
C:\Users\xyz\Documents\Java\javastudy\src\org\tij\exercises>java HelloWorld
So I moved back to the main directory and executed:
java org.tij.exercises.HelloWorld
and it worked, i.e.:
C:\Users\xyz\Documents\Java\javastudy\src>java org.tij.exercises.HelloWorld
Hello World!!
Make an empty new branch like this:
true | git mktree | xargs git commit-tree | xargs git branch proj-doc
If your proj-doc files are already in a commit under a single subdir you can make the new branch this way:
git commit-tree thatcommit:path/to/dir | xargs git branch proj-doc
which might be more convenient than git branch --orphan
if that would leave you with a lot of git rm
and git mv
ing to do.
Try
git branch --set-upstream proj-doc origin/proj-doc
and see if that helps with your fetching-too-much problem. Also if you really only want to fetch a single branch it's safest to just specify it on the commandline.
HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
jQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
This code will work. The answer from samplebias is almost correct, but you need a third change:
int addNodeBottom(int val, node *head){
//create new node
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
fprintf(stderr, "Unable to allocate memory for new node\n");
exit(-1);
}
newNode->value = val;
newNode->next = NULL; // Change 1
//check for first insertion
if(head->next == NULL){
head->next = newNode;
printf("added at beginning\n");
}
else
{
//else loop through the list and find the last
//node, insert next to it
node *current = head;
while (true) { // Change 2
if(current->next == NULL)
{
current->next = newNode;
printf("added later\n");
break; // Change 3
}
current = current->next;
};
}
return 0;
}
Change 1: newNode->next
must be set to NULL
so we don't insert invalid pointers at the end of the list.
Change 2/3: The loop is changed to an endless loop that will be jumped out with break;
when we found the last element. Note how while(current->next != NULL)
contradicted if(current->next == NULL)
before.
EDIT: Regarding the while loop, this way it is much better:
node *current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
printf("added later\n");
I don't know about android, but Safari on the iPhone or iPod touch will play all videos full screen because of the small screen size. On the iPad it will play the video on the page but allow the user to make it full screen.
I had the same need to fill up a column with a sequence series for each value on another column. I tried all the answers above and could not fix the problem. I solved it with a simple VBA macro.
My data have the same structure (but with 3000 rows):
Here below the code:
> Sub Seq_N3() ' ' Seq_N3 Macro ' Sequence numbering of N3 based on N2 value
> do N2
> Dim N2 As Integer
> Dim seq As Integer
>
> With ActiveSheet
>
> For N2 = 1 To 7 Step 1
> seq = 1 '
> .Range("B2").Select '
>
> Do While ActiveCell.Offset(0, -1).Value2 <> 0
>
> If ActiveCell.Offset(0, -1).Value2 = N2 Then
> ActiveCell.Value2 = seq
> seq = seq + 1
> ActiveCell.Offset(1, 0).Select
> Else
> ActiveCell.Offset(1, 0).Select
> End If
>
> Loop
>
> Next N2
>
> End With End Sub
Hope it helps!
You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().
http://www.php.net/manual/en/reflectionclass.getdoccomment.php
For markdown table syntax see:
https://www.markdownguide.org/extended-syntax/#tables
Quick summary:
To quickly understand the syntax used in other answers, it helps to start from a more complete intuitive and easier to remember syntax, and then a minimalized version with the same result.
Basic example:
| Header A | Header B |
| -------------- | -------------- |
| row 1 col 1 | row 1 col 2 |
| row 2 column 1 | row 2 column 2 |
Same result in a more minimalist form (cell widths can vary) :
Header A | Header B
--- | ---
row 1 col 1 | row 1 col 2
row 2 column 1 | row 2 column 2
And more related to the question: side by side images with labels on top:
label 1 | label 2
--- | ---
![](https://...image1.png) | ![](https://...image2.png)
( use :---
, ---:
, and :---:
for (text) alignment in the column, respectively: left, right, center )
objective-c is the primary language used.
i believe there is a mono touch framework that can be used with c#
Adobe also is working in some tools, one is this iPhone Packager which can utilize actionscript code
from time import time
start_time = time()
...
end_time = time()
time_taken = end_time - start_time # time_taken is in seconds
hours, rest = divmod(time_taken,3600)
minutes, seconds = divmod(rest, 60)
You should be aware that [^a-zA-Z]
will replace characters not being itself in the character range A-Z/a-z. That means special characters like é
, ß
etc. or cyrillic characters and such will be removed.
If the replacement of these characters is not wanted use pre-defined character classes instead:
str.replaceAll("[^\\p{IsAlphabetic}\\p{IsDigit}]", "");
PS: \p{Alnum}
does not achieve this effect, it acts the same as [A-Za-z0-9]
.
As simple as running this in Python3:
import os
externalIP = os.popen('curl -s ifconfig.me').readline()
print(externalIP)
I use this with a daily cron job to check if I should send an email on the first day of any given month to my affiliates. It's a few more lines than the other answers but solid as a rock.
//is this the first day of the month?
$date = date('Y-m-d');
$pieces = explode("-", $date);
$day = $pieces[2];
//if it's not the first day then stop
if($day != "01") {
echo "error - it's not the first of the month today";
exit;
}
String String_firstNumber = JOptionPane.showInputDialog("Input Semisecond");
int Int_firstNumber = Integer.parseInt(firstNumber);
Now your Int_firstnumber
contains integer value of String_fristNumber
.
hope it helped
android:keepScreenOn="true"
could be better option to have from layout XML.
More info: https://developer.android.com/training/scheduling/wakelock.html
With querySelectorAll you can select the elements you want without the same id using css selector:
var elems = document.querySelectorAll("#id1, #id1, #id3");
Looks like IE8-IE7 can't understand multiple Google Web Font styles through the same file request using the link
tags href
.
These two links helped me figure this out:
The only way I have gotten it to work in IE7-IE8 is to only have one Google Web Font request. And only have one font style in the href
of the link
tag:
So normally you would have this, declaring multiple font styles in the same request:
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400,600,300,800,700,400italic" />
But in IE7-IE8 add a IE conditional and specify each Google font style separately and it will work:
<!--[if lte IE 8]>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:400" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:700" />
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:800" />
<![endif]-->
Hope this can help others!
I suspect that the SelectedItem property of the ComboBox does not change until the control has been validated (which occurs when the control loses focus), whereas the SelectedValue property changes whenever the user selects an item.
Here is a reference to the focus events that occur on controls:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx
There are voiced concerns about performance, but no data is offered. Let me suggest a simple test.
(NOTE: date
on macOS does not offer nanoseconds, so this must be done on Linux.)
I have created append_test.sh on GitHub with the contents:
#!/bin/bash -e
output(){
ptime=$ctime;
ctime=$(date +%s.%N);
delta=$(bc <<<"$ctime - $ptime");
printf "%2s. %16s chars time: %s delta: %s\n" $n "$(bc <<<"10*(2^$n)")" $ctime $delta;
}
method1(){
echo 'Method: a="$a$a"'
for n in {1..32}; do a="$a$a"; output; done
}
method2(){
echo 'Method: a+="$a"'
for n in {1..32}; do a+="$a"; output; done
}
ctime=0; a="0123456789"; time method$1
Test 1:
$ ./append_test.sh 1
Method: a="$a$a"
1. 20 chars time: 1513640431.861671143 delta: 1513640431.861671143
2. 40 chars time: 1513640431.865036344 delta: .003365201
3. 80 chars time: 1513640431.868200952 delta: .003164608
4. 160 chars time: 1513640431.871273553 delta: .003072601
5. 320 chars time: 1513640431.874358253 delta: .003084700
6. 640 chars time: 1513640431.877454625 delta: .003096372
7. 1280 chars time: 1513640431.880551786 delta: .003097161
8. 2560 chars time: 1513640431.883652169 delta: .003100383
9. 5120 chars time: 1513640431.886777451 delta: .003125282
10. 10240 chars time: 1513640431.890066444 delta: .003288993
11. 20480 chars time: 1513640431.893488326 delta: .003421882
12. 40960 chars time: 1513640431.897273327 delta: .003785001
13. 81920 chars time: 1513640431.901740563 delta: .004467236
14. 163840 chars time: 1513640431.907592388 delta: .005851825
15. 327680 chars time: 1513640431.916233664 delta: .008641276
16. 655360 chars time: 1513640431.930577599 delta: .014343935
17. 1310720 chars time: 1513640431.954343112 delta: .023765513
18. 2621440 chars time: 1513640431.999438581 delta: .045095469
19. 5242880 chars time: 1513640432.086792464 delta: .087353883
20. 10485760 chars time: 1513640432.278492932 delta: .191700468
21. 20971520 chars time: 1513640432.672274631 delta: .393781699
22. 41943040 chars time: 1513640433.456406517 delta: .784131886
23. 83886080 chars time: 1513640435.012385162 delta: 1.555978645
24. 167772160 chars time: 1513640438.103865613 delta: 3.091480451
25. 335544320 chars time: 1513640444.267009677 delta: 6.163144064
./append_test.sh: fork: Cannot allocate memory
Test 2:
$ ./append_test.sh 2
Method: a+="$a"
1. 20 chars time: 1513640473.460480052 delta: 1513640473.460480052
2. 40 chars time: 1513640473.463738638 delta: .003258586
3. 80 chars time: 1513640473.466868613 delta: .003129975
4. 160 chars time: 1513640473.469948300 delta: .003079687
5. 320 chars time: 1513640473.473001255 delta: .003052955
6. 640 chars time: 1513640473.476086165 delta: .003084910
7. 1280 chars time: 1513640473.479196664 delta: .003110499
8. 2560 chars time: 1513640473.482355769 delta: .003159105
9. 5120 chars time: 1513640473.485495401 delta: .003139632
10. 10240 chars time: 1513640473.488655040 delta: .003159639
11. 20480 chars time: 1513640473.491946159 delta: .003291119
12. 40960 chars time: 1513640473.495354094 delta: .003407935
13. 81920 chars time: 1513640473.499138230 delta: .003784136
14. 163840 chars time: 1513640473.503646917 delta: .004508687
15. 327680 chars time: 1513640473.509647651 delta: .006000734
16. 655360 chars time: 1513640473.518517787 delta: .008870136
17. 1310720 chars time: 1513640473.533228130 delta: .014710343
18. 2621440 chars time: 1513640473.560111613 delta: .026883483
19. 5242880 chars time: 1513640473.606959569 delta: .046847956
20. 10485760 chars time: 1513640473.699051712 delta: .092092143
21. 20971520 chars time: 1513640473.898097661 delta: .199045949
22. 41943040 chars time: 1513640474.299620758 delta: .401523097
23. 83886080 chars time: 1513640475.092311556 delta: .792690798
24. 167772160 chars time: 1513640476.660698221 delta: 1.568386665
25. 335544320 chars time: 1513640479.776806227 delta: 3.116108006
./append_test.sh: fork: Cannot allocate memory
The errors indicate that my Bash got up to 335.54432 MB before it crashed. You could change the code from doubling the data to appending a constant to get a more granular graph and failure point. But I think this should give you enough information to decide whether you care. Personally, below 100 MB I don't. Your mileage may vary.
According to the docs, #Rails.env
wraps RAILS_ENV
:
# File vendor/rails/railties/lib/initializer.rb, line 55
def env
@_env ||= ActiveSupport::StringInquirer.new(RAILS_ENV)
end
But, look at specifically how it's wrapped, using ActiveSupport::StringInquirer
:
Wrapping a string in this class gives you a prettier way to test for equality. The value returned by Rails.env is wrapped in a StringInquirer object so instead of calling this:
Rails.env == "production"
you can call this:
Rails.env.production?
So they aren't exactly equivalent, but they're fairly close. I haven't used Rails much yet, but I'd say #Rails.env
is certainly the more visually attractive option due to using StringInquirer
.
C++98 doesn't provide a direct syntax for anything but zeroing (or for non-POD elements, value-initializing) the array. For that you just write C(): arr() {}
.
I thing Roger Pate is wrong about the alleged limitations of C++0x aggregate initialization, but I'm too lazy to look it up or check it out, and it doesn't matter, does it? EDIT: Roger was talking about "C++03", I misread it as "C++0x". Sorry, Roger. ?
A C++98 workaround for your current code is to wrap the array in a struct
and initialize it from a static constant of that type. The data has to reside somewhere anyway. Off the cuff it can look like this:
class C
{
public:
C() : arr( arrData ) {}
private:
struct Arr{ int elem[3]; };
Arr arr;
static Arr const arrData;
};
C::Arr const C::arrData = {{1, 2, 3}};
See Python Web Frameworks wiki.
You probably do not need the full stack frameworks, but the remaining list is still quite long.
Since the technical part has been pretty much answered, my comment is just in relation with the confusion that produce this recycled keyword.
Being Python a very eloquent programming language, the misuse of a keyword is more notorious. The else
keyword perfectly describes part of the flow of a decision tree, "if you can't do this, (else) do that". It's implied in our own language.
Instead, using this keyword with while
and for
statements creates confusion. The reason, our career as programmers has taught us that the else
statement resides within a decision tree; its logical scope, a wrapper that conditionally return a path to follow. Meanwhile, loop statements have a figurative explicit goal to reach something. The goal is met after continuous iterations of a process.
if / else
indicate a path to follow. Loops follow a path until the "goal" is completed.
The issue is that else
is a word that clearly define the last option in a condition. The semantics of the word are both shared by Python and Human Language. But the else word in Human Language is never used to indicate the actions someone or something will take after something is completed. It will be used if, in the process of completing it, an issue rises (more like a break statement).
At the end, the keyword will remain in Python. It's clear it was mistake, clearer when every programmer tries to come up with a story to understand its usage like some mnemonic device. I'd have loved if they have chosen instead the keyword then
. I believe that this keyword fits perfectly in that iterative flow, the payoff after the loop.
It resembles that situation that some child has after following every step in assembling a toy: And THEN what Dad?
Or You can use
grep -n . file1 |tail -LineNumberToStartWith|grep regEx
This will take care of numbering the lines in the file
grep -n . file1
This will print the last-LineNumberToStartWith
tail -LineNumberToStartWith
And finally it will grep your desired lines(which will include line number as in orignal file)
grep regEX
According to Tom Hawtin
A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.
Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:
//ECMAScript
var f, g;
function foo() {
var x = 0;
f = function() { return ++x; };
g = function() { return --x; };
x = 1;
print('inside foo, call to f(): ' + f()); // "2"
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"
Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:
int a[1] = {0}
interface Function1 {
public final IntBag value = new IntBag();
public int apply();
}
class Closure implements Function1 {
private IntBag x = value;
Function1 f;
Function1 g;
@Override
public int apply() {
// print('inside foo, call to f(): ' + f()); // "2"
// inside apply, call to f.apply()
System.out.println("inside foo, call to f.apply(): " + f.apply());
return 0;
}
public Closure() {
f = new Function1() {
@Override
public int apply() {
x.add(1);
return x.get();
}
};
g = new Function1() {
@Override
public int apply() {
x.add(-1);
return x.get();
}
};
// x = 1;
x.set(1);
}
}
public class ClosureTest {
public static void main(String[] args) {
// foo()
Closure foo = new Closure();
foo.apply();
// print('call to g(): ' + g()); // "1"
System.out.println("call to foo.g.apply(): " + foo.g.apply());
// print('call to f(): ' + f()); // "2"
System.out.println("call to foo.f.apply(): " + foo.f.apply());
}
}
It prints:
inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2
Alternatively, if you're working in .NET v4.5 or above, try using System.Web.MimeMapping.GetMimeMapping(yourFileName) to get MIME types. It is much better than hard-coding strings.
I built the following ant-task for deployment based on the jboss deployment docs:
<target name="deploy" depends="jboss.environment, buildwar">
<!-- Build path for deployed war-file -->
<property name="deployed.war" value="${jboss.home}/${jboss.deploy.dir}/${war.filename}" />
<!-- remove current deployed war -->
<delete file="${deployed.war}.deployed" failonerror="false" />
<waitfor maxwait="10" maxwaitunit="second">
<available file="${deployed.war}.undeployed" />
</waitfor>
<delete dir="${deployed.war}" />
<!-- copy war-file -->
<copy file="${war.filename}" todir="${jboss.home}/${jboss.deploy.dir}" />
<!-- start deployment -->
<echo>start deployment ...</echo>
<touch file="${deployed.war}.dodeploy" />
<!-- wait for deployment to complete -->
<waitfor maxwait="10" maxwaitunit="second">
<available file="${deployed.war}.deployed" />
</waitfor>
<echo>deployment ok!</echo>
</target>
${jboss.deploy.dir}
is set to standalone/deployments
If you want to always prune
when you fetch
, I can suggest to use Aliases.
Just type git config -e
to open your editor and change the configuration for a specific project and add a section like
[alias]
pfetch = fetch --prune
the when you fetch with git pfetch
the prune will be done automatically.
If it is MySql you can try
SELECT @n := @n + 1 n,
first_name,
last_name
FROM table1, (SELECT @n := 0) m
ORDER BY first_name, last_name
And for SQLServer
SELECT row_number() OVER (ORDER BY first_name, last_name) n,
first_name,
last_name
FROM table1
There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps
This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.
javascript it a rather timtoady language )
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
Note: You can first preview what your patch will do:
First the stats:
git apply --stat a_file.patch
Then a dry run to detect errors:
git apply --check a_file.patch
Finally, you can use git am
to apply your patch as a commit. This also allows you to sign off an applied patch.
This can be useful for later reference.
git am --signoff < a_file.patch
See an example in this article:
In your git log, you’ll find that the commit messages contain a “Signed-off-by” tag. This tag will be read by Github and others to provide useful info about how the commit ended up in the code.
We use SubClass extends SuperClass only when the subclass wants to use some functionality (methods or instance variables) that is already declared in the SuperClass, or if I want to slightly modify the functionality of the SuperClass (Method overriding). But say, I have an Animal class(SuperClass) and a Dog class (SubClass) and there are few methods that I have defined in the Animal class eg. doEat(); , doSleep(); ... and many more.
Now, my Dog class can simply extend the Animal class, if i want my dog to use any of the methods declared in the Animal class I can invoke those methods by simply creating a Dog object. So this way I can guarantee that I have a dog that can eat and sleep and do whatever else I want the dog to do.
Now, imagine, one day some Cat lover comes into our workspace and she tries to extend the Animal class(cats also eat and sleep). She makes a Cat object and starts invoking the methods.
But, say, someone tries to make an object of the Animal class. You can tell how a cat sleeps, you can tell how a dog eats, you can tell how an elephant drinks. But it does not make any sense in making an object of the Animal class. Because it is a template and we do not want any general way of eating.
So instead, I will prefer to make an abstract class that no one can instantiate but can be used as a template for other classes.
So to conclude, Interface is nothing but an abstract class(a pure abstract class) which contains no method implementations but only the definitions(the templates). So whoever implements the interface just knows that they have the templates of doEat(); and doSleep(); but they have to define their own doEat(); and doSleep(); methods according to their need.
You extend only when you want to reuse some part of the SuperClass(but keep in mind, you can always override the methods of your SuperClass according to your need) and you implement when you want the templates and you want to define them on your own(according to your need).
I will share with you a piece of code: You try it with different sets of inputs and look at the results.
class AnimalClass {
public void doEat() {
System.out.println("Animal Eating...");
}
public void sleep() {
System.out.println("Animal Sleeping...");
}
}
public class Dog extends AnimalClass implements AnimalInterface, Herbi{
public static void main(String[] args) {
AnimalInterface a = new Dog();
Dog obj = new Dog();
obj.doEat();
a.eating();
obj.eating();
obj.herbiEating();
}
public void doEat() {
System.out.println("Dog eating...");
}
@Override
public void eating() {
System.out.println("Eating through an interface...");
// TODO Auto-generated method stub
}
@Override
public void herbiEating() {
System.out.println("Herbi eating through an interface...");
// TODO Auto-generated method stub
}
}
Defined Interfaces :
public interface AnimalInterface {
public void eating();
}
interface Herbi {
public void herbiEating();
}
As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)
The only reason that the names matter is the default make rules, visible via make -p
, which use some of them.
If you write all your own rules, you get to pick all your own macro names.
In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS
, CPPFLAGS
, and CXXFLAGS
. CFLAGS
for the C compiler, CXXFLAGS
for C++, and CPPFLAGS
for both.
Why is CPPFLAGS
in both? Conventionally, it's the home of preprocessor flags (-D
, -U
) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.
P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.
and of course the following:
var count = $("#myList").children().length;
can be condensed down to: (by removing the 'var' which is not necessary to set a variable)
count = $("#myList").children().length;
however this is cleaner:
count = $("#mylist li").size();
You may try this:
Page::where('id', $id)->update(array('image' => 'asdasd'));
There are other ways too but no need to use Page::find($id);
in this case. But if you use find()
then you may try it like this:
$page = Page::find($id);
// Make sure you've got the Page model
if($page) {
$page->image = 'imagepath';
$page->save();
}
Also you may use:
$page = Page::findOrFail($id);
So, it'll throw an exception if the model with that id was not found.
To achieve the 360 degree rotation, here is the Working Solution.
The HTML:
<img class="image" src="your-image.png">
The CSS:
.image {
overflow: hidden;
transition-duration: 0.8s;
transition-property: transform;
}
.image:hover {
transform: rotate(360deg);
-webkit-transform: rotate(360deg);
}
You have to hover on the image and you will get the 360 degree rotation effect.
PS: Add a -webkit-
extension for it to work on chrome and other webkit browers. You can check the updated fiddle for webkit HERE
Using IntelliJ Idea:
1) Invalidate Caches, and 2) right click on resources, New Resources directory, type = raw 3) build
note in step 2: I was concerned that simply adding a raw directory wouldn't be enough...
For posterity, I ran into this with an azure function, using the azure durable function / durable tasks framework. It turns out I had an outdated version of the azure functions runtime installed locally. updating it fixed it.
This answer is an attempt at a technical answer rather than opinion.
If we want to be POSIX purists, we define a line as:
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_206
An incomplete line as:
A sequence of one or more non- <newline> characters at the end of the file.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_195
A text file as:
A file that contains characters organized into zero or more lines. The lines do not contain NUL characters and none can exceed {LINE_MAX} bytes in length, including the <newline> character. Although POSIX.1-2008 does not distinguish between text files and binary files (see the ISO C standard), many utilities only produce predictable or meaningful output when operating on text files. The standard utilities that have such restrictions always specify "text files" in their STDIN or INPUT FILES sections.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_397
A string as:
A contiguous sequence of bytes terminated by and including the first null byte.
Source: https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html#tag_03_396
From this then, we can derive that the only time we will potentially encounter any type of issues are if we deal with the concept of a line of a file or a file as a text file (being that a text file is an organization of zero or more lines, and a line we know must terminate with a <newline>).
Case in point: wc -l filename
.
From the wc
's manual we read:
A line is defined as a string of characters delimited by a <newline> character.
What are the implications to JavaScript, HTML, and CSS files then being that they are text files?
In browsers, modern IDEs, and other front-end applications there are no issues with skipping EOL at EOF. The applications will parse the files properly. It has to since not all Operating Systems conform to the POSIX standard, so it would be impractical for non-OS tools (e.g. browsers) to handle files according to the POSIX standard (or any OS-level standard).
As a result, we can be relatively confident that EOL at EOF will have virtually no negative impact at the application level - regardless if it is running on a UNIX OS.
At this point we can confidently say that skipping EOL at EOF is safe when dealing with JS, HTML, CSS on the client-side. Actually, we can state that minifying any one of these files, containing no <newline> is safe.
We can take this one step further and say that as far as NodeJS is concerned it too cannot adhere to the POSIX standard being that it can run in non-POSIX compliant environments.
What are we left with then? System level tooling.
This means the only issues that may arise are with tools that make an effort to adhere their functionality to the semantics of POSIX (e.g. definition of a line as shown in wc
).
Even so, not all shells will automatically adhere to POSIX. Bash for example does not default to POSIX behavior. There is a switch to enable it: POSIXLY_CORRECT
.
Food for thought on the value of EOL being <newline>: https://www.rfc-editor.org/old/EOLstory.txt
Staying on the tooling track, for all practical intents and purposes, let's consider this:
Let's work with a file that has no EOL. As of this writing the file in this example is a minified JavaScript with no EOL.
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o x.js
curl http://cdnjs.cloudflare.com/ajax/libs/AniJS/0.5.0/anijs-min.js -o y.js
$ cat x.js y.js > z.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 x.js
-rw-r--r-- 1 milanadamovsky 7905 Aug 14 23:17 y.js
-rw-r--r-- 1 milanadamovsky 15810 Aug 14 23:18 z.js
Notice the cat
file size is exactly the sum of its individual parts. If the concatenation of JavaScript files is a concern for JS files, the more appropriate concern would be to start each JavaScript file with a semi-colon.
As someone else mentioned in this thread: what if you want to cat
two files whose output becomes just one line instead of two? In other words, cat
does what it's supposed to do.
The man
of cat
only mentions reading input up to EOF, not <newline>. Note that the -n
switch of cat
will also print out a non- <newline> terminated line (or incomplete line) as a line - being that the count starts at 1 (according to the man
.)
-n Number the output lines, starting at 1.
Now that we understand how POSIX defines a line , this behavior becomes ambiguous, or really, non-compliant.
Understanding a given tool's purpose and compliance will help in determining how critical it is to end files with an EOL. In C, C++, Java (JARs), etc... some standards will dictate a newline for validity - no such standard exists for JS, HTML, CSS.
For example, instead of using wc -l filename
one could do awk '{x++}END{ print x}' filename
, and rest assured that the task's success is not jeopardized by a file we may want to process that we did not write (e.g. a third party library such as the minified JS we curl
d) - unless our intent was truly to count lines in the POSIX compliant sense.
Conclusion
There will be very few real life use cases where skipping EOL at EOF for certain text files such as JS, HTML, and CSS will have a negative impact - if at all. If we rely on <newline> being present, we are restricting the reliability of our tooling only to the files that we author and open ourselves up to potential errors introduced by third party files.
Moral of the story: Engineer tooling that does not have the weakness of relying on EOL at EOF.
Feel free to post use cases as they apply to JS, HTML and CSS where we can examine how skipping EOL has an adverse effect.
You don't need anything special for adding paramaters. Just like you had it.
Route::get('groups/(:any)', array('as' => 'group', 'uses' => 'groups@show'));
class Groups_Controller extends Base_Controller {
public $restful = true;
public function get_show($groupID) {
return 'I am group id ' . $groupID;
}
}
You can use
$now = new DateTime();
$date = $now->modify('+1 day')->format('Y-m-d H:i:s');
an alternative would be to do something like:
SELECT
CAST(P0.seconds as bigint) as seconds
FROM
(
SELECT
seconds
FROM
TableName
WHERE
ISNUMERIC(seconds) = 1
) P0
There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.
Option Explicit
Public Numbers As Variant, Tens As Variant
Sub SetNums()
Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub
Function WordNum(MyNumber As Double) As String
Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
' This macro was written by Chris Mead - www.MeadInKent.co.uk
If Abs(MyNumber) > 999999999 Then
WordNum = "Value too large"
Exit Function
End If
SetNums
' String representation of amount (excl decimals)
NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
For n = 3 To 1 Step -1 'analyse the absolute number as 3 sets of 3 digits
StrNo = Format(ValNo(n), "000")
If ValNo(n) > 0 Then
Temp1 = GetTens(Val(Right(StrNo, 2)))
If Left(StrNo, 1) <> "0" Then
Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
If Temp1 <> "" Then Temp2 = Temp2 & " and "
Else
Temp2 = ""
End If
If n = 3 Then
If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
WordNum = Trim(Temp2 & Temp1)
End If
If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
End If
Next n
NumStr = Trim(Str(Abs(MyNumber)))
' Values after the decimal place
DecimalPosition = InStr(NumStr, ".")
Numbers(0) = "Zero"
If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
Temp1 = " point"
For n = DecimalPosition + 1 To Len(NumStr)
Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
Next n
WordNum = WordNum & Temp1
End If
If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
WordNum = "Zero" & WordNum
End If
End Function
Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
If TensNum <= 19 Then
GetTens = Numbers(TensNum)
Else
Dim MyNo As String
MyNo = Format(TensNum, "00")
GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
End If
End Function
After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)
It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.
Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)
you will see a Words equivalent of the numeric value.
This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel
This is a pretty way to do that:
function time_converter($sec_time, $format='h:m:s'){
$hour = intval($sec_time / 3600) >= 10 ? intval($sec_time / 3600) : '0'.intval($sec_time / 3600);
$minute = intval(($sec_time % 3600) / 60) >= 10 ? intval(($sec_time % 3600) / 60) : '0'.intval(($sec_time % 3600) / 60);
$sec = intval(($sec_time % 3600) % 60) >= 10 ? intval(($sec_time % 3600) % 60) : '0'.intval(($sec_time % 3600) % 60);
$format = str_replace('h', $hour, $format);
$format = str_replace('m', $minute, $format);
$format = str_replace('s', $sec, $format);
return $format;
}
If you have a parameter where you may need to indicate the absence of a value, it's common practice to make the parameter a pointer value and pass in NULL.
A better solution in most cases (from a safety perspective) is to use boost::optional. This allows you to pass in optional values by reference and also as a return value.
// Sample method using optional as input parameter
void PrintOptional(const boost::optional<std::string>& optional_str)
{
if (optional_str)
{
cout << *optional_str << std::endl;
}
else
{
cout << "(no string)" << std::endl;
}
}
// Sample method using optional as return value
boost::optional<int> ReturnOptional(bool return_nothing)
{
if (return_nothing)
{
return boost::optional<int>();
}
return boost::optional<int>(42);
}
It does includes boundaries.
declare @startDate date = cast('15-NOV-2016' as date)
declare @endDate date = cast('30-NOV-2016' as date)
create table #test (c1 date)
insert into #test values(cast('15-NOV-2016' as date))
insert into #test values(cast('20-NOV-2016' as date))
insert into #test values(cast('30-NOV-2016' as date))
select * from #test where c1 between @startDate and @endDate
drop table #test
RESULT c1
2016-11-15
2016-11-20
2016-11-30
declare @r1 int = 10
declare @r2 int = 15
create table #test1 (c1 int)
insert into #test1 values(10)
insert into #test1 values(15)
insert into #test1 values(11)
select * from #test1 where c1 between @r1 and @r2
drop table #test1
RESULT c1
10
11
15
There are at least two ways for achieving this in base graph (my examples are for the x-axis, but work the same for the y-axis):
Use par(xaxp = c(x1, x2, n))
or plot(..., xaxp = c(x1, x2, n))
to define the position (x1
& x2
) of the extreme tick marks and the number of intervals between the tick marks (n
). Accordingly, n+1
is the number of tick marks drawn. (This works only if you use no logarithmic scale, for the behavior with logarithmic scales see ?par
.)
You can suppress the drawing of the axis altogether and add the tick marks later with axis()
.
To suppress the drawing of the axis use plot(... , xaxt = "n")
.
Then call axis()
with side
, at
, and labels
: axis(side = 1, at = v1, labels = v2)
. With side
referring to the side of the axis (1 = x-axis, 2 = y-axis), v1
being a vector containing the position of the ticks (e.g., c(1, 3, 5)
if your axis ranges from 0 to 6 and you want three marks), and v2
a vector containing the labels for the specified tick marks (must be of same length as v1
, e.g., c("group a", "group b", "group c")
). See ?axis
and my updated answer to a post on stats.stackexchange for an example of this method.
Option 2 is correct.
The nested list should be inside a <li>
element of the list in which it is nested.
Link to the W3C Wiki on Lists (taken from comment below): HTML Lists Wiki.
Link to the HTML5 W3C ul
spec: HTML5 ul
. Note that a ul
element may contain exactly zero or more li
elements. The same applies to HTML5 ol
.
The description list (HTML5 dl
) is similar, but allows both dt
and dd
elements.
More Notes:
dl
= definition list.ol
= ordered list (numbers).ul
= unordered list (bullets).int days = (int) (milliseconds / 86 400 000 )
i couldn't change the permissions on the sharepoint i'm using but got a round it by uploading .url files with the drag and drop multiple files uploader.
Using the normal upload didn't work because they are intepreted by the file open dialog when you try to open them singly so it just tries to open the target not the .url file.
.url files can be made by saving a favourite with internet exploiter.
URL-encoded payload must be provided on the body
parameter of the http.NewRequest(method, urlStr string, body io.Reader)
method, as a type that implements io.Reader
interface.
Based on the sample code:
package main
import (
"fmt"
"net/http"
"net/url"
"strconv"
"strings"
)
func main() {
apiUrl := "https://api.com"
resource := "/user/"
data := url.Values{}
data.Set("name", "foo")
data.Set("surname", "bar")
u, _ := url.ParseRequestURI(apiUrl)
u.Path = resource
urlStr := u.String() // "https://api.com/user/"
client := &http.Client{}
r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
resp, _ := client.Do(r)
fmt.Println(resp.Status)
}
resp.Status
is 200 OK
this way.
here's an answer that does follow the syntax of
$(element).hasAnyOfClasses("class1","class2","class3")
(function($){
$.fn.hasAnyOfClasses = function(){
for(var i= 0, il=arguments.length; i<il; i++){
if($self.hasClass(arguments[i])) return true;
}
return false;
}
})(jQuery);
it's not the fastest, but its unambiguous and the solution i prefer. bench: http://jsperf.com/hasclasstest/10
Just noting that I've just changed my config.xml to look like Sebastian's example.
Something that's also helpful in debugging all this especially if you don't do local builds... is to download the XAP/IPA/APK files as built from PhoneGap cloud and create folders for each. Rename each file with a .ZIP extension and extract the contents of each to their respective folders. So basically, you can now see what's in the package that will be shipped to the phone.
Doing this, I can see that for the Microsoft Phone platform it's largely ignoring all my attempts at replacing the icon or splash screen. If you then replace the ApplicationIcon.png and SplashScreenImage.jpg, then re-zip the folderset and rename it again as a .XAP file you can then deploy it to your phone and it will work perfectly. Somehow, there's a way of just getting the PhoneGap build to turn your icon.png and icon.jpg into those two files. Perhaps Masood's suggestion is a possibility here and utilize a hook script.
Doing the same for the .IPA file (iOS) results in several files like icon-something.png at the parent level above www. They all appear to be blank.
Doing the same for the .APK file (Android) results in a res/drawable-something set of folders and it appears to have my icon.png in each one. It's the closest to a success I can claim at the moment.
You might want to consider also checking if a value is finite via Double.isFinite(value)
. Since Java 8 there is a new method in Double
class where you can check at once if a value is not NaN and infinity.
/**
* Returns {@code true} if the argument is a finite floating-point
* value; returns {@code false} otherwise (for NaN and infinity
* arguments).
*
* @param d the {@code double} value to be tested
* @return {@code true} if the argument is a finite
* floating-point value, {@code false} otherwise.
* @since 1.8
*/
public static boolean isFinite(double d)
I think the following makes a bit more sense for print strings in reverse, but maybe that's just me:
for char in reversed( myString ):
print( char, end = "" )
@jeremiahbuddha mentioned that apply works on row/columns, while applymap works element-wise. But it seems you can still use apply for element-wise computation....
frame.apply(np.sqrt)
Out[102]:
b d e
Utah NaN 1.435159 NaN
Ohio 1.098164 0.510594 0.729748
Texas NaN 0.456436 0.697337
Oregon 0.359079 NaN NaN
frame.applymap(np.sqrt)
Out[103]:
b d e
Utah NaN 1.435159 NaN
Ohio 1.098164 0.510594 0.729748
Texas NaN 0.456436 0.697337
Oregon 0.359079 NaN NaN
You can copy by inspect element and target the div you want to copy. Just press ctrl+c and then your div will be copy and paste in your code it will run easily.
<script type="text/javascript">
$(window).on('load',function(){
setTimeout(function(){ alert(" //show popup"); }, 5000);
});
</script>
All these answers listed above, that use max-device-width
or max-device-height
for media queries, suffer from very strong bug: they also target a lot of other popular mobile devices (probably unwanted and never tested, or that will hit the market in future).
This queries will work for any device that has a smaller screen, and probably your design will be broken.
Combined with similar device-specific media queries (for HTC, Samsung, IPod, Nexus...) this practice will launch a time-bomb. For debigging, this idea can make your CSS an uncontrolled spagetti. You can never test all possible devices.
Please be aware that the only media query always targeting IPhone5 and nothing else, is:
/* iPhone 5 Retina regardless of IOS version */
@media (device-height : 568px)
and (device-width : 320px)
and (-webkit-min-device-pixel-ratio: 2)
/* and (orientation : todo: you can add orientation or delete this comment)*/ {
/*IPhone 5 only CSS here*/
}
Note that exact width and height, not max-width is checked here.
Now, what is the solution? If you want to write a webpage that will look good on all possible devices, the best practice is to you use degradation
/* degradation pattern we are checking screen width only sure, this will change is turning from portrait to landscape*/
/*css for desktops here*/
@media (max-device-width: 1024px) {
/*IPad portrait AND netbooks, AND anything with smaller screen*/
/*make the design flexible if possible */
/*Structure your code thinking about all devices that go below*/
}
@media (max-device-width: 640px) {
/*Iphone portrait and smaller*/
}
@media (max-device-width: 540px) {
/*Smaller and smaller...*/
}
@media (max-device-width: 320px) {
/*IPhone portrait and smaller. You can probably stop on 320px*/
}
If more than 30% of your website visitors come from mobile, turn this scheme upside-down, providing mobile-first approach. Use min-device-width
in that case. This will speed up webpage rendering for mobile browsers.
It may also be usefull to understand the difference in term of Session Bean Identity when using @EJB and @Inject.
According to the specifications the following code will always be true
:
@EJB Cart cart1;
@EJB Cart cart2;
… if (cart1.equals(cart2)) { // this test must return true ...}
Using @Inject instead of @EJB there is not the same.
see also stateless session beans identity for further info
You can use two way
1) if ( val == null )
2) if ( val === undefine )
Just complementing what Devart said, the below code is not ordering according to the question:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;
The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:
SELECT t1.* FROM messages t1
JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;
Regards,
I was having the same problem using my class SharedModule.
export class SharedModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: SharedModule,
providers: [MyService]
}
}
}
Then I changed it putting directly in the app.modules this way
@NgModule({declarations: [
AppComponent,
NaviComponent],imports: [BrowserModule,RouterModule.forRoot(ROUTES),providers: [MoviesService],bootstrap: [MyService] })
Obs: I'm using "@angular/core": "^6.0.2".
I hope its help you.
Another approach is to disable the text box on the client side.
In your case you have only one textbox that you need to disable but consider the case where you have multiple input, select, and textarea fields that yout need to disable.
It is much easier to do it via jquery + (since we can not rely on data coming from the client) add some logic to the controller to prevent these fields from being saved.
Here is an example:
<input id="document_Status" name="document.Status" type="hidden" value="2" />
$(document).ready(function () {
disableAll();
}
function disableAll() {
var status = $('#document_Status').val();
if (status != 0) {
$("input").attr('disabled', true);
$("textarea").attr('disabled', true);
$("select").attr('disabled', true);
}
}
Here is how to get rid of the top section header in a grouped UITableView, in Swift:
tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))
<div class="container">_x000D_
<div class="row">_x000D_
<div class="col d-flex justify-content-center">_x000D_
CenterContent_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Enable 'flex' for the column as we want & use justify-content-center
A reset will normally change everything, but you can use git stash
to pick what you want to keep. As you mentioned, stash
doesn't accept a path directly, but it can still be used to keep a specific path with the --keep-index
flag. In your example, you would stash the b directory, then reset everything else.
# How to make files a/* reappear without changing b and without recreating a/c?
git add b #add the directory you want to keep
git stash --keep-index #stash anything that isn't added
git reset #unstage the b directory
git stash drop #clean up the stash (optional)
This gets you to a point where the last part of your script will output this:
After checkout:
# On branch master
# Changes not staged for commit:
#
# modified: b/a/ba
#
no changes added to commit (use "git add" and/or "git commit -a")
a/a/aa
a/b/ab
b/a/ba
I believe this was the target result (b remains modified, a/* files are back, a/c is not recreated).
This approach has the added benefit of being very flexible; you can get as fine-grained as you want adding specific files, but not other ones, in a directory.
Usually when I want to pass arguments to an alias in Bash, I use a combination of an alias and a function like this, for instance:
function __t2d {
if [ "$1x" != 'x' ]; then
date -d "@$1"
fi
}
alias t2d='__t2d'
This line:
myForm.file.$setValidity("myForm.file.$error.size", false);
Should be
$scope.myForm.file.$setValidity("size", false);
If you are planning to run the angular project in custom host/IP and Port there is no need of making changes in config file
The following command worked for me
ng serve --host aaa.bbb.ccc.ddd --port xxxx
Where,
aaa.bbb.ccc.ddd --> IP you want to run the project
xxx --> Port you want to run the project
Example
ng serve --host 192.168.322.144 --port 6300
Result for me was
If you use bower.json file to specify your dependencies:
{
"dependencies": {
...
"photo-swipe": "[email protected]:dimsemenov/PhotoSwipe.git#v3.0.x",
#bower 1.4 (tested with that version) can read repositorios with uri format
"photo-swipe": "git://github.com/dimsemenov/PhotoSwipe.git#v3.0.x",
}
}
Just remember bower also searches for released versions and tags so you can point to almost everything, and can interprate basic query patterns like previous example. that will fetch latest minor update of version 3.0 (tested from bower 1.3.5)
Update, as the question description also mention using only a URL and no mention of a github repository.
Another example is to execute this command using the desired url, like:
bower install gmap3MarkerWithLabel=http://google-maps-utility-library-v3.googlecode.com/svn/tags/markerwithlabel/1.0/src/markerwithlabel.js -S
that command downloads your js library puts in {your destination path}/gmap3MarkerWithLabel/index.js and automatically creates an entry in your bower.json file called gmap3MarkerWithLabel: "..." After that, you can only execute bower update gmap3MarkerWithLabel
if needed.
Funny thing if you do the process backwars (add manually the entry in bower.json, an then bower install entryName) it doesn't work, you get a
bower ENOTFOUND Package gmapV3MarkerWithLabel not found
You could set the image as a background image. Since it resides in a div
, and the div
is undraggable, the image will be undraggable:
<div style="background-image: url("image.jpg");">
</div>
$fromMail = 'set your from mail';
$boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
$subjectMail = "New design submitted by " . $userDisplayName;
$contentHtml = '<div>Dear Admin<br /><br />The following design is submitted by '. $userName .'.<br /><br /><a href="'.$sdLink.'"><b>Click here</b></a> to check the design.</div>';
$contentHtml .= '<div><a href="'.$imageUrl.'"><img src="'.$imageUrl.'" width="250" height="95" border="0" alt="my picture"></a></div>';
$contentHtml .= '<div>Name : '.$name.'<br />Description : '. $description .'</div>';
$headersMail = '';
$headersMail .= 'From: ' . $fromMail . "\r\n" . 'Reply-To: ' . $fromMail . "\r\n";
$headersMail .= 'Return-Path: ' . $fromMail . "\r\n";
$headersMail .= 'MIME-Version: 1.0' . "\r\n";
$headersMail .= "Content-Type: multipart/alternative; boundary = \"" . $boundary . "\"\r\n\r\n";
$headersMail .= '--' . $boundary . "\r\n";
$headersMail .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
$headersMail .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$headersMail .= rtrim(chunk_split(base64_encode($contentHtml)));
try {
if (mail($toMail, $subjectMail, "", $headersMail)) {
$status = 'success';
$msg = 'Mail sent successfully.';
} else {
$status = 'failed';
$msg = 'Unable to send mail.';
}
} catch(Exception $e) {
$msg = $e->getMessage();
}
This works fine for me.It includes mail with image and a link and works for all sorts of mail ids. The clue is to use all the header perfectly.
If you are testing it from localhost, then set the below before checking:
How to set mail send from localhost xampp:
comment everything in D:/xampp/sendmail/sendmail.ini
and mention the below under
[sendmail]
smtp_server=smtp.gmail.com smtp_port=587 error_logfile=error.log debug_logfile=debug.log [email protected] auth_password=your-mail-password [email protected]
In D:/xampp/php/php.ini
a. Under
[mail function]
SMTP = smtp.gmail.com smtp_port = 587
b. set sendmail_from = [email protected]
c. uncomment sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t"
Hence it should be look like below
sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t"
d. comment sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe" Hence it should be look like below
;sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe"
e. mail.add_x_header=Off
This code sample is taken from csharp-examples.net, written by Jan Slama:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
XML:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
CODE:
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>" XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
sed -i '/pattern/d' file
Use 'd' to delete a line. This works at least with GNU-Sed.
If your Sed doesn't have the option, to change a file in place, maybe you can use an intermediate file, to store the modification:
sed '/pattern/d' file > tmpfile && mv tmpfile file
Writing directly to the source usually doesn't work: sed '/pattern/d' file > file
so make a copy before trying out, if you doubt it.
Per the MSDN documentation for sys.database_permissions, this query lists all permissions explicitly granted or denied to principals in the database you're connected to:
SELECT DISTINCT pr.principal_id, pr.name, pr.type_desc,
pr.authentication_type_desc, pe.state_desc, pe.permission_name
FROM sys.database_principals AS pr
JOIN sys.database_permissions AS pe
ON pe.grantee_principal_id = pr.principal_id;
Per Managing Databases and Logins in Azure SQL Database, the loginmanager and dbmanager roles are the two server-level security roles available in Azure SQL Database. The loginmanager role has permission to create logins, and the dbmanager role has permission to create databases. You can view which users belong to these roles by using the query you have above against the master database. You can also determine the role memberships of users on each of your user databases by using the same query (minus the filter predicate) while connected to them.
Sometimes Xcode when overrides methods adds class func
instead of just func
. Then in static method you can't see instance properties. It is very easy to overlook it. That was my case.
OWASP discusses this:
What's the difference between the cache-control directives: no-cache, and no-store?
The no-cache directive in a response indicates that the response must not be used to serve a subsequent request i.e. the cache must not display a response that has this directive set in the header but must let the server serve the request. The no-cache directive can include some field names; in which case the response can be shown from the cache except for the field names specified which should be served from the server. The no-store directive applies to the entire message and indicates that the cache must not store any part of the response or any request that asked for it.
Am I totally safe with these directives?
No. But generally, use both Cache-Control: no-cache, no-store and Pragma: no-cache, in addition to Expires: 0 (or a sufficiently backdated GMT date such as the UNIX epoch). Non-html content types like pdf, word documents, excel spreadsheets, etc often get cached even when the above cache control directives are set (although this varies by version and additional use of must-revalidate, pre-check=0, post-check=0, max-age=0, and s-maxage=0 in practice can sometimes result at least in file deletion upon browser closure in some cases due to browser quirks and HTTP implementations). Also, 'Autocomplete' feature allows a browser to cache whatever the user types in an input field of a form. To check this, the form tag or the individual input tags should include 'Autocomplete="Off" ' attribute. However, it should be noted that this attribute is non-standard (although it is supported by the major browsers) so it will break XHTML validation.
Source here.
I wanted to answer to the following question which is a little bit different than this:
Best way to print messages on multiple lines
He wanted to show lines from repeated characters too. He wanted this output:
----------------------------------------
# Operator Micro-benchmarks
# Run_mode: short
# Num_repeats: 5
# Num_runs: 1000
----------------------------------------
You can create those lines inside f-strings with a multiplication, like this:
run_mode, num_repeats, num_runs = 'short', 5, 1000
s = f"""
{'-'*40}
# Operator Micro-benchmarks
# Run_mode: {run_mode}
# Num_repeats: {num_repeats}
# Num_runs: {num_runs}
{'-'*40}
"""
print(s)
select sys_context('USERENV','INSTANCE_NAME') from dual;
&
select instance_name from v$instance;
will give you the instance name.
You can also use select * from global_name;
to view the global name of the instance.
There is no subquery needed with this statement, which is better written as
select u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
or
select u.*
from Users u inner join CompanyRolesToUsers c
on u.Id = c.UserId --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
That being said, in LINQ it would be
from u in Users
from c in CompanyRolesToUsers
where u.Id == c.UserId &&
u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
or
from u in Users
join c in CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is...
Unset will destroy a particular session variable whereas session_destroy()
will destroy all the session data for that user.
It really depends on your application as to which one you should use. Just keep the above in mind.
unset($_SESSION['name']); // will delete just the name data
session_destroy(); // will delete ALL data associated with that user.
Your regex pattern needs to be in delimiters:
$numpattern="/^([0-9]+)$/";
You could also use lambda
. Useful if you're using django.utils.timezone.now
date = models.DateField(_("Date"), default=lambda: now().date())
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
};
});
Put ' ; ' after function definition...
You can do it like this too:
user@host: $ cat<<EOF > file.txt
$ > 1 line
$ > other line
$ > n line
$ > EOF
user@host: $ _
I believe there is a lot of ways to use it.
A null pointer exception is an indicator that you are using an object without initializing it.
For example, below is a student class which will use it in our code.
public class Student {
private int id;
public int getId() {
return this.id;
}
public setId(int newId) {
this.id = newId;
}
}
The below code gives you a null pointer exception.
public class School {
Student student;
public School() {
try {
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
Because you are using student
, but you forgot to initialize it like in the
correct code shown below:
public class School {
Student student;
public School() {
try {
student = new Student();
student.setId(12);
student.getId();
}
catch(Exception e) {
System.out.println("Null pointer exception");
}
}
}
My worry is if I say delete evertything with an ID (>79 AND < 296) then it may literally wipe the whole table...
That wont happen because you will have a where clause. What happens is that, if you have a statement like delete * from Table1 where id between 70 and 1296
, the first thing that sql query processor will do is to scan the table and look for those records in that range and then apply a delete.
All of the applications delivered with Android (Calendar, Contacts, Email, etc) are all open-source, but not part of the SDK. The source for those projects is here: https://android.googlesource.com/ (look at /platform/packages/apps). I've referred to those sources several times when I've used an application on my phone and wanted to see how a particular feature was implemented.
For Python 3:
ListOfStrings = []
ListOfStrings.append('foo')
ListOfStrings.append('oof')
for idx, item in enumerate(ListOfStrings):
if 'foo' in item:
ListOfStrings[idx] = "bar"
Well, the main reason would be for separating the interface from the implementation. The header declares "what" a class (or whatever is being implemented) will do, while the cpp file defines "how" it will perform those features.
This reduces dependencies so that code that uses the header doesn't necessarily need to know all the details of the implementation and any other classes/headers needed only for that. This will reduce compilation times and also the amount of recompilation needed when something in the implementation changes.
It's not perfect, and you would usually resort to techniques like the Pimpl Idiom to properly separate interface and implementation, but it's a good start.
By this way, you hold a form by his ID and throw all his content. This technic is fastiest.
document.forms["id_form"].reset();
You could also just run
go build
in your project folder myproject/go/src/myprog
Then you can just type
./myprog
to run your app
I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.
If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.
#!/bin/bash
FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""
cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}
EOF
Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt
This can also be used to output blocks of text to the console with the same rules by omitting the file name
#!/bin/bash
VAR_EXAMPLE="\"string\""
cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console
EOF
Will output "${VAR_EXAMPLE}="string" to console" to the console
It's called the Big O notation, and describes the search time for various algorithms.
O(1) means that the worst case run time is constant. For most situation it means that you dont acctually need to search the collection, you cand find what you are searching for right away.
Having sifted through a variety of answers on SO and Google, I still couldn't find an optimal approach. Most answers suggest we leave the application and rely on 3rd party tool Composer to do the job, but I'm not convinced coupling to a tool just to include a file is wise.
Andrew Brown's answer came the closest to how I think it should be approached, but (at least in 5.1), the service provider step is unnecessary. Heisian's answer highlights the use of PSR-4
which brings us one step closer. Here's my final implementation for helpers in views:
First, create a helper file anywhere in your apps directory, with a namespace:
namespace App\Helpers;
class BobFinder
{
static function bob()
{
return '<strong>Bob?! Is that you?!</strong>';
}
}
Next, alias your class in config\app.php
, in the aliases
array:
'aliases' => [
// Other aliases
'BobFinder' => App\Helpers\BobFinder::class
]
And that should be all you need to do. PSR-4
and the alias should expose the helper to your views, so in your view, if you type:
{!! BobFinder::bob() !!}
It should output:
<strong>Bob?! Is that you?!</strong>
You probably need to use reflection to get the types of them to check. To get the type of the List: Get generic type of java.util.List
an example of a key value pair is:
[key: string]: string
you can put anything as the value, of course
There is LIKE
operator is added in Entity Framework Core 2.0
:
var query = from e in _context.Employees
where EF.Functions.Like(e.Title, "%developer%")
select e;
Comparing to ... where e.Title.Contains("developer") ...
it is really translated to SQL
LIKE
rather than CHARINDEX
we see for Contains
method.
After you change PATH
with the GUI, close and re-open the console window.
This works because only programs started after the change will see the new PATH
.
Execute this command in the command window you have open:
set PATH=%PATH%;C:\your\path\here\
This command appends C:\your\path\here\
to the current PATH
.
Breaking it down:
set
– A command that changes cmd's environment variables only for the current cmd session; other programs and the system are unaffected.PATH=
– Signifies that PATH
is the environment variable to be temporarily changed.%PATH%;C:\your\path\here\
– The %PATH%
part expands to the current value of PATH
, and ;C:\your\path\here\
is then concatenated to it. This becomes the new PATH
.The other answer requires that you enter the Administrator account password. Also, running under an account in the Administrator Group is not the same as run as administrator see: UAC on Wikipedia
Windows 7 Instructions
In order to run as an Administrator, create a shortcut for the batch file.
Then you can set the shortcut to run as administrator:
Now when you double click the shortcut it will prompt you for UAC confirmation and then Run as administrator (which as I said above is different than running under an account in the Administrator Group)
Check the screenshot below
Note: When you do so to Run As Administrator, the current directory (path) will not be same as the bat file. This can cause some problems in many cases that the bat file refer to relative files beside it. For example, in my Windows 7 the cur dir will be SYSTEM32 instead of bat file location! To workaround it, you should use
cd "%~dp0"
or better
pushd "%~dp0"
to ensure cur dir is at the same path where the bat file is.
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
All of this can easily be acheived in the xaml by adding the following code in the grid
<Grid>
<Grid.Background>
<ImageBrush ImageSource="/MyProject;component/Images/bg.png"/>
</Grid.Background>
</Grid>
Left for you to do, is adding a folder to the solution called 'Images' and adding an existing file to your new 'Images' folder, in this case called 'bg.png'
If you're open to using libraries, try installing forked-path (with either easy_install or pip).
Then you can do:
from path import path
s = path(filename).bytes()
This library is fairly new, but it's a fork of a library that's been floating around Python for years and has been used quite a bit. Since I found this library years ago, I very seldom use os.path
or open()
any more.
Another reason for the error (amongst many others that cropped up when changing the target build of a Win32 project to X64) was not having the C++ 64 bit compilers installed as noted at the top of this page.
Further to philipvr's comment on child headers, (in my case) an explicit include of winnt.h being unnecessary when windows.h was being used.
You can check the below code just create a index.html
and run it.
<!DOCTYPE html>
<html>
<head>
<style>
table {
border-spacing: 10px;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<table cellspacing="0" cellpadding="0">
<th>Col 1</th>
<th>Col 2</th>
<th>Col 3</th>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</table>
</body>
</html>
_x000D_
OUTPUT :
You could replace "^0*(.*)"
to "$1"
with regex
Just subtract january 1 from the date:
import datetime
today = datetime.datetime.now()
day_of_year = (today - datetime.datetime(today.year, 1, 1)).days + 1
If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:
Handle the ClientSizeChanged event
for the panel, making the
label fill the space:
private void Panel2_ClientSizeChanged(object sender, EventArgs e)
{
label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
}
Set Auto-Size
for the label to true
Dock
for the label to Fill
var days = [
"Sunday",
"Monday",
"...", //etc
"Saturday"
];
console.log(days[new Date().getDay()]);
Simple, read the Date object in JavaScript manual
To do other things with date, like get a readable string from it, I use:
var d = new Date();
d.toLocaleString();
If you just want time or date use:
d.toLocaleTimeString();
d.toLocaleDateString();
You can parse dates either by doing:
var d = new Date(dateToParse);
or
var d = Date.parse(dateToParse);
I have tried to add
jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
However, that didn't helped. On the H2 site, I have found following, which indeed could help in some cases.
By default, closing the last connection to a database closes the database. For an in-memory database, this means the content is lost. To keep the database open, add ;DB_CLOSE_DELAY=-1 to the database URL. To keep the content of an in-memory database as long as the virtual machine is alive, use jdbc:h2:mem:test;DB_CLOSE_DELAY=-1.
However, my issue was that just the schema supposed to be different than default one. So insted of using
JDBC URL: jdbc:h2:mem:test
I had to use:
JDBC URL: jdbc:h2:mem:testdb
Then the tables were visible
I think you are creating a document that looks like this:
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
This is not a valid XML document as it has more than one root element. You must have a single top-level element, as in
<mydocument>
<mycatch>
....
</mycatch>
<mycatch>
....
</mycatch>
....
</mydocument>
"hello world".split.each{|i| i.capitalize!}.join(' ')
There aren't many JavaScript decoders.
There is one at http://www.webqr.com/index.html
The easiest way is to run ZXing or similar on your server. You can then POST the image and get the decoded result back in the response.
I've always used this syntax, which yields more predictable results than using !=.
<xsl:when test="not($AccountNumber = '12345') and not($Balance = '0')" />
$('.submit').filter(':checked').each(function() {
//This is same as 'continue'
if(something){
return true;
}
//This is same as 'break'
if(something){
return false;
}
});
Here's a simple VBA solution I wrote that works with Windows, Unix, Mac, and URL paths.
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
You can test the output using this code:
'Visual Basic for Applications
http = "https://www.server.com/docs/Letter.txt"
unix = "/home/user/docs/Letter.txt"
dos = "C:\user\docs\Letter.txt"
win = "\\Server01\user\docs\Letter.txt"
blank = ""
sPath = unix
sFileName = Mid(Mid(sPath, InStrRev(sPath, "/") + 1), InStrRev(sPath, "\") + 1)
sFolderName = Left(sPath, Len(sPath) - Len(sFileName))
Debug.print "Folder: " & sFolderName & " File: " & sFileName
Also see: Wikipedia - Path (computing)
Nowdays, Primefaces 5.x have a attribute in panelGrid named "columnClasses".
.no-border {
border-style: hidden !important ; /* or none */
}
So, to a panelGrid with 2 columns, repeat two times the css class.
<p:panelGrid columns="2" columnClasses="no-border, no-border">
To other elements, the ugly " !important " is not necessary, but to the border just with it work fine to me.
If you want to find the button only by its class name and using jQLite only, you can do like below:
var myListButton = $document.find('button').filter(function() {
return angular.element(this).hasClass('multi-files');
});
Hope this helps. :)
Let's say I have 32-bit ARGB value with 8-bits per channel. I want to replace the alpha component with another alpha value, such as 0x45
unsigned long alpha = 0x45
unsigned long pixel = 0x12345678;
pixel = ((pixel & 0x00FFFFFF) | (alpha << 24));
The mask turns the top 8 bits to 0, where the old alpha value was. The alpha value is shifted up to the final bit positions it will take, then it is OR-ed into the masked pixel value. The final result is 0x45345678 which is stored into pixel.
when you click anywhere in the explorer tree and start typing something on the keyboard, the search keyword appears in the top right corner of the screen : ("module.ts")
And when you hover over the keyword with the mouse cursor, you can click on "Enable Filter on Type" to filter tree with your search !
In my taste, it's also very concise to combine zip()
with xrange(n)
(or range(n)
in Python3), which works nice on generators as well and seems to be more flexible for changes in general.
# Option #1: taking the first n elements as a list
[x for _, x in zip(xrange(n), generator)]
# Option #2, using 'next()' and taking care for 'StopIteration'
[next(generator) for _ in xrange(n)]
# Option #3: taking the first n elements as a new generator
(x for _, x in zip(xrange(n), generator))
# Option #4: yielding them by simply preparing a function
# (but take care for 'StopIteration')
def top_n(n, generator):
for _ in xrange(n): yield next(generator)
I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
which gives this value on my machine:
C:\Python25\Python.exe
You just read the registry key to get the location.
However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.
What if you are using this to determine the current selector to find its children
so this holds: <ol>
then there is <li>
s under how to write a selector
var count = $(this+"> li").length;
wont work..
Padding
Padding is a CSS property that defines the space between an element content and its border (if it has a border). If an element has a border around it, padding will give space from that border to the element content which appears in that border. If an element does not have a border around it, then adding padding has no effect at all on that element, because there is no border to give space from.
Margin
Margin is a CSS property that defines the space of outside of an element to its next outside element.
Margin affects elements that both have or do not have borders. If an element has a border, margin defines the space from this border to the next outer element. If an element does not have a border, then margin defines the space from the element content to the next outer element.
Difference Between Padding and Margin
So the difference between margin and padding is that while padding deals with the inner space, margin deals with the outer space to the next outer element.
Python library authors put the version number in <module>.__version__
. You can print it by running this on the command line:
python -c 'import keras; print(keras.__version__)'
If it's Windows terminal, enclose snippet with double-quotes like below
python -c "import keras; print(keras.__version__)"