SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'
RESULT: 0.97 %
You start by writing a class that derives from Attribute:
public class MyCustomAttribute: Attribute
{
public string SomeProperty { get; set; }
}
Then you could decorate anything (class, method, property, ...) with this attribute:
[MyCustomAttribute(SomeProperty = "foo bar")]
public class Foo
{
}
and finally you would use reflection to fetch it:
var customAttributes = (MyCustomAttribute[])typeof(Foo).GetCustomAttributes(typeof(MyCustomAttribute), true);
if (customAttributes.Length > 0)
{
var myAttribute = customAttributes[0];
string value = myAttribute.SomeProperty;
// TODO: Do something with the value
}
You could limit the target types to which this custom attribute could be applied using the AttributeUsage attribute:
/// <summary>
/// This attribute can only be applied to classes
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public class MyCustomAttribute : Attribute
Important things to know about attributes:
You can't serialize a collection of objects without specifying the expected types. You must pass the list of expected types to the constructor of XmlSerializer
(the extraTypes
parameter) :
List<object> list = new List<object>();
list.Add(new Foo());
list.Add(new Bar());
XmlSerializer xs = new XmlSerializer(typeof(object), new Type[] {typeof(Foo), typeof(Bar)});
using (StreamWriter streamWriter = System.IO.File.CreateText(fileName))
{
xs.Serialize(streamWriter, list);
}
If all the objects of your list inherit from the same class, you can also use the XmlInclude
attribute to specify the expected types :
[XmlInclude(typeof(Foo)), XmlInclude(typeof(Bar))]
public class MyBaseClass
{
}
Use display instead of visibility. display: none for invisible and no setting for visible.
Well, the API for Integer.valueOf(String)
does indeed say that the String
is interpreted exactly as if it were given to Integer.parseInt(String)
. However, valueOf(String)
returns a new
Integer()
object whereas parseInt(String)
returns a primitive int
.
If you want to enjoy the potential caching benefits of Integer.valueOf(int)
, you could also use this eyesore:
Integer k = Integer.valueOf(Integer.parseInt("123"))
Now, if what you want is the object and not the primitive, then using valueOf(String)
may be more attractive than making a new object out of parseInt(String)
because the former is consistently present across Integer
, Long
, Double
, etc.
<span class="txt">Some Text</span>
.txt:hover {
text-decoration: underline;
}
The first thing is to understand that, the Dispatcher is not designed to run long blocking operation (such as retrieving data from a WebServer...). You can use the Dispatcher when you want to run an operation that will be executed on the UI thread (such as updating the value of a progress bar).
What you can do is to retrieve your data in a background worker and use the ReportProgress method to propagate changes in the UI thread.
If you really need to use the Dispatcher directly, it's pretty simple:
Application.Current.Dispatcher.BeginInvoke(
DispatcherPriority.Background,
new Action(() => this.progressBar.Value = 50));
Solution if you are using Ionic Capacitor, Angular Material, and need to support iOS 11.
document.activeElement.parentElement.parentElement.scrollIntoView({block: 'center', behavior: 'smooth'});
The key is to scroll to the parent of the parent which is the wrapper around the input. This wrapper includes the label for the input which is now no longer cut off.
If you only need to support iOS 14 the "block" center param actually works, so this is sufficient:
document.activeElement.scrollIntoView({block: 'center', behavior: 'smooth'});
You can reset the padding (and I think everything else) with initial
to the default.
p {
padding: initial;
}
There are method join
for string objects:
".".join(("a","b","c"))
npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.
If the --dry-run flag is used then no changes will actually be made.
If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.
In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.
If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.
npm dedupe
npm ddp
Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.
For example, consider this dependency graph:
a
+-- b <-- depends on [email protected]
| `-- [email protected]
`-- d <-- depends on c@~1.0.9
`-- [email protected]
In this case, npm-dedupe will transform the tree to:
a
+-- b
+-- d
`-- [email protected]
Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.
The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.
DataGridView.Refresh
and And DataGridView.Update
are methods that are inherited from Control. They have to do with redrawing the control which is why new rows don't appear.
My guess is the data retrieval is on the Form_Load. If you want your Button on Form B to retrieve the latest data from the database then that's what you have to do whatever Form_Load is doing.
A nice way to do that is to separate your data retrieval calls into a separate function and call it from both the From Load and Button Click events.
This is a potential enhancement to the great solution that @Kano and @Mx offered. If you want to preserve TabIndex ordering, add this sort in the middle:
// Sort by explicit Tab Index, if any
var sort_by_TabIndex = function (elementA, elementB) {
let a = elementA.tabIndex || 1;
let b = elementB.tabIndex || 1;
if (a < b) { return -1; }
if (a > b) { return 1; }
return 0;
}
focussable.sort(sort_by_TabIndex);
Postgresql have limit.
Oracle's code:
select *
from
tbl
where rownum <= 1000;
same in Postgresql's code:
select *
from
tbl
limit 1000
You should make another XML-spring configuration file in your test resource folder or just copy the old one, it looks fine, but if you're trying to start a web context for testing a micro service, just put the following code as your master test class and inherits from that:
@WebAppConfiguration
@RunWith(SpringRunner.class)
@ContextConfiguration(locations = "classpath*:spring-test-config.xml")
public abstract class AbstractRestTest {
@Autowired
private WebApplicationContext wac;
}
As far as I know, it's not possible to change the content of the buttons, at least not easily. It's fairly easy to have your own custom alert box using JQuery UI though
global $DB;
$status = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");
if($status == false)
{
die("Didn't Update");
}
If you are using mysql_query
in the backend (whatever $DB->query()
uses to query the database), it will return a TRUE
or FALSE
for INSERT
, UPDATE
, and DELETE
(and a few others), commands, based on their status.
It worth mentioning that the build time will be increased for VS 2015 users after:
Install-Package Microsoft.Net.Compilers
Those who are using VS 2015 and have to keep this package in their projects can fix increased build time.
Edit file packages\Microsoft.Net.Compilers.1.2.2\build\Microsoft.Net.Compilers.props
and clean it up. The file should look like:
<Project DefaultTargets="Build"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
</Project>
Doing so forces a project to be built as it was before adding Microsoft.Net.Compilers
package
Probably the best way to check for errors in runtime API code is to define an assert style handler function and wrapper macro like this:
#define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); }
inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) exit(code);
}
}
You can then wrap each API call with the gpuErrchk
macro, which will process the return status of the API call it wraps, for example:
gpuErrchk( cudaMalloc(&a_d, size*sizeof(int)) );
If there is an error in a call, a textual message describing the error and the file and line in your code where the error occurred will be emitted to stderr
and the application will exit. You could conceivably modify gpuAssert
to raise an exception rather than call exit()
in a more sophisticated application if it were required.
A second related question is how to check for errors in kernel launches, which can't be directly wrapped in a macro call like standard runtime API calls. For kernels, something like this:
kernel<<<1,1>>>(a);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaDeviceSynchronize() );
will firstly check for invalid launch argument, then force the host to wait until the kernel stops and checks for an execution error. The synchronisation can be eliminated if you have a subsequent blocking API call like this:
kernel<<<1,1>>>(a_d);
gpuErrchk( cudaPeekAtLastError() );
gpuErrchk( cudaMemcpy(a_h, a_d, size * sizeof(int), cudaMemcpyDeviceToHost) );
in which case the cudaMemcpy
call can return either errors which occurred during the kernel execution or those from the memory copy itself. This can be confusing for the beginner, and I would recommend using explicit synchronisation after a kernel launch during debugging to make it easier to understand where problems might be arising.
Note that when using CUDA Dynamic Parallelism, a very similar methodology can and should be applied to any usage of the CUDA runtime API in device kernels, as well as after any device kernel launches:
#include <assert.h>
#define cdpErrchk(ans) { cdpAssert((ans), __FILE__, __LINE__); }
__device__ void cdpAssert(cudaError_t code, const char *file, int line, bool abort=true)
{
if (code != cudaSuccess)
{
printf("GPU kernel assert: %s %s %d\n", cudaGetErrorString(code), file, line);
if (abort) assert(0);
}
}
Both approaches will catch all exceptions. There is no significant difference between your two code examples except that the first will generate a compiler warning because ex
is declared but not used.
But note that some exceptions are special and will be rethrown automatically.
ThreadAbortException
is a special exception that can be caught, but it will automatically be raised again at the end of the catch block.
http://msdn.microsoft.com/en-us/library/system.threading.threadabortexception.aspx
As mentioned in the comments, it is usually a very bad idea to catch and ignore all exceptions. Usually you want to do one of the following instead:
Catch and ignore a specific exception that you know is not fatal.
catch (SomeSpecificException)
{
// Ignore this exception.
}
Catch and log all exceptions.
catch (Exception e)
{
// Something unexpected went wrong.
Log(e);
// Maybe it is also necessary to terminate / restart the application.
}
Catch all exceptions, do some cleanup, then rethrow the exception.
catch
{
SomeCleanUp();
throw;
}
Note that in the last case the exception is rethrown using throw;
and not throw ex;
.
I have never used jekyll, but it's main page says that it uses Liquid, and according to their docs, I think the following should work:
<ul> {% for page in site.pages %} {% if page.title != 'index' %} <li><div class="drvce"><a href="{{ page.url }}">{{ page.title }}</a></div></li> {% endif %} {% endfor %} </ul>
ProductionWorker
extends Employee
, thus it is said that it has all the capabilities of an Employee. In order to accomplish that, Java automatically puts a super();
call in each constructor's first line, you can put it manually but usually it is not necessary. In your case, it is necessary because the call to super();
cannot be placed automatically due to the fact that Employee's constructor has parameters.
You either need to define a default constructor in your Employee
class, or call super('Erkan', 21, new Date());
in the first line of the constructor in ProductionWorker.
One way is to loop through the keys of the dictionary, which I recommend:
foreach(int key in sp.Keys)
dynamic value = sp[key];
Another way, is to loop through the dictionary as a sequence of pairs:
foreach(KeyValuePair<int, dynamic> pair in sp)
{
int key = pair.Key;
dynamic value = pair.Value;
}
I recommend the first approach, because you can have more control over the order of items retrieved if you decorate the Keys
property with proper LINQ statements, e.g., sp.Keys.OrderBy(x => x)
helps you retrieve the items in ascending order of the key. Note that Dictionary
uses a hash table data structure internally, therefore if you use the second method the order of items is not easily predictable.
Update (01 Dec 2016): replaced var
s with actual types to make the answer more clear.
If you have already installed app on your device, try to change bundle identifer on the web .plist (not app plist) with something else like "com.vistair.docunet-test2", after that refresh webpage and try to reinstall... It works for me
User interactive approach:
git clean -i -fd
Remove .classpath [y/N]? N
Remove .gitignore [y/N]? N
Remove .project [y/N]? N
Remove .settings/ [y/N]? N
Remove src/com/amazon/arsdumpgenerator/inspector/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove src/com/amazon/arsdumpgenerator/s3/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/manifest/ [y/N]? y
Remove tst/com/amazon/arsdumpgenerator/s3/ [y/N]? y
-i for interactive
-f for force
-d for directory
-x for ignored files(add if required)
Note: Add -n or --dry-run to just check what it will do.
Worth noting that to use git add --patch
for a new file you need to first add the file to index with git add --intent-to-add
:
git add -N file
git add -p file
I convert String to Date in format ("yyyy-MM-dd") to save into Mysql data base .
String date ="2016-05-01";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date parsed = format.parse(date);
java.sql.Date sql = new java.sql.Date(parsed.getTime());
sql it's my output in date format
This just worked for me on Ubuntu 16:
Download ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip') from Oracle web site and then do following script (you can do piece by piece and I did as a ROOT):
apt-get install -y python-dev build-essential libaio1
mkdir -p /opt/ora/
cd /opt/ora/
## Now put 2 ZIP files:
# ('instantclient-basic-linux.x64-12.2.0.1.0.zip' and 'instantclient-sdk-linux.x64-12.2.0.1.0.zip')
# into /opt/ora/ and unzip them -> both will be unzipped into 1 directory: /opt/ora/instantclient_12_2
rm -rf /etc/profile.d/oracle.sh
echo "export ORACLE_HOME=/opt/ora/instantclient_12_2" >> /etc/profile.d/oracle.sh
echo "export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$ORACLE_HOME" >> /etc/profile.d/oracle.sh
chmod 777 /etc/profile.d/oracle.sh
source /etc/profile.d/oracle.sh
env | grep -i ora # This will check current ENVIRONMENT settings for Oracle
rm -rf /etc/ld.so.conf.d/oracle.conf
echo "/opt/ora/instantclient_12_2" >> /etc/ld.so.conf.d/oracle.conf
ldconfig
cd $ORACLE_HOME
ls -lrth libclntsh* # This will show which version of 'libclntsh' you have... --> needed for following line:
ln -s libclntsh.so.12.1 libclntsh.so
pip install cx_Oracle # Maybe not needed but I did it anyway (only pip install cx_Oracle without above steps did not work for me...)
Your python scripts are now ready to use 'cx_Oracle'... Enjoy!
A lot of people seem to be looking for this answer. I found it buried in an answer to another question here: Syncing column width of between tables in two different frames, etc
Of the dozens of methods I have tried this is the only method I found that works reliably to allow you to have a scrolling bottom table with the header table having the same widths.
Here is how I did it, first I improved upon the jsfiddle above to create this function, which works on both td
and th
(in case that trips up others who use th
for styling of their header rows).
var setHeaderTableWidth= function (headertableid,basetableid) {
$("#"+headertableid).width($("#"+basetableid).width());
$("#"+headertableid+" tr th").each(function (i) {
$(this).width($($("#"+basetableid+" tr:first td")[i]).width());
});
$("#" + headertableid + " tr td").each(function (i) {
$(this).width($($("#" + basetableid + " tr:first td")[i]).width());
});
}
Next, you need to create two tables, NOTE the header table should have an extra TD
to leave room in the top table for the scrollbar, like this:
<table id="headertable1" class="input-cells table-striped">
<thead>
<tr style="background-color:darkgray;color:white;"><th>header1</th><th>header2</th><th>header3</th><th>header4</th><th>header5</th><th>header6</th><th></th></tr>
</thead>
</table>
<div id="resizeToBottom" style="overflow-y:scroll;overflow-x:hidden;">
<table id="basetable1" class="input-cells table-striped">
<tbody >
<tr>
<td>testdata</td>
<td>2</td>
<td>3</td>
<td>4</span></td>
<td>55555555555555</td>
<td>test</td></tr>
</tbody>
</table>
</div>
Then do something like:
setHeaderTableWidth('headertable1', 'basetable1');
$(window).resize(function () {
setHeaderTableWidth('headertable1', 'basetable1');
});
This is the only solution that I found on Stack Overflow that works out of many similar questions that have been posted, that works in all my cases.
For example, I tried the jQuery stickytables plugin which does not work with durandal, and the Google Code project here https://code.google.com/p/js-scroll-table-header/issues/detail?id=2
Other solutions involving cloning the tables, have poor performance, or suck and don't work in all cases.
There is no need for these overly complex solutions. Just make two tables like the examples below and call setHeaderTableWidth function like described here and boom, you are done.
If this does not work for you, you probably were playing with your CSS box-sizing property and you need to set it correctly. It is easy to screw up your CSS content by accident. There are many things that can go wrong, so just be aware/careful of that. This approach works for me.
For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.
How to get a max value:
$highest_weight = max(array_column($details, 'Weight'));
How to get the min value
$lowest_weight = min(array_column($details, 'Weight'));
There might two issues
1) $blogs may be a stdObject
or
2) The properties of the array might be the stdObject
Try using var_dump($blogs) and see the actual problem if the properties of array have stdObject try like this
$blog->id;
$blog->content;
$blog->title;
FWIW CloudFront supports streaming as well. Might be better than plain streaming from instances.
Insert command tree in bash.
Also, there is a DOS comnand "tree". You can displays directory paths and files in each subdirectory with command:
tree /F
JSONP is the best option, in my opinion. Try to figure out why you get the syntax error - are you sure the received data is not JSON? Then maybe you're using the API wrong somehow.
Another way you could use, but I don't think that it applies in your case, is have an iFrame in the page which src is in the domain you want to call. Have it do the calls for you, and then use JS to communicate between the iFrame and the page. This will bypass the cross domain, but only if you can have the iFrame's src in the domain you want to call.
use this code <script> $('#someid').attr('disabled,'true'); </script>
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
You should use the I/O Library where you can find all functions at the io
table and then use file:read
to get the file content.
local open = io.open
local function read_file(path)
local file = open(path, "rb") -- r read mode and b binary mode
if not file then return nil end
local content = file:read "*a" -- *a or *all reads the whole file
file:close()
return content
end
local fileContent = read_file("foo.html");
print (fileContent);
Not sure why, but in my case, the reason was because I was running Anaconda terminal instead of the CMD.
After I use CMD and update the path settings as mentioned by all comments above the issue solved on my side.
I had a similar problem and since I couldn't find a sufficient solution, I also created a serialization library for javascript: https://github.com/wavesoft/jbb (as a matter of fact it's a bit more, since it's mainly intended for bundling resources)
It is close to Binary-JSON but it adds a couple of additional features, such as metadata for the objects being encoded and some extra optimizations like data de-duplication, cross-referencing to other bundles and structure-level compression.
However there is a catch: In order to keep the bundle size small there are no type information in the bundle. Such information are provided in a separate "profile" that describes your objects for encoding and decoding. For optimization reasons this information is given in a form of script.
But you can make your life easier using the gulp-jbb-profile
(https://github.com/wavesoft/gulp-jbb-profile) utility for generating the encodeing/decoding scripts from simple YAML object specifications like this:
# The 'Person' object has the 'age' and 'isOld'
# properties
Person:
properties:
- age
- isOld
For example you can have a look on the jbb-profile-three
profile.
When you have your profile ready, you can use JBB like this:
var JBBEncoder = require('jbb/encode');
var MyEncodeProfile = require('profile/profile-encode');
// Create a new bundle
var bundle = new JBBEncoder( 'path/to/bundle.jbb' );
// Add one or more profile(s) in order for JBB
// to understand your custom objects
bundle.addProfile(MyEncodeProfile);
// Encode your object(s) - They can be any valid
// javascript object, or objects described in
// the profiles you added previously.
var p1 = new Person(77);
bundle.encode( p1, 'person' );
var people = [
new Person(45),
new Person(77),
...
];
bundle.encode( people, 'people' );
// Close the bundle when you are done
bundle.close();
And you can read it back like this:
var JBBDecoder = require('jbb/decode');
var MyDecodeProfile = require('profile/profile-decode');
// Instantiate a new binary decoder
var binaryLoader = new JBBDecoder( 'path/to/bundle' );
// Add your decoding profile
binaryLoader.addProfile( MyDecodeProfile );
// Add one or more bundles to load
binaryLoader.add( 'bundle.jbb' );
// Load and callback when ready
binaryLoader.load(function( error, database ) {
// Your objects are in the database
// and ready to use!
var people = database['people'];
});
I have search for this problem and i got the following answers:
"C:\Program Files\Apache-tomcat-7.0.69\"
remove the extra backslash (\
)Your problem will be solved
The names of the first dataframe do not match the names of the second one. Just as the error message says.
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] FALSE
If you do not care about the names of the 3rd or 4th columns of the second df, you can coerce them to be the same:
> names(xd.small[[1]]) <- names(xd.small[[2]])
> identical(names(xd.small[[1]]), names(xd.small[[2]]) )
[1] TRUE
Then things should proceed happily.
New versions of application servers removed the ability of binding to your entire network interface and limited it just to the local interface (localhost). The reason being was for security. From what I know, Tomcat and JBoss implement the same security measures.
If you want to bind it to another IP you can explicitly set it in your connector string:
address="192.168.1.100"
-b 192.168.1.100
as a command line. Just remember that binding 0.0.0.0
allows anyone access to your box to access that server. It will bind to all addresses. If that is what you want, then use 0.0.0.0, if it isn't then specify the address you would like to explicitly bind instead.
Just make sure you understand the consequences binding to all addresses (0.0.0.0)
A small work around I used many times
Promise.resolve(data).then(() => {
console.log( "! changement de la date du composant !" );
this.dateNow = new Date();
this.cdRef.detectChanges();
});
_x000D_
Thanks to both Tony and Paul for the quick feedback, its very helpful. I actually figure out a solution through POJO. Here it is:
if (cell_value.indexOf("\"") != -1 || cell_value.indexOf(",") != -1) {
cell_value = cell_value.replaceAll("\"", "\"\"");
row.append("\"");
row.append(cell_value);
row.append("\"");
} else {
row.append(cell_value);
}
in short if there is special character like comma or double quote within the string in side the cell, then first escape the double quote("\""
) by adding additional double quote (like "\"\""
), then put the whole thing into a double quote (like "\""+theWholeThing+"\""
)
Use sys.getsizeof
to get the size of an object, in bytes.
>>> from sys import getsizeof
>>> a = 42
>>> getsizeof(a)
12
>>> a = 2**1000
>>> getsizeof(a)
146
>>>
Note that the size and layout of an object is purely implementation-specific. CPython, for example, may use totally different internal data structures than IronPython. So the size of an object may vary from implementation to implementation.
The method works if you provide an array. The output of
String[] helloWorld = {"Hello", "World"};
System.out.println(helloWorld);
System.out.println(Arrays.toString(helloWorld));
is
[Ljava.lang.String;@45a877
[Hello, World]
(the number after @
is almost always different)
Please tell us the return type of Employee.getSelectCancel()
try to use an asterisk before list's name with print statement:
names = ["Sam", "Peter", "James", "Julian", "Ann"]
print(*names)
output:
Sam Peter James Julian Ann
I use Anypoint Studio (an Eclipse based IDE). In my case everything worked well, until I found out that while running the java code, something totally different is executed. Then I have deleted the .class files. After this point I got the error message from this question's title. Cleaning the project didn't solve the problem.
After restarting the IDE everything worked well again.
This method works fine both in http and https. Just one line :)
if (Uri.IsWellFormedUriString("https://www.google.com", UriKind.Absolute))
MSDN: IsWellFormedUriString
In my case, the static content was already being served:
app.use('/*', express.static(path.join(__dirname, '../pub/index.html')));
...and everything in the app seemed to rely on that in some way. (path
dep is require('path')
)
So, a) yes, it can be a file; and b) you can make a redirect!
app.get('/', function (req, res) { res.redirect('/index.html') });
Now anyone hitting /
gets /index.html
which is served statically from ../pub/index.html
.
Hope this helps someone else.
We could look at error object for a property code
that mentions the possible system error and in cases of ETIMEDOUT
where a network call fails, act accordingly.
if (err.code === 'ETIMEDOUT') {
console.log('My dish error: ', util.inspect(err, { showHidden: true, depth: 2 }));
}
Here is a version of Robert B's answer that works for List<T>
and sorting by a specified String property of the object using Reflection and no 3rd party libraries
/**
* Sorts a List by the specified String property name of the object.
*
* @param list
* @param propertyName
*/
public static <T> void sortList(List<T> list, final String propertyName) {
if (list.size() > 0) {
Collections.sort(list, new Comparator<T>() {
@Override
public int compare(final T object1, final T object2) {
String property1 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object1);
String property2 = (String)ReflectionUtils.getSpecifiedFieldValue (propertyName, object2);
return property1.compareToIgnoreCase (property2);
}
});
}
}
public static Object getSpecifiedFieldValue (String property, Object obj) {
Object result = null;
try {
Class<?> objectClass = obj.getClass();
Field objectField = getDeclaredField(property, objectClass);
if (objectField!=null) {
objectField.setAccessible(true);
result = objectField.get(obj);
}
} catch (Exception e) {
}
return result;
}
public static Field getDeclaredField(String fieldName, Class<?> type) {
Field result = null;
try {
result = type.getDeclaredField(fieldName);
} catch (Exception e) {
}
if (result == null) {
Class<?> superclass = type.getSuperclass();
if (superclass != null && !superclass.getName().equals("java.lang.Object")) {
return getDeclaredField(fieldName, type.getSuperclass());
}
}
return result;
}
See the doc : it will close all running tasks using the executable file something.exe
, more or less like linux' killall
This error occurs, due to connection limit reaches the maximum limit, defined in the configuration file my.cnf
.
In order to fix this error, login to MySQL as root
user (Note: you can login as root, since, mysql will pre-allocate additional one connection for root user
) and increase the max_connections variable by using the following command:
SET GLOBAL max_connections = 500;
This change will be there, until next server restart. In order to make this change permanent, you have to modify in your configuration file. You can do this by,
vi /etc/my.cnf
[mysqld]
max_connections = 500
This article has detailed step by step workaround to fix this error. Have a look at it, I hope it may help you. Thanks.
For API level 17 or higher, View.generateViewId()
will solve this problem. The utility method provides a unique id that is not used in build time.
public static AlertDialog showAlertDialogWithoutTitle(Context context,String msg)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
alertDialogBuilder.setMessage(msg).setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
return alertDialogBuilder.create();
}
Define the expected and desired output for a normal case, with correct input.
Now, implement the test by declaring a class, name it anything (Usually something like TestAddingModule), and add the testAdd method to it (i.e. like the one below) :
assertEquals(expectedVal,calculatedVal)
.Test your method by running it (in Eclipse, right click, select Run as ? JUnit test).
//for normal addition
@Test
public void testAdd1Plus1()
{
int x = 1 ; int y = 1;
assertEquals(2, myClass.add(x,y));
}
Add other cases as desired.
Test that your method handles Null inputs gracefully (example below).
//if you are using 0 as default for null, make sure your class works in that case.
@Test
public void testAdd1Plus1()
{
int y = 1;
assertEquals(0, myClass.add(null,y));
}
This worked for me, within an ASP.NET MVC3 site where I'd left the framework to setup unobtrusive validation etc., in case it's useful to anyone:
$("form").data("validator").settings.ignore = "";
The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.
For example:
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
As I am unable to comment, hence posting as a separate answer
To find duplicates on the basis of more than one column, mention every column name as below, and it will return you all the duplicated rows set:
df[df[['product_uid', 'product_title', 'user']].duplicated() == True]
Create a file with .gitignore & put the folder or file name which one you want to ignore.
to ignore everything below node_modules folder
echo node_modules/ > .gitignore
Rather than using booleans, why not just set the button to false when its clicked, so you do that in your actionPerformed method. Its more efficient..
if (command.equals("w"))
{
FileConverter fc = new FileConverter();
btnConvertDocuments.setEnabled(false);
}
$diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
$itemCost
and $itemQty
are returning null
or zero, check them what they come with to code from user input
also to check if it's not empty data add:
if (!empty($_POST['num1'])) {
$itemQty = $_POST['num1'];
}
and you can check this link for POST validation before using it in variable
https://www.virendrachandak.com/techtalk/php-isset-vs-empty-vs-is_null/
The Top Voted Answer is out of date. I just installed MySQL 5.7 and the service name is now MySQL57
so the new command is
net stop MySQL57
or
If you dont want to query for it just create an entity, and then delete it.
Customer customer = new Customer() { Id = 1 } ;
context.AttachTo("Customers", customer);
context.DeleteObject(customer);
context.Savechanges();
Install Java 7u21 from here: http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase7-521261.html#jdk-7u21-oth-JPR
set these variables:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home"
export PATH=$JAVA_HOME/bin:$PATH
Run your app and fun :)
(Minor update: put variable value in quote)
Only slightly related to the question, but try to wrap your head around this one. So un-intuitive:
import java.nio.file.*;
class Main {
public static void main(String[] args) {
Path p1 = Paths.get("/personal/./photos/./readme.txt");
Path p2 = Paths.get("/personal/index.html");
Path p3 = p1.relativize(p2);
System.out.println(p3); //prints ../../../../index.html !!
}
}
@Zugwait's answer is correct. req.param()
is deprecated. You should use req.params
, req.query
or req.body
.
But just to make it clearer:
req.params
will be populated with only the route values. That is, if you have a route like /users/:id
, you can access the id
either in req.params.id
or req.params['id']
.
req.query
and req.body
will be populated with all params, regardless of whether or not they are in the route. Of course, parameters in the query string will be available in req.query
and parameters in a post body will be available in req.body
.
So, answering your questions, as color
is not in the route, you should be able to get it using req.query.color
or req.query['color']
.
You can specify '-m32' or '-m64' to select the compilation mode.
When dealing with autoconf (configure) scripts, I usually set CC="gcc -m64" (or CC="gcc -m32") in the environment so that everything is compiled with the correct bittiness. At least, usually...people find endless ways to make that not quite work, but my batting average is very high (way over 95%) with it.
You may use Upsert with $setOnInsert operator.
db.Table.update({noExist: true}, {"$setOnInsert": {xxxYourDocumentxxx}}, {upsert: true})
$result = preg_replace('/ /', '%20', 'your string here');
you may also consider using
$result = urlencode($yourstring)
to escape other special characters as well
I don't know how stubhub's api works, but generally it should look like this:
s = requests.Session()
data = {"login":"my_login", "password":"my_password"}
url = "http://example.net/login"
r = s.post(url, data=data)
Now your session contains cookies provided by login form. To access cookies of this session simply use
s.cookies
Any further actions like another requests will have this cookie
It might be the JavaScript check for some valid condition.
Two things you can perform a/c to your requirements:
String barcode="0000000047166";
WebElement strLocator = driver.findElement(By.xpath("//*[@id='div-barcode']"));
strLocator.sendKeys(barcode);
You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.
public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
{
var attributes = new List<TAttribute>();
var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
if (action != null)
{
attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
attributes.AddRange(GetAttributes(action.MethodInfo));
}
return HandleRequirementAsync(context, requirement, attributes);
}
protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);
private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
{
return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
}
}
Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
public string Name { get; }
public PermissionAttribute(string name) : base("Permission")
{
Name = name;
}
}
Then create a Requirement to add to your Policy
public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
//Add any custom requirement properties if you have them
}
Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.
public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
{
foreach (var permissionAttribute in attributes)
{
if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
{
return;
}
}
context.Succeed(requirement);
}
private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
{
//Implement your custom user permission logic here
}
}
And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.
services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();
services.AddAuthorization(options =>
{
options.AddPolicy("Permission", policyBuilder =>
{
policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
});
});
Now you can simply decorate your Controllers and Actions with your custom attribute.
[Permission("AccessCustomers")]
public class CustomersController
{
[Permission("AddCustomer")]
IActionResult AddCustomer([FromBody] Customer customer)
{
//Add customer
}
}
Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens
Can be used as a one-liner too:
function repeat(str, len) {
while (str.length < len) str += str.substr(0, len-str.length);
return str;
}
Best approach to add a brand logo inside a navbar-inner
class and a container. About the <h3>
issue <h3>
has a certain padding given to it in bootstrap as @creimers told. And if you are using a bigger image, increase the height of navbar too or the logo will float outside.
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="navbar-inner"> <!--changes made here-->
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">
<img src="http://placehold.it/150x50&text=Logo" alt="">
</a>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-right">
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</div>
</div>
</div>
</nav>
You have #include "fun.cpp"
in mainfile.cpp
so compiling with:
g++ -o hw1 mainfile.cpp
will work, however if you compile by linking these together like
g++ -g -std=c++11 -Wall -pedantic -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic -c -o mainfile.o mainfile.cpp
As they mention above, adding #include "fun.hpp"
will need to be done or it won't work. However, your case with the funct()
function is slightly different than my problem.
I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.
Prepare an array (in my case it is 2d array):
// prepare a 2d array in c#
ArrayList header = new ArrayList { "Task Name", "Hours"};
ArrayList data1 = new ArrayList {"Work", 2};
ArrayList data2 = new ArrayList { "Eat", 2 };
ArrayList data3 = new ArrayList { "Sleep", 2 };
ArrayList data = new ArrayList {header, data1, data2, data3};
// convert it in json
string dataStr = JsonConvert.SerializeObject(data, Formatting.None);
// store it in viewdata/ viewbag
ViewBag.Data = new HtmlString(dataStr);
Parse it in the view.
<script>
var data = JSON.parse('@ViewBag.Data');
console.log(data);
</script>
In your case you can directly use variable name instead of ViewBag.Data.
When Object variables are initially used in a language like Java, they have absolutely no value at all - not zero, but literally no value - that is null
For instance: String s;
If you were to use s
, it would actually have a value of null
, because it holds absolute nothing.
An empty string, however, is a value - it is a string of no characters.
String s; //Inits to null
String a =""; //A blank string
Null
is essentially 'nothing' - it's the default 'value' (to use the term loosely) that Java assigns to any Object variable that was not initialized.
Null
isn't really a value - and as such, doesn't have properties. So, calling anything that is meant to return a value - such as .length()
, will invariably return an error, because 'nothing' cannot have properties.
To go into more depth, by creating s1 = "";
you are initializing an object, which can have properties, and takes up relevant space in memory. By using s2;
you are designating that variable name to be a String, but are not actually assigning any value at that point.
See ?Control
or the R Language Definition:
> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
So do_while
does not exist as a separate construct in R, but you can fake it with:
repeat( { expressions}; if (! end_cond_expr ) {break} )
If you want to see the help page you cannot type ?while
or ?repeat
at the console but rather need to use ?'repeat'
or ?'while'
. All the "control-constructs" including if
are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".
Please try the following code
Uri.fromFile(new File("/sdcard/sample.jpg"))
convert_objects is deprecated.
For pandas >= 0.17.0, use pd.to_numeric
df["2nd"] = pd.to_numeric(df["2nd"])
I faced the same basic problem: trying to combine the functionality of a textbox and a select box which are fundamentally different things in the html spec.
The good news is that selectize.js does exactly this:
Selectize is the hybrid of a textbox and box. It's jQuery-based and it's useful for tagging, contact lists, country selectors, and so on.
One approach is to combine the search strings into a regex pattern as in this answer.
I know this may be a stale issue, but I was having problems getting any of these solutions to work for me. Specifically, I found that if any changes were made to the view after it was inflated that those changes would not get incorporated into the rendered bitmap.
Here's the method which ended up working for my case. With one caveat, however. prior to calling getViewBitmap(View)
I inflated my view and asked it to layout with known dimensions. This was needed since my view layout would make it zero height/width until content was placed inside.
View view = LayoutInflater.from(context).inflate(layoutID, null);
//Do some stuff to the view, like add an ImageView, etc.
view.layout(0, 0, width, height);
Bitmap getViewBitmap(View view)
{
//Get the dimensions of the view so we can re-layout the view at its current size
//and create a bitmap of the same size
int width = view.getWidth();
int height = view.getHeight();
int measuredWidth = View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY);
int measuredHeight = View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.EXACTLY);
//Cause the view to re-layout
view.measure(measuredWidth, measuredHeight);
view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
//Create a bitmap backed Canvas to draw the view into
Bitmap b = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
//Now that the view is laid out and we have a canvas, ask the view to draw itself into the canvas
view.draw(c);
return b;
}
The "magic sauce" for me was found here: https://groups.google.com/forum/#!topic/android-developers/BxIBAOeTA1Q
Cheers,
Levi
You don't need a third party package to get this information. pypi provides simple JSON feeds for all packages under
https://pypi.org/pypi/{PKG_NAME}/json
Here's some Python code using only the standard library which gets all versions.
import json
import urllib2
from distutils.version import StrictVersion
def versions(package_name):
url = "https://pypi.org/pypi/%s/json" % (package_name,)
data = json.load(urllib2.urlopen(urllib2.Request(url)))
versions = data["releases"].keys()
versions.sort(key=StrictVersion)
return versions
print "\n".join(versions("scikit-image"))
That code prints (as of Feb 23rd, 2015):
0.7.2
0.8.0
0.8.1
0.8.2
0.9.0
0.9.1
0.9.2
0.9.3
0.10.0
0.10.1
here i show you my orignal code for automating jqueryui calender from its official site "https://jqueryui.com/resources/demos/datepicker/default.html".
copy paste the code and see it working like charm :)
vote up if you like it :) regards Avadh Goyal
public class JQueryDatePicker2 {
static int targetDay = 0, targetMonth = 0, targetYear = 0;
static int currenttDate = 0, currenttMonth = 0, currenttYear = 0;
static int jumMonthBy = 0;
static boolean increment = true;
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String dateToSet = "16/12/2016";
getCurrentDayMonth();
System.out.println(currenttDate);
System.out.println(currenttMonth);
System.out.println(currenttYear);
getTargetDayMonthYear(dateToSet);
System.out.println(targetDay);
System.out.println(targetMonth);
System.out.println(targetYear);
calculateToHowManyMonthToJump();
System.out.println(jumMonthBy);
System.out.println(increment);
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\avadh.goyal\\Desktop\\selenium-2.52.0\\web driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to(
"https://jqueryui.com/resources/demos/datepicker/default.html");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElement(By.xpath("//*[@id='datepicker']")).click();
for (int i = 0; i < jumMonthBy; i++) {
if (increment) {
driver.findElement(
By.xpath("//*[@id='ui-datepicker-div']/div/a[2]/span"))
.click();
} else {
driver.findElement(
By.xpath("//*[@id='ui-datepicker-div']/div/a[1]/span"))
.click();
}
Thread.sleep(1000);
}
driver.findElement(By.linkText(Integer.toString(targetDay))).click();
}
public static void getCurrentDayMonth() {
Calendar cal = Calendar.getInstance();
currenttDate = cal.get(Calendar.DAY_OF_MONTH);
currenttMonth = cal.get(Calendar.MONTH) + 1;
currenttYear = cal.get(Calendar.YEAR);
}
public static void getTargetDayMonthYear(String dateString) {
int firstIndex = dateString.indexOf("/");
int lastIndex = dateString.lastIndexOf("/");
String day = dateString.substring(0, firstIndex);
targetDay = Integer.parseInt(day);
String month = dateString.substring(firstIndex + 1, lastIndex);
targetMonth = Integer.parseInt(month);
String year = dateString.substring(lastIndex + 1, dateString.length());
targetYear = Integer.parseInt(year);
}
public static void calculateToHowManyMonthToJump() {
if ((targetMonth - currenttMonth) > 0) {
jumMonthBy = targetMonth - currenttMonth;
} else {
jumMonthBy = currenttMonth - targetMonth;
increment = false;
}
}
}
Using KeyGenerator
would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory
is a method that should be used for pre-existing keys.
OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec
around it.
But there are still advantages to the method you are using: the KeyGenerator
is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[]
that hold key information as they may be leaked into a swap file (this may be the case anyway though).
Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator
would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.
Finally, and in my case the most important reason, it that the KeyGenerator
method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[]
with the SecretKeySpec
then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator
can be supplied with a provider so that the key is directly generated within the secure token.
As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.
In my case I had to run php artisan optimize:clear
in order to make everything to work again.
make sure to open the command line with "run as administrator" rights in the right click before typing the entire mongod things
The orginal polarToCartesian function by wdebeaum is correct:
var angleInRadians = angleInDegrees * Math.PI / 180.0;
Reversing of start and end points by using:
var start = polarToCartesian(x, y, radius, endAngle);
var end = polarToCartesian(x, y, radius, startAngle);
Is confusing (to me) because this will reverse the sweep-flag. Using:
var start = polarToCartesian(x, y, radius, startAngle);
var end = polarToCartesian(x, y, radius, endAngle);
with the sweep-flag = "0" draws "normal" counter-clock-wise arcs, which I think is more straight forward. See https://developer.mozilla.org/en-US/docs/Web/SVG/Tutorial/Paths
Take a look at Path.Combine
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
Use the appropriate methods in Scripting.FileSystemObject. Then your code will be more portable to VBScript and VB.net. To get you started, you'll need to include:
Dim fso As Object
Set fso = VBA.CreateObject("Scripting.FileSystemObject")
Then you could use
Call fso.CopyFile(source, destination[, overwrite] )
where source and destination are the full names (including paths) of the file.
See https://docs.microsoft.com/en-us/office/vba/Language/Reference/user-interface-help/copyfile-method
you need to use ++$counter
, not $++counter
, hence the reason it isn't working..
I quickly did this for anyone else coming onto this page:
<object width="425" height="344">
<param name="movie" value="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"</param>
<param name="allowFullScreen" value="true"></param>
<param name="allowScriptAccess" value="always"></param>
<embed src="http://www.youtube.com/v/u1zgFlCw8Aw?fs=1"
type="application/x-shockwave-flash"
allowfullscreen="true"
allowscriptaccess="always"
width="425" height="344">
</embed>
</object>
For database insertion, all you need is mysql_real_escape_string
(or use parameterized queries). You generally don't want to alter data before saving it, which is what would happen if you used htmlentities
. That would lead to a garbled mess later on when you ran it through htmlentities
again to display it somewhere on a webpage.
Use htmlentities
when you are displaying the data on a webpage somewhere.
Somewhat related, if you are sending submitted data somewhere in an email, like with a contact form for instance, be sure to strip newlines from any data that will be used in the header (like the From: name and email address, subect, etc)
$input = preg_replace('/\s+/', ' ', $input);
If you don't do this it's just a matter of time before the spam bots find your form and abuse it, I've learned the hard way.
I am surprised that none of the answers mentioned the insertAdjacentHTML()
method. Check it out here. The first parameter is where you want the string appended and takes ("beforebegin", "afterbegin", "beforeend", "afterend"). In the OP's situation you would use "beforeend". The second parameter is just the html string.
Basic usage:
var d1 = document.getElementById('one');
d1.insertAdjacentHTML('beforeend', '<div id="two">two</div>');
An excellent answer given by msigman. I just want to add that in windows 10 you can find IIS Express System Tray (32 bit)
process under Visual Studio
process:
A lazy way of doing this if there are alot of tables to be deleted.
Get table using the below
Copy and paste the table names from the result set and paste it after the DROP command.
actually it's an ownership problem
try to:
ls -l /var/run/asterisk/asterisk.ctl
you will see that the file has ownership of 'root'
although you have changed the ownership with:
chown -R asterisk /var/run/asterisk
once you restart the asterisk server the ownership gets back to the 'root' again
they should be for 'asterisk:asterisk' user and group
Basem Hegazy
Another reason to use $state.params
is for non-URL based state, which (to my mind) is woefully underdocumented and very powerful.
I just discovered this while googling about how to pass state without having to expose it in the URL and answered a question elsewhere on SO.
Basically, it allows this sort of syntax:
<a ui-sref="toState(thingy)" class="list-group-item" ng-repeat="thingy in thingies">{{ thingy.referer }}</a>
Use LAST_INSERT_ID()
from your SQL query.
Or
You can also use mysql_insert_id()
to get it using PHP.
run-sequence is the most clear way (at least until Gulp 4.0 is released)
With run-sequence, your task will look like this:
var sequence = require('run-sequence');
/* ... */
gulp.task('develop', function (done) {
sequence('clean', 'coffee', done);
});
But if you (for some reason) prefer not using it, gulp.start
method will help:
gulp.task('develop', ['clean'], function (done) {
gulp.on('task_stop', function (event) {
if (event.task === 'coffee') {
done();
}
});
gulp.start('coffee');
});
Note: If you only start task without listening to result, develop
task will finish earlier than coffee
, and that may be confusing.
You may also remove event listener when not needed
gulp.task('develop', ['clean'], function (done) {
function onFinish(event) {
if (event.task === 'coffee') {
gulp.removeListener('task_stop', onFinish);
done();
}
}
gulp.on('task_stop', onFinish);
gulp.start('coffee');
});
Consider there is also task_err
event you may want to listen to.
task_stop
is triggered on successful finish, while task_err
appears when there is some error.
You may also wonder why there is no official documentation for gulp.start()
. This answer from gulp member explains the things:
gulp.start
is undocumented on purpose because it can lead to complicated build files and we don't want people using it
(source: https://github.com/gulpjs/gulp/issues/426#issuecomment-41208007)
After digging around for a while:
The shortest way to add swipes for all 4 directions is:
override func viewDidLoad() {
super.viewDidLoad()
for direction in [UISwipeGestureRecognizer.Direction.down, .up, .left, .right]{
let swipeGest = UISwipeGestureRecognizer(target: self, action: #selector(swipeAction(_:)))
swipeGest.direction = direction
self.view.addGestureRecognizer(swipeGest)
}
}
@objc func swipeAction(_ gesture: UISwipeGestureRecognizer){
switch gesture.direction {
case UISwipeGestureRecognizer.Direction.right:
print("Swiped right")
case UISwipeGestureRecognizer.Direction.down:
print("Swiped down")
case UISwipeGestureRecognizer.Direction.left:
print("Swiped left")
case UISwipeGestureRecognizer.Direction.up:
print("Swiped up")
default: break
}
I use a classical javascript to set value to hidden input
$scope.SetPersonValue = function (PersonValue)
{
document.getElementById('TypeOfPerson').value = PersonValue;
if (PersonValue != 'person')
{
document.getElementById('Discount').checked = false;
$scope.isCollapsed = true;
}
else
{
$scope.isCollapsed = false;
}
}
Actually, the internal behavior is translating the anonymous object to a dictionary. So what I do in these scenarios is go for a dictionary:
@{
var htmlAttributes = new Dictionary<string, object>
{
{ "class" , "form-control"},
{ "placeholder", "Why?" }
};
if (Model.IsDisabled)
{
htmlAttributes.Add("disabled", "disabled");
}
}
@Html.EditorFor(m => m.Description, new { htmlAttributes = htmlAttributes })
Or, as Stephen commented here:
@Html.EditorFor(m => m.Description,
Model.IsDisabled ? (object)new { disabled = "disabled" } : (object)new { })
Dictionary objects allow you to iterate over their items. Also, with pattern matching and the division from __future__
you can do simplify things a bit.
Finally, you can separate your logic from your printing to make things a bit easier to refactor/debug later.
from __future__ import division
def Pythag(league):
def win_percentages():
for team, (runs_scored, runs_allowed) in league.iteritems():
win_percentage = round((runs_scored**2) / ((runs_scored**2)+(runs_allowed**2))*1000)
yield win_percentage
for win_percentage in win_percentages():
print win_percentage
I believe you just need to put the list 'bullet' outside of the padding.
li {
list-style-position: outside;
padding-left: 1em;
}
Something likes this
public void testPrintOut() {
int val1 = 8;
String val2 = "$951.23";
String val3 = "$215.92";
String val4 = "$198,301.22";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
val1 = 9;
val2 = "$950.19";
val3 = "$216.95";
val4 = "$198,084.26";
System.out.println(String.format("%03d %7s %7s %11s", val1, val2, val3, val4));
}
Using the Joda-Time 2.4 library. The DateTimeFormat
class is a factory of DateTimeFormatter
formatters. That class offers a forStyle
method to access formatters appropriate to a Locale
.
DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );
The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.
Note that we specified both a Locale and a time zone. Some people confuse the two.
We need all those pieces to properly generate a string representation of a date-time value.
Below would also work, but you cannot put in the getter of a decimal property. The getter of a decimal property can only return a decimal, for which formatting does not apply.
decimal moneyvalue = 1921.39m;
string currencyValue = moneyvalue.ToString("C");
I run vscode from my command line by navigating to the folder with the code and running
code .
If you do that all your bash
/zsh
variables are passed into vs code. You can update your .bashrc
/.zshrc
file or just do
export KEY=value
before opening it.
xcopy "C:\Documents and Settings\user\Desktop\?????????" "D:\Backup" /s /e /y /i
Probably the problem is the space.Try with quotes.
Use the LayoutBuilder Widget that will give you constraints that you can use to obtain the height that excludes the AppBar and the padding. Then use a SizedBox and provide the width and height using the constraints from the LayoutBuilder
return LayoutBuilder(builder: (context2, constraints) {
return Column(
children: <Widget>[
SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
...
Hi url should be calling a function which in return will give response
$.ajax({
url:'function to call url',
...
...
});
try using/calling API facebook method
Yes. Only override it in that one Activity
with
@Override
public void onBackPressed()
{
// code here to show dialog
super.onBackPressed(); // optional depending on your needs
}
don't put this code in any other Activity
Yes, you can assign one instance of a struct to another using a simple assignment statement.
In the case of non-pointer or non pointer containing struct members, assignment means copy.
In the case of pointer struct members, assignment means pointer will point to the same address of the other pointer.
Let us see this first hand:
#include <stdio.h>
struct Test{
int foo;
char *bar;
};
int main(){
struct Test t1;
struct Test t2;
t1.foo = 1;
t1.bar = malloc(100 * sizeof(char));
strcpy(t1.bar, "t1 bar value");
t2.foo = 2;
t2.bar = malloc(100 * sizeof(char));
strcpy(t2.bar, "t2 bar value");
printf("t2 foo and bar before copy: %d %s\n", t2.foo, t2.bar);
t2 = t1;// <---- ASSIGNMENT
printf("t2 foo and bar after copy: %d %s\n", t2.foo, t2.bar);
//The following 3 lines of code demonstrate that foo is deep copied and bar is shallow copied
strcpy(t1.bar, "t1 bar value changed");
t1.foo = 3;
printf("t2 foo and bar after t1 is altered: %d %s\n", t2.foo, t2.bar);
return 0;
}
request.url
request.path #to get path except the base url
Assuming your df.index is sorted you can use:
df.loc[df.index.max() + 1] = None
It handles well different indexes and column types.
[EDIT] it works with pd.DatetimeIndex if there is a constant frequency, otherwise we must specify the new index exactly e.g:
df.loc[df.index.max() + pd.Timedelta(milliseconds=1)] = None
long example:
df = pd.DataFrame([[pd.Timestamp(12432423), 23, 'text_field']],
columns=["timestamp", "speed", "text"],
index=pd.DatetimeIndex(start='2111-11-11',freq='ms', periods=1))
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 1 entries, 2111-11-11 to 2111-11-11
Freq: L
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null int64
text 1 non-null object
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 32.0+ bytes
df.loc[df.index.max() + 1] = None
df.info()
<class 'pandas.core.frame.DataFrame'>
DatetimeIndex: 2 entries, 2111-11-11 00:00:00 to 2111-11-11 00:00:00.001000
Data columns (total 3 columns):
timestamp 1 non-null datetime64[ns]
speed 1 non-null float64
text 1 non-null object
dtypes: datetime64[ns](1), float64(1), object(1)
memory usage: 64.0+ bytes
df.head()
timestamp speed text
2111-11-11 00:00:00.000 1970-01-01 00:00:00.012432423 23.0 text_field
2111-11-11 00:00:00.001 NaT NaN NaN
In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:
request.AddJsonBody(new { A = "foo", B = "bar" });
This method sets content type to application/json and serializes the object to a JSON string.
i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64
First execute python3
then type the command import pygame
,now you can see the output
How about
<img style="display: none;" src="a.gif">
That will disable the display completely, and not leave a placeholder
adding muted="muted"
property to HTML5 tag solved my issue
Refining upon the answers found here I came up with the following:
getCurrentScript.js
var getCurrentScript = function () {
if (document.currentScript) {
return document.currentScript.src;
} else {
var scripts = document.getElementsByTagName('script');
return scripts[scripts.length-1].src;
}
};
module.exports = getCurrentScript;
getCurrentScriptPath.js
var getCurrentScript = require('./getCurrentScript');
var getCurrentScriptPath = function () {
var script = getCurrentScript();
var path = script.substring(0, script.lastIndexOf('/'));
return path;
};
module.exports = getCurrentScriptPath;
BTW: I'm using CommonJS module format and bundling with webpack.
You can use geom_col() directly. See the differences between geom_bar() and geom_col() in this link https://ggplot2.tidyverse.org/reference/geom_bar.html
geom_bar() makes the height of the bar proportional to the number of cases in each group If you want the heights of the bars to represent values in the data, use geom_col() instead.
ggplot(data_country)+aes(x=country,y = conversion_rate)+geom_col()
I know it's been a while this has been posted, but with iOS 7.1, a few things have changed.
So far, if you are developing an App, you MUST have a valid SSL certificate recognized by Apple, otherwise you will get an error message on you iDevice. No more self-signed certificates. See here a list:
http://support.apple.com/kb/ht5012
Additionally, if you are here, it means that you are trying to make you iDevice resolve a name (to your https server), on a test or development environment.
Instead of using squid, which is a great application, you could simply run a very basic DNS server like dnsmasq. It will use your hosts file as a first line of name resolution, so, you can basically fool your iDevice there, saying that www.blah.com is 192.168.10.10.
The configuration file is as simple as 3 to 4 lines, and you can even configure its internal DHCP server if you want.
Here is mine:
listen-address=192.168.10.35
domain-needed
bogus-priv
no-dhcp-interface=eth0
local=/localnet/
Of course you have to configure networking on your iDevice to use that DNS (192.168.10.35 in my case), or just start using DHCP from that server anyway, after properly configured.
Additionally, if dnsmasq cannot resolve the name internally, it uses your regular DNS server (like 8.8.8.8) to resolve it for you. VERY simple, elegant, and solved my problems with iDevice App installation in-house.
By the way, solves many name resolution problems with regular macs (OS X) as well.
Now, my rant: bloody Apple. Making a device safe should not include castrating the operating system or the developers.
Here's a very simple answer:
NSURL *scriptUrl = [NSURL URLWithString:@"http://www.google.com/m"];
NSData *data = [NSData dataWithContentsOfURL:scriptUrl];
if (data)
NSLog(@"Device is connected to the Internet");
else
NSLog(@"Device is not connected to the Internet");
The URL should point to an extremely small website. I use Google's mobile website here, but if I had a reliable web server I'd upload a small file with just one character in it for maximum speed.
If checking whether the device is somehow connected to the Internet is everything you want to do, I'd definitely recommend using this simple solution. If you need to know how the user is connected, using Reachability is the way to go.
Careful: This will briefly block your thread while it loads the website. In my case, this wasn't a problem, but you should consider this (credits to Brad for pointing this out).
Notice that you're using Observable#map to convert the raw Response
object your base Observable emits to a parsed representation of the JSON response.
If I understood you correctly, you want to map
again. But this time, converting that raw JSON to instances of your Model
. So you would do something like:
http.get('api/people.json')
.map(res => res.json())
.map(peopleData => peopleData.map(personData => new Person(personData)))
So, you started with an Observable that emits a Response
object, turned that into an observable that emits an object of the parsed JSON of that response, and then turned that into yet another observable that turned that raw JSON into an array of your models.
from your question I assume that you already have your data in hdfs.
So you don't need to LOAD DATA
, which moves the files to the default hive location /user/hive/warehouse
. You can simply define the table using the external
keyword, which leaves the files in place, but creates the table definition in the hive metastore. See here:
Create Table DDL
eg.:
create external table table_name (
id int,
myfields string
)
location '/my/location/in/hdfs';
Please note that the format you use might differ from the default (as mentioned by JigneshRawal in the comments). You can use your own delimiter, for example when using Sqoop:
row format delimited fields terminated by ','
psql --pset=format=FORMAT
Great for executing queries from command line, e.g.
psql --pset=format=unaligned -c "select bandanavalue from bandana where bandanakey = 'atlassian.confluence.settings';"
Another way to do it on Ubuntu 18.0.4
sudo /usr/share/kibana/bin/kibana --version
Arrays in C++ cannot change size at runtime. For that purpose, you should use vector<int>
instead.
vector<int> arr;
arr.push_back(1);
arr.push_back(2);
// arr.size() will be the number of elements in the vector at the moment.
As mentioned in the comments, vector
is defined in vector
header and std
namespace. To use it, you should:
#include <vector>
and also, either use std::vector
in your code or add
using std::vector;
or
using namespace std;
after the #include <vector>
line.
All credits to @Martijn Pieters in the comments:
You can use the function last_insert_rowid()
:
The
last_insert_rowid()
function returns theROWID
of the last row insert from the database connection which invoked the function. Thelast_insert_rowid()
SQL function is a wrapper around thesqlite3_last_insert_rowid()
C/C++ interface function.
There are multiple tools, mentioned by many great answers, I'm going to pick one.
I downloaded latest version (5.1.7) from [AngusJ]: Resource Hacker. All the needed information can be found on that page (command line options, scripts, ...). In the following walkthrough I'm going to operate on 2 executables (lab rats) which (for obvious reasons) I've copied in my cwd:
Before going further, I want to mention that ResourceHacker has a funny terminal output, and the the following copy / paste fragments might generate a bit of confusion.
This is more like a preliminary step, to get acquainted with the environment, to show there's no funky business going on, ...
e:\Work\Dev\StackOverflow\q000284258> sopr.bat *** Set shorter prompt to better fit when pasted in StackOverflow (or other) pages *** [prompt]> dir Volume in drive E is Work Volume Serial Number is 3655-6FED Directory of e:\Work\Dev\StackOverflow\q000284258 2019-01-28 20:09 <DIR> . 2019-01-28 20:09 <DIR> .. 2016-11-03 09:17 5,413,376 cmake.exe 2019-01-03 02:06 5,479,424 ResourceHacker.exe 2019-01-28 20:30 496 ResourceHacker.ini 3 File(s) 10,893,296 bytes 2 Dir(s) 103,723,261,952 bytes free [prompt]> set PATH=%PATH%;c:\Install\x64\CMake\CMake\3.6.3\bin [prompt]> .\cmake --help >nul 2>&1 [prompt]> echo %errorlevel% 0 [prompt]> .\ResourceHacker.exe -help [prompt]> ================================== Resource Hacker Command Line Help: ================================== -help : displays these abbreviated help instructions. -help commandline : displays help for single commandline instructions -help script : displays help for script file instructions. [prompt]> echo %errorlevel% 0
As seen, the executables are OK, they run fine, and here's how their Details (that we care about) look like:
Resource files are text files that contain resources. A resource (simplified) has:
For more details check [MS.Docs]: About Resource Files. There are many tools (mentioned in existing answers) that facilitate resource file editing like:
But, since it's about Resource Hacker, and:
I'm going to use it for this step (-action extract
)
Next, In order for a resource to be embedded into an .exe (.dll, ...) it must be compiled to a binary form, which fits into the PE format. Again, there are lots of tools who can achieve this, but as you probably guessed I'm going to stick to Resource Hacker (-action compile
).
[prompt]> :: Extract the resources into a file [prompt]> .\ResourceHacker.exe -open .\ResourceHacker.exe -save .\sample.rc -action extract -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 20:58:03] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\ResourceHacker.exe -save .\sample.rc -action extract -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Save : e:\Work\Dev\StackOverflow\q000284258\sample.rc Success! [prompt]> :: Modify the resource file and set our own values [prompt]> [prompt]> :: Compile the resource file [prompt]> .\ResourceHacker.exe -open .\sample.rc -save .\sample.res -action compile -log con [prompt]> [28 Jan 2019, 20:59:51] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\sample.rc -save .\sample.res -action compile -log con Open : e:\Work\Dev\StackOverflow\q000284258\sample.rc Save : e:\Work\Dev\StackOverflow\q000284258\sample.res Compiling: e:\Work\Dev\StackOverflow\q000284258\sample.rc Success! [prompt]> dir /b cmake.exe ResourceHacker.exe ResourceHacker.ini sample.rc sample.res
In your case saving and editing the resource file won't be necessary, as the file will already be present, I just did it for demonstrating purposes. Below it's the resource file after being modified (and thus before being compiled).
sample.rc:
1 VERSIONINFO
FILEVERSION 3,1,4,1592
PRODUCTVERSION 2,7,1,8
FILEOS 0x4
FILETYPE 0x1
{
BLOCK "StringFileInfo"
{
BLOCK "040904E4"
{
VALUE "CompanyName", "Cristi Fati\0"
VALUE "FileDescription", "20190128 - SO q000284258 demo\0"
VALUE "FileVersion", "3.1.4.1592\0"
VALUE "ProductName", "Colonel Panic\0"
VALUE "InternalName", "100\0"
VALUE "LegalCopyright", "(c) Cristi Fati 1999-2999\0"
VALUE "OriginalFilename", "ResHack\0"
VALUE "ProductVersion", "2.7.1.8\0"
}
}
BLOCK "VarFileInfo"
{
VALUE "Translation", 0x0409 0x04E4
}
}
This will also be performed by Resource Hacker (-action addoverwrite
). Since the .exes are already copied I'm going to edit their resources in place.
[prompt]> .\ResourceHacker.exe -open .\cmake.exe -save .\cmake.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 21:17:19] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHacker.exe -open .\cmake.exe -save .\cmake.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\cmake.exe Save : e:\Work\Dev\StackOverflow\q000284258\cmake.exe Resource: e:\Work\Dev\StackOverflow\q000284258\sample.res Added: VERSIONINFO,1,1033 Success! [prompt]> copy ResourceHacker.exe ResourceHackerTemp.exe 1 file(s) copied. [prompt]> .\ResourceHackerTemp.exe -open .\ResourceHacker.exe -save .\ResourceHacker.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con [prompt]> [28 Jan 2019, 21:19:29] Current Directory: e:\Work\Dev\StackOverflow\q000284258 Commandline: .\ResourceHackerTemp.exe -open .\ResourceHacker.exe -save .\ResourceHacker.exe -res .\sample.res -action addoverwrite -mask VersionInfo,, -log con Open : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Save : e:\Work\Dev\StackOverflow\q000284258\ResourceHacker.exe Resource: e:\Work\Dev\StackOverflow\q000284258\sample.res Modified: VERSIONINFO,1,1033 Success! [prompt]> del /f /q ResourceHackerTemp.* [prompt]> dir Volume in drive E is Work Volume Serial Number is 3655-6FED Directory of e:\Work\Dev\StackOverflow\q000284258 2019-01-28 21:20 <DIR> . 2019-01-28 21:20 <DIR> .. 2016-11-03 09:17 5,414,400 cmake.exe 2019-01-03 02:06 5,479,424 ResourceHacker.exe 2019-01-28 21:17 551 ResourceHacker.ini 2019-01-28 20:05 1,156 sample.rc 2019-01-28 20:59 792 sample.res 5 File(s) 10,896,323 bytes 2 Dir(s) 103,723,253,760 bytes free
As seen, I had to d a little trick (gainarie) as I can't (at least I don't think I can) modify the .exe while in use.
This is an optional phase, to make sure that:
[prompt]> .\cmake --help >nul 2>&1 [prompt]> echo %errorlevel% 0 [prompt]> .\ResourceHacker.exe -help [prompt]> ================================== Resource Hacker Command Line Help: ================================== -help : displays these abbreviated help instructions. -help commandline : displays help for single commandline instructions -help script : displays help for script file instructions. [prompt]> echo %errorlevel% 0
And their Details:
I would rather use plt.clf()
after every plt.show()
to just clear the current figure instead of closing and reopening it, keeping the window size and giving you a better performance and much better memory usage.
Similarly, you could do plt.cla()
to just clear the current axes.
To clear a specific axes, useful when you have multiple axes within one figure, you could do for example:
fig, axes = plt.subplots(nrows=2, ncols=2)
axes[0, 1].clear()
If you used only $json_string = json_encode($data, JSON_PRETTY_PRINT);
, you will get in the browser something like this (using the Facebook link from the question :) ):
but if you used a chrome Extension like JSONView (even without the PHP option above), then you get a more pretty readable debuggable solution where you can even Fold/Collapse each single JSON object easily like this:
You don't specify which OS.
Under Windows (for my application - a long running risk management application) we observed that we could go no further than 1280MB on Windows 32bit. I doubt that running a 32bit JVM under 64bit would make any difference.
We ported the app to Linux and we are running a 32bit JVM on 64bit hardware and have had a 2.2GB VM running pretty easily.
The biggest problem you may have is GC depending on what you are using memory for.
For the OP's command:
select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0, Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from #tmp_CTF**
I get this error:
Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.
when debugging something like this split the long line up so you'll get a better row number:
select compid
,2
, convert(datetime
, '01/01/'
+ CONVERT(char(4)
,cal_yr)
,101)
,0
, Update_dt
, th1
, th2
, th3_pc
, Update_id
, Update_dt
,1
from #tmp_CTF**
this now results in:
Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.
which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:
from [#tmp_CTF**]
if that is the table name.
You can probably use
new Date().setUTCHours(0,0,0,0)
if you need the value only once.
If you follow the stackoverflow podcasts you can hear Jeff (and Geoff?) discuss its greatness. https://blog.stackoverflow.com/2008/08/podcast-17/. But remember that using these separate layers means things are easier in the future--and harder now. And layers can make things slower. And you may not need them. But don't let that stop you from learning what it is--when building big, robust, long-lived systems, it's invaluable.
var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);
Not really - the background image is bounded by the element it's applied to, and the overflow properties only apply to the content (i.e. markup) within an element.
You can add another div into your footer div and apply the background image to that, though, and have that overflow instead.
If you are running the program with python, try running it with python3.
Actually MySQL provide a lot of easy to use function in daily life without more effort from user side-
NOW() it produce date and time both in current scenario whereas CURDATE() produce date only, CURTIME() display time only, we can use one of them according to our need with CAST or merge other calculation it, MySQL rich in these type of function.
NOTE:- You can see the difference using query select NOW() as NOWDATETIME, CURDATE() as NOWDATE, CURTIME() as NOWTIME ;
I would like to praise josh3736's answer for providing some excellent historical context. While it's well articulated, the CSS landscape has changed in the almost five years since this question was asked. When this question was asked, px
was the correct answer, but that no longer holds true today.
tl;dr: use rem
Historically px
units typically represented one device pixel. With devices having higher and higher pixel density this no longer holds for many devices, such as with Apple's Retina Display.
rem
units represent the root em size. It's the font-size
of whatever matches :root
. In the case of HTML, it's the <html>
element; for SVG, it's the <svg>
element. The default font-size
in every browser* is 16px
.
At the time of writing, rem
is supported by approximately 98% of users. If you're worried about that other 2%, I'll remind you that media queries are also supported by approximately 98% of users.
px
The majority of CSS examples on the internet use px
values because they were the de-facto standard. pt
, in
and a variety of other units could have been used in theory, but they didn't handle small values well as you'd quickly need to resort to fractions, which were longer to type, and harder to reason about.
If you wanted a thin border, with px
you could use 1px
, with pt
you'd need to use 0.75pt
for consistent results, and that's just not very convenient.
rem
rem
's default value of 16px
isn't a very strong argument for its use. Writing 0.0625rem
is worse than writing 0.75pt
, so why would anyone use rem
?
There are two parts to rem
's advantage over other units.
px
value of rem
to whatever you'd likeBrowser zoom has changed a lot over the years. Historically many browsers would only scale up font-size
, but that changed pretty rapidly when websites realized that their beautiful pixel-perfect designs were breaking any time someone zoomed in or out. At this point, browsers scale the entire page, so font-based zooming is out of the picture.
Respecting a user's wishes is not out of the picture. Just because a browser is set to 16px
by default, doesn't mean any user can't change their preferences to 24px
or 32px
to correct for low vision or poor visibility (e.x. screen glare). If you base your units off of rem
, any user at a higher font-size will see a proportionally larger site. Borders will be bigger, padding will be bigger, margins will be bigger, everything will scale up fluidly.
If you base your media queries on rem
, you can also make sure that the site your users see fits their screen. A user with font-size
set to 32px
on a 640px
wide browser, will effectively be seeing your site as shown to a user at 16px
on a 320px
wide browser. There's absolutely no loss for RWD in using rem
.
px
ValueBecause rem
is based on the font-size
of the :root
node, if you want to change what 1rem
represents, all you have to do is change the font-size
:
:root {_x000D_
font-size: 100px;_x000D_
}_x000D_
body {_x000D_
font-size: 1rem;_x000D_
}
_x000D_
<p>Don't ever actually do this, please</p>
_x000D_
Whatever you do, don't set the :root
element's font-size
to a px
value.
If you set the font-size
on html
to a px
value, you've blown away the user's preferences without a way to get them back.
If you want to change the apparent value of rem
, use %
units.
The math for this is reasonably straight-forward.
The apparent font-size of :root
is 16px
, but lets say we want to change it to 20px
. All we need to do is multiply 16
by some value to get 20
.
Set up your equation:
16 * X = 20
And solve for X
:
X = 20 / 16
X = 1.25
X = 125%
:root {_x000D_
font-size: 125%;_x000D_
}
_x000D_
<p>If you're using the default font-size, I'm 20px tall.</p>
_x000D_
Doing everything in multiples of 20
isn't all that great, but a common suggestion is to make the apparent size of rem
equal to 10px
. The magic number for that is 10/16
which is 0.625
, or 62.5%
.
:root {_x000D_
font-size: 62.5%;_x000D_
}
_x000D_
<p>If you're using the default font-size, I'm 10px tall.</p>
_x000D_
The problem now is that your default font-size
for the rest of the page is set way too small, but there's a simple fix for that: Set a font-size
on body
using rem
:
:root {_x000D_
font-size: 62.5%;_x000D_
}_x000D_
_x000D_
body {_x000D_
font-size: 1.6rem;_x000D_
}
_x000D_
<p>I'm the default font-size</p>
_x000D_
It's important to note, with this adjustment in place, the apparent value of rem
is 10px
which means any value you might have written in px
can be converted directly to rem
by bumping a decimal place.
padding: 20px;
turns into
padding: 2rem;
The apparent font-size you choose is up to you, so if you want there's no reason you can't use:
:root {
font-size: 6.25%;
}
body {
font-size: 16rem;
}
and have 1rem
equal 1px
.
So there you have it, a simple solution to respect user wishes while also avoiding over-complicating your CSS.
I was afraid you might ask that. As much as I'd like to pretend that rem
is magic and solves-all-things, there are still some issues of note. Nothing deal-breaking in my opinion, but I'm going to call them out so you can't say I didn't warn you.
em
)One of the first issues you'll run into with rem
involves media queries. Consider the following code:
:root {
font-size: 1000px;
}
@media (min-width: 1rem) {
:root {
font-size: 1px;
}
}
Here the value of rem
changes depending on whether the media-query applies, and the media query depends on the value of rem
, so what on earth is going on?
rem
in media queries uses the initial value of font-size
and should not (see Safari section) take into account any changes that may have happened to the font-size
of the :root
element. In other words, it's apparent value is always 16px
.
This is a bit annoying, because it means that you have to do some fractional calculations, but I have found that most common media queries already use values that are multiples of 16.
| px | rem |
+------+-----+
| 320 | 20 |
| 480 | 30 |
| 768 | 48 |
| 1024 | 64 |
| 1200 | 75 |
| 1600 | 100 |
Additionally if you're using a CSS preprocessor, you can use mixins or variables to manage your media queries, which will mask the issue entirely.
SafariUnfortunately there's a known bug with Safari where changes to the :root
font-size do actually change the calculated rem
values for media query ranges. This can cause some very strange behavior if the font-size of the :root
element is changed within a media query. Fortunately the fix is simple: use em
units for media queries.
If you switch between projects various different projects, it's quite possible that the apparent font-size of rem
will have different values. In one project, you might be using an apparent size of 10px
where in another project the apparent size might be 1px
. This can be confusing and cause issues.
My only recommendation here is to stick with 62.5%
to convert rem
to an apparent size of 10px
, because that has been more common in my experience.
If you're writing CSS that's going to be used on a site that you don't control, such as for an embedded widget, there's really no good way to know what apparent size rem
will have. If that's the case, feel free to keep using px
.
If you still want to use rem
though, consider releasing a Sass or LESS version of the stylesheet with a variable to override the scaling for the apparent size of rem
.
* I don't want to spook anyone away from using rem
, but I haven't been able to officially confirm that every browser uses 16px
by default. You see, there are a lot of browsers and it wouldn't be all that hard for one browser to have diverged ever so slightly to, say 15px
or 18px
. In testing, however I have not seen a single example where a browser using default settings in a system using default settings had any value other than 16px
. If you find such an example, please share it with me.
That means it is timezone naive, so you can't use it with datetime.astimezone
you can give it a timezone like this
import pytz # 3rd party: $ pip install pytz
u = datetime.utcnow()
u = u.replace(tzinfo=pytz.utc) #NOTE: it works only with a fixed utc offset
now you can change timezones
print(u.astimezone(pytz.timezone("America/New_York")))
To get the current time in a given timezone, you could pass tzinfo to datetime.now()
directly:
#!/usr/bin/env python
from datetime import datetime
import pytz # $ pip install pytz
print(datetime.now(pytz.timezone("America/New_York")))
It works for any timezone including those that observe daylight saving time (DST) i.e., it works for timezones that may have different utc offsets at different times (non-fixed utc offset). Don't use tz.localize(datetime.now())
-- it may fail during end-of-DST transition when the local time is ambiguous.
sed
If one would like to do this systematically for all external links, CSS is no option. However, one could run the following sed
command once the (X)HTML has been created from Markdown:
sed -i 's|href="http|target="_blank" href="http|g' index.html
This can be further automated in a single workflow when a Makefile
with build instructions is employed.
PS: This answer was written at a time when extension link_attributes
was not yet available in Pandoc.
Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML.
Adding a value of selected
to the item we want to appear as a header forces it to show in the first place as a placeholder.
Something like:
<option selected disabled>Choose here</option>
The complete markup should be along these lines:
<select>
<option selected disabled>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
You can take a look at this fiddle, and here's the result:
If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden
attribute like so:
<select>
<option selected disabled hidden>Choose here</option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
<option value="5">Five</option>
</select>
Check the fiddle here and the screenshot below.
Here is the solution:
<select>
<option style="display:none;" selected>Select language</option>
<option>Option 1</option>
<option>Option 2</option>
</select>
Starting with HTML5, <input type="date" />
will do just fine.
Yep! Use the link:
https://m.google.com/app/plus/x/?v=compose&content=YOUR_TEXT
It's SHARE url (not used for plus one) button.
If this will not work (not for me) try this url:
https://plusone.google.com/_/+1/confirm?hl=ru&url=_URL_&title=_TITLE_
Or see this solution:
Adding a Google Plus (one or share) link to an email newsletter
I do it like this - from my point of view the easiest way:
set the form's 'StartPosition' to 'Manual', and add this to the form's designer:
Private Sub InitializeComponent()
.
.
.
Me.Location=New Point(-2000,-2000)
.
.
.
End Sub
Make sure that the location is set to something beyond or below the screen's dimensions. Later, when you want to show the form, set the Location to something within the screen's dimensions.
Return ABDeadlineType
from repository:
public interface ABDeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
List<ABDeadlineType> findAllSummarizedBy();
}
and then convert to DeadlineType. Manually or use mapstruct.
Or call constructor from @Query
annotation:
public interface DeadlineTypeRepository extends JpaRepository<ABDeadlineType, Long> {
@Query("select new package.DeadlineType(a.id, a.code) from ABDeadlineType a ")
List<DeadlineType> findAllSummarizedBy();
}
Or use @Projection
:
@Projection(name = "deadline", types = { ABDeadlineType.class })
public interface DeadlineType {
@Value("#{target.id}")
String getId();
@Value("#{target.code}")
String getText();
}
Update:
Spring can work without @Projection
annotation:
public interface DeadlineType {
String getId();
String getText();
}
Note that if you are trying to pass to a "figure level" method in seaborn (for example lmplot
, catplot
/ factorplot
, jointplot
) you can and should specify this within the arguments using height
and aspect
.
sns.catplot(data=df, x='xvar', y='yvar',
hue='hue_bar', height=8.27, aspect=11.7/8.27)
See https://github.com/mwaskom/seaborn/issues/488 and Plotting with seaborn using the matplotlib object-oriented interface for more details on the fact that figure level methods do not obey axes specifications.
You can use the is function
if( $('#cartContent').is(':empty') ) { }
or use the length
if( $('#cartContent:empty').length ) { }
Why not try fadeOut?
$(document).ready(function() {_x000D_
$('#plsme').fadeOut(5000); // 5 seconds x 1000 milisec = 5000 milisec_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div id='plsme'>Loading... Please Wait</div>
_x000D_
fadeOut (Javascript Pure):
Passing the dataframes to concat in a dictionary, results in a multi-index dataframe from which you can easily delete the duplicates, which results in a multi-index dataframe with the differences between the dataframes:
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
import pandas as pd
DF1 = StringIO("""Date Fruit Num Color
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 8.6 Orange
2013-11-24 Apple 7.6 Green
2013-11-24 Celery 10.2 Green
""")
DF2 = StringIO("""Date Fruit Num Color
2013-11-24 Banana 22.1 Yellow
2013-11-24 Orange 8.6 Orange
2013-11-24 Apple 7.6 Green
2013-11-24 Celery 10.2 Green
2013-11-25 Apple 22.1 Red
2013-11-25 Orange 8.6 Orange""")
df1 = pd.read_table(DF1, sep='\s+')
df2 = pd.read_table(DF2, sep='\s+')
#%%
dfs_dictionary = {'DF1':df1,'DF2':df2}
df=pd.concat(dfs_dictionary)
df.drop_duplicates(keep=False)
Result:
Date Fruit Num Color
DF2 4 2013-11-25 Apple 22.1 Red
5 2013-11-25 Orange 8.6 Orange
If you have several dialogs that could be opened on a page, this will allow any of them to be closed by clicking on the background:
$('body').on('click','.ui-widget-overlay', function() {
$('.ui-dialog').filter(function () {
return $(this).css("display") === "block";
}).find('.ui-dialog-content').dialog('close');
});
(Only works for modal dialogs, as it relies on '.ui-widget-overlay'. And it does close all open dialogs any time the background of one of them is clicked.)
Suppose a 9800GT GPU:
https://www.tutorialspoint.com/cuda/cuda_threads.htm
A block cannot have more active threads than 512 therefore __syncthreads
can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:
func1();
__syncthreads();
func2();
__syncthreads();
then the kernel must run twice and the order of execution will be:
Note:
The main point is __syncthreads
is a block-wide operation and it does not synchronize all threads.
I'm not sure about the exact number of threads that __syncthreads
can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.
Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads
.
I would greatly appreciate if someone test this again for a more accurate piece of information.
Think of Web service as a web api. API is such a general term now so a web service is an interface to functionality, usually business related, that you can get to from the network over a variety of protocols.
.container {_x000D_
background: tomato;_x000D_
display: flex;_x000D_
flex-flow: row wrap;_x000D_
align-content: space-between;_x000D_
justify-content: space-between;_x000D_
}_x000D_
_x000D_
.item {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: gold;_x000D_
border: 1px solid black;_x000D_
font-size: 30px;_x000D_
line-height: 100px;_x000D_
text-align: center;_x000D_
margin: 10px;_x000D_
}
_x000D_
<div class="container">_x000D_
<div>_x000D_
<div class="item">1</div>_x000D_
<div class="item">2</div>_x000D_
<div class="item">3</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">4</div>_x000D_
<div class="item">5</div>_x000D_
<div class="item">6</div>_x000D_
</div>_x000D_
<div>_x000D_
<div class="item">7</div>_x000D_
<div class="item">8</div>_x000D_
<div class="item">9</div>_x000D_
</div>_x000D_
<div class="item">10</div>_x000D_
</div>
_x000D_
you could try wrapping the items in a dom element like here. with this you dont have to know a lot of css just having a good structure will solve the problem.
Well, you might look at System.Threading.Semaphore
class. Other than that - no, you have to make this yourself. AFAIK there is no such built-in collection.
Do like this
List<Object[]> list = HQL.list(); // get your lsit here but in Object array
your query is : "SELECT houses.id, addresses.country, addresses.region,..."
for(Object[] obj : list){
String houseId = String.valueOf(obj[0]); // houseId is at first place in your query
String country = String.valueof(obj[1]); // country is at second and so on....
.......
}
this way you can get the mixed objects with ease, but you should know in advance at which place what value you are getting or you can just check by printing the values to know. sorry for the bad english I hope this help
Yes dear,then you have to use Ajax technology. to changes contents of particular html tag:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<title>Ajax Page</title>
<script>
setInterval(function () { autoloadpage(); }, 30000); // it will call the function autoload() after each 30 seconds.
function autoloadpage() {
$.ajax({
url: "URL of the destination page",
type: "POST",
success: function(data) {
$("div#wrapper").html(data); // here the wrapper is main div
}
});
}
</script>
</head>
<body>
<div id="wrapper">
contents will be changed automatically.
</div>
</body>
</html>
The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.
## set the levels in order we want
theTable <- within(theTable,
Position <- factor(Position,
levels=names(sort(table(Position),
decreasing=TRUE))))
## plot
ggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)
In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.
theTable$Position <- factor(theTable$Position, levels = c(...))
USING FLEX
display: flex;
height: 100%;
align-items: center;
justify-content: center;
@phidah... Here is a very interesting solution to your problem: http://24ways.org/2005/have-your-dom-and-script-it-too
So it would look like this instead:
<img src="empty.gif" onload="alert('test');this.parentNode.removeChild(this);" />
The result stated above may be correct, but isn't working with the latest webdriver. Here is my solution for the above question. Simple and sweet
http_proxy = "ip_addr:port"
https_proxy = "ip_addr:port"
webdriver.DesiredCapabilities.FIREFOX['proxy']={
"httpProxy":http_proxy,
"sslProxy":https_proxy,
"proxyType":"MANUAL"
}
driver = webdriver.Firefox()
OR
http_proxy = "http://ip:port"
https_proxy = "https://ip:port"
proxyDict = {
"http" : http_proxy,
"https" : https_proxy,
}
driver = webdriver.Firefox(proxy=proxyDict)
[Hg Tortoise 4.6.1] If it's recent action, you can use "Rollback/Undo" action (Ctrl+U).
thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.
The best way of doing it is to just trigger Bootstrap's click event with a hover. This way, it should still remain touch device friendly.
$('.dropdown').hover(function(){
$('.dropdown-toggle', this).trigger('click');
});
For UNIX, at least, this works...
import commands
username = commands.getoutput("echo $(whoami)")
print username
edit: I just looked it up and this works on Windows and UNIX:
import commands
username = commands.getoutput("whoami")
On UNIX it returns your username, but on Windows, it returns your user's group, slash, your username.
--
I.E.
UNIX returns: "username"
Windows returns: "domain/username"
--
It's interesting, but probably not ideal unless you are doing something in the terminal anyway... in which case you would probably be using os.system
to begin with. For example, a while ago I needed to add my user to a group, so I did (this is in Linux, mind you)
import os
os.system("sudo usermod -aG \"group_name\" $(whoami)")
print "You have been added to \"group_name\"! Please log out for this to take effect"
I feel like that is easier to read and you don't have to import pwd or getpass.
I also feel like having "domain/user" could be helpful in certain applications in Windows.
Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:
#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas
I'm not sure but it looks like that the background-color is inherited as transparent from the body.
Below is the program to execute the rest api in python-
import requests
url = 'https://url'
data = '{ "platform": { "login": { "userName": "name", "password": "pwd" } } }'
response = requests.post(url, data=data,headers={"Content-Type": "application/json"})
print(response)
sid=response.json()['platform']['login']['sessionId'] //to extract the detail from response
print(response.text)
print(sid)
You can achieve this by setting the android:theme
attribute to @android:style/Theme.NoTitleBar
on your <activity>
element in your AndroidManifest.xml like this:
<activity android:name=".Activity"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
You could also use strdup
:
The strdup() function returns a pointer to a new string which is a duplicate of the string s.
Memory for the new string is obtained with malloc(3), and can be freed with free(3).
For you example:
char *a = strdup("stack overflow");
Here are two common reasons:
You can use it for security. Grant no permissions on the main table and create views that limits column or row access and grant permissions to users to see the view.
You can use use it for convenience. Join together some tables that you use together all the time in the view. This can make queries consistent and easier.
You could simply replace the separator characters by NULL characters, and store the address after the newly created NULL character in a new char* pointer:
char* input = "asdf|qwer"
char* parts[10];
int partcount = 0;
parts[partcount++] = input;
char* ptr = input;
while(*ptr) { //check if the string is over
if(*ptr == '|') {
*ptr = 0;
parts[partcount++] = ptr + 1;
}
ptr++;
}
Note that this code will of course not work if the input string contains more than 9 separator characters.
According to RFC2965 3.3.1 (which might or might not be followed by browsers), unless the port is explicitly specified via the port
parameter of the Set-Cookie
header, cookies might or might not be sent to any port.
Google's Browser Security Handbook says: by default, cookie scope is limited to all URLs on the current host name - and not bound to port or protocol information. and some lines later There is no way to limit cookies to a single DNS name only [...] likewise, there is no way to limit them to a specific port. (Also, keep in mind, that IE does not factor port numbers into its same-origin policy at all.)
So it does not seem to be safe to rely on any well-defined behavior here.
I was facing the same issue then i made my key 16 byte and it's working properly now. Create your key exactly 16 byte. It will surely work.
its pretty simple
Date someDate = new DateTime();
string timeOfDay = someDate.ToString("hh:mm tt");
// hh - shows hour and mm - shows minute - tt - shows AM or PM
This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC
This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.
using (var context = new DataDb())
{
var ctx = ((System.Data.Entity.Infrastructure.IObjectContextAdapter)context).ObjectContext;
ctx.ExecuteStoreCommand("DELETE FROM [TableName] WHERE Name= {0}", Name);
}
or
using (var context = new DataDb())
{
context.Database.ExecuteSqlCommand("TRUNCATE TABLE [TableName]");
}
you use bad character like ? and & and etc ...
edit it to new code
see this links
also you can use urlencode
$val=urlencode('http://google.com/?var=234&key=234')
use this and it's gonna work:
$('select[name=selValue]').selectpicker('val', 1);
var rowHandle = gridView.FocusedRowHandle;
var obj = gridView.GetRowCellValue(rowHandle, "FieldName");
//For example
int val= Convert.ToInt32(gridView.GetRowCellValue(rowHandle, "FieldName"));
I had a similar problem and I solved with this
.format();
The array constructor has an ambiguous syntax, and JSLint just hurts your feelings after all.
Also, your example code is broken, the second var
statement will raise a SyntaxError
. You're setting the property length
of the array test
, so there's no need for another var
.
As far as your options go, array.length
is the only "clean" one. Question is, why do you need to set the size in the first place? Try to refactor your code to get rid of that dependency.
You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.
See http://docs.python.org/release/2.3/lib/module-string.html
To avoid the race condition @GregPettit mentions, one can use:
($("element").data('bs.modal') || {})._isShown // Bootstrap 4
($("element").data('bs.modal') || {}).isShown // Bootstrap <= 3
as discussed in Twitter Bootstrap Modal - IsShown.
When the modal is not yet opened, .data('bs.modal')
returns undefined
, hence the || {}
- which will make isShown
the (falsy) value undefined
. If you're into strictness one could do ($("element").data('bs.modal') || {isShown: false}).isShown
Avoiding Select
and Activate
is the move that makes you a bit better VBA developer. In general, Select
and Activate
are used when a macro is recorded, thus the Parent
worksheet or range is always considered the active one.
This is how you may avoid Select
and Activate
in the following cases:
From (code generated with macro recorder):
Sub Makro2()
Range("B2").Select
Sheets.Add After:=ActiveSheet
Sheets("Tabelle1").Select
Sheets("Tabelle1").Name = "NewName"
ActiveCell.FormulaR1C1 = "12"
Range("B2").Select
Selection.Copy
Range("B3").Select
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub
To:
Sub TestMe()
Dim ws As Worksheet
Set ws = Worksheets.Add
With ws
.Name = "NewName"
.Range("B2") = 12
.Range("B2").Copy Destination:=.Range("B3")
End With
End Sub
From:
Sheets("Source").Select
Columns("A:D").Select
Selection.Copy
Sheets("Target").Select
Columns("A:D").Select
ActiveSheet.Paste
To:
Worksheets("Source").Columns("A:D").Copy Destination:=Worksheets("Target").Range("a1")
You may access them with []
, which is really beautiful, compared to the other way. Check yourself:
Dim Months As Range
Dim MonthlySales As Range
Set Months = Range("Months")
Set MonthlySales = Range("MonthlySales")
Set Months =[Months]
Set MonthlySales = [MonthlySales]
The example from above would look like this:
Worksheets("Source").Columns("A:D").Copy Destination:=Worksheets("Target").[A1]
Usually, if you are willing to select
, most probably you are copying something. If you are only interested in the values, this is a good option to avoid select:
Range("B1:B6").Value = Range("A1:A6").Value
This is probably the most common mistake in vba. Whenever you copy ranges, sometimes the worksheet is not referenced and thus VBA considers the wrong sheet the ActiveWorksheet.
'This will work only if the 2. Worksheet is selected!
Public Sub TestMe()
Dim rng As Range
Set rng = Worksheets(2).Range(Cells(1, 1), Cells(2, 2)).Copy
End Sub
'This works always!
Public Sub TestMe2()
Dim rng As Range
With Worksheets(2)
.Range(.Cells(1, 1), .Cells(2, 2)).Copy
End With
End Sub
.Select
or .Activate
for anything?.Activate
and .Select
is when you want make sure that a specific Worksheet is selected for visual reasons. E.g., that your Excel would always open with the cover worksheet selected first, disregarding which which was the ActiveSheet when the file was closed.Thus, something like the code below is absolutely OK:
Private Sub Workbook_Open()
Worksheets("Cover").Activate
End Sub
Another good example is when you need to export all sheets into one PDF file, as mentioned in this case - How to avoid select/active statements in VBA in this example?
When a command only works with ActiveWindow
like ActiveWindow.Zoom or ActiveWindow.FreezePanes
str.splitlines
method should give you exactly that.
>>> data = """a,b,c
... d,e,f
... g,h,i
... j,k,l"""
>>> data.splitlines()
['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']
You can load local CSV file to Hive only if:
hive
or beeline
for upload.