When you decide between fixed width and fluid width you need to think in terms of your ENTIRE page. Generally, you want to pick one or the other, but not both. The examples you listed in your question are, in-fact, in the same fixed-width page. In other words, the Scaffolding page is using a fixed-width layout. The fixed grid and fluid grid on the Scaffolding page are not meant to be examples, but rather the documentation for implementing fixed and fluid width layouts.
The proper fixed width example is here. The proper fluid width example is here.
When observing the fixed width example, you should not see the content changing sizes when your browser is greater than 960px wide. This is the maximum (fixed) width of the page. Media queries in a fixed-width design will designate the minimum widths for particular styles. You will see this in action when you shrink your browser window and see the layout snap to a different size.
Conversely, the fluid-width layout will always stretch to fit your browser window, no matter how wide it gets. The media queries indicate when the styles change, but the width of containers are always a percentage of your browser window (rather than a fixed number of pixels).
The 'responsive' media queries are all ready to go. You just need to decide if you want to use a fixed width or fluid width layout for your page.
Previously, in bootstrap 2, you had to use row-fluid
inside a fluid container and row
inside a fixed container. With the introduction of bootstrap 3, row-fluid
was removed, do no longer use it.
EDIT: As per the comments, some jsFiddles for:
These fiddles are completely Bootstrap-free, based on pure CSS media queries, which makes them a good starting point, for anyone willing to craft similar solution without using Twitter Bootstrap.
You can try this:
td p {word-break:break-all;}
This, however, makes it appear like this when there's enough space, unless you add a <br>
tag:
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
So, I would then suggest adding <br>
tags where there are newlines, if possible.
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Also, if this doesn't solve your problem, there's a similar thread here.
Here is the Java Implementation:
public static String reverseAllWords(String given_string)
{
if(given_string == null || given_string.isBlank())
return given_string;
char[] str = given_string.toCharArray();
int start = 0;
// Reverse the entire string
reverseString(str, start, given_string.length() - 1);
// Reverse the letters of each individual word
for(int end = 0; end <= given_string.length(); end++)
{
if(end == given_string.length() || str[end] == ' ')
{
reverseString(str, start, end-1);
start = end + 1;
}
}
return new String(str);
}
// In-place reverse string method
public static void reverseString(char[] str, int start, int end)
{
while(start < end)
{
char temp = str[start];
str[start++] = str[end];
str[end--] = temp;
}
}
You can give tooltipTemplate a function, and format the tooltip as you wish:
tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}
Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.
DECLARE @id INT
DECLARE @name NVARCHAR(100)
DECLARE @getid CURSOR
SET @getid = CURSOR FOR
SELECT table.id,
table.name
FROM table
WHILE 1=1
BEGIN
FETCH NEXT
FROM @getid INTO @id, @name
IF @@FETCH_STATUS < 0 BREAK
EXEC stored_proc @varName=@id, @otherVarName='test', @varForName=@name
END
CLOSE @getid
DEALLOCATE @getid
You can add hash info in next page url to move browser at specific position(any html element), after page is loaded.
This is can done in this way:
add hash in the url of next_page : example.com#hashkey
$( document ).ready(function() {
##get hash code at next page
var hashcode = window.location.hash;
## move page to any specific position of next page(let that is div with id "hashcode")
$('html,body').animate({scrollTop: $('div#'+hascode).offset().top},'slow');
});
I have been composing my Jersey 1.17 services the following way:
FileStreamingOutput
public class FileStreamingOutput implements StreamingOutput {
private File file;
public FileStreamingOutput(File file) {
this.file = file;
}
@Override
public void write(OutputStream output)
throws IOException, WebApplicationException {
FileInputStream input = new FileInputStream(file);
try {
int bytes;
while ((bytes = input.read()) != -1) {
output.write(bytes);
}
} catch (Exception e) {
throw new WebApplicationException(e);
} finally {
if (output != null) output.close();
if (input != null) input.close();
}
}
}
GET
@GET
@Produces("application/pdf")
public StreamingOutput getPdf(@QueryParam(value="name") String pdfFileName) {
if (pdfFileName == null)
throw new WebApplicationException(Response.Status.BAD_REQUEST);
if (!pdfFileName.endsWith(".pdf")) pdfFileName = pdfFileName + ".pdf";
File pdf = new File(Settings.basePath, pdfFileName);
if (!pdf.exists())
throw new WebApplicationException(Response.Status.NOT_FOUND);
return new FileStreamingOutput(pdf);
}
And the client, if you need it:
Client
private WebResource resource;
public InputStream getPDFStream(String filename) throws IOException {
ClientResponse response = resource.path("pdf").queryParam("name", filename)
.type("application/pdf").get(ClientResponse.class);
return response.getEntityInputStream();
}
If you want all the bars to get the same color (fill
), you can easily add it inside geom_bar
.
ggplot(data=df, aes(x=c1+c2/2, y=c3)) +
geom_bar(stat="identity", width=c2, fill = "#FF6666")
Add fill = the_name_of_your_var
inside aes
to change the colors depending of the variable :
c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2)
Use scale_fill_manual()
if you want to manually the change of colors.
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) +
geom_bar(stat="identity", width=c2) +
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))
I've used the following code a few times and it works sweet:
$("body").click(function(e){
// Check what has been clicked:
var target = $(e.target);
if(target.is("#target")){
// The target was clicked
// Do something...
}
});
You should include <string.h>
(or its C++ equivalent, <cstring>
).
Java ships in 2 versions: JRE & SDK (used to be called JDK)
The JRE in addition to not containing the compiler, also doesn't contain all of the libraries available in the JDK (tools.jar is one of them)
When you download Java at: http://java.sun.com/javase/downloads/index.jsp, make sure to select the JDK version and install it. If you have both a JDK & JRE, make sure that ANT is using the JDK, you can check JAVA_HOME (environment variable), and on the commandline if you do "javac -version" you should get a version description.
I wrote a wrapper using the ExpressionTree variant and c#7 (if somebody is interested):
public class Accessor<T>
{
private Action<T> Setter;
private Func<T> Getter;
public Accessor(Expression<Func<T>> expr)
{
var memberExpression = (MemberExpression)expr.Body;
var instanceExpression = memberExpression.Expression;
var parameter = Expression.Parameter(typeof(T));
if (memberExpression.Member is PropertyInfo propertyInfo)
{
Setter = Expression.Lambda<Action<T>>(Expression.Call(instanceExpression, propertyInfo.GetSetMethod(), parameter), parameter).Compile();
Getter = Expression.Lambda<Func<T>>(Expression.Call(instanceExpression, propertyInfo.GetGetMethod())).Compile();
}
else if (memberExpression.Member is FieldInfo fieldInfo)
{
Setter = Expression.Lambda<Action<T>>(Expression.Assign(memberExpression, parameter), parameter).Compile();
Getter = Expression.Lambda<Func<T>>(Expression.Field(instanceExpression,fieldInfo)).Compile();
}
}
public void Set(T value) => Setter(value);
public T Get() => Getter();
}
And use it like:
var accessor = new Accessor<string>(() => myClient.WorkPhone);
accessor.Set("12345");
Assert.Equal(accessor.Get(), "12345");
$(".thisClass[id!='thisId']").doAction();
Documentation on selectors: http://api.jquery.com/category/selectors/
Here is a nice way to display the information that you want:
SELECT B.table_catalog as 'Database_Name',
B.table_name as 'Table_Name',
stuff((select ', ' + A.column_name
from INFORMATION_SCHEMA.COLUMNS A
where A.Table_name = B.Table_Name
FOR XML PATH(''),TYPE).value('(./text())[1]','NVARCHAR(MAX)')
, 1, 2, '') as 'Columns'
FROM INFORMATION_SCHEMA.COLUMNS B
WHERE B.TABLE_NAME like '%%'
AND B.COLUMN_NAME like '%%'
GROUP BY B.Table_Catalog, B.Table_Name
Order by 1 asc
Add anything between either '%%' in the main select to narrow down what tables and/or column names you want.
An index friendly way of doing this is:
where (field is not null and field <> '')
If there aren't many rows or this field isn't indexed, you can use:
where isnull(field,'') <> ''
Try this:
ls -l | awk -F : '{sum+=$5} END {print "AVG=",sum/NR}'
NR is an AWK builtin variable to count the no. of records
For anyone want to get time elapsed value instead of console output :
use process.hrtime() as @D.Deriso suggestion, below is my simpler approach :
function functionToBeMeasured() {
var startTime = process.hrtime();
// do some task...
// ......
var elapsedSeconds = parseHrtimeToSeconds(process.hrtime(startTime));
console.log('It takes ' + elapsedSeconds + 'seconds');
}
function parseHrtimeToSeconds(hrtime) {
var seconds = (hrtime[0] + (hrtime[1] / 1e9)).toFixed(3);
return seconds;
}
I know it's a bit late but it still might help someone. I did it like this:
<div ng-repeat="product in products" ng-if="$index % 3 == 0" class="row">
<div class="col-xs-4">{{products[$index]}}</div>
<div class="col-xs-4" ng-if="products.length > ($index + 1)">{{products[$index + 1]}}</div>
<div class="col-xs-4" ng-if="products.length > ($index + 2)">{{products[$index + 2]}}</div>
</div>
This one works for me:
<?php
if(isset($_GET['action']))
{
//your code
echo 'Welcome';
}
?>
<form id="frm" method="post" action="?action" >
<input type="submit" value="Submit" id="submit" />
</form>
This link can be helpful:
For jQuery 1.8+, this will no longer work because the internal data is placed in a different object.
The latest unofficial (but works in previous versions as well, at least in 1.7.2) way of doing it now is -
$._data(element, "events")
The underscore ("_") is what makes the difference here. Internally, it is calling $.data(element, name, null, true)
, the last (fourth) parameter is an internal one ("pvt").
In addition to fedorqui's correct answer, I would like to show the difference between string length and byte length:
myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
LANG=$oLang LC_ALL=$oLcAll
printf "%s is %d char len, but %d bytes len.\n" "${myvar}" $chrlen $bytlen
will render:
Généralités is 11 char len, but 14 bytes len.
you could even have a look at stored chars:
myvar='Généralités'
chrlen=${#myvar}
oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#myvar}
printf -v myreal "%q" "$myvar"
LANG=$oLang LC_ALL=$oLcAll
printf "%s has %d chars, %d bytes: (%s).\n" "${myvar}" $chrlen $bytlen "$myreal"
will answer:
Généralités has 11 chars, 14 bytes: ($'G\303\251n\303\251ralit\303\251s').
Nota: According to Isabell Cowan's comment, I've added setting to $LC_ALL
along with $LANG
.
Argument work same as regular variables
strLen() {
local bytlen sreal oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#1}
printf -v sreal %q "$1"
LANG=$oLang LC_ALL=$oLcAll
printf "String '%s' is %d bytes, but %d chars len: %s.\n" "$1" $bytlen ${#1} "$sreal"
}
will work as
strLen théorème
String 'théorème' is 10 bytes, but 8 chars len: $'th\303\251or\303\250me'
printf
correction tool:If you:
for string in Généralités Language Théorème Février "Left: ?" "Yin Yang ?";do
printf " - %-14s is %2d char length\n" "'$string'" ${#string}
done
- 'Généralités' is 11 char length
- 'Language' is 8 char length
- 'Théorème' is 8 char length
- 'Février' is 7 char length
- 'Left: ?' is 7 char length
- 'Yin Yang ?' is 10 char length
Not really pretty... For this, there is a little function:
strU8DiffLen () {
local bytlen oLang=$LANG oLcAll=$LC_ALL
LANG=C LC_ALL=C
bytlen=${#1}
LANG=$oLang LC_ALL=$oLcAll
return $(( bytlen - ${#1} ))
}
Then now:
for string in Généralités Language Théorème Février "Left: ?" "Yin Yang ?";do
strU8DiffLen "$string"
printf " - %-$((14+$?))s is %2d chars length, but uses %2d bytes\n" \
"'$string'" ${#string} $((${#string}+$?))
done
- 'Généralités' is 11 chars length, but uses 14 bytes
- 'Language' is 8 chars length, but uses 8 bytes
- 'Théorème' is 8 chars length, but uses 10 bytes
- 'Février' is 7 chars length, but uses 8 bytes
- 'Left: ?' is 7 chars length, but uses 9 bytes
- 'Yin Yang ?' is 10 chars length, but uses 12 bytes
But there left some strange UTF-8 behaviour, like double-spaced chars, zero spaced chars, reverse deplacement and other that could not be as simple...
Have a look at diffU8test.sh or diffU8test.sh.txt for more limitations.
In python 3 you can use os.scandir():
for i in os.scandir(path):
if i.is_file():
print('File: ' + i.path)
elif i.is_dir():
print('Folder: ' + i.path)
What follows is the easiest way to install a Java application as system service in Linux.
Let's assume you are using systemd
(which any modern distro nowadays does):
Firstly, create a service file in /etc/systemd/system
named e.g. javaservice.service
with this content:
[Unit]
Description=Java Service
[Service]
User=nobody
# The configuration file application.properties should be here:
WorkingDirectory=/data
ExecStart=/usr/bin/java -Xmx256m -jar application.jar --server.port=8081
SuccessExitStatus=143
TimeoutStopSec=10
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target
Secondly, notify systemd
of the new service file:
systemctl daemon-reload
and enable it, so it runs on boot:
systemctl enable javaservice.service
Eventually, you can use the following commands to start/stop your new service:
systemctl start javaservice
systemctl stop javaservice
systemctl restart javaservice
systemctl status javaservice
Provided you are using systemd
, this is the most non-intrusive and clean way to set up a Java application as system-service.
What I like especially about this solution is the fact that you don't need to install and configure any other software. The shipped systemd
does all the work for you, and your service behaves like any other system service. I use it in production for a while now, on different distros, and it just works as you would expect.
Another plus is that, by using /usr/bin/java
, you can easily add jvm
paramters such as -Xmx256m
.
Also read the systemd
part in the official Spring Boot documentation:
http://docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html
You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:
mLocationClient.requestLocationUpdates(mLocationRequest, this);
Be sure that the LocationListener you're implementing is from the google api, that is import this:
import com.google.android.gms.location.LocationListener;
and not this:
import android.location.LocationListener;
and it should work just fine.
It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html
In a word, no. You can have several forms in a page but they should not be nested.
From the html5 working draft:
4.10.3 The
form
elementContent model:
Flow content, but with no form element descendants.
I needed the following bindings to get mine to work:
<binding name="SI_PurchaseRequisition_ISBindingSSL">
<security mode="Transport">
<transport clientCredentialType="Basic" proxyCredentialType="None" realm="" />
</security>
</binding>
When modal hide? we check like this :
$('.yourmodal').on('hidden.bs.modal', function () {
// do something here
})
days + hours
. Minutes are not included.hh:mm
or x hours y minutes
, would require additional calculations and string formatting.timedelta
math, and is faster than using .astype('timedelta64[h]')
timedelta
objects: See supported operations.datetime64[ns] dtype
. It is required that all relevant columns are converted using pandas.to_datetime()
.import pandas as pd
# test data from OP, with values already in a datetime format
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000'), pd.Timestamp('2014-01-23 10:07:47.660000')],
'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000'), pd.Timestamp('2014-01-23 18:50:41.420000')]}
# test dataframe; the columns must be in a datetime format; use pandas.to_datetime if needed
df = pd.DataFrame(data)
# add a timedelta column if wanted. It's added here for information only
# df['time_delta_with_sub'] = df.from_date.sub(df.to_date) # also works
df['time_delta'] = (df.from_date - df.to_date)
# create a column with timedelta as total hours, as a float type
df['tot_hour_diff'] = (df.from_date - df.to_date) / pd.Timedelta(hours=1)
# create a colume with timedelta as total minutes, as a float type
df['tot_mins_diff'] = (df.from_date - df.to_date) / pd.Timedelta(minutes=1)
# display(df)
to_date from_date time_delta tot_hour_diff tot_mins_diff
0 2014-01-24 13:03:12.050 2014-01-26 23:41:21.870 2 days 10:38:09.820000 58.636061 3518.163667
1 2014-01-27 11:57:18.240 2014-01-27 15:38:22.540 0 days 03:41:04.300000 3.684528 221.071667
2 2014-01-23 10:07:47.660 2014-01-23 18:50:41.420 0 days 08:42:53.760000 8.714933 522.896000
.total_seconds()
was added and merged when the core developer was on vacation, and would not have been approved.
.total_xx
methods.# convert the entire timedelta to seconds
# this is the same as td / timedelta(seconds=1)
(df.from_date - df.to_date).dt.total_seconds()
[out]:
0 211089.82
1 13264.30
2 31373.76
dtype: float64
# get the number of days
(df.from_date - df.to_date).dt.days
[out]:
0 2
1 0
2 0
dtype: int64
# get the seconds for hours + minutes + seconds, but not days
# note the difference from total_seconds
(df.from_date - df.to_date).dt.seconds
[out]:
0 38289
1 13264
2 31373
dtype: int64
dateutil
maintainer:
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
(df.from_date - df.to_date).dt.total_seconds() / 3600
dateutil
module provides powerful extensions to the standard datetime
module.%%timeit
testimport pandas as pd
# dataframe with 2M rows
data = {'to_date': [pd.Timestamp('2014-01-24 13:03:12.050000'), pd.Timestamp('2014-01-27 11:57:18.240000')], 'from_date': [pd.Timestamp('2014-01-26 23:41:21.870000'), pd.Timestamp('2014-01-27 15:38:22.540000')]}
df = pd.DataFrame(data)
df = pd.concat([df] * 1000000).reset_index(drop=True)
%%timeit
(df.from_date - df.to_date) / pd.Timedelta(hours=1)
[out]:
43.1 ms ± 1.05 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
%%timeit
(df.from_date - df.to_date).astype('timedelta64[h]')
[out]:
59.8 ms ± 1.29 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
You are inside a namespace
so you should use \Exception
to specify the global namespace:
try {
$this->buildXMLHeader();
} catch (\Exception $e) {
return $e->getMessage();
}
In your code you've used catch (Exception $e)
so Exception
is being searched in/as:
App\Services\PayUService\Exception
Since there is no Exception
class inside App\Services\PayUService
so it's not being triggered. Alternatively, you can use a use
statement at the top of your class like use Exception;
and then you can use catch (Exception $e)
.
You can do that in PL/SQL Developer v10.
1. Click on Table that you want to generate script for.
2. Click Export data.
3. Check if table is selected that you want to export data for.
4. Click on SQL inserts tab.
5. Add where clause if you don't need the whole table.
6. Select file where you will find your SQL script.
7. Click export.
<div class="post_category">
<?php $category = get_the_category();
$allcategory = get_the_category();
foreach ($allcategory as $category) {
?>
<a class="btn"><?php echo $category->cat_name;; ?></a>
<?php
}
?>
</div>
The home-grown core Java solution that I use to decorate existing factories:
public class ThreadFactoryNameDecorator implements ThreadFactory {
private final ThreadFactory defaultThreadFactory;
private final String suffix;
public ThreadFactoryNameDecorator(String suffix) {
this(Executors.defaultThreadFactory(), suffix);
}
public ThreadFactoryNameDecorator(ThreadFactory threadFactory, String suffix) {
this.defaultThreadFactory = threadFactory;
this.suffix = suffix;
}
@Override
public Thread newThread(Runnable task) {
Thread thread = defaultThreadFactory.newThread(task);
thread.setName(thread.getName() + "-" + suffix);
return thread;
}
}
In action:
Executors.newSingleThreadExecutor(new ThreadFactoryNameDecorator("foo"));
Does m
really need to be a data.frame()
or will a matrix()
suffice?
m <- matrix(0, ncol = 30, nrow = 2)
You can wrap a data.frame()
around that if you need to:
m <- data.frame(m)
or all in one line: m <- data.frame(matrix(0, ncol = 30, nrow = 2))
Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000
or Access-Control-Allow-Origin: *
on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true
on the POST response as well.
Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept
to match the requested header.
My choice was to use .includes()
extending the Array.prototype as @Darrin Dimitrov suggested:
Array.prototype.pushIfNotIncluded = function (element) {
if (!this.includes(element)) {
array.push(element);
}
}
Just remembering that includes
comes from es6 and does not work on IE:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
We use a CTE wrapped in Dynamic SQL (because our application requires dynamic sorting of data server side) within a stored procedure. I can provide a basic example if you'd like.
I haven't had a chance to look at the T/SQL that LINQ produces. Can someone post a sample?
We don't use LINQ or straight access to the tables as we require the extra layer of security (granted the dynamic SQL breaks this somewhat).
Something like this should do the trick. You can add in parameterized values for parameters, etc.
exec sp_executesql 'WITH MyCTE AS (
SELECT TOP (10) ROW_NUMBER () OVER ' + @SortingColumn + ' as RowID, Col1, Col2
FROM MyTable
WHERE Col4 = ''Something''
)
SELECT *
FROM MyCTE
WHERE RowID BETWEEN 10 and 20'
In Visual Studio 2019 you can find cl.exe inside
32-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx86\x86
64-BIT : C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.20.27508\bin\Hostx64\x64
Before trying to compile either run vcvars32 for 32-Bit compilation or vcvars64 for 64-Bit.
32-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars32.bat"
64-BIT : "C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Auxiliary\Build\vcvars64.bat"
If you can't find the file or the directory, try going to C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC
and see if you can find a folder with a version number. If you can't, then you probably haven't installed C++ through the Visual Studio Installation yet.
Often, a Python program is run by naming a .py file on the command line:
$ python my_program.py
You can also create a directory or zipfile full of code, and include a __main__.py
. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py
automatically:
$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program
You'll have to decide for yourself whether your application could benefit from being executed like this.
Note that a __main__
module usually doesn't come from a __main__.py
file. It can, but it usually doesn't. When you run a script like python my_program.py
, the script will run as the __main__
module instead of the my_program
module. This also happens for modules run as python -m my_module
, or in several other ways.
If you saw the name __main__
in an error message, that doesn't necessarily mean you should be looking for a __main__.py
file.
In November 2017 Google released the Room Persistence Library.
From the documentation:
The Room persistence library provides an abstraction layer over SQLite to allow fluent database access while harnessing the full power of SQLite.
The library helps you create a cache of your app's data on a device that's running your app. This cache, which serves as your app's single source of truth, allows users to view a consistent copy of the key information within your app, regardless of whether users have an internet connection.
The Room database has a callback when the database is first created or opened. You can use the create callback to populate your database.
Room.databaseBuilder(context.applicationContext,
DataDatabase::class.java, "Sample.db")
// prepopulate the database after onCreate was called
.addCallback(object : Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
// moving to a new thread
ioThread {
getInstance(context).dataDao()
.insert(PREPOPULATE_DATA)
}
}
})
.build()
Code from this blog post.
Storing files in your database will lead to a huge database size. You may not like that, for development, testing, backups, etc.
Instead, you'd use FileStream (SQL-Server) or BFILE (Oracle).
There is no default-implementation of BFILE/FileStream in Postgres, but you can add it: https://github.com/darold/external_file
And further information (in french) can be obtained here:
http://blog.dalibo.com/2015/01/26/Extension_BFILE_pour_PostgreSQL.html
To answer the acual question:
Apart from bytea
, for really large files, you can use LOBS:
// http://stackoverflow.com/questions/14509747/inserting-large-object-into-postgresql-returns-53200-out-of-memory-error
// https://github.com/npgsql/Npgsql/wiki/User-Manual
public int InsertLargeObject()
{
int noid;
byte[] BinaryData = new byte[123];
// Npgsql.NpgsqlCommand cmd ;
// long lng = cmd.LastInsertedOID;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
using (Npgsql.NpgsqlTransaction transaction = connection.BeginTransaction())
{
try
{
NpgsqlTypes.LargeObjectManager manager = new NpgsqlTypes.LargeObjectManager(connection);
noid = manager.Create(NpgsqlTypes.LargeObjectManager.READWRITE);
NpgsqlTypes.LargeObject lo = manager.Open(noid, NpgsqlTypes.LargeObjectManager.READWRITE);
// lo.Write(BinaryData);
int i = 0;
do
{
int length = 1000;
if (i + length > BinaryData.Length)
length = BinaryData.Length - i;
byte[] chunk = new byte[length];
System.Array.Copy(BinaryData, i, chunk, 0, length);
lo.Write(chunk, 0, length);
i += length;
} while (i < BinaryData.Length);
lo.Close();
transaction.Commit();
} // End Try
catch
{
transaction.Rollback();
throw;
} // End Catch
return noid;
} // End Using transaction
} // End using connection
} // End Function InsertLargeObject
public System.Drawing.Image GetLargeDrawing(int idOfOID)
{
System.Drawing.Image img;
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
lock (connection)
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
NpgsqlTypes.LargeObject lo = lbm.Open(takeOID(idOfOID), NpgsqlTypes.LargeObjectManager.READWRITE); //take picture oid from metod takeOID
byte[] buffer = new byte[32768];
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
int read;
while ((read = lo.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
} // Whend
img = System.Drawing.Image.FromStream(ms);
} // End Using ms
lo.Close();
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End lock connection
} // End Using connection
return img;
} // End Function GetLargeDrawing
public void DeleteLargeObject(int noid)
{
using (Npgsql.NpgsqlConnection connection = new Npgsql.NpgsqlConnection(GetConnectionString()))
{
if (connection.State != System.Data.ConnectionState.Open)
connection.Open();
using (Npgsql.NpgsqlTransaction trans = connection.BeginTransaction())
{
NpgsqlTypes.LargeObjectManager lbm = new NpgsqlTypes.LargeObjectManager(connection);
lbm.Delete(noid);
trans.Commit();
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
} // End Using trans
} // End Using connection
} // End Sub DeleteLargeObject
I've changed my code like this and it works:
CREATE or REPLACE TRIGGER test001
AFTER INSERT OR UPDATE OR DELETE ON tabletest001
REFERENCING OLD AS old_buffer NEW AS new_buffer
FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00')
DECLARE
Operation NUMBER;
CustomerCode CHAR(10 BYTE);
BEGIN
IF DELETING THEN
Operation := 3;
CustomerCode := :old_buffer.field1;
END IF;
IF INSERTING THEN
Operation := 1;
CustomerCode := :new_buffer.field1;
END IF;
IF UPDATING THEN
Operation := 2;
CustomerCode := :new_buffer.field1;
END IF;
// DO SOMETHING ...
EXCEPTION
WHEN OTHERS THEN ErrorCode := SQLCODE;
END;
I faced the same problem. I had a zip archive which java.util.zip.ZipFile was not able to handle but WinRar unpacked it just fine. I found article on SDN about compressing and decompressing options in Java. I slightly modified one of example codes to produce method which was finally capable of handling the archive. Trick is in using ZipInputStream instead of ZipFile and in sequential reading of zip archive. This method is also capable of handling empty zip archive. I believe you can adjust the method to suit your needs as all zip classes have equivalent subclasses for .jar archives.
public void unzipFileIntoDirectory(File archive, File destinationDir)
throws Exception {
final int BUFFER_SIZE = 1024;
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream(archive);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
File destFile;
while ((entry = zis.getNextEntry()) != null) {
destFile = FilesystemUtils.combineFileNames(destinationDir, entry.getName());
if (entry.isDirectory()) {
destFile.mkdirs();
continue;
} else {
int count;
byte data[] = new byte[BUFFER_SIZE];
destFile.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(destFile);
dest = new BufferedOutputStream(fos, BUFFER_SIZE);
while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
fos.close();
}
}
zis.close();
fis.close();
}
Yes, that is fully possible (i.e. I do exactly this); you just need to reference the right dll (System.ServiceProcess.dll) and add an installer class...
[RunInstaller(true)]
public sealed class MyServiceInstallerProcess : ServiceProcessInstaller
{
public MyServiceInstallerProcess()
{
this.Account = ServiceAccount.NetworkService;
}
}
[RunInstaller(true)]
public sealed class MyServiceInstaller : ServiceInstaller
{
public MyServiceInstaller()
{
this.Description = "Service Description";
this.DisplayName = "Service Name";
this.ServiceName = "ServiceName";
this.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
}
}
static void Install(bool undo, string[] args)
{
try
{
Console.WriteLine(undo ? "uninstalling" : "installing");
using (AssemblyInstaller inst = new AssemblyInstaller(typeof(Program).Assembly, args))
{
IDictionary state = new Hashtable();
inst.UseNewContext = true;
try
{
if (undo)
{
inst.Uninstall(state);
}
else
{
inst.Install(state);
inst.Commit(state);
}
}
catch
{
try
{
inst.Rollback(state);
}
catch { }
throw;
}
}
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
}
If you are using Python 3, it is recommended to simply call super() without any argument:
class Car(object):
condition = "new"
def __init__(self, model, color, mpg):
self.model = model
self.color = color
self.mpg = mpg
class ElectricCar(Car):
def __init__(self, battery_type, model, color, mpg):
self.battery_type=battery_type
super().__init__(model, color, mpg)
car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__
Do not call super with class as it may lead to infinite recursion exceptions as per this answer.
Less SELECT statements. Also, less performance consuming. Credits to: [email protected]
SELECT *
FROM (SELECT t.*,
rownum AS rn
FROM shhospede t) a
WHERE a.rn >= in_first
AND a.rn <= in_first;
There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
The macro ARRAYELEMENTCOUNT(x)
that everyone is making use of evaluates incorrectly. This, realistically, is just a sensitive matter, because you can't have expressions that result in an 'array' type.
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x[0]))
ARRAYELEMENTCOUNT(p + 1);
Actually evaluates as:
(sizeof (p + 1) / sizeof (p + 1[0]));
Whereas
/* Compile as: CL /P "macro.c" */
# define ARRAYELEMENTCOUNT(x) (sizeof (x) / sizeof (x)[0])
ARRAYELEMENTCOUNT(p + 1);
It correctly evaluates to:
(sizeof (p + 1) / sizeof (p + 1)[0]);
This really doesn't have a lot to do with the size of arrays explicitly. I've just noticed a lot of errors from not truly observing how the C preprocessor works. You always wrap the macro parameter, not an expression in might be involved in.
This is correct; my example was a bad one. But that's actually exactly what should happen. As I previously mentioned p + 1
will end up as a pointer type and invalidate the entire macro (just like if you attempted to use the macro in a function with a pointer parameter).
At the end of the day, in this particular instance, the fault doesn't really matter (so I'm just wasting everyone's time; huzzah!), because you don't have expressions with a type of 'array'. But really the point about preprocessor evaluation subtles I think is an important one.
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
You have to set up the your location timezone. So that follow below process
Open your MSQLWorkbench
write a simple sql command like this;
select now();
And also your url could be like this;
url = "jdbc:mysql://localhost:3306/your_database_name?serverTimezone=UTC";
It's best if you worked with DataSet
s and/or DataTable
s. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:
ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);
.. which will produce a beautiful excelsheet with a nice table!
Now to serve your file, assuming you have an ExcelPackage
object as in your code above called pck
..
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
Do you want to make a string out of them?
String s = new StringBuilder().append(char1).append(char2).append(char3).toString();
Note that
String b = "b";
String s = "a" + b + "c";
Actually compiles to
String s = new StringBuilder("a").append(b).append("c").toString();
Edit: as litb pointed out, you can also do this:
"" + char1 + char2 + char3;
That compiles to the following:
new StringBuilder().append("").append(c).append(c1).append(c2).toString();
Edit (2): Corrected string append comparison since, as cletus points out, a series of strings is handled by the compiler.
The purpose of the above is to illustrate what the compiler does, not to tell you what you should do.
You then commit the
composer.json
to your project and everyone else on your team can run composer install to install your project dependencies.The point of the lock file is to record the exact versions that are installed so they can be re-installed. This means that if you have a version spec of 1.* and your co-worker runs composer update which installs 1.2.4, and then commits the composer.lock file, when you composer install, you will also get 1.2.4, even if 1.3.0 has been released. This ensures everybody working on the project has the same exact version.
This means that if anything has been committed since the last time a composer install was done, then, without a lock file, you will get new third-party code being pulled down.
Again, this is a problem if you’re concerned about your code breaking. And it’s one of the reasons why it’s important to think about Composer as being centered around the composer.lock file.
Source: Composer: It’s All About the Lock File.
Commit your application's composer.lock (along with composer.json) into version control. This is important because the install command checks if a lock file is present, and if it is, it downloads the versions specified there (regardless of what composer.json says). This means that anyone who sets up the project will download the exact same version of the dependencies. Your CI server, production machines, other developers in your team, everything and everyone runs on the same dependencies, which mitigates the potential for bugs affecting only some parts of the deployments. Even if you develop alone, in six months when reinstalling the project you can feel confident the dependencies installed are still working even if your dependencies released many new versions since then.
Source: Composer - Basic Usage.
You can also remove your header line:
<div data-role="header">...</div>
which removes the close button.
I have some issue, the fix is:
greetings!
First up, going by the function name xssRequest it sounds like you're trying cross site request - which if that's right, you're not going to be able to read the contents of the iframe.
On the other hand, if the iframe's URL is on your domain you can access the body, but I've found that if I use a timeout to remove the iframe the callback works fine:
// possibly excessive use of jQuery - but I've got a live working example in production
$('#myUniqueID').load(function () {
if (typeof callback == 'function') {
callback($('body', this.contentWindow.document).html());
}
setTimeout(function () {$('#frameId').remove();}, 50);
});
Can be achieved also with scriptrunner
ScriptRunner.exe -appvscript demoA.cmd arg1 arg2 -appvscriptrunnerparameters -wait -timeout=30 -rollbackonerror -appvscript demoB.ps1 arg3 arg4 -appvscriptrunnerparameters -wait -timeout=30
Which also have some features as rollback , timeout and waiting.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
Edit: I found this JQuery script which is doing what you are asking for, I didn't test it though.
@Input() set categoryId(categoryId: number) {
console.log(categoryId)
}
please try using this method. Hope this helps
Lint was the name of a program that would go through your C code and identify problems before you compiled, linked, and ran it. It was a static checker, much like FindBugs today for Java.
Like Google, "lint" became a verb that meant static checking your source code.
I tried the following and it didn't work on my environment:
bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory());
But different property worked like a charm:
bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, getCustomSocketFactory());
The rest of the code was taken from the first reply.
In Excel for Mac at least, you can do this by saving as "CSV for MS DOS" which adds double quotes for any field which needs them.
This works regardless of the size of its contents
.centered {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
source: https://css-tricks.com/quick-css-trick-how-to-center-an-object-exactly-in-the-center/
R.color.black
or some color are obviously integers. It needs a RGB value. You can give your own like #FF123454
which represents various primary colors
Here is what I use to convert to the XSD datetime format:
from datetime import datetime
datetime.now().replace(microsecond=0).isoformat()
# You get your ISO string
I came across this question when looking for the XSD date time format (xs:dateTime
). I needed to remove the microseconds from isoformat
.
EDIT Ignore this answer. There are now better answers. See the comments. Use + theme_classic()
EDIT
This is a better version. The bug mentioned below in the original post remains (I think). But the axis line is drawn under the panel. Therefore, remove both the panel.border
and panel.background
to see the axis lines.
library(ggplot2)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
ggplot(df, aes(x = a, y = b)) + geom_point() +
theme_bw() +
theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank())
Original post
This gets close. There was a bug with axis.line
not working on the y-axis (see here), that appears not to be fixed yet. Therefore, after removing the panel border, the y-axis has to be drawn in separately using geom_vline
.
library(ggplot2)
library(grid)
a <- seq(1,20)
b <- a^0.25
df <- as.data.frame(cbind(a,b))
p = ggplot(df, aes(x = a, y = b)) + geom_point() +
scale_y_continuous(expand = c(0,0)) +
scale_x_continuous(expand = c(0,0)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
p
The extreme points are clipped, but the clipping can be undone using code by baptiste.
gt <- ggplot_gtable(ggplot_build(p))
gt$layout$clip[gt$layout$name=="panel"] <- "off"
grid.draw(gt)
Or use limits
to move the boundaries of the panel.
ggplot(df, aes(x = a, y = b)) + geom_point() +
xlim(0,22) + ylim(.95, 2.1) +
scale_x_continuous(expand = c(0,0), limits = c(0,22)) +
scale_y_continuous(expand = c(0,0), limits = c(.95, 2.2)) +
theme_bw() +
opts(axis.line = theme_segment(colour = "black"),
panel.grid.major = theme_blank(),
panel.grid.minor = theme_blank(),
panel.border = theme_blank()) +
geom_vline(xintercept = 0)
Can an interface extend multiple interfaces in java?
Answer is: Yes.
According to JLS
An interface may be declared to be a direct extension of one or more other interfaces, meaning that it implicitly specifies all the member types, abstract methods, and constants of the interfaces it extends, except for any member types and constants that it may hide.
My suspect is of course actual base64 data, otherwise it looks good to me. See this fiddle where similar scheme is working. You may try specifying char set.
<div>_x000D_
<p>Taken from wikpedia</p>_x000D_
<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA_x000D_
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO_x000D_
9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot" />_x000D_
</div>
_x000D_
You can try this base64 decoder to see if your base64 data is correct or not.
You can extract all the information from the DbEntityValidationException
with the following code (you need to add the namespaces: System.Data.Entity.Validation
and System.Diagnostics
to your using
list):
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
DirectoryInfo objDir = new DirectoryInfo(direcotryPath);
DirectoryInfo [] directoryNames = objDir.GetDirectories("*.*", SearchOption.AllDirectories);
This will give you all the directories and subdirectories.
MyDataGridView.RowHeadersVisible = False; Before binding and rename each columns header and set columns width. To help my failing memory when I search, because I will search ... that's for sure ;-)
How to do it without using cURL with straight-up PHP: http://netevil.org/blog/2006/nov/http-post-from-php-without-curl
Use the php's OR (||)
logical operator for php isset()
with multiple operator
e.g
if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {
}
In some cases (as one commenter mentioned) this might be caused if you are moving the player within DOM, like append
or etc..
Use square bracket around variable name.
var objname = 'myobject';
{[objname]}.value = 'value';
To complement these other answers, the //
operator also offers significant (3x) performance benefits over /
, presuming you want integer division.
$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop
$ python -m timeit '20.5 / 2'
10,000,000 loops, best of 3: 48.4 nsec per loop
$ python -m timeit '20 / 2'
10,000,000 loops, best of 3: 43.0 nsec per loop
$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop
You are getting that error because when the param1
if statements are evaluated, param is always null due to being scoped variables without delayed expansion.
When parentheses are used, all the commands and variables within those parentheses are expanded. And at that time, param1 has no value making the if statements invalid. When using delayed expansion, the variables are only expanded when the command is actually called.
Also I recommend using if not defined
command to determine if a variable is set.
@echo off
setlocal EnableExtensions EnableDelayedExpansion
cls
title ~USB Wizard~
echo What do you want to do?
echo 1.Enable/Disable USB Storage Devices.
echo 2.Enable/Disable Writing Data onto USB Storage.
echo 3.~Yet to come~.
set "a=%globalparam1%"
goto :aCheck
:aPrompt
set /p "a=Enter Choice: "
:aCheck
if not defined a goto :aPrompt
echo %a%
IF "%a%"=="2" (
title USB WRITE LOCK
echo What do you want to do?
echo 1.Apply USB Write Protection
echo 2.Remove USB Write Protection
::param1
set "param1=%globalparam2%"
goto :param1Check
:param1Prompt
set /p "param1=Enter Choice: "
:param1Check
if not defined param1 goto :param1Prompt
echo !param1!
if "!param1!"=="1" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000001
echo USB Write is Locked!
)
if "!param1!"=="2" (
REG ADD HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\StorageDevicePolicies\ /v WriteProtect /t REG_DWORD /d 00000000
echo USB Write is Unlocked!
)
)
pause
endlocal
@unique72 answer as a simple function or line, you may need to replace Object, with the respective class type you wish to 'slice'. Two variants are given to suit various needs.
/// Extract out array from starting position onwards
public static Object[] sliceArray( Object[] inArr, int startPos ) {
return Arrays.asList(inArr).subList(startPos, inArr.length).toArray();
}
/// Extract out array from starting position to ending position
public static Object[] sliceArray( Object[] inArr, int startPos, int endPos ) {
return Arrays.asList(inArr).subList(startPos, endPos).toArray();
}
lines = f.readlines()
reads all the lines of the file f. So it makes sense that there aren't any more line to read in the file f. If you want to read the file line by line, use readline().
You probably want to check the length of the string first and do something like this:
if (!myStr.empty())
{
char lastChar = *myStr.rbegin();
}
Teradata table or view stores NULL as "?" and SQL considers it as a character or string. This is the main reason for the error "The value violated the integrity constraints for the column." when data is ported from Teradata source to SQL destination. Solution 1: Allow the destination table to hold NULL Solution 2: Convert the '?' character to be stored as some value in the destination table.
As you said, "almost every system".
char
is probably one of the less likely to change, but once you start using uint16_t
and friends, using uint8_t
blends better, and may even be part of a coding standard.
If you already have MinGW installed in Windows 7, just simply do the following:
C:\MinGW\bin\mingw32-make.exe
file in the same folder.mingw32-make.exe
to make.exe
.Tested working in my laptop for above steps.
Important note
The following discussion assumes that we are talking about code structured as in the example above: no matter which alternative is chosen, an exception will cause the method to logically stop doing whatever it was in the middle of.
As long as you intend to do the same thing no matter which statement in the try
block throws an exception, then it's certainly better to use a single try
/catch
. For example:
function createCar()
{
try {
install_engine();
install_brakes();
} catch (Exception $e) {
die("I could not create a car");
}
}
Multiple try
/catch
blocks are useful if you can and intend to handle the failure in a manner specific to what exactly caused it.
function makeCocktail()
{
try {
pour_ingredients();
stir();
} catch (Exception $e) {
die("I could not make you a cocktail");
}
try {
put_decorative_umbrella();
} catch (Exception $e) {
echo "We 're out of umbrellas, but the drink itself is fine"
}
}
React 16+
Child Component
import React from 'react'
class ChildComponent extends React.Component
{
constructor(props){
super(props);
}
render()
{
return <div>
<button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
</div>
}
}
export default ChildComponent;
Parent Component
import React from "react";
import ChildComponent from "./childComponent";
class MasterComponent extends React.Component
{
constructor(props)
{
super(props);
this.state={
master:'master',
message:''
}
this.greetHandler=this.greetHandler.bind(this);
}
greetHandler(childName){
if(typeof(childName)=='object')
{
this.setState({
message:`this is ${this.state.master}`
});
}
else
{
this.setState({
message:`this is ${childName}`
});
}
}
render()
{
return <div>
<p> {this.state.message}</p>
<button onClick={this.greetHandler}>Click Me</button>
<ChildComponent greetChild={this.greetHandler}></ChildComponent>
</div>
}
}
export default MasterComponent;
As of right now, I do not know of any. It appears the code academy folks have set their sites on Ruby on Rails. They do not rule Java out of the picture however.
With Ubuntu :
sudo apt-get install php5-json
sudo service php5-fpm restart
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.
From stack trace:
HikariPool: Timeout failure pool HikariPool-0 stats (total=20, active=20, idle=0, waiting=0) Means pool reached maximum connections limit set in configuration.
The next line: HikariPool-0 - Connection is not available, request timed out after 30000ms. Means pool waited 30000ms for free connection but your application not returned any connection meanwhile.
Mostly it is connection leak (connection is not closed after borrowing from pool), set leakDetectionThreshold to the maximum value that you expect SQL query would take to execute.
otherwise, your maximum connections 'at a time' requirement is higher than 20 !
Similar behavior exists when module attribute names begin with a single underscore (e.g. _foo).
Module attributes named as such will not be copied into an importing module when using the from*
method, e.g.:
from bar import *
However, this is a convention and not a language constraint. These are not private attributes; they can be referenced and manipulated by any importer. Some argue that because of this, Python can not implement true encapsulation.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(2, 2)
To turn off axes for all subplots, do either:
[axi.set_axis_off() for axi in ax.ravel()]
or
map(lambda axi: axi.set_axis_off(), ax.ravel())
http://www.markrafferty.com/wp-content/w3tc/min/7415c412.e68ae1.css
Line 11:
.postItem img {
height: auto;
width: 450px;
}
You can either edit your CSS, or you can listen to Mageek and use INLINE STYLING to override the CSS styling that's happening:
<img src="theSource" style="width:30px;" />
Avoid setting both width and height, as the image itself might not be scaled proportionally. But you can set the dimensions to whatever you want, as per Mageek's example.
Eclipse does not search if the "File name patterns" field is empty.
So, if you want to search some text, write within "Containing text" field
and leave
by default "File name patterns" with asterisk (*).
If you get an error 1044 (42000) when you try to run SQL commands in MySQL (which installed along XAMPP server) cmd prompt, then here's the solution:
Close your MySQL command prompt.
Open your cmd prompt (from Start menu -> run -> cmd) which will show: C:\Users\User>_
Go to MySQL.exe by Typing the following commands:
C:\Users\User>cd\
C:\>cd xampp
C:\xampp>cd mysql
C:\xxampp\mysql>cd bin
C:\xampp\mysql\bin>mysql -u root
Now try creating a new database by typing:
mysql> create database employee;
if it shows:
Query OK, 1 row affected (0.00 sec)
mysql>
Then congrats ! You are good to go...
Even with Rollin_s's tip, Dave Webb's answer didn't work for me. The text in the right TextView
was still overlapping the text in the left TextView
.
I eventually got the behavior I wanted with something like this:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<TextView
android:id="@+id/mytextview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true" />
<TextView
android:id="@+id/mytextview2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/mytextview1"
android:gravity="right"/>
</RelativeLayout>
Note that mytextview2 has "android:layout_width"
set as "match_parent"
.
Hope this helps someone!
by XML:
<EditText
android:id="@+id/search_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="@string/search"
android:imeOptions="actionSearch"
android:inputType="text" />
By Java:
editText.clearFocus();
InputMethodManager in = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
Can't you style the forms themselves? Then, style the divs accordingly.
form
{
/* styles */
}
You can always overrule inherited styles by making it important:
form
{
/* styles */ !important
}
Just another note that you can a id/string enum with the following:
class EnumyObjects{
public static BOUNCE={str:"Bounce",id:1};
public static DROP={str:"Drop",id:2};
public static FALL={str:"Fall",id:3};
}
i'd use a simple one line comparisant for these use cases
$username = trim($_POST['userName'])?:'Anonymous';
This is for the use case you are certain error logging is off so you don't get a warning that the variable isn't initialised.
this is the paranoid version:
$username = !empty(trim(isset($_POST['userName'])?$_POST['userName']:''))?$_POST['userName']:'Anonymous';
This implements a check if the $_POST
variable is set. before accessing it.
The title
attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).
As such, the mindful approach here would be to serve all users. I would add both title
and aria-label
attributes (serving different types of users and different types of usage of the web).
Here's a good article that explains aria-label
in depth
You can 'goto case label' http://www.blackwasp.co.uk/CSharpGoto.aspx
The goto statement is a simple command that unconditionally transfers the control of the program to another statement. The command is often criticised with some developers advocating its removal from all high-level programming languages because it can lead to spaghetti code. This occurs when there are so many goto statements or similar jump statements that the code becomes difficult to read and maintain. However, there are programmers who point out that the goto statement, when used carefully, provides an elegant solution to some problems...
request
module usersTimeouts
There are two main types of timeouts: connection timeouts and read timeouts. A connect timeout occurs if the timeout is hit while your client is attempting to establish a connection to a remote machine (corresponding to the
connect()
call on the socket). A read timeout occurs any time the server is too slow to send back a part of the response.
Note that connection timeouts emit an ETIMEDOUT
error, and read timeouts emit an ECONNRESET
error.
The FileUpload.AllowMultiple property in .NET 4.5 and higher will allow you the control to select multiple files.
Below 4.5 like 4.0(vs 2010) we can use jquery for multiple file upload in single control,using,2 js files: http://code.jquery.com/jquery-1.8.2.js and http://code.google.com/p/jquery-multifile-plugin/
in aspx file upload tag,add like class="multi"
<asp:FileUpload ID="FileUpload1" class="multi" runat="server" />
If you want working example go to link download sample.
We have similar situation right now and as of this answer, I am using laravel 5.6 release.
I will not use your example in the question but mine, because it's related though.
I have route like this:
Route::name('your.name.here')->get('/your/uri', 'YourController@someMethod');
Then in your controller method, make sure you include
use Illuminate\Http\Request;
and this should be above your controller, most likely a default, if generated using php artisan
, now to get variable from the url it should look like this:
public function someMethod(Request $request)
{
$foo = $request->input("start");
$bar = $request->input("limit");
// some codes here
}
Regardless of the HTTP verb, the input() method may be used to retrieve user input.
https://laravel.com/docs/5.6/requests#retrieving-input
Hope this help.
Kill the braces.
var defaults = {
backgroundcolor: '#000',
color: '#fff',
weekdays: ['sun','mon','tue','wed','thu','fri','sat']
};
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.
Swift 3 version (butt_img must be an Image Set into Assets.xcassets or Images.xcassets folder in Xcode):
btnTwo.setBackgroundImage(UIImage(named: "butt_img"), for: .normal)
btnTwo.setTitle("My title", for: .normal)
Anyway, if you want the image to be scaled to fill the button's size, you may add a UIImageView
over it and assign it your image:
let img = UIImageView()
img.frame = btnTwo.frame
img.contentMode = .scaleAspectFill
img.clipsToBounds = true
img.image = UIImage(named: "butt_img")
btnTwo.addSubview(img)
I tried the above solutions but it didn't work for me, just incase there any other person in the same shoes, this is what I did. I updated apt-get with the following command
sudo add-apt-repository ppa:ondrej/php
this i installed with php curl for the version of php that i was using, mine was
sudo apt-get install php7.1-curl
Refinement over Daniel's response:
HTTP Only Proxy configuration
gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"
HTTPS Only Proxy configuration
gradlew -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"
Both HTTP and HTTPS Proxy configuration
gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 -Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 "-Dhttp.nonProxyHosts=*.nonproxyrepos.com|localhost"
Proxy configuration with user and password
gradlew -Dhttp.proxyHost=127.0.0.1 -Dhttp.proxyPort=3128 - Dhttps.proxyHost=127.0.0.1 -Dhttps.proxyPort=3129 -Dhttps.proxyUser=user -Dhttps.proxyPassword=pass -Dhttp.proxyUser=user -Dhttp.proxyPassword=pass -Dhttp.nonProxyHosts=host1.com|host2.com
worked for me (with gradle.properties
in either homedir or project dir, build was still failing). Thanks for pointing the issue at gradle that gave this workaround. See reference doc at https://docs.gradle.org/current/userguide/build_environment.html#sec:accessing_the_web_via_a_proxy
Update
You can also put these properties into gradle-wrapper.properties
(see: https://stackoverflow.com/a/50492027/474034).
Take advantage of SORT and LIMIT as you would with pagination. If you want the ith block of rows, use OFFSET.
SELECT val FROM big_table
where val = someval
ORDER BY id DESC
LIMIT n;
In response to Nir: The sort operation is not necessarily penalized, this depends on what the query planner does. Since this use case is crucial for pagination performance, there are some optimizations (see link above). This is true in postgres as well "ORDER BY ... LIMIT can be done without sorting " E.7.1. Last bullet
explain extended select id from items where val = 48 order by id desc limit 10;
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
| 1 | SIMPLE | items | const | PRIMARY | PRIMARY | 4 | const | 1 | Using index |
+----+-------------+-------+-------+---------------+---------+---------+-------+------+-------------+
You can use dangerouslySetInnerHTML
Just send the html as a normal string
<MyComponent text="This is <strong>not</strong> working." />
And render in in the JSX code like this:
<h2 className="header-title-right wow fadeInRight"
dangerouslySetInnerHTML={{__html: props.text}} />
Just be careful if you are rendering data entered by the user. You can be victim of a XSS attack
Here's the documentation: https://facebook.github.io/react/tips/dangerously-set-inner-html.html
This occurred for me, here is how I fixed. I used Cygwin and it hanged so I tried prompting for username/password on commit :
git config --global core.askpass "git-gui--askpass"
Once I executed git push -u origin master
and entered username password, it still did hang but appeared to commit to GitHub.
Used same command from dos prompt : git push -u origin master
Git does not hang. So perhaps issue related to CygWin in my case.
This is not really an answer but maybe someone will find it useful:
When using TK GUI on Windows, and you need to call shell commands from rubyw, you will always have an annoying CMD window popping up for less then a second.
To avoid this you can use:
WIN32OLE.new('Shell.Application').ShellExecute('ipconfig > log.txt','','','open',0)
or
WIN32OLE.new('WScript.Shell').Run('ipconfig > log.txt',0,0)
Both will store the ipconfig
output inside log.txt
, but no windows will come up.
You will need to require 'win32ole'
inside your script.
system()
, exec()
and spawn()
will all pop up that annoying window when using TK and rubyw.
The answer is correct, but you don't need to declare a variable. A string can contain your character:
"This string contains omega, that looks like this: \u03A9"
Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.
Probably you haven't injected $http
service to your controller. There are several ways of doing that.
Please read this reference about DI. Then it gets very simple:
function MyController($scope, $http) {
// ... your code
}
I am running VSCommunity 2015 in Win8.1 virtual machine installed inside a Parallels 11 virtual machine installed on my Mac OSX El Capitan. To my surprise and delight it installed and ran fine. I used it for 2 weeks without signing into my Microsoft account. I tried to login 6 weeks later and got the 30 day trial screen shown above.
However for me I was able to simply click on the link above shown as "Check for an updated license" and was prompted in to log in to my Microsoft account. I did so and it granted me a license successfully and was seamless. Now under License Status it displays as "This product is licensed to: ".
I guess I got lucky as I'm guessing this is how it is supposed to work.
[sidebar]: Over the decades I've disliked most MS products but have been out of the VS IDE development tools game for awhile, and I have to say using VSComm15 has been flawless. Using it to learn C# and the IDE itself for a new contract job and it worked perfectly and has great features.
I managed to fix this issue without having to add any triple-slash reference to the TS bootstrap file, change to ES6 (which brings a bunch of issues, just as @DatBoi said) update VS2015's NodeJS
and/or NPM
bundled builds or install typings
globally.
Here's what I did in few steps:
typings
in the project's package.json
file.script
block in the package.json
file to execute/update typings
after each NPM action.typings.json
file in the project's root folder containing a reference to core-js
, which is one of the best shim/polyfill packages out there at the moment to fix ES5/ES6 issues.Here's how the package.json
file should look like (relevant lines only):
{
"version": "1.0.0",
"name": "YourProject",
"private": true,
"dependencies": {
...
"typings": "^1.3.2",
...
},
"devDependencies": {
...
},
"scripts": {
"postinstall": "typings install"
}
}
And here's the typings.json
file:
{
"globalDependencies": {
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320"
}
}
(Jasmine
and Node
are not required, but I suggest to keep them in case you'll need to in the future).
This fix is working fine with Angular2 RC1 to RC4, which is what I needed, but I think it will also fix similar issues with other ES6-enabled library packages as well.
AFAIK, I think this is the cleanest possible way of fixing it without messing up the VS2015 default settings.
For more info and a detailed analysis of the issue, I also suggest to read this post on my blog.
Using TripleDESCryptoServiceProvider in System.Security.Cryptography :
public static class CryptoHelper
{
private const string Key = "MyHashString";
private static TripleDESCryptoServiceProvider GetCryproProvider()
{
var md5 = new MD5CryptoServiceProvider();
var key = md5.ComputeHash(Encoding.UTF8.GetBytes(Key));
return new TripleDESCryptoServiceProvider() { Key = key, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 };
}
public static string Encrypt(string plainString)
{
var data = Encoding.UTF8.GetBytes(plainString);
var tripleDes = GetCryproProvider();
var transform = tripleDes.CreateEncryptor();
var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);
return Convert.ToBase64String(resultsByteArray);
}
public static string Decrypt(string encryptedString)
{
var data = Convert.FromBase64String(encryptedString);
var tripleDes = GetCryproProvider();
var transform = tripleDes.CreateDecryptor();
var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length);
return Encoding.UTF8.GetString(resultsByteArray);
}
}
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
try something like this:
a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];
this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).
basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.
I noticed that when using the Apache http client configuration with a pooling manager, the accepted answer doesn't work.
In this case it appears that the ClientConfig.sslContext
and ClientConfig.hostnameVerifier
setters are silently ignored. So if you are using connection pooling with the apache client http client config, you should be able to use the following code to get ssl verification to be ignored:
ClientConfig clientConfig = new ClientConfig();
// ... configure your clientConfig
SSLContext sslContext = null;
try {
sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[] {
new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public void checkServerTrusted(X509Certificate[] x509Certificates, String s) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
}
}, null);
} catch (NoSuchAlgorithmException e) {
//logger.debug("Ignoring 'NoSuchAlgorithmException' while ignoring ssl certificate validation.");
} catch (KeyManagementException e) {
//logger.debug("Ignoring 'KeyManagementException' while ignoring ssl certificate validation.");
}
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", new SSLConnectionSocketFactory(sslContext, new AbstractVerifier() {
@Override
public void verify(String host, String[] cns, String[] subjectAlts) {
}
}))
.build();
connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
clientConfig.property(ApacheClientProperties.CONNECTION_MANAGER, connectionManager);
return ClientBuilder.newClient(clientConfig);
This should work:
ax1.plot(xtr, color='r', label='HHZ 1')
ax1.legend(loc="upper right")
ax2.plot(xtr, color='r', label='HHN')
ax2.legend(loc="upper right")
ax3.plot(xtr, color='r', label='HHE')
ax3.legend(loc="upper right")
For Ex: IF you have a table with two columns one is ID and second is number and wants to find out the cumulative sum.
SELECT ID,Number,SUM(Number)OVER(ORDER BY ID) FROM T
In read.table
(and its relatives) it is the na.strings
argument which specifies which strings are to be interpreted as missing values NA
. The default value is na.strings = "NA"
If missing values in an otherwise numeric variable column are coded as something else than "NA
", e.g. ".
" or "N/A
", these rows will be interpreted as character
, and then the whole column is converted to character
.
Thus, if your missing values are some else than "NA
", you need to specify them in na.strings
.
What I have observed is: if you use openssl to generate certificates, it captures both the text part and the base64 certificate part in the crt file. The strict pem format says (wiki definition) that the file should start and end with BEGIN and END.
.pem – (Privacy Enhanced Mail) Base64 encoded DER certificate, enclosed between "-----BEGIN CERTIFICATE-----" and "-----END CERTIFICATE-----"
So for some libraries (I encountered this in java) that expect strict pem format, the generated crt would fail the validation as an 'invalid pem format'.
Even if you copy or grep the lines with BEGIN/END CERTIFICATE, and paste it in a cert.pem file, it should work.
Here is what I do, not very clean, but works for me, basically it filters the text starting from BEGIN line:
grep -A 1000 BEGIN cert.crt > cert.pem
If you are not using GitBash - you need to start your ssh-agent using this command
start-ssh-agent.cmd
This is brutally buried in the comments and hard to find. This should be accepted answer.
If your ssh agent is not set up, you can open PowerShell as admin and set it to manual mode
Get-Service -Name ssh-agent | Set-Service -StartupType Manual
if(strcmp(sr1,str2)) // this returns 0 if strings r equal
flag=0;
else flag=1; // then last check the variable flag value and print the message
OR
char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);
for(int i=0;str1[i]!='\0';i++)
{
if(str[i]==str2[i])
flag=0;
else {flag=1; break;}
}
//check the value of flag if it is 0 then strings r equal simple :)
Its very simple to install Mongo DB on windows 7 ( i used 32 bit win7 OS)
2.u can install Mongodb from thius website ( acc to ur OS) http://www.mongodb.org/downloads?_ga=1.79549524.1754732149.1410784175
4.copy the mongodb folder from c:programfiles to d: [optional]
5.After installation open command prompt ( as administrator .. right click on cmd and u will find the option)
navigate to D:\MongoDB 2.6 Standard\bin
run mongo.exe ... you might get this error
If you get then no isse you just need to do following steps
i) try the coomand in following image yo will get to know the error
ii)This means that u neeed to create a directory \data\db
iii) now you have two options either create above directory in c drive or create any "xyz" name directory somewhere else ( doesnot make and diffrence) .. lets create a directory of mongodata in d:
colured in orange will be the command u need to run .. it will open the new command propmt which we known as mongo shell (or mongodb shell)
11.dont close the shell[any of command promt as well] as in this we will create /delete/insert our databse operations
a) show databases b) show current databse c) creation of collection / inserting data into it (name will be test) d) show data of collection
12.please find scrren shot of results of our operation .. please not :- dont close any command propmt
a diffrent structure type of number is object id :- which is created automatically
Hope you get some important info for installing mongodb DB.
What you can do is to hide the ReCaptcha Control behind a div. Then make your styling on this div. And set the css "pointer-events: none" on it, so you can click through the div (Click through a DIV to underlying elements).
The checkbox should be in a place where the user is clicking.
I guess these days you would do:
import subprocess
subprocess.run(["pwd"], cwd="sub-dir")
AngularJS Developer Guide - CSS classes used by AngularJS
- @property {boolean} $untouched True if control has not lost focus yet.
- @property {boolean} $touched True if control has lost focus.
- @property {boolean} $pristine True if user has not interacted with the control yet.
- @property {boolean} $dirty True if user has already interacted with the control.
In my case i just needed to pass the whole url and encode only the value of each parameters. I didn't find a common code to do that so (!!) so i created this small method to do the job :
public static String encodeUrl(String url) throws Exception {
if (url == null || !url.contains("?")) {
return url;
}
List<String> list = new ArrayList<>();
String rootUrl = url.split("\\?")[0] + "?";
String paramsUrl = url.replace(rootUrl, "");
List<String> paramsUrlList = Arrays.asList(paramsUrl.split("&"));
for (String param : paramsUrlList) {
if (param.contains("=")) {
String key = param.split("=")[0];
String value = param.replace(key + "=", "");
list.add(key + "=" + URLEncoder.encode(value, "UTF-8"));
}
else {
list.add(param);
}
}
return rootUrl + StringUtils.join(list, "&");
}
public static String decodeUrl(String url) throws Exception {
return URLDecoder.decode(url, "UTF-8");
}
It uses org.apache.commons.lang3.StringUtils
Normal answer for this question if you really want to get something like content//media/external/video/media/18576
(e.g. for your video mp4 absolute path) and not just file///storage/emulated/0/DCIM/Camera/20141219_133139.mp4
:
MediaScannerConnection.scanFile(this,
new String[] { file.getAbsolutePath() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
Log.i("onScanCompleted", uri.getPath());
}
});
Accepted answer is wrong (cause it will not return content//media/external/video/media/*
)
Uri.fromFile(file).toString()
only returns something like file///storage/emulated/0/*
which is a simple absolute path of a file on the sdcard but with file//
prefix (scheme)
You can also get content
uri using MediaStore
database of Android
TEST (what returns Uri.fromFile
and what returns MediaScannerConnection
):
File videoFile = new File("/storage/emulated/0/video.mp4");
Log.i(TAG, Uri.fromFile(videoFile).toString());
MediaScannerConnection.scanFile(this, new String[] { videoFile.getAbsolutePath() }, null,
(path, uri) -> Log.i(TAG, uri.toString()));
Output:
I/Test: file:///storage/emulated/0/video.mp4
I/Test: content://media/external/video/media/268927
Use some design patterns, you can mix UIWebView and WKWebView. The key point is to design a unique browser interface. But you should pay more attention to your app's current functionality, for example: if your app using NSURLProtocol to enhance network ability, using WKWebView you have no chance to do the same thing. Because NSURLProtocol only effects the current process, and WKWebView using muliti-process architecture, the networking staff is in a seperate process.
Here is my solution:
arr = []
arr.append([1,2,3])
arr.append([4,5,6])
np_arr = np.array(arr)
Add attributed text color in swift code.
Swift 4:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
label.attributedText = attributedString
for Swift 3:
let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];
let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
label.attributedText = attributedString
I think you must firstly add a .wav file to Resources. For example you have sound file named Sound.wav. After you added the Sound.wav file to Resources, you can use this code:
System.Media.SoundPlayer player = new System.Media.SoundPlayer(Properties.Resources.Sound);
player.Play();
This is another way to play sound.
Your fns is a cellstr array. You need to index in to it with {} instead of () to get the single string out as char.
fns{i}
teststruct.(fns{i})
Indexing in to it with () returns a 1-long cellstr array, which isn't the same format as the char array that the ".(name)" dynamic field reference wants. The formatting, especially in the display output, can be confusing. To see the difference, try this.
name_as_char = 'a'
name_as_cellstr = {'a'}
If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.
Here's one way:
CString str;
str.Format("%d", 5);
In your case, try _T("%d")
or L"%d"
rather than "%d"
Swift 4.2 and Xcode 10 Initialize label before viewDidLoad.
lazy var topLeftLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "TopLeft"
return label
}()
In viewDidLoad add label to the view and apply constraints.
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(topLeftLabel)
topLeftLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 10).isActive = true
topLeftLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 10).isActive = true
}
After your DataBind()
:
lstDepartment.SelectedIndex = 0; //first item
or
lstDepartment.SelectedValue = "Yourvalue"
or
//add error checking, just an example, FindByValue may return null
lstDepartment.Items.FindByValue("Yourvalue").Selected = true;
or
//add error checking, just an example, FindByText may return null
lstDepartment.Items.FindByText("Yourvalue").Selected = true;
The problem is the import of ProjectsListComponent
in your ProjectsModule
. You should not import that, but add it to the export array, if you want to use it outside of your ProjectsModule
.
Other issues are your project routes. You should add these to an exportable variable, otherwise it's not AOT compatible. And you should -never- import the BrowserModule
anywhere else but in your AppModule
. Use the CommonModule
to get access to the *ngIf, *ngFor...etc
directives:
@NgModule({
declarations: [
ProjectsListComponent
],
imports: [
CommonModule,
RouterModule.forChild(ProjectRoutes)
],
exports: [
ProjectsListComponent
]
})
export class ProjectsModule {}
project.routes.ts
export const ProjectRoutes: Routes = [
{ path: 'projects', component: ProjectsListComponent }
]
CSS:
#block_container
{
text-align:center;
}
#bloc1, #bloc2
{
display:inline;
}
HTML
<div id="block_container">
<div id="bloc1"><?php echo " version ".$version." Copyright © All Rights Reserved."; ?></div>
<div id="bloc2"><img src="..."></div>
</div>
Also, you shouldn't put raw content into <div>
's, use an appropriate tag such as <p>
or <span>
.
Edit: Here is a jsFiddle demo.
Considering this still shows up when we search for EF in .NET Core, I'll post my answer here (Since it has haunted me a lot). Note that there are some subtleties with the EF 6 .NET version (No initial command, and you will need to delete "Snapshot" files)
(Tested in .NET Core 2.1)
Here are the steps:
_efmigrationhistory
table.ApplicationDbContextSnapshot.cs
, and delete them.Add-Migration InitialMigration
Please note: You must delete ALL the Snapshot files. I spent countless hours just deleting the database... This will generate an empty migration if you don't do it.
Also, in #3 you can just name your migration however you want.
Here are some additional resources: asp.net CORE Migrations generated empty
To escape '
you simly need to put another before: ''
As the second answer shows it's possible to escape single quote like this:
select 'it''s escaped'
result will be
it's escaped
If you're concatenating SQL into a VARCHAR to execute (i.e. dynamic SQL), then I'd recommend parameterising the SQL. This has the benefit of helping guard against SQL injection plus means you don't have to worry about escaping quotes like this (which you do by doubling up the quotes).
e.g. instead of doing
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = ''AAA'''
EXECUTE(@SQL)
try this:
DECLARE @SQL NVARCHAR(1000)
SET @SQL = 'SELECT * FROM MyTable WHERE Field1 = @Field1'
EXECUTE sp_executesql @SQL, N'@Field1 VARCHAR(10)', 'AAA'
If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years
" demo , and hit view source:
$("#restricting").datepicker({
yearRange: "-20:+0", // this is the option you're looking for
showOn: "both",
buttonImage: "templates/images/calendar.gif",
buttonImageOnly: true
});
You'll want to do the same (obviously changing -20
to -100
or something).
Update:
These articles in my blog describe the differences between the methods in more detail:
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: SQL Server
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: PostgreSQL
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: Oracle
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: MySQL
There are three ways to do such a query:
LEFT JOIN / IS NULL
:
SELECT *
FROM common
LEFT JOIN
table1 t1
ON t1.common_id = common.common_id
WHERE t1.common_id IS NULL
NOT EXISTS
:
SELECT *
FROM common
WHERE NOT EXISTS
(
SELECT NULL
FROM table1 t1
WHERE t1.common_id = common.common_id
)
NOT IN
:
SELECT *
FROM common
WHERE common_id NOT IN
(
SELECT common_id
FROM table1 t1
)
When table1.common_id
is not nullable, all these queries are semantically the same.
When it is nullable, NOT IN
is different, since IN
(and, therefore, NOT IN
) return NULL
when a value does not match anything in a list containing a NULL
.
This may be confusing but may become more obvious if we recall the alternate syntax for this:
common_id = ANY
(
SELECT common_id
FROM table1 t1
)
The result of this condition is a boolean product of all comparisons within the list. Of course, a single NULL
value yields the NULL
result which renders the whole result NULL
too.
We never cannot say definitely that common_id
is not equal to anything from this list, since at least one of the values is NULL
.
Suppose we have these data:
common
--
1
3
table1
--
NULL
1
2
LEFT JOIN / IS NULL
and NOT EXISTS
will return 3
, NOT IN
will return nothing (since it will always evaluate to either FALSE
or NULL
).
In MySQL
, in case on non-nullable column, LEFT JOIN / IS NULL
and NOT IN
are a little bit (several percent) more efficient than NOT EXISTS
. If the column is nullable, NOT EXISTS
is the most efficient (again, not much).
In Oracle
, all three queries yield same plans (an ANTI JOIN
).
In SQL Server
, NOT IN
/ NOT EXISTS
are more efficient, since LEFT JOIN / IS NULL
cannot be optimized to an ANTI JOIN
by its optimizer.
In PostgreSQL
, LEFT JOIN / IS NULL
and NOT EXISTS
are more efficient than NOT IN
, sine they are optimized to an Anti Join
, while NOT IN
uses hashed subplan
(or even a plain subplan
if the subquery is too large to hash)
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
The solution for me was sooo dumb!!
I was using Python 3.8 in my environment. I made a new environment using Python 3.7, and the install worked fine.
An alternative solution is to introduce a method to the file instance that would do the explicit conversion.
import types
def _write_str(self, ascii_str):
self.write(ascii_str.encode('ascii'))
source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)
And then you can use it as source_file.write_str("Hello World")
.
LTRIM(RTRIM(FCT_TYP_CD)) & ') AND (' & LTRIM(RTRIM(DEP_TYP_ID)) & ')'
I think you're missing a )
on both of the trims. Some SQL versions support just TRIM which does both L and R trims...
As mentioned in the comments to the question, the JDBC-ODBC Bridge is - as the name indicates - only a mechanism for the JDBC layer to "talk to" the ODBC layer. Even if you had a JDBC-ODBC Bridge on your Mac you would also need to have
So, for most people, using JDBC-ODBC Bridge technology to manipulate ACE/Jet ("Access") databases is really a practical option only under Windows. It is also important to note that the JDBC-ODBC Bridge will be has been removed in Java 8 (ref: here).
There are other ways of manipulating ACE/Jet databases from Java, such as UCanAccess and Jackcess. Both of these are pure Java implementations so they work on non-Windows platforms. For details on how to use UCanAccess see
Write this javascript in each page
if (self == top)
{ window.location = "Home.aspx"; }
Then it will automatically redirects to home page.
The getElementByClass
does not exists, probably you want to use getElementsByClassName
. However you can use alternative approach (used in angular/vue/react... templates)
function stop(ta) {_x000D_
console.log(ta.value) // document['player'].stopMusicExt(ta.value);_x000D_
ta.value='';_x000D_
}
_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 1'>_x000D_
<input type="button" onclick="stop(this)" class="stopMusic" value='Stop 2'>
_x000D_
An alternate solution that copies one file at a time and does not require ROBOCOPY:
@echo off
setlocal enabledelayedexpansion
set "SOURCE_DIR=C:\Source"
set "DEST_DIR=C:\Destination"
set FILENAMES_TO_COPY=data.zip info.txt
for /R "%SOURCE_DIR%" %%F IN (%FILENAMES_TO_COPY%) do (
if exist "%%F" (
set FILE_DIR=%%~dpF
set FILE_INTERMEDIATE_DIR=!FILE_DIR:%SOURCE_DIR%=!
xcopy /E /I /Y "%%F" "%DEST_DIR%!FILE_INTERMEDIATE_DIR!"
)
)
The outer for statement generates any possible path combination of subdirectory in SOURCE_DIR
and name in FILENAMES_TO_COPY
. For each existing file xcopy is invoked. FILE_INTERMEDIATE_DIR
holds the file's subdirectory path within SOURCE_DIR
which needs to be created in DEST_DIR
.
The problems were:
The solution based on omerkirk's answer involves:
autoOpen: false, width: "auto", height: "auto"
Here is a rough outline of code:
<div class="thumb">
<a href="http://jsfiddle.net/yBNVr/show/" data-title="Std 4:3 ratio video" data-width="512" data-height="384"><img src="http://dummyimage.com/120x90/000/f00&text=Std+4-3+ratio+video" /></a></li>
<a href="http://jsfiddle.net/yBNVr/1/show/" data-title="HD 16:9 ratio video" data-width="512" data-height="288"><img src="http://dummyimage.com/120x90/000/f00&text=HD+16-9+ratio+video" /></a></li>
</div>
$(function () {
var iframe = $('<iframe frameborder="0" marginwidth="0" marginheight="0" allowfullscreen></iframe>');
var dialog = $("<div></div>").append(iframe).appendTo("body").dialog({
autoOpen: false,
modal: true,
resizable: false,
width: "auto",
height: "auto",
close: function () {
iframe.attr("src", "");
}
});
$(".thumb a").on("click", function (e) {
e.preventDefault();
var src = $(this).attr("href");
var title = $(this).attr("data-title");
var width = $(this).attr("data-width");
var height = $(this).attr("data-height");
iframe.attr({
width: +width,
height: +height,
src: src
});
dialog.dialog("option", "title", title).dialog("open");
});
});
Demo here and code here. And another example along similar lines
an array does not contain index when elements are associative. An array in php can contain mixed values like this:
$var = array("apple", "banana", "foo" => "grape", "carrot", "bar" => "donkey");
print_r($var);
Gives you:
Array
(
[0] => apple
[1] => banana
[foo] => grape
[2] => carrot
[bar] => donkey
)
What are you trying to achieve since you need the index value in an associative array?
Right click on the stored procedure and select Script Stored Procedure as | CREATE To | New Query Editor Window / Clipboard / File.
You can also do Modify when you right click on the stored procedure.
For multiple procedures at once, click on the Stored Procedures folder, hit F7 to open the Object Explorer Details pane, hold Ctrl and click to select all the ones that you want, and then right click and select Script Stored Procedure as | CREATE To.
I had the same problem using regex with bash scripting. I used a 2-step solution using pipes with grep -o applying
'\[(.*?)\]'
first, then
'\b.*\b'
Obviously not as efficient at the other answers, but an alternative.
Look into twitter cards.
The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook
sharing.
Example:
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">
Save a snapshot of the database into a dump.rdb by either running BGSAVE
or SAVE
from the command line. This will create a file named dump.rdb in the same folder as your redis server. See a list of all server commands.
Copy this dump.rdb to the other redis server you want to migrate to. When redis starts up, it looks for this file to initialize the database from.
--save-dev
is used to save the package for development purpose.
Example: unit tests, minification.. --save
is used to save the
package required for the application to run.items[node.ind] = items[node.ind]._replace(v=node.v)
(Note: Don't be discouraged to use this solution because of the leading underscore in the function _replace. Specifically for namedtuple some functions have leading underscore which is not for indicating they are meant to be "private")
Seriously, question exists five years and no nice facade?
function is_dir(path) {
try {
var stat = fs.lstatSync(path);
return stat.isDirectory();
} catch (e) {
// lstatSync throws an error if path doesn't exist
return false;
}
}
Here's one way to do it. It handles negative numbers as well as an added bonus.
const numbers = [1, 2, 3];
const moveElement = (array, from, to) => {
const copy = [...array];
const valueToMove = copy.splice(from, 1)[0];
copy.splice(to, 0, valueToMove);
return copy;
};
console.log(moveElement(numbers, 0, 2))
// > [2, 3, 1]
console.log(moveElement(numbers, -1, -3))
// > [3, 1, 2]
It involves editing the registry, but service information can be found in HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services
. Find the service you want to redirect, locate the ImagePath
subkey and change that value.
I used to get the same problem, but solved it by pointing to the right jre used for the project.
Right click on the project properties java builpath see the jre selected edit it select alternate jre installed jre select the right one ok After changing right click on project>maven>update project
Hope it helps. Attaching screen shot.
Your query is doing 7 * 8
x(4) = 4+3 = 7
and y(4) = 4*2 = 8
what happens is when function x is called it creates function y, it does not run it.
$percentage = 50;
$totalWidth = 350;
$new_width = ($percentage / 100) * $totalWidth;
Extended - to provide more details based on some comments
The error
Error TS2306: File 'test.ts' is not a module.
Comes from the fact described here http://exploringjs.com/es6/ch_modules.html
17. Modules
This chapter explains how the built-in modules work in ECMAScript 6.
17.1 OverviewIn ECMAScript 6, modules are stored in files. There is exactly one module per file and one file per module. You have two ways of exporting things from a module. These two ways can be mixed, but it is usually better to use them separately.
17.1.1 Multiple named exports
There can be multiple named exports:
//------ lib.js ------ export const sqrt = Math.sqrt; export function square(x) { return x * x; } export function diag(x, y) { return sqrt(square(x) + square(y)); } ...
17.1.2 Single default export
There can be a single default export. For example, a function:
//------ myFunc.js ------ export default function () { ··· } // no semicolon!
Based on the above we need the export
, as a part of the test.js file. Let's adjust the content of it like this:
// test.js - exporting es6
export module App {
export class SomeClass {
getName(): string {
return 'name';
}
}
export class OtherClass {
getName(): string {
return 'name';
}
}
}
And now we can import it with these thre ways:
import * as app1 from "./test";
import app2 = require("./test");
import {App} from "./test";
And we can consume imported stuff like this:
var a1: app1.App.SomeClass = new app1.App.SomeClass();
var a2: app1.App.OtherClass = new app1.App.OtherClass();
var b1: app2.App.SomeClass = new app2.App.SomeClass();
var b2: app2.App.OtherClass = new app2.App.OtherClass();
var c1: App.SomeClass = new App.SomeClass();
var c2: App.OtherClass = new App.OtherClass();
and call the method to see it in action:
console.log(a1.getName())
console.log(a2.getName())
console.log(b1.getName())
console.log(b2.getName())
console.log(c1.getName())
console.log(c2.getName())
Original part is trying to help to reduce the amount of complexity in usage of the namespace
I would really strongly suggest to check this Q & A:
Let me cite the first sentence:
Do not use "namespaces" in external modules.
Don't do this.
Seriously. Stop.
...
In this case, we just do not need module
inside of test.ts
. This could be the content of it adjusted test.ts
:
export class SomeClass
{
getName(): string
{
return 'name';
}
}
Read more here
In the previous example, when we consumed each validator, each module only exported one value. In cases like this, it's cumbersome to work with these symbols through their qualified name when a single identifier would do just as well.
The
export =
syntax specifies a single object that is exported from the module. This can be a class, interface, module, function, or enum. When imported, the exported symbol is consumed directly and is not qualified by any name.
we can later consume it like this:
import App = require('./test');
var sc: App.SomeClass = new App.SomeClass();
sc.getName();
Read more here:
In some cases, you may want to only load a module under some conditions. In TypeScript, we can use the pattern shown below to implement this and other advanced loading scenarios to directly invoke the module loaders without losing type safety.
The compiler detects whether each module is used in the emitted JavaScript. For modules that are only used as part of the type system, no require calls are emitted. This culling of unused references is a good performance optimization, and also allows for optional loading of those modules.
The core idea of the pattern is that the import id = require('...') statement gives us access to the types exposed by the external module. The module loader is invoked (through require) dynamically, as shown in the if blocks below. This leverages the reference-culling optimization so that the module is only loaded when needed. For this pattern to work, it's important that the symbol defined via import is only used in type positions (i.e. never in a position that would be emitted into the JavaScript).
The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).
There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.
See this wikipedia article on Matrix Multiplication for more information.
Make sure you have MainActivity
and .ScanActivity
into your AndroidManifest.xml
file:
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ScanActivity">
</activity>
The mipmap folders are for placing your app/launcher icons (which are shown on the homescreen) in only. Any other drawable assets you use should be placed in the relevant drawable folders as before.
According to this Google blogpost:
It’s best practice to place your app icons in mipmap- folders (not the drawable- folders) because they are used at resolutions different from the device’s current density.
When referencing the mipmap- folders ensure you are using the following reference:
android:icon="@mipmap/ic_launcher"
The reason they use a different density is that some launchers actually display the icons larger than they were intended. Because of this, they use the next size up.
It's either through system property
-Dorg.slf4j.simpleLogger.defaultLogLevel=debug
or simplelogger.properties
file on the classpath
see http://www.slf4j.org/api/org/slf4j/impl/SimpleLogger.html for details
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
I was getting this same H10 app crashed error in Heroku. I clicked 'restart all dynos' in the heroku interface, and problem solved.
Your approach was not too far off, but you are only checking whether long
and int
are of the same size. Theoretically, they could both be 64 bits, in which case your check would fail, assuming both to be 32 bits. Here is a check that actually checks the size of the types themselves, not their relative size:
#if ((UINT_MAX) == 0xffffffffu)
#define INT_IS32BIT
#else
#define INT_IS64BIT
#endif
#if ((ULONG_MAX) == 0xfffffffful)
#define LONG_IS32BIT
#else
#define LONG_IS64BIT
#endif
In principle, you can do this for any type for which you have a system defined macro with the maximal value.
Note, that the standard requires long long
to be at least 64 bits even on 32 bit systems.
I don't know what qualifies as best but zxing has a qr code generator for java, is actively developed, and is liberally licensed.
To get JSON quickly into Java objects (Maps) that you can then 'drill' and work with, you can use json-io (https://github.com/jdereg/json-io). This library will let you read in a JSON String, and get back a 'Map of Maps' representation.
If you have the corresponding Java classes in your JVM, you can read the JSON in and it will parse it directly into instances of the Java classes.
JsonReader.jsonToMaps(String json)
where json is the String containing the JSON to be read. The return value is a Map where the keys will contain the JSON fields, and the values will contain the associated values.
JsonReader.jsonToJava(String json)
will read the same JSON string in, and the return value will be the Java instance that was serialized into the JSON. Use this API if you have the classes in your JVM that were written by
JsonWriter.objectToJson(MyClass foo).
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
Extract From Jettison:
public static String quote(String string) {
if (string == null || string.length() == 0) {
return "\"\"";
}
char c = 0;
int i;
int len = string.length();
StringBuilder sb = new StringBuilder(len + 4);
String t;
sb.append('"');
for (i = 0; i < len; i += 1) {
c = string.charAt(i);
switch (c) {
case '\\':
case '"':
sb.append('\\');
sb.append(c);
break;
case '/':
// if (b == '<') {
sb.append('\\');
// }
sb.append(c);
break;
case '\b':
sb.append("\\b");
break;
case '\t':
sb.append("\\t");
break;
case '\n':
sb.append("\\n");
break;
case '\f':
sb.append("\\f");
break;
case '\r':
sb.append("\\r");
break;
default:
if (c < ' ') {
t = "000" + Integer.toHexString(c);
sb.append("\\u" + t.substring(t.length() - 4));
} else {
sb.append(c);
}
}
}
sb.append('"');
return sb.toString();
}
The problem is that there is no app installed to handle opening the PDF. You should use the Intent Chooser, like so:
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() +"/"+ filename);
Intent target = new Intent(Intent.ACTION_VIEW);
target.setDataAndType(Uri.fromFile(file),"application/pdf");
target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Intent intent = Intent.createChooser(target, "Open File");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries
You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx
Answer is Objective C
if (player.timeControlStatus == AVPlayerTimeControlStatusPlaying) {
//player is playing
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusPaused) {
//player is pause
}
else if (player.timeControlStatus == AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate) {
//player is waiting to play
}
How about print (x, y)
at once.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54
plt.plot(A,B)
for xy in zip(A, B): # <--
ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--
plt.grid()
plt.show()
I'm writing slider ui control to provide drag feature, this is my way to prevent content from selecting when user is dragging:
function disableSelect(event) {
event.preventDefault();
}
function startDrag(event) {
window.addEventListener('mouseup', onDragEnd);
window.addEventListener('selectstart', disableSelect);
// ... my other code
}
function onDragEnd() {
window.removeEventListener('mouseup', onDragEnd);
window.removeEventListener('selectstart', disableSelect);
// ... my other code
}
bind startDrag
on your dom:
<button onmousedown="startDrag">...</button>
If you want to statically disable text select on all element, execute the code when elements are loaded:
window.addEventListener('selectstart', function(e){ e.preventDefault(); });
I know this is a very old thread but I was looking for a solution to the same problem and I came across this before eventually finding the answer and I wanted to just post it here so somebody else in my shoes would have a shorter trek across the internet.
****Note that you probably have to run cmd.exe as an administrator for this to work**
So here we go, open up the prompt (as an adminstrator) and go to your System32 directory. Then run
C:\Windows\System32>cd ras
Now you'll be in the ras directory. Now it's time to create a temporary file with our connection info that we will then append onto the rasphone.pbk file that will allow us to use the rasdial command.
So to create our temp file run:
C:\Windows\System32\ras>copy con temp.txt
Now it will let you type the contents of the file, which should look like this:
[CONNECTION NAME]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=vpn.server.address.com
So replace CONNECTION NAME and vpn.server.address.com with the desired connection name and the vpn server address you want.
Make a new line and press Ctrl+Z to finish and save.
Now we will append this onto the rasphone.pbk file that may or may not exist depending on if you already have network connections configured or not. To do this we will run the following command:
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
This will append the contents of temp.txt to the end of rasphone.pbk, or if rasphone.pbk doesn't exist it will be created. Now we might as well delete our temp file:
C:\Windows\System32\ras>del temp.txt
Now we can connect to our newly configured VPN server with the following command:
C:\Windows\System32\ras>rasdial "CONNECTION NAME" myUsername myPassword
When we want to disconnect we can run:
C:\Windows\System32\ras>rasdial /DISCONNECT
That should cover it! I've included a direct copy and past from the command line of me setting up a connection for and connecting to a canadian vpn server with this method:
Microsoft Windows [Version 6.2.9200]
(c) 2012 Microsoft Corporation. All rights reserved.
C:\Windows\system32>cd ras
C:\Windows\System32\ras>copy con temp.txt
[Canada VPN Connection]
MEDIA=rastapi
Port=VPN2-0
Device=WAN Miniport (IKEv2)
DEVICE=vpn
PhoneNumber=ca.justfreevpn.com
^Z
1 file(s) copied.
C:\Windows\System32\ras>type temp.txt >> rasphone.pbk
C:\Windows\System32\ras>del temp.txt
C:\Windows\System32\ras>rasdial "Canada VPN Connection" justfreevpn 2932
Connecting to Canada VPN Connection...
Verifying username and password...
Connecting to Canada VPN Connection...
Connecting to Canada VPN Connection...
Verifying username and password...
Registering your computer on the network...
Successfully connected to Canada VPN Connection.
Command completed successfully.
C:\Windows\System32\ras>rasdial /DISCONNECT
Command completed successfully.
C:\Windows\System32\ras>
Hope this helps.
I was checking how ax.axvline does work, and I've written a small function that resembles part of its idea:
import matplotlib.pyplot as plt
import matplotlib.lines as mlines
def newline(p1, p2):
ax = plt.gca()
xmin, xmax = ax.get_xbound()
if(p2[0] == p1[0]):
xmin = xmax = p1[0]
ymin, ymax = ax.get_ybound()
else:
ymax = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmax-p1[0])
ymin = p1[1]+(p2[1]-p1[1])/(p2[0]-p1[0])*(xmin-p1[0])
l = mlines.Line2D([xmin,xmax], [ymin,ymax])
ax.add_line(l)
return l
So, if you run the following code you will realize how does it work. The line will span the full range of your plot (independently on how big it is), and the creation of the line doesn't rely on any data point within the axis, but only in two fixed points that you need to specify.
import numpy as np
x = np.linspace(0,10)
y = x**2
p1 = [1,20]
p2 = [6,70]
plt.plot(x, y)
newline(p1,p2)
plt.show()
The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.
grep -q "something" file
[[ !? -eq 0 ]] && echo "yes" || echo "no"
The problem in my case was that I was running the command inside a python virtual environment and it didn't had the path to /usr/local/mysql/bin though I have put it in the .bash_profile file. Just exporting the path in the virtual env worked for me.
For your info sql_config resides inside bin directory.
As said in previous answers the 'normal' way is to add it to a JScrollPane, but sometimes you don't want it to scroll (don't ask me when:)). Then you can add the TableHeader yourself. Like this:
JPanel tablePanel = new JPanel(new BorderLayout());
JTable table = new JTable();
tablePanel.add(table, BorderLayout.CENTER);
tablePanel.add(table.getTableHeader(), BorderLayout.NORTH);
As mentioned, the difference is primarily the size of the underlying variables, which in each case get larger to allow more characters to be represented.
However, fonts, encoding and things are wickedly complicated (unnecessarily?), so a big link is needed to fill in more detail:
http://www.cs.tut.fi/~jkorpela/chars.html#ascii
Don't expect to understand it all, but if you don't want to have problems later it's worth learning as much as you can, as early as you can (or just getting someone else to sort it out for you).
Paul.
Use the -p flag and add /udp
suffix to the port number.
-p 53160:53160/udp
Full command
sudo docker run -p 53160:53160 \
-p 53160:53160/udp -p 58846:58846 \
-p 8112:8112 -t -i aostanin/deluge /start.sh
If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.
You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile
(EXPOSE does not publish the port):
EXPOSE 8285/udp
Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)
Maybe you could add a static class with your custom namespace and the same class name:
using CLRConsole = System.Console;
namespace ExtensionMethodsDemo
{
public static class Console
{
public static void WriteLine(string value)
{
CLRConsole.WriteLine(value);
}
public static void WriteBlueLine(string value)
{
System.ConsoleColor currentColor = CLRConsole.ForegroundColor;
CLRConsole.ForegroundColor = System.ConsoleColor.Blue;
CLRConsole.WriteLine(value);
CLRConsole.ForegroundColor = currentColor;
}
public static System.ConsoleKeyInfo ReadKey(bool intercept)
{
return CLRConsole.ReadKey(intercept);
}
}
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteBlueLine("This text is blue");
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(ex.StackTrace);
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
}
}
}
To disable the warning while connecting to a database in Java, use the below concept -
autoReconnect=true&useSSL=false
Just need to change connectionURL like :
String connectionURL = jdbc:mysql://localhost:3306/Peoples?autoReconnect=true&useSSL=false
This will disable SSL and also suppress the SSL errors.
I had a similar solution like @maximilianus. The difference was that my .repositories files were called _remote.repositores and I had to delete them to make it work.
For eg in my case I deleted
After doing so my errors disappeared.
You're taking name
in document.getElementById()
Your cb
should be txt206451
(ID Attribute) not name
attribute.
Or
You can have it by document.getElementsByName()
var cb = document.getElementsByName('field206451')[0]; // First one
OR
var cb = document.getElementById('txt206451');
And for setting values into hidden use document.getElementsByName()
like following
var cb = document.getElementById('txt206451');
var label = document.getElementsByName('label206451')[0]; // Get the first one of index
console.log(label);
cb.addEventListener('change', function (evt) { // use change here. not neccessarily
if (this.checked) {
label.value = 'Thanks'
} else {
label.value = '0'
}
}, false);
As long as you override equals()
on each key and value contained in the map, then m1.equals(m2)
should be reliable to check for maps equality.
The same result can be obtained also by comparing toString()
of each map as you suggested, but using equals()
is a more intuitive approach.
May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals()
. More details about this see here.