Consider the following:
int n;
for(n = 0; n < 10; ++n) {
break;
}
System.out.println(n);
break causes the loop to terminate and the value of n is 0.
int n;
for(n = 0; n < 10; ++n) {
continue;
}
System.out.println(n);
continue causes the program counter to return to the first line of the loop (the condition is checked and the value of n is increment) and the final value of n is 10.
It should also be noted that break only terminates the execution of the loop it is within:
int m;
for(m = 0; m < 5; ++m)
{
int n;
for(n = 0; n < 5; ++n) {
break;
}
System.out.println(n);
}
System.out.println(m);
Will output something to the effect of
0
0
0
0
0
5
you can follow BaseAdapter
and create your custome Xml
file and bind it with you BaseAdpter
and populate it with Listview
see here need to change xml
file as Require.
Constructors append implicit conversion. To suppress this implicit conversion it is required to declare a constructor with a parameter explicit.
In C++11 you can also specify an "operator type()" with such keyword http://en.cppreference.com/w/cpp/language/explicit With such specification you can use operator in terms of explicit conversions, and direct initialization of object.
P.S. When using transformations defined BY USER (via constructors and type conversion operator) it is allowed only one level of implicit conversions used. But you can combine this conversions with other language conversions
Trying to run cleanup while your files are open gave me problems. as soon as I closed my application (Visual studio) I ran clean up and it was successful
For anyone, like me, trying to set a query string on the action and wondering why it's not working-
You cannot set a query string for a GET form submission, but I have found you can for a POST.
For a GET submission you must set the values in hidden inputs e.g.
an action of: "/handleformsubmission?foo=bar"
would have be added as the hidden field like: <input type="hidden" name="foo" value="bar" />
This can be done add dynamically in JavaScript as (where clickedButton is the submitted button that was clicked:
var form = clickedButton.form;
var hidden = document.createElement("input");
hidden.setAttribute("type", "hidden");
hidden.setAttribute("name", "foo");
hidden.setAttribute("value", "bar");
form.appendChild(hidden);
See this question for more info submitting a GET form with query string params and hidden params disappear
A Record lets you create a new type from a Union. The values in the Union are used as attributes of the new type.
For example, say I have a Union like this:
type CatNames = "miffy" | "boris" | "mordred";
Now I want to create an object that contains information about all the cats, I can create a new type using the values in the CatName Union as keys.
type CatList = Record<CatNames, {age: number}>
If I want to satisfy this CatList, I must create an object like this:
const cats:CatList = {
miffy: { age:99 },
boris: { age:16 },
mordred: { age:600 }
}
You get very strong type safety:
I used this recently to create a Status component. The component would receive a status prop, and then render an icon. I've simplified the code quite a lot here for illustrative purposes
I had a union like this:
type Statuses = "failed" | "complete";
I used this to create an object like this:
const icons: Record<
Statuses,
{ iconType: IconTypes; iconColor: IconColors }
> = {
failed: {
iconType: "warning",
iconColor: "red"
},
complete: {
iconType: "check",
iconColor: "green"
};
I could then render by destructuring an element from the object into props, like so:
const Status = ({status}) => <Icon {...icons[status]} />
If the Statuses union is later extended or changed, I know my Status component will fail to compile and I'll get an error that I can fix immediately. This allows me to add additional error states to the app.
Note that the actual app had dozens of error states that were referenced in multiple places, so this type safety was extremely useful.
This expression will check if the first letter to be alphabetic and the remaining characters to be alphanumeric or any of the following special characters: @,#,%,&,
^[A-Za-z][A-Za-z0-9@#%&\*]*$
While there are suggestions above for "doing it the python way", if one wants to really have a logic based on EOF, then I suppose using exception handling is the way to do it --
try:
line = raw_input()
... whatever needs to be done incase of no EOF ...
except EOFError:
... whatever needs to be done incase of EOF ...
Example:
$ echo test | python -c "while True: print raw_input()"
test
Traceback (most recent call last):
File "<string>", line 1, in <module>
EOFError: EOF when reading a line
Or press Ctrl-Z at a raw_input()
prompt (Windows, Ctrl-Z Linux)
You could use Qt which, in case you don't know, is C++ with a bunch of additional libraries and classes and whatnot. Qt has a very convenient QByteArray class which I'm quite sure would suit your needs.
Use the global
flag in regexp:
var replaced = str.replace(/%20/g, " ");
^
So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d
import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}
The command
pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06
where pd.Panel(d)[item] yields a dataframe
pd.Panel(d)['SPX Index']
2014-11-03 2014-11-04 2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33
You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.
pd.Panel(d).to_frame().reset_index()
major minor RAY Index SPX Index
PX_LAST 2014-11-03 1199.460 2017.81
PX_LAST 2014-11-04 1195.323 2012.10
PX_LAST 2014-11-05 1200.936 2023.57
PX_LAST 2014-11-06 1206.061 2031.21
PX_OPEN 2014-11-03 1200.140 2018.21
PX_OPEN 2014-11-04 1197.690 2015.81
PX_OPEN 2014-11-05 1195.320 2015.29
PX_OPEN 2014-11-06 1200.620 2023.33
Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html
Just as an example
pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major minor 2014-11-03 2014-11-04 2014-11-05 2014-11-06
RAY Index PX_LAST 1199.46 1195.323 1200.936 1206.061
RAY Index PX_OPEN 1200.14 1197.690 1195.320 1200.620
SPX Index PX_LAST 2017.81 2012.100 2023.570 2031.210
SPX Index PX_OPEN 2018.21 2015.810 2015.290 2023.330
Hope this helps.
First create the project from the following link to create larave 7 project: Create Project
Now you need to enter your project folder using the following command:
cd myproject
Now try to run artisan
command, such as, php artisan
.
Or it may happen if you didn't install compose. So if you didn't install composer then run composer install
and try again artisan
command.
os.path.getsize(path)
Return the size, in bytes, of path. Raise os.error if the file does not exist or is inaccessible.
I got the same problem while running unit tests. I found this workaround solution:
The following workaround allows to get rid of this message:
File workaround = new File(".");
System.getProperties().put("hadoop.home.dir", workaround.getAbsolutePath());
new File("./bin").mkdirs();
new File("./bin/winutils.exe").createNewFile();
STR_TO_DATE('12/31/2011', '%m/%d/%Y')
Perfectly simple use of aggregate (equivalent to fold in other languages):
var firstBorn = People.Aggregate((min, x) => x.DateOfBirth < min.DateOfBirth ? x : min);
The only downside is that the property is accessed twice per sequence element, which might be expensive. That's hard to fix.
DriverManager
is a fairly old way of doing things. The better way is to get a DataSource
, either by looking one up that your app server container already configured for you:
Context context = new InitialContext();
DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/myDB");
or instantiating and configuring one from your database driver directly:
MysqlDataSource dataSource = new MysqlDataSource();
dataSource.setUser("scott");
dataSource.setPassword("tiger");
dataSource.setServerName("myDBHost.example.org");
and then obtain connections from it, same as above:
Connection conn = dataSource.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT ID FROM USERS");
...
rs.close();
stmt.close();
conn.close();
It may means that you forgot include a header file that define this struct/union. For example:
foo.h file:
typedef union
{
struct
{
uint8_t FIFO_BYTES_AVAILABLE : 4;
uint8_t STATE : 3;
uint8_t CHIP_RDY : 1;
};
uint8_t status;
} RF_CHIP_STATUS_t;
RF_CHIP_STATUS_t getStatus();
main.c file:
.
.
.
if (getStatus().CHIP_RDY) /* This will generate the error, you must add the #include "foo.h" */
.
.
.
In WPF there are certain 'container' controls that automatically resize their contents and there are some that don't.
Here are some that do not resize their contents (I'm guessing that you are using one or more of these):
StackPanel
WrapPanel
Canvas
TabControl
Here are some that do resize their contents:
Grid
UniformGrid
DockPanel
Therefore, it is almost always preferable to use a Grid
instead of a StackPanel
unless you do not want automatic resizing to occur. Please note that it is still possible for a Grid
to not size its inner controls... it all depends on your Grid.RowDefinition
and Grid.ColumnDefinition
settings:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="100" /> <!--<<< Exact Height... won't resize -->
<RowDefinition Height="Auto" /> <!--<<< Will resize to the size of contents -->
<RowDefinition Height="*" /> <!--<<< Will resize taking all remaining space -->
</Grid.RowDefinitions>
</Grid>
You can find out more about the Grid
control from the Grid
Class page on MSDN. You can also find out more about these container controls from the WPF Container Controls Overview page on MSDN.
Further resizing can be achieved using the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties. The default value of these properties is Stretch
which will stretch elements to fit the size of their containing controls. However, when they are set to any other value, the elements will not stretch.
UPDATE >>>
In response to the questions in your comment:
Use the Grid.RowDefinition
and Grid.ColumnDefinition
settings to organise a basic structure first... it is common to add Grid
controls into the cells of outer Grid
controls if need be. You can also use the Grid.ColumnSpan
and Grid.RowSpan
properties to enable controls to span multiple columns and/or rows of a Grid
.
It is most common to have at least one row/column with a Height
/Width
of "*"
which will fill all remaining space, but you can have two or more with this setting, in which case the remaining space will be split between the two (or more) rows/columns. 'Auto' is a good setting to use for the rows/columns that are not set to '"*"', but it really depends on how you want the layout to be.
There is no Auto
setting that you can use on the controls in the cells, but this is just as well, because we want the Grid
to size the controls for us... therefore, we don't want to set the Height
or Width
of these controls at all.
The point that I made about the FrameworkElement.HorizontalAlignment
and FrameworkElement.VerticalAlignment
properties was just to let you know of their existence... as their default value is already Stretch
, you don't generally need to set them explicitly.
The Margin
property is generally just used to space your controls out evenly... if you drag and drop controls from the Visual Studio Toolbox, VS will set the Margin
property to place your control exactly where you dropped it but generally, this is not what we want as it will mess with the auto sizing of controls. If you do this, then just delete or edit the Margin
property to suit your needs.
Use IFERROR(value, value_if_error)
This question is very similar to:
Here is how I solved this problem, and dealt with the user hitting the X as well as Ctrl-C. Notice the use of ManualResetEvents. These will cause the main thread to sleep which frees the CPU to process other threads while waiting for either exit, or cleanup. NOTE: It is necessary to set the TerminationCompletedEvent at the end of main. Failure to do so causes unnecessary latency in termination due to the OS timing out while killing the application.
namespace CancelSample
{
using System;
using System.Threading;
using System.Runtime.InteropServices;
internal class Program
{
/// <summary>
/// Adds or removes an application-defined HandlerRoutine function from the list of handler functions for the calling process
/// </summary>
/// <param name="handler">A pointer to the application-defined HandlerRoutine function to be added or removed. This parameter can be NULL.</param>
/// <param name="add">If this parameter is TRUE, the handler is added; if it is FALSE, the handler is removed.</param>
/// <returns>If the function succeeds, the return value is true.</returns>
[DllImport("Kernel32")]
private static extern bool SetConsoleCtrlHandler(ConsoleCloseHandler handler, bool add);
/// <summary>
/// The console close handler delegate.
/// </summary>
/// <param name="closeReason">
/// The close reason.
/// </param>
/// <returns>
/// True if cleanup is complete, false to run other registered close handlers.
/// </returns>
private delegate bool ConsoleCloseHandler(int closeReason);
/// <summary>
/// Event set when the process is terminated.
/// </summary>
private static readonly ManualResetEvent TerminationRequestedEvent;
/// <summary>
/// Event set when the process terminates.
/// </summary>
private static readonly ManualResetEvent TerminationCompletedEvent;
/// <summary>
/// Static constructor
/// </summary>
static Program()
{
// Do this initialization here to avoid polluting Main() with it
// also this is a great place to initialize multiple static
// variables.
TerminationRequestedEvent = new ManualResetEvent(false);
TerminationCompletedEvent = new ManualResetEvent(false);
SetConsoleCtrlHandler(OnConsoleCloseEvent, true);
}
/// <summary>
/// The main console entry point.
/// </summary>
/// <param name="args">The commandline arguments.</param>
private static void Main(string[] args)
{
// Wait for the termination event
while (!TerminationRequestedEvent.WaitOne(0))
{
// Something to do while waiting
Console.WriteLine("Work");
}
// Sleep until termination
TerminationRequestedEvent.WaitOne();
// Print a message which represents the operation
Console.WriteLine("Cleanup");
// Set this to terminate immediately (if not set, the OS will
// eventually kill the process)
TerminationCompletedEvent.Set();
}
/// <summary>
/// Method called when the user presses Ctrl-C
/// </summary>
/// <param name="reason">The close reason</param>
private static bool OnConsoleCloseEvent(int reason)
{
// Signal termination
TerminationRequestedEvent.Set();
// Wait for cleanup
TerminationCompletedEvent.WaitOne();
// Don't run other handlers, just exit.
return true;
}
}
}
Notice that this doesn't work in Windows.
The module pxssh does exactly what you want:
For example, to run 'ls -l' and to print the output, you need to do something like that :
from pexpect import pxssh
s = pxssh.pxssh()
if not s.login ('localhost', 'myusername', 'mypassword'):
print "SSH session failed on login."
print str(s)
else:
print "SSH session login successful"
s.sendline ('ls -l')
s.prompt() # match the prompt
print s.before # print everything before the prompt.
s.logout()
Some links :
Pxssh docs : http://dsnra.jpl.nasa.gov/software/Python/site-packages/Contrib/pxssh.html
Pexpect (pxssh is based on pexpect) : http://pexpect.readthedocs.io/en/stable/
Assuming that your assembly/exe has FileIO permission is itself, well is not right. Your application may not run with admin rights. Its important to consider Code Access Security and requesting permissions Sample code:
FileIOPermission f2 = new FileIOPermission(FileIOPermissionAccess.Read, "C:\\test_r");
f2.AddPathList(FileIOPermissionAccess.Write | FileIOPermissionAccess.Read, "C:\\example\\out.txt");
try
{
f2.Demand();
}
catch (SecurityException s)
{
Console.WriteLine(s.Message);
}
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
I think the explanation of why exception is thrown is very clear with the answers provided here. I just wish to complement with the way I usually work with these collections. Because, some times, I use the collection more then once and have to test if null every time. To avoid that, I do the following:
var returnArray = DoSomething() ?? Enumerable.Empty<int>();
foreach (int i in returnArray)
{
// do some more stuff
}
This way we can use the collection as much as we want without fear the exception and we don't polute the code with excessive conditional statements.
Using the null check operator ?.
is also a great approach. But, in case of arrays (like the example in the question), it should be transformed into List before:
int[] returnArray = DoSomething();
returnArray?.ToList().ForEach((i) =>
{
// do some more stuff
});
You should use GlassFish for Java EE enterprise applications. Some things to consider:
A web Server means: Handling HTTP requests (usually from browsers).
A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.
An Application Server (e.g. GlassFish) means: *It can manage Java EE applications (usually both servlet/JSP and EJBs).
Tomcat - is run by Apache community - Open source and has two flavors:
No commercial support available (only community support)
JBoss - Run by RedHat This is a full-stack support for JavaEE and it is a certified Java EE container. This includes Tomcat as web container internally. This also has two flavors:
Glassfish - Run by Oracle This is also a full stack certified Java EE Container. This has its own web container (not Tomcat). This comes from Oracle itself, so all new specs will be tested and implemented with Glassfish first. So, always it would support the latest spec. I am not aware of its support models.
What worked for me:
Since yesterday, I have been trying to install the Eclipse plugin - "Remote System Explorer" from the Eclipse marketplace on a freshly downloaded Eclipse 4.8 as shown below,
and everytime I was getting this error:
Unable to read repository at http://download.eclipse.org/releases/kepler/. Unable to read repository at http://download.eclipse.org/releases/kepler/201306260900/content.jar. download.eclipse.org:80 failed to respond
which brought me to this SO post.
I tried a few solutions mentioned here in the different answers like this one and this one and this one, but none of them worked. I just gave up almost, thinking that either the corporate network here is somehow blocking the specific download requests or the 4.8 version of Eclipse is buggy.
Discovery:
I could not reload all the paths under 'Window' -> 'Preferences' -> 'Install/Update' -> 'Available Software Sites'
.
Preconditions:
What did work for me from the beginning was:
Finally, this answer put me on the right track - for my specific case, at least. Just my step was to do the exact opposite of what that answer was doing.
Solution:
I had to change all the http:\\
paths to https:\\
and suddenly it started to work. I don't know who - either IE/Edge on Windows 10 or the Windows 10 firewall or the company firewall is blocking HTTP communications. But with HTTPS, I can finally install plugins from the Marketplace.
I must say, what is strange is that not all the paths required https
. Except a few, the rest seemed to have had no problem working with HTTP
. But I anyways changed all to HTTPS
, just for good measure.
Note: In case during the update, this same error pops up again, then see in the repositories that any new paths added by eclipse during the update, are also HTTPS and not HTTP.
Rather than use multiple classes or class inheritance, perhaps a single Toy class that knows what "kind" it is:
class Toy:
num = 0
def __init__(self, name, kind, *args):
self.name = name
self.kind = kind
self.data = args
self.num = Toy.num
Toy.num += 1
def __repr__(self):
return ' '.join([self.name,self.kind,str(self.num)])
def playWith(self):
print self
def getNewToy(name, kind):
return Toy(name, kind)
t1 = Toy('Suzie', 'doll')
t2 = getNewToy('Jack', 'robot')
print t1
t2.playWith()
Running it:
$ python toy.py
Suzie doll 0
Jack robot 1
As you can see, getNewToy
is really unnecessary. Now you can modify playWith
to check the value of self.kind
and change behavior, you can redefine playWith
to designate a playmate:
def playWith(self, who=None):
if who: pass
print self
t1.playWith(t2)
value = value.setScale(2, RoundingMode.CEILING)
int array[ROW][COLUMN]={1};
This initialises only the first element to 1. Everything else gets a 0.
In the first instance, you're doing the same - initialising the first element to 0, and the rest defaults to 0.
The reason is straightforward: for an array, the compiler will initialise every value you don't specify with 0.
With a char
array you could use memset
to set every byte, but this will not generally work with an int
array (though it's fine for 0).
A general for
loop will do this quickly:
for (int i = 0; i < ROW; i++)
for (int j = 0; j < COLUMN; j++)
array[i][j] = 1;
Or possibly quicker (depending on the compiler)
for (int i = 0; i < ROW*COLUMN; i++)
*((int*)a + i) = 1;
Try this
AppDomain.CurrentDomain.SetupInformation.ConfigurationFile
For the replacement string and the replacement pattern as specified by $
.
here a resume:
link to doc : here
"hello _there_".replace(/_(.*?)_/g, "<div>$1</div>")
Note:
If you want to have a $
in the replacement string use $$
. Same as with vscode snippet system.
These steps worked for me in iOS 10.
Another variant:
List<MyType> items = new List<MyType>();
items.AddRange(myDico.values);
Defining an object in Scala is like defining a class in Java that has only static methods. However, in Scala an object can extend another superclass, implement interfaces, and be passed around as though it were an instance of a class. (So it's like the static methods on a class but better).
I assume you are using windows. Open the command prompt and type ipconfig
and find out your local address (on your pc) it should look something like 192.168.1.13
or 192.168.0.5
where the end digit is the one that changes. It should be next to IPv4 Address.
If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13
If you have a virtual host then you will need root to edit the hosts file.
If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.
See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.
Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).
If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow
to allow,deny
in the httpd.conf
file. You can access this by the WAMP menu.
To eliminate possible causes of the issue for now set your config file to
<Directory />
Options FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
<RequireAll>
Require all granted
</RequireAll>
</Directory>
As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.
Config file that fixed the problem:
https://gist.github.com/samvaughton/6790739
Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.
For Swift:
AVPlayer:
let player = AVPlayer(URL: NSURL(string: "http://www.sample.com/movie.mov"))
if (player.rate != 0 && player.error == nil) {
println("playing")
}
Update:
player.rate > 0
condition changed to player.rate != 0
because if video is playing in reverse it can be negative thanks to Julian for pointing out.
Note: This might look same as above(Maz's) answer but in Swift '!player.error' was giving me a compiler error so you have to check for error using 'player.error == nil' in Swift.(because error property is not of 'Bool' type)
AVAudioPlayer:
if let theAudioPlayer = appDelegate.audioPlayer {
if (theAudioPlayer.playing) {
// playing
}
}
AVQueuePlayer:
if let theAudioQueuePlayer = appDelegate.audioPlayerQueue {
if (theAudioQueuePlayer.rate != 0 && theAudioQueuePlayer.error == nil) {
// playing
}
}
Png files can handle transparency.
So you could use this question Save plot to image file instead of displaying it using Matplotlib so as to save you graph as a png
file.
And if you want to turn all white pixel transparent, there's this other question : Using PIL to make all white pixels transparent?
If you want to turn an entire area to transparent, then there's this question: And then use the PIL library like in this question Python PIL: how to make area transparent in PNG? so as to make your graph transparent.
In newer browser (excluding IE11), a simple solution to prevent parent-child margin collapsing is to use display: flow-root
. However, you would still need other techniques to prevent adjacent element collapsing.
DEMO (before)
.parent {_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
DEMO (after)
.parent {_x000D_
display: flow-root;_x000D_
background-color: grey;_x000D_
}_x000D_
_x000D_
.child {_x000D_
height: 16px;_x000D_
margin-top: 16px;_x000D_
margin-bottom: 16px;_x000D_
background-color: blue;_x000D_
}
_x000D_
<div class="parent">_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
<div class="child"></div>_x000D_
</div>
_x000D_
I needed a progress bar that would fit in popup bubble message (notify-send
) to represent TV volume level. Recently I've been writing a music player in python and the TV picture is turned off most of the time.
#!/bin/bash
# Show a progress bar at step number $1 (from 0 to 100)
function is_int() { test "$@" -eq "$@" 2> /dev/null; }
# Parameter 1 must be integer
if ! is_int "$1" ; then
echo "Not an integer: ${1}"
exit 1
fi
# Parameter 1 must be >= 0 and <= 100
if [ "$1" -ge 0 ] && [ "$1" -le 100 ] 2>/dev/null
then
:
else
echo bad volume: ${1}
exit 1
fi
# Main function designed for quickly copying to another program
Main () {
Bar="" # Progress Bar / Volume level
Len=25 # Length of Progress Bar / Volume level
Div=4 # Divisor into Volume for # of blocks
Fill="¦" # Fill up to $Len
Arr=( "?" "?" "¦" "?" ) # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4
FullBlock=$((${1} / Div)) # Number of full blocks
PartBlock=$((${1} % Div)) # Size of partial block (array index)
while [[ $FullBlock -gt 0 ]]; do
Bar="$Bar${Arr[0]}" # Add 1 full block into Progress Bar
(( FullBlock-- )) # Decrement full blocks counter
done
# If remainder zero no partial block, else append character from array
if [[ $PartBlock -gt 0 ]]; then
Bar="$Bar${Arr[$PartBlock]}"
fi
while [[ "${#Bar}" -lt "$Len" ]]; do
Bar="$Bar$Fill" # Pad Progress Bar with fill character
done
echo Volume: "$1 $Bar"
exit 0 # Remove this line when copying into program
} # Main
Main "$@"
Use this script to test the progress bar in the terminal.
#!/bin/bash
# test_progress_bar3
Main () {
tput civis # Turn off cursor
for ((i=0; i<=100; i++)); do
CurrLevel=$(./progress_bar3 "$i") # Generate progress bar 0 to 100
echo -ne "$CurrLevel"\\r # Reprint overtop same line
sleep .04
done
echo -e \\n # Advance line to keep last progress
echo "$0 Done"
tput cnorm # Turn cursor back on
} # Main
Main "$@"
This section details how notify-send
is used to quickly spam popup bubble messages to the desktop. This is required because volume level can change many times a second and the default bubble message behavior is for a message to stay on the desktop for many seconds.
From the script above the main
function was copied to a new functioned called VolumeBar
in an existing bash script called tvpowered
. The exit 0
command in the copied main
function was removed.
Here's how to call it and let Ubuntu's notify-send
command know we will be spamming popup bubble message:
VolumeBar $CurrVolume
# Ask Ubuntu: https://askubuntu.com/a/871207/307523
notify-send --urgency=critical "tvpowered" \
-h string:x-canonical-private-synchronous:volume \
--icon=/usr/share/icons/gnome/48x48/devices/audio-speakers.png \
"Volume: $CurrVolume $Bar"
This is the new line which tells notify-send
to immediately replace last popup bubble:
-h string:x-canonical-private-synchronous:volume \
volume
groups the popup bubble messages together and new messages in this group immediately replaces the previous. You can use anything
instead of volume
.
Do you merely want to print the string that way, or do you want that to be the internal representation of the string? If the latter, create it as a raw string by prefixing it with r
: r"Hello\tWorld\nHello World"
.
>>> a = r"Hello\tWorld\nHello World"
>>> a # in the interpreter, this calls repr()
'Hello\\tWorld\\nHello World'
>>> print a
Hello\tWorld\nHello World
Also, \s
is not an escape character, except in regular expressions, and then it still has a much different meaning than what you're using it for.
Foreign keys do not create indexes. Only alternate key constraints(UNIQUE) and primary key constraints create indexes. This is true in Oracle and SQL Server.
Even though @Ignacio gave you a straightforward solution, I thought I might add an answer that gives you some more details about the issues with your code...
# You are not saving this result into a variable to reuse
os.path.join(src_dir, f)
# Should be
src_path = os.path.join(src_dir, f)
# you open the file but you dont again use a variable to reference
with open(f)
# should be
with open(src_path) as fh
# this is actually just looping over each character
# in each result of your os.listdir
for line in f
# you should loop over lines in the open file handle
for line in fh
# write? Is this a method you wrote because its not a python builtin function
write(line)
# write to the file
fh.write(line)
I had the same issue, and I uncomment extension=pdo_sqlite
and ran the migration
and everything worked fine.
According to the GCC page for C++11:
To enable C++0x support, add the command-line parameter -std=c++0x to your g++ command line. Or, to enable GNU extensions in addition to C++0x extensions, add -std=gnu++0x to your g++ command line. GCC 4.7 and later support -std=c++11 and -std=gnu++11 as well.
Did you compile with -std=gnu++0x
?
Despite of supported API from .Net frameworks regarding checking existing process by process ID, those functions are very slow. It costs a huge amount of CPU cycles to run Process.GetProcesses() or Process.GetProcessById/Name().
A much quicker method to check a running process by ID is to use native API OpenProcess(). If return handle is 0, the process doesn't exist. If handle is different than 0, the process is running. There's no guarantee this method would work 100% at all time due to permission.
You could use getNetworkCountryIso()
from TelephonyManager
to get the country the phone is currently in (although apparently this is unreliable on CDMA networks).
If it is possible in your case, you could make your methods method1(arg1)
... method7()
protected instead of private so they could be accesible from test class within the same package. Then you can simply test all theese methods separately.
You can safely delete the table manually or using query. It will be recreated automatically.
DROP TABLE DATABASECHANGELOGLOCK;
Do it with
toolbar.setTitleTextAppearance(context, R.style.TitleTextStyle);
//this is style where you can customize your color scheme
<style name="TitleTextStyle" parent="@android:style/TextAppearance.Holo.Widget.ActionBar.Title">
<item name="android:fontFamily">@string/you_font_family</item>
<item name="android:textStyle">normal</item>
<item name="android:textAppearance">@style/you_text_style</item>
<item name="android:textColor">#000000</item>
<item name="android:textSize">20sp</item>
</style>
In Bootstrap 4 there is the utility class border-right
which you can use.
So for example you can do:
<div class="row">
<div class="col-6 border-right"></div>
<div class="col-6"></div>
</div>
try this code
Intent photo= new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(photo, CAMERA_PIC_REQUEST);
sys.maxint is not the largest integer supported by python. It's the largest integer supported by python's regular integer type.
Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build. Let me know your results with it. Everything executes fine on this end in Safari, FF, Opera on OSX. It is exclusively for fixing a problematic IE8 bug, and may have unintended results:
function ie8SafePreventEvent(e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.stop()
};
e.returnValue = false;
e.stopPropagation();
}
Usage:
$('a').click(function (e) {
// Execute code here
ie8SafePreventEvent(e);
return false;
})
You need to alias the subquery.
SELECT name FROM (SELECT name FROM agentinformation) a
or to be more explicit
SELECT a.name FROM (SELECT name FROM agentinformation) a
Update: you can read the more complex answer, which contains more methods and information.
There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).
The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.
It has also command line mode. Moreover it allows you to upgrade all installed packages at once.
setup.exe-x86_64.exe -q --packages=bash,vim
Example use:
setup.exe-x86_64.exe -q --packages="bash,vim"
You can create an alias for easier use, for example:
alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"
Then you can for example install the Vim package with:
cyg-get vim
While the accepted and most upvoted answer is great, I additionally find it useful trying to explain the difference only by words:
merge
rebase
summary: When possible, rebase is almost always better. Making re-integration into the main branch easier.
Because? ? your feature work can be presented as one big ‘patch file’ (aka diff) in respect to the main branch, not having to ‘explain’ multiple parents: At least two, coming from one merge, but likely many more, if there were several merges. Unlike merges, multiple rebases do not add up. (another big plus)
You can load multiple scripts dynamically like this in your component.ts
file:
loadScripts() {
const dynamicScripts = [
'https://platform.twitter.com/widgets.js',
'../../../assets/js/dummyjs.min.js'
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
node.charset = 'utf-8';
document.getElementsByTagName('head')[0].appendChild(node);
}
}
and call this method inside the constructor,
constructor() {
this.loadScripts();
}
Note : For more scripts to be loaded dynamically, add them to dynamicScripts
array.
Use:
+ scale_y_continuous(labels = scales::percent)
Or, to specify formatting parameters for the percent:
+ scale_y_continuous(labels = scales::percent_format(accuracy = 1))
(the command labels = percent
is obsolete since version 2.2.1 of ggplot2)
Login in with System Admin User Account and execute below SQL Procedure.
begin
dbms_xdb.sethttpport('Your Port Number');
end;
Then open the Browser and access the below URL
Chrome Developer Tools has an Audits tab which can show unused CSS selectors.
Run an audit, then, under Web Page Performance see Remove unused CSS rules
If you are using IIS 7.5 or later you can generate the machine key from IIS and save it directly to your web.config, within the web farm you then just copy the new web.config to each server.
web.config
file of your application.web.config
file.Full Details can be seen @ Easiest way to generate MachineKey – Tips and tricks: ASP.NET, IIS and .NET development…
Abstract your initialization into a method, and call the method from mounted
and wherever else you want.
new Vue({
methods:{
init(){
//call API
//Setup game
}
},
mounted(){
this.init()
}
})
Then possibly have a button in your template to start over.
<button v-if="playerWon" @click="init">Play Again</button>
In this button, playerWon
represents a boolean value in your data that you would set when the player wins the game so the button appears. You would set it back to false in init
.
the easiest way in python 3.x
text = "hi , I'm text"
text.encode('utf-8')
I was having some difficulty translating actual VB.NET to the Expression subset that SSRS uses. You definitely inspired me though and this is what I came up with.
StartDate
=dateadd("d",0,dateserial(year(dateadd("d",-1,dateserial(year(Today),month(Today),1))),month(dateadd("d",-1,dateserial(year(Today),month(Today),1))),1))
End Date
=dateadd("d",0,dateserial(year(Today),month(Today),1))
I know it's a bit recursive for the StartDate (first day of last month). Is there anything I'm missing here? These are strictly date fields (i.e. no time), but I think this should capture leap year, etc.
How did I do?
Use putty. Put install directory path in environment values (PATH), and restart your PC if required.
Open cmd (command prompt) and type
C:/> pscp "C:\Users/gsjha/Desktop/example.txt" user@host:/home/
It'll be copied to the system.
Using @joran's sample data,
ggplot(dat, aes(x=xx, fill=yy)) + geom_histogram(alpha=0.2, position="identity")
note that the default position of geom_histogram
is "stack."
see "position adjustment" of this page:
Otherwise... if
getenforce
returns
Enforcing
Then maybe you should call
setenforce 0
mount -o rw,remount /system
setenforce 1
There are multiple remote linux machines, and I need to write a shell script which will execute the same set of commands in each machine. (Including some sudo operations). How can this be done using shell scripting?
You can do this with ssh, for example:
#!/bin/bash
USERNAME=someUser
HOSTS="host1 host2 host3"
SCRIPT="pwd; ls"
for HOSTNAME in ${HOSTS} ; do
ssh -l ${USERNAME} ${HOSTNAME} "${SCRIPT}"
done
When ssh'ing to the remote machine, how to handle when it prompts for RSA fingerprint authentication.
You can add the StrictHostKeyChecking=no
option to ssh:
ssh -o StrictHostKeyChecking=no -l username hostname "pwd; ls"
This will disable the host key check and automatically add the host key to the list of known hosts. If you do not want to have the host added to the known hosts file, add the option -o UserKnownHostsFile=/dev/null
.
Note that this disables certain security checks, for example protection against man-in-the-middle attack. It should therefore not be applied in a security sensitive environment.
Flying Saucer xhtmlrenderer repeats the THEAD on every page of PDF output, if you add the following to your CSS:
table {
-fs-table-paginate: paginate;
}
(It works at least since the R8 release.)
Following on from LAXIT KUMAR's recommendation, we've found that at times the registry URL can get corrupted, not sure how this is happening, however to cure, just reset it:
npm config set registry https://registry.npmjs.org
The 404 disappeared as it was going to the correct location again.
See the (quite) recent answer on the matplotlib repository, in which the following solution is suggested:
If you want to set the xticklabels:
ax.set_xticks([1,4,5])
ax.set_xticklabels([1,4,5], fontsize=12)
If you want to only increase the fontsize of the xticklabels, using the default values and locations (which is something I personally often need and find very handy):
ax.tick_params(axis="x", labelsize=12)
To do it all at once:
plt.setp(ax.get_xticklabels(), fontsize=12, fontweight="bold",
horizontalalignment="left")`
I solved the issue by Changing the port no. in adrs-instances.xml file:
\JDEV_USER_HOME\system11.1.1.3.37.56.60\o.j2ee\adrs-instances.xml
I suggest you use http-request, so that even redirects are managed.
var http = require('http-request');
var options = {url: 'http://localhost/foo.pdf'};
http.get(options, '/path/to/foo.pdf', function (error, result) {
if (error) {
console.error(error);
} else {
console.log('File downloaded at: ' + result.file);
}
});
Using filter_var() will fail for urls with non-ascii chars, e.g. (http://pt.wikipedia.org/wiki/Guimarães). The following function encode all non-ascii chars (e.g. http://pt.wikipedia.org/wiki/Guimar%C3%A3es) before calling filter_var().
Hope this helps someone.
<?php
function validate_url($url) {
$path = parse_url($url, PHP_URL_PATH);
$encoded_path = array_map('urlencode', explode('/', $path));
$url = str_replace($path, implode('/', $encoded_path), $url);
return filter_var($url, FILTER_VALIDATE_URL) ? true : false;
}
// example
if(!validate_url("http://somedomain.com/some/path/file1.jpg")) {
echo "NOT A URL";
}
else {
echo "IS A URL";
}
The first problem encountered with your code is the message
Local variable OrdersPerHour might not be initialized before accessing.
It happens because in the case where your database query would throw an exception, the value might not be set to something (you have an empty catch clause).
To fix this, set the value to what you'd want to have if the query fails, which is probably 0
:
int? OrdersPerHour = 0;
Once this is fixed, now there's the error you're posting about. This happens because your method signature declares you are returning an int
, but you are in fact returning a nullable int, int?
, variable.
So to get the int
part of your int?
, you can use the .Value
property:
return OrdersPerHour.Value;
However, if you declared your OrdersPerHour to be null
at start instead of 0
, the value can be null so a proper validation before returning is probably needed (Throw a more specific exception, for example).
To do so, you can use the HasValue
property to be sure you're having a value before returning it:
if (OrdersPerHour.HasValue){
return OrdersPerHour.Value;
}
else{
// Handle the case here
}
As a side note, since you're coding in C# it would be better if you followed C#'s conventions. Your parameter and variables should be in camelCase, not PascalCase. So User
and OrdersPerHour
would be user
and ordersPerHour
.
Note for the answer-seekers (who I also was) - if using arc is not obligatory, a far simpler solution to draw a part-circle is to use stroke-dasharray
of SVG <circle>
.
Divide dash array into two elements, and scale their range to the desired angle. Starting angle can be adjusted using stroke-dashoffset
.
Not a single cosine in sight.
Full example with explanations: https://codepen.io/mjurczyk/pen/wvBKOvP
If you want to add it directly in the toolbar.
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.AppBarLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/app_bar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<SearchView
android:id="@+id/searchView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:iconifiedByDefault="false"
android:queryHint="Search"
android:layout_centerHorizontal="true" />
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
You should really make a difference between:
There are many scenarios where those 2 values are mismatching such as:
In most cases you would want to use the interface orientation and you can get it via the window:
private var windowInterfaceOrientation: UIInterfaceOrientation? {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
}
In case you also want to support < iOS 13 (such as iOS 12) you would do the following:
private var windowInterfaceOrientation: UIInterfaceOrientation? {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
} else {
return UIApplication.shared.statusBarOrientation
}
}
Now you need to define where to react to the window interface orientation change. There are multiple ways to do that but the optimal solution is to do it within
willTransition(to newCollection: UITraitCollection
.
This inherited UIViewController method which can be overridden will be trigger every time the interface orientation will be change. Consequently you can do all your modifications in the latter.
Here is a solution example:
class ViewController: UIViewController {
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
guard let windowInterfaceOrientation = self.windowInterfaceOrientation else { return }
if windowInterfaceOrientation.isLandscape {
// activate landscape changes
} else {
// activate portrait changes
}
})
}
private var windowInterfaceOrientation: UIInterfaceOrientation? {
return UIApplication.shared.windows.first?.windowScene?.interfaceOrientation
}
}
By implementing this method you'll then be able to react to any change of orientation to your interface. But keep in mind that it won't be triggered at the opening of the app so you will also have to manually update your interface in viewWillAppear()
.
I've created a sample project which underlines the difference between device orientation and interface orientation. Additionally it will help you to understand the different behavior depending on which lifecycle step you decide to update your UI.
Feel free to clone and run the following repository: https://github.com/wjosset/ReactToOrientation
Just for completeness: You can pass slice
a vector of indices:
df %>% arrange(stopSequence) %>% group_by(id) %>% slice(c(1,n()))
which gives
id stopId stopSequence
1 1 a 1
2 1 c 3
3 2 b 1
4 2 c 4
5 3 b 1
6 3 a 3
On Linux, the symlink /proc/<pid>/exe
has the path of the executable. Use the command readlink -f /proc/<pid>/exe
to get the value.
On AIX, this file does not exist. You could compare cksum <actual path to binary>
and cksum /proc/<pid>/object/a.out
.
This is what I did and it works so far in a MVC 5 application.
Controller's return type is ContentResult.
public ContentResult DoSomething()
{
if(somethingIsTrue)
{
Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
Response.Write("My Message");
return new ContentResult();
}
//Do something in here//
string json = "whatever json goes here";
return new ContentResult{Content = json, ContentType = "application/json"};
}
And on client side this is what ajax function looks like
$.ajax({
type: "POST",
url: URL,
data: DATA,
dataType: "json",
success: function (json) {
//Do something with the returned json object.
},
error: function (xhr, status, errorThrown) {
//Here the status code can be retrieved like;
xhr.status;
//The message added to Response object in Controller can be retrieved as following.
xhr.responseText;
}
});
You can use the datetime module
import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')
Note that:
I am using replace
since the colons are not allowed in filenames in many operating systems.
That's it, this will give you a unique filename every single time.
How about just Dir.mkdir('dir') rescue nil
?
Native methods allow you to use code from other languages such as C or C++ in your java code. You use them when java doesn't provide the functionality that you need. For example, if I were writing a program to calculate some equation and create a line graph of it, I would use java, because it is the language I am best in. However, I am also proficient in C. Say in part of my program I need to calculate a really complex equation. I would use a native method for this, because I know some C++ and I know that C++ is much faster than java, so if I wrote my method in C++ it would be quicker. Also, say I want to interact with another program or device. This would also use a native method, because C++ has something called pointers, which would let me do that.
If your static variables need to be set at runtime then a static {...}
block is very helpful.
For example, if you need to set the static member to a value which is stored in a config file or database.
Also useful when you want to add values to a static Map
member as you can't add these values in the initial member declaration.
This is the way I've been doing this sort of stuff. Angular tends to favor declarative manipulation of the dom rather than a imperative one(at least that's the way I've been playing with it).
The markup
<table class="table">
<thead>
<tr>
<th>
<input type="checkbox"
ng-click="selectAll($event)"
ng-checked="isSelectedAll()">
</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="e in entities" ng-class="getSelectedClass(e)">
<td>
<input type="checkbox" name="selected"
ng-checked="isSelected(e.id)"
ng-click="updateSelection($event, e.id)">
</td>
<td>{{e.title}}</td>
</tr>
</tbody>
</table>
And in the controller
var updateSelected = function(action, id) {
if (action === 'add' && $scope.selected.indexOf(id) === -1) {
$scope.selected.push(id);
}
if (action === 'remove' && $scope.selected.indexOf(id) !== -1) {
$scope.selected.splice($scope.selected.indexOf(id), 1);
}
};
$scope.updateSelection = function($event, id) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
updateSelected(action, id);
};
$scope.selectAll = function($event) {
var checkbox = $event.target;
var action = (checkbox.checked ? 'add' : 'remove');
for ( var i = 0; i < $scope.entities.length; i++) {
var entity = $scope.entities[i];
updateSelected(action, entity.id);
}
};
$scope.getSelectedClass = function(entity) {
return $scope.isSelected(entity.id) ? 'selected' : '';
};
$scope.isSelected = function(id) {
return $scope.selected.indexOf(id) >= 0;
};
//something extra I couldn't resist adding :)
$scope.isSelectedAll = function() {
return $scope.selected.length === $scope.entities.length;
};
EDIT: getSelectedClass()
expects the entire entity but it was being called with the id of the entity only, which is now corrected
System.Windows.Forms.Control.MousePosition
Gets the position of the mouse cursor in screen coordinates. "The Position property is identical to the Control.MousePosition property."
Wikipedia explains it better then I could
From the article - Top is 1st Tier:
Use return
operator:
function FUNCT {
if [ blah is false ]; then
return 1 # or return 0, or even you can omit the argument.
else
keep running the function
fi
}
There is a visual studio plugin to support the java language: http://visualstudiogallery.msdn.microsoft.com/bc561769-36ff-4a40-9504-e266e8706f93
Below code works fine before 18 API :-
public String getRealPathFromURI(Uri contentUri) {
// can post image
String [] proj={MediaStore.Images.Media.DATA};
Cursor cursor = managedQuery( contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
below code use on kitkat :-
public static String getPath(final Context context, final Uri uri) {
final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
// DocumentProvider
if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
// ExternalStorageProvider
if (isExternalStorageDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
if ("primary".equalsIgnoreCase(type)) {
return Environment.getExternalStorageDirectory() + "/" + split[1];
}
// TODO handle non-primary volumes
}
// DownloadsProvider
else if (isDownloadsDocument(uri)) {
final String id = DocumentsContract.getDocumentId(uri);
final Uri contentUri = ContentUris.withAppendedId(
Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
return getDataColumn(context, contentUri, null, null);
}
// MediaProvider
else if (isMediaDocument(uri)) {
final String docId = DocumentsContract.getDocumentId(uri);
final String[] split = docId.split(":");
final String type = split[0];
Uri contentUri = null;
if ("image".equals(type)) {
contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
} else if ("video".equals(type)) {
contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
} else if ("audio".equals(type)) {
contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
}
final String selection = "_id=?";
final String[] selectionArgs = new String[] {
split[1]
};
return getDataColumn(context, contentUri, selection, selectionArgs);
}
}
// MediaStore (and general)
else if ("content".equalsIgnoreCase(uri.getScheme())) {
return getDataColumn(context, uri, null, null);
}
// File
else if ("file".equalsIgnoreCase(uri.getScheme())) {
return uri.getPath();
}
return null;
}
/**
* Get the value of the data column for this Uri. This is useful for
* MediaStore Uris, and other file-based ContentProviders.
*
* @param context The context.
* @param uri The Uri to query.
* @param selection (Optional) Filter used in the query.
* @param selectionArgs (Optional) Selection arguments used in the query.
* @return The value of the _data column, which is typically a file path.
*/
public static String getDataColumn(Context context, Uri uri, String selection,
String[] selectionArgs) {
Cursor cursor = null;
final String column = "_data";
final String[] projection = {
column
};
try {
cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
null);
if (cursor != null && cursor.moveToFirst()) {
final int column_index = cursor.getColumnIndexOrThrow(column);
return cursor.getString(column_index);
}
} finally {
if (cursor != null)
cursor.close();
}
return null;
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is ExternalStorageProvider.
*/
public static boolean isExternalStorageDocument(Uri uri) {
return "com.android.externalstorage.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is DownloadsProvider.
*/
public static boolean isDownloadsDocument(Uri uri) {
return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}
/**
* @param uri The Uri to check.
* @return Whether the Uri authority is MediaProvider.
*/
public static boolean isMediaDocument(Uri uri) {
return "com.android.providers.media.documents".equals(uri.getAuthority());
}
see below link for more info:-
If you still can't access the management console after a fresh install, check if the management console was enabled. To enable it:
Go to the RabbitMQ command prompt.
Type:
rabbitmq-plugins enable rabbitmq_management
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
Easiest option:
<script type="text/javascript">
function frameload(){
alert("iframe loaded")
}
</script>
<iframe onload="frameload()" src=...>
JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage
var obj = {"nissan": "sentra", "color": "green"};
localStorage.setItem('myStorage', JSON.stringify(obj));
And to retrieve the object later
var obj = JSON.parse(localStorage.getItem('myStorage'));
I do not think any of these answers are flexible enough for a large enterprise level application. I'm not a fan of overusing the ViewBag, but in this case, for flexibility, I'd make an exception. Here's what I'd do...
You should have a base controller on all of your controllers. Add your Layout data OnActionExecuting in your base controller (or OnActionExecuted if you want to defer that)...
public class BaseController : Controller
{
protected override void OnActionExecuting(ActionExecutingContext
filterContext)
{
ViewBag.LayoutViewModel = MyLayoutViewModel;
}
}
public class HomeController : BaseController
{
public ActionResult Index()
{
return View(homeModel);
}
}
Then in your _Layout.cshtml pull your ViewModel from the ViewBag...
@{
LayoutViewModel model = (LayoutViewModel)ViewBag.LayoutViewModel;
}
<h1>@model.Title</h1>
Or...
<h1>@ViewBag.LayoutViewModel.Title</h1>
Doing this doesn't interfere with the coding for your page's controllers or view models.
Use java reflection
Creating New Objects There is no equivalent to method invocation for constructors, because invoking a constructor is equivalent to creating a new object (to be the most precise, creating a new object involves both memory allocation and object construction). So the nearest equivalent to the previous example is to say:
import java.lang.reflect.*;
public class constructor2 {
public constructor2()
{
}
public constructor2(int a, int b)
{
System.out.println(
"a = " + a + " b = " + b);
}
public static void main(String args[])
{
try {
Class cls = Class.forName("constructor2");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Constructor ct
= cls.getConstructor(partypes);
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = ct.newInstance(arglist);
}
catch (Throwable e) {
System.err.println(e);
}
}
}
which finds a constructor that handles the specified parameter types and invokes it, to create a new instance of the object. The value of this approach is that it's purely dynamic, with constructor lookup and invocation at execution time, rather than at compilation time.
print "Number of lines: $nids\n";
print "Content: $ids\n";
How did Perl complain? print $ids
should work, though you probably want a newline at the end, either explicitly with print
as above or implicitly by using say
or -l/$\.
If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}
:
print "foo${ids}bar";
Here are two functions to calculate distance and bearing, which are based on the code in previous messages and https://gist.github.com/jeromer/2005586 (added tuple type for geographical points in lat, lon format for both functions for clarity). I tested both functions and they seem to work right.
#coding:UTF-8
from math import radians, cos, sin, asin, sqrt, atan2, degrees
def haversine(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = pointA[0]
lon1 = pointA[1]
lat2 = pointB[0]
lon2 = pointB[1]
# convert decimal degrees to radians
lat1, lon1, lat2, lon2 = map(radians, [lat1, lon1, lat2, lon2])
# haversine formula
dlon = lon2 - lon1
dlat = lat2 - lat1
a = sin(dlat/2)**2 + cos(lat1) * cos(lat2) * sin(dlon/2)**2
c = 2 * asin(sqrt(a))
r = 6371 # Radius of earth in kilometers. Use 3956 for miles
return c * r
def initial_bearing(pointA, pointB):
if (type(pointA) != tuple) or (type(pointB) != tuple):
raise TypeError("Only tuples are supported as arguments")
lat1 = radians(pointA[0])
lat2 = radians(pointB[0])
diffLong = radians(pointB[1] - pointA[1])
x = sin(diffLong) * cos(lat2)
y = cos(lat1) * sin(lat2) - (sin(lat1)
* cos(lat2) * cos(diffLong))
initial_bearing = atan2(x, y)
# Now we have the initial bearing but math.atan2 return values
# from -180° to + 180° which is not what we want for a compass bearing
# The solution is to normalize the initial bearing as shown below
initial_bearing = degrees(initial_bearing)
compass_bearing = (initial_bearing + 360) % 360
return compass_bearing
pA = (46.2038,6.1530)
pB = (46.449, 30.690)
print haversine(pA, pB)
print initial_bearing(pA, pB)
There are several tools for converting Matlab to Python code.
The only one that's seen recent activity (last commit from June 2018) is Small Matlab to Python compiler (also developed here: SMOP@chiselapp).
Other options include:
Also, for those interested in an interface between the two languages and not conversion:
pymatlab
: communicate from Python by sending data to the MATLAB workspace, operating on them with scripts and pulling back the resulting data.pymat2
: continuation of the seemingly abandoned PyMat.mlabwrap
, mlabwrap-purepy: make Matlab look like Python library (based on PyMat).oct2py
: run GNU Octave commands from within Python.pymex
: Embeds the Python Interpreter in Matlab, also on File Exchange.matpy
: Access MATLAB in various ways: create variables, access .mat files, direct interface to MATLAB engine (requires MATLAB be installed).Btw might be helpful to look here for other migration tips:
On a different note, though I'm not a fortran
fan at all, for people who might find it useful there is:
You must use an aggregate function on the columns against which you are not grouping. In this example, I arbitrarily picked the Min function. You are combining the rows with the same FruitType
value. If I have two rows with the same FruitType
value but different Fruit_Id
values for example, what should the system do?
Select Min(tblFruit_id) As tblFruit_id
, tblFruit_FruitType
From tblFruit
Group By tblFruit_FruitType
In your User
model, add the following line in the User
class:
public $timestamps = true;
Now, whenever you save or update a user, Laravel will automatically update the created_at
and updated_at
fields.
Update:
If you want to set the created at manually you should use the date format Y-m-d H:i:s
. The problem is that the format you have used is not the same as Laravel uses for the created_at
field.
Update: Nov 2018 Laravel 5.6
"message": "Access level to App\\Note::$timestamps must be public",
Make sure you have the proper access level as well. Laravel 5.6 is public
.
Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.
tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
exit 0
I had a git conflict left in my workspace.xml i.e.
<<<<———————HEAD
which caused the unknown tag error. It is a bit annoying that it doesn’t name the file.
You can use the latest version of the jQuery library by any of the following.
Google Ajax API CDN (also supports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2"></script>
/jquery.min.js
Microsoft CDN (also aupports SSL via HTTPS)
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.min.js"></script>
Ajax CDN Announcement, Microsoft Ajax CDN Documentation
jQuery CDN (via Media Temple)
<script type="text/javascript" src=" http://code.jquery.com/jquery-1.7.2.min.js"></script>
** Minified version
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.js"></script>
** Development (Full) version
In my case same error is there , I am using Asyanc / Await functions , for this needs to add AWAIT for findOne
Ex:const foundUser = User.findOne ({ "email" : req.body.email });
above , foundUser always contains Object value in both cases either user found or not because it's returning values before finishing findOne .
const foundUser = await User.findOne ({ "email" : req.body.email });
above , foundUser returns null if user is not there in collection with provided condition . If user found returns user document.
For Developer certificate, you need to create a developer .mobileprovision profile and install add it to your XCode. In case you want to distribute the app using an adhoc distribution profile you will require AdHoc Distribution certificate and private key installed in your keychain.
If you have not created the cert, here are steps to create it. Incase it has already been created by someone in your team, ask him to share the cert and private key. If that someone is no longer in your team then you can revoke the cert from developer account and create new.
If you're using MVC 3 and Razor you can also use the following:
@Html.RadioButtonFor(model => model.blah, true) Yes
@Html.RadioButtonFor(model => model.blah, false) No
In 2020 for TextField, via functional components:
const Content = () => {
...
const textFieldRef = useRef();
const readTextFieldValue = () => {
console.log(textFieldRef.current.value)
}
...
return(
...
<TextField
id="myTextField"
label="Text Field"
variant="outlined"
inputRef={textFieldRef}
/>
...
)
}
Note that this isn't complete code.
How about making the <div id="mainWrapperDivWithBGImage">
as three divs, where the two outside divs hold the rounded corners images, and the middle div simply has a background-color to match the rounded corner images. Then you could simply place the other elements inside the middle div, or:
#outside_left{width:10px; float:left;}
#outside_right{width:10px; float:right;}
#middle{background-color:#color of rnd_crnrs_foo.gif; float:left;}
Then
HTML:
<div id="mainWrapperDivWithBGImage">
<div id="outside_left><img src="rnd_crnrs_left.gif" /></div>
<div id="middle">
<div id="another_div"><img src="foo.gif" /></div>
<div id="outside_right><img src="rnd_crnrs_right.gif" /></div>
</div>
You may have to do position:relative; and such.
According to the below source you should do the follwong:
Go to the installation folder "C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE", find the executable file(If your VS express 2013 is VS express 2013 for web, the executable file is VWDExpress.exe).
Right-click the file, select the tab "compatibility". Disable all compatibility settings over here
So , please try to disable any component 'compatibility' settings (turning off the compatibility service is not enough in that case).
In addition, can you upload the installing log?
To do this, follow these steps:
OK,
One of the more difficult concepts to grasp about Excel VSTO programming is that you don't refer to cells like an array, Worksheet[0][0]
won't give you cell A1, it will error out on you. Even when you type into A1 when Excel is open, you are actually entering data into Range A1. Therefore you refer to cells as Named Ranges. Here's an example:
Excel.Worksheet sheet = workbook.Sheets["Sheet1"] as Excel.Worksheet;
Excel.Range range = sheet.get_Range("A1", Missing.Value)
You can now literally type:
range.Text // this will give you the text the user sees
range.Value2 // this will give you the actual value stored by Excel (without rounding)
If you want to do something like this:
Excel.Range range = sheet.get_Range("A1:A5", Missing.Value)
if (range1 != null)
foreach (Excel.Range r in range1)
{
string user = r.Text
string value = r.Value2
}
There might be a better way, but this has worked for me.
The reason you need to use Value2
and not Value
is because the Value
property is a parametrized and C# doesn't support them yet.
As for the cleanup code, i will post that when i get to work tomorrow, i don't have the code with me, but it's very boilerplate. You just close and release the objects in the reverse order you created them. You can't use a Using()
block because the Excel.Application or Excel.Workbook doesn't implement IDisposable
, and if you don't clean-up, you will be left with a hanging Excel objects in memory.
Note:
Visibility
property Excel doesn't display, which can be disconcerting to your users, but if you want to just rip the data out, that is probably good enoughI hope that gets you started, let me know if you need further clarification. I'll post a complete
here is a complete sample:
using System;
using System.IO;
using System.Reflection;
using NUnit.Framework;
using ExcelTools = Ms.Office;
using Excel = Microsoft.Office.Interop.Excel;
namespace Tests
{
[TestFixture]
public class ExcelSingle
{
[Test]
public void ProcessWorkbook()
{
string file = @"C:\Users\Chris\Desktop\TestSheet.xls";
Console.WriteLine(file);
Excel.Application excel = null;
Excel.Workbook wkb = null;
try
{
excel = new Excel.Application();
wkb = ExcelTools.OfficeUtil.OpenBook(excel, file);
Excel.Worksheet sheet = wkb.Sheets["Data"] as Excel.Worksheet;
Excel.Range range = null;
if (sheet != null)
range = sheet.get_Range("A1", Missing.Value);
string A1 = String.Empty;
if( range != null )
A1 = range.Text.ToString();
Console.WriteLine("A1 value: {0}", A1);
}
catch(Exception ex)
{
//if you need to handle stuff
Console.WriteLine(ex.Message);
}
finally
{
if (wkb != null)
ExcelTools.OfficeUtil.ReleaseRCM(wkb);
if (excel != null)
ExcelTools.OfficeUtil.ReleaseRCM(excel);
}
}
}
}
I'll post the functions from ExcelTools tomorrow, I don't have that code with me either.
Edit: As promised, here are the Functions from ExcelTools you might need.
public static Excel.Workbook OpenBook(Excel.Application excelInstance, string fileName, bool readOnly, bool editable,
bool updateLinks) {
Excel.Workbook book = excelInstance.Workbooks.Open(
fileName, updateLinks, readOnly,
Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, editable, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
return book;
}
public static void ReleaseRCM(object o) {
try {
System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
} catch {
} finally {
o = null;
}
}
To be frank, this stuff is much easier if you use VB.NET. It's in C# because I didn't write it. VB.NET does option parameters well, C# does not, hence the Type.Missing. Once you typed Type.Missing twice in a row, you run screaming from the room!
As for you question, you can try to following:
http://msdn.microsoft.com/en-us/library/microsoft.office.interop.excel.range.find(VS.80).aspx
I will post an example when I get back from my meeting... cheers
Edit: Here is an example
range = sheet.Cells.Find("Value to Find",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Excel.XlSearchDirection.xlNext,
Type.Missing,
Type.Missing, Type.Missing);
range.Text; //give you the value found
Here is another example inspired by this site:
range = sheet.Cells.Find("Value to find", Type.Missing, Type.Missing,Excel.XlLookAt.xlWhole,Excel.XlSearchOrder.xlByColumns,Excel.XlSearchDirection.xlNext,false, false, Type.Missing);
It helps to understand the parameters.
P.S. I'm one of those weird people who enjoys learning COM automation. All this code steamed from a tool I wrote for work which required me to process over 1000+ spreadsheets from the lab each Monday.
public bool MojTestPalindrome (string word)
{
bool yes = false;
char[]test1 = word.ToArray();
char[] test2 = test1.Reverse().ToArray();
for (int i=0; i< test2.Length; i++)
{
if (test1[i] != test2[test2.Length - 1 - i])
{
yes = false;
break;
}
else {
yes = true;
}
}
if (yes == true)
{
return true;
}
else
return false;
}
These are utf-8 encoded characters. Use utf8_decode() to convert them to normal ISO-8859-1 characters.
See ?read.table
. Basically, when you use read.table
, you specify a number indicating the column:
##Row names in the first column
read.table(filname.txt, row.names=1)
Try to install your application by using yum
command
yum install application_name
None of these answers worked for me. Our app was crashing when a url contained non-English characters.
let unreserved = "-._~/?%$!:"
let allowed = NSMutableCharacterSet.alphanumeric()
allowed.addCharacters(in: unreserved)
let escapedString = urlString.addingPercentEncoding(withAllowedCharacters: allowed as CharacterSet)
Depending on the parameters of what you are trying to do, you may want to just create your own character set. The above allows for english characters, and -._~/?%$!:
This is the shortest command I could find that does the job:
ps -ax | awk '/[t]he_app_name/{print $1}'
Putting brackets around the first letter stops awk from finding the awk process itself.
Here is another solution using css transform (for performance purposes on mobiles, see answer of @mate64 ) without having to use animations and keyframes.
I created two versions to slide-in from either side.
$('#toggle').click(function() {_x000D_
$('.slide-in').toggleClass('show');_x000D_
});
_x000D_
.slide-in {_x000D_
z-index: 10; /* to position it in front of the other content */_x000D_
position: absolute;_x000D_
overflow: hidden; /* to prevent scrollbar appearing */_x000D_
}_x000D_
_x000D_
.slide-in.from-left {_x000D_
left: 0;_x000D_
}_x000D_
_x000D_
.slide-in.from-right {_x000D_
right: 0;_x000D_
}_x000D_
_x000D_
.slide-in-content {_x000D_
padding: 5px 20px;_x000D_
background: #eee;_x000D_
transition: transform .5s ease; /* our nice transition */_x000D_
}_x000D_
_x000D_
.slide-in.from-left .slide-in-content {_x000D_
transform: translateX(-100%);_x000D_
-webkit-transform: translateX(-100%);_x000D_
}_x000D_
_x000D_
.slide-in.from-right .slide-in-content {_x000D_
transform: translateX(100%);_x000D_
-webkit-transform: translateX(100%);_x000D_
}_x000D_
_x000D_
.slide-in.show .slide-in-content {_x000D_
transform: translateX(0);_x000D_
-webkit-transform: translateX(0);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="slide-in from-left">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<div class="slide-in from-right">_x000D_
<div class="slide-in-content">_x000D_
<ul>_x000D_
<li>One</li>_x000D_
<li>Two</li>_x000D_
<li>Three</li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
std::vector
has a method size()
which returns the number of elements in the vector.
(Yes, this is tongue-in-cheek answer)
I had the same issue when updating an older project. Here's what I did to resolve it:
The projects that used Entity Framework 5 and .NET 4 were installing the Entity Framework dll version 4.4. Once I switched the .NET version to 4.5 on the project, the dll version would be 5.
My problem came from older projects being on .NET 4 and a newer project running .NET 4.5 so there were 2 dll versions of EF in my solution.
Hope this helps someone...
This is almost the same code, but in more nice look
bound <- floor((nrow(df)/4)*3) #define % of training and test set
df <- df[sample(nrow(df)), ] #sample rows
df.train <- df[1:bound, ] #get training set
df.test <- df[(bound+1):nrow(df), ] #get test set
If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."
<bindings>
<basicHttpBinding>
<binding name="MyBasicHttpBinding">
<security mode="None">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="MyServiceBehavior" name="MyService">
<endpoint
binding="basicHttpBinding"
bindingConfiguration="MyBasicHttpBinding"
name="basicEndPoint"
contract="IMyService"
/>
</service>
Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access
Pass a duration to show()
and hide()
:
When a duration is provided,
.show()
becomes an animation method.
E.g. element.delay(1000).show(0)
I totally chose another way for this method.
app.component.ts
import { Router } from '@angular/router';
export class AppComponent {
constructor(
private router: Router,
) {}
routerComment() {
this.router.navigateByUrl('/marketing/social/comment');
}
}
app.component.html
<button (click)="routerComment()">Router Link </button>
You're comparing apples to oranges here:
webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service
basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.
So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).
Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:
basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security
wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network
For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding
public void getCityStateFromLocal() {
AssetManager am = getAssets();
InputStream inputStream = null;
try {
inputStream = am.open("city_state.txt");
} catch (IOException e) {
e.printStackTrace();
}
ObjectMapper mapper = new ObjectMapper();
Map<String, String[]> map = new HashMap<String, String[]>();
try {
map = mapper.readValue(getStringFromInputStream(inputStream), new TypeReference<Map<String, String[]>>() {
});
} catch (IOException e) {
e.printStackTrace();
}
ConstantValues.arrayListStateName.clear();
ConstantValues.arrayListCityByState.clear();
if (map.size() > 0)
{
for (Map.Entry<String, String[]> e : map.entrySet()) {
CityByState cityByState = new CityByState();
String key = e.getKey();
String[] value = e.getValue();
ArrayList<String> s = new ArrayList<String>(Arrays.asList(value));
ConstantValues.arrayListStateName.add(key);
s.add(0,"Select City");
cityByState.addValue(s);
ConstantValues.arrayListCityByState.add(cityByState);
}
}
ConstantValues.arrayListStateName.add(0,"Select States");
}
// Convert InputStream to String
public String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb + "";
}
You need to set autoincrement property of id column to true when you create the table or you can alter your existing table to do this.
i had the same problem . i just convert
@Styles.Render("~/Content/css")
and @Scripts.Render("~/bundles/modernizr") to
@Styles.Render("/Content/css")
@Scripts.Render("/bundles/modernizr")
and its worked. just dont forget to convert
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
to
@Scripts.Render("/bundles/jquery")
@Scripts.Render("/bundles/bootstrap")
have nice time
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Basically, you need to catch the OperationCanceledException
and check the state of the cancellation token that was passed to SendAsync
(or GetAsync
, or whatever HttpClient
method you're using):
IsCancellationRequested
is true), it means the request really was canceledOf course, this isn't very convenient... it would be better to receive a TimeoutException
in case of timeout. I propose a solution here based on a custom HTTP message handler: Better timeout handling with HttpClient
For AWS S3, setting the Cross-origin resource sharing (CORS) to the following worked for me:
[
{
"AllowedHeaders": [
"Authorization"
],
"AllowedMethods": [
"GET",
"HEAD"
],
"AllowedOrigins": [
"*"
],
"ExposeHeaders": []
}
]
HEAD is just a special pointer that points to the local branch you’re currently on.
From the Pro Git book, chapter 3.1 Git Branching - Branches in a Nutshell, in the section Creating a New Branch:
What happens if you create a new branch? Well, doing so creates a new pointer for you to move around. Let’s say you create a new branch called testing. You do this with the git branch command:
$ git branch testing
This creates a new pointer at the same commit you’re currently on
How does Git know what branch you’re currently on? It keeps a special pointer called HEAD. Note that this is a lot different than the concept of HEAD in other VCSs you may be used to, such as Subversion or CVS. In Git, this is a pointer to the local branch you’re currently on. In this case, you’re still on master. The git branch command only created a new branch — it didn’t switch to that branch.
<iframe src="https://www.youtube.com/embed/7cjVj1ZyzyE?autoplay=1&loop=1&playlist=7cjVj1ZyzyE&mute=1" frameborder="0" allowfullscreen></iframe>
_x000D_
mute=1
If you're planning to only set a few of the values in the array, but want to get the (custom) default value most of the time, you could try something like this:
public class SparseArray<T>
{
private Dictionary<int, T> values = new Dictionary<int, T>();
private T defaultValue;
public SparseArray(T defaultValue)
{
this.defaultValue = defaultValue;
}
public T this [int index]
{
set { values[index] = value; }
get { return values.ContainsKey(index) ? values[index] ? defaultValue; }
}
}
You'll probably need to implement other interfaces to make it useful, such as those on array itself.
According to facebooks best practices it is like this (2016)
Use images that are at least 1200 x 630 pixels for the best display on high resolution devices. At the minimum, you should use images that are 600 x 315 pixels to display link page posts with larger images. Images can be up to 8MB in size.
If your image is smaller than 600 x 315 px, it will still display in the link page post, but the size will be much smaller.
We've also redesigned link page posts so that the aspect ratio for images is the same across desktop and mobile News Feed. Try to keep your images as close to 1.91:1 aspect ratio as possible to display the full image in News Feed without any cropping.
The minimum image size is 200 x 200 pixels. If you try to use an image smaller than this you will see an error in the Sharing Debugger.
There are two different image sizes to use for game apps:
Open Graph Stories Images appear in a square format. Image ratios for these apps should be 600 x 600 px. Non-open Graph Stories Images appear in a rectangular format. You should use a 1.91:1 image ratio, such as 600 x 314 px.
Building on Yan Foto's answer (the v2 api), I created a simple Python script to list the tags for a given image.
Usage:
./docker-registry-list.py alpine
Output:
{
"name": "library/alpine",
"tags": [
"2.6",
"2.7",
"3.1",
"3.2",
"3.3",
"3.4",
"3.5",
"3.6",
"3.7",
"edge",
"latest"
]
}
I tried following format, working fine
*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php
I created the table in postgres 10 and both of the following worked:
select count(*) from us
and
select count(a is null) from us
attr_accessor
is getter
, setter
method.
whereas attr_accessible
is to say that particular attribute is accessible or not. that's it.
I wish to add we should use Strong parameter instead of attr_accessible
to protect from mass asignment.
Cheers!
I don't know anything about EF really, but in LINQ to SQL you usually express a LIKE clause using String.Contains:
where entity.Name.Contains("xyz")
translates to
WHERE Name LIKE '%xyz%'
(Use StartsWith
and EndsWith
for other behaviour.)
I'm not entirely sure whether that's helpful, because I don't understand what you mean when you say you're trying to implement LIKE. If I've misunderstood completely, let me know and I'll delete this answer :)
You can use autocomplete="new-password"
<input type="email" name="email">
<input type="password" name="password" autocomplete="new-password">
Works in:
In my case, I had to find the difference of dates in seconds. The date was a UTC date string, so I converted it to a local date object. This is what I did:
let utc1 = new Date();
let utc2 = null;
const dateForCompare = new Date(valueFromServer);
dateForCompare.setTime(dateForCompare.getTime() - dateForCompare.getTimezoneOffset() *
60000);
utc2 = dateForCompare;
const seconds = Math.floor(utc1 - utc2) / 1000;
You can also use this syntax (L[start:stop:step]
):
mylist = [1,2,3,4,5,6,7,8,9,10]
for i in mylist[::2]:
print i,
# prints 1 3 5 7 9
for i in mylist[1::2]:
print i,
# prints 2 4 6 8 10
Where the first digit is the starting index (defaults to beginning of list or 0), 2nd is ending slice index (defaults to end of list), and the third digit is the offset or step.
Try GRANT ADMINISTER BULK OPERATIONS TO [server_login]
. It is a server level permission, not a database level. This has fixed a similar issue for me in that past (using OPENROWSET I believe).
Try this
var geocoder;
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(latitude, longitude);
geocoder.geocode(
{'latLng': latlng},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var add= results[0].formatted_address ;
var value=add.split(",");
count=value.length;
country=value[count-1];
state=value[count-2];
city=value[count-3];
alert("city name is: " + city);
}
else {
alert("address not found");
}
}
else {
alert("Geocoder failed due to: " + status);
}
}
);
TL;DR:
git checkout HEAD path/to/file
git stash apply
Long version:
You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD
. You can undo changes to a specific file with git checkout HEAD path/to/file
. After removing the cause of the conflict, you can apply as usual.
The answer for your question:
You can find out the current key-bindings following this link
You can even edit the key-binding as per your preference.
You are already doing it in your code. Run this example below. The catch will "handle" the exception, and you can move forward, assuming whatever you caught and handled did not break code down the road which you did not anticipate.
try{
throw new Exception();
}catch (Exception ex){
ex.printStackTrace();
}
System.out.println("Made it!");
However, you should always handle an exception properly. You can get yourself into some pretty messy situations and write difficult to maintain code by "ignoring" exceptions. You should only do this if you are actually handling whatever went wrong with the exception to the point that it really does not affect the rest of the program.
You'll want to convert the image to a byte[]
in C#, and then you'll have the database column as varbinary(MAX)
After that, it's just like saving any other data type.
There are some ways to overcome the cross-domain barrier:
There are some plugins that help with cross-domain requests:
Heads up!
The best way to overcome this problem, is by creating your own proxy in the back-end, so that your proxy will point to the services in other domains, because in the back-end not exists the same origin policy restriction. But if you can't do that in back-end, then pay attention to the following tips.
Using third-party proxies is not a secure practice, because they can keep track of your data, so it can be used with public information, but never with private data.
CORS Anywhere is a node.js proxy which adds CORS headers to the proxied request.
To use the API, just prefix the URL with the API URL. (Supports https: see github repository)
If you want to automatically enable cross-domain requests when needed, use the following snippet:
$.ajaxPrefilter( function (options) {
if (options.crossDomain && jQuery.support.cors) {
var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
//options.url = "http://cors.corsproxy.io/url=" + options.url;
}
});
$.get(
'http://en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
Whatever Origin is a cross domain jsonp access. This is an open source alternative to anyorigin.com.
To fetch the data from google.com, you can use this snippet:
// It is good specify the charset you expect.
// You can use the charset you want instead of utf-8.
// See details for scriptCharset and contentType options:
// http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
$.ajaxSetup({
scriptCharset: "utf-8", //or "ISO-8859-1"
contentType: "application/json; charset=utf-8"
});
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function (data) {
console.log("> ", data);
//If the expected response is text/plain
$("#viewer").html(data.contents);
//If the expected response is JSON
//var response = $.parseJSON(data.contents);
});
CORS Proxy is a simple node.js proxy to enable CORS request for any website. It allows javascript code on your site to access resources on other domains that would normally be blocked due to the same-origin policy.
How does it work? CORS Proxy takes advantage of Cross-Origin Resource Sharing, which is a feature that was added along with HTML 5. Servers can specify that they want browsers to allow other websites to request resources they host. CORS Proxy is simply an HTTP Proxy that adds a header to responses saying "anyone can request this".
This is another way to achieve the goal (see www.corsproxy.com). All you have to do is strip http:// and www. from the URL being proxied, and prepend the URL with www.corsproxy.com/
$.get(
'http://www.corsproxy.com/' +
'en.wikipedia.org/wiki/Cross-origin_resource_sharing',
function (response) {
console.log("> ", response);
$("#viewer").html(response);
});
Recently I found this one, it involves various security oriented Cross Origin Remote Sharing utilities. But it is a black-box with Flash as backend.
You can see it in action here: CORS proxy browser
Get the source code on GitHub: koto/cors-proxy-browser
With modern Git versions, the command to use would be:
git push -u origin <branch_name_test>
This will automatically set the branch name to track from remote and push in one go.
preg_replace("/[[:blank:]]+/"," ",$input)
According to Microsoft documentation, should NEVER use async void
Do not do this: The following example uses
async void
which makes the HTTP request complete when the first await is reached:
Which is ALWAYS a bad practice in ASP.NET Core apps.
Accesses the HttpResponse after the HTTP request is complete.
Crashes the process.
In order for that to work $time
has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00');
which is what you seem to do, because then I get 0:30 and 1:30 as results too.
Try
$time = strtotime('10:00');
As an alternative, consider using DateTime (the below requires PHP 5.3 though):
$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M')); // substract 30 minutes
echo $dt->format('H:i'); // echo modified time
$dt->add(new DateInterval('PT1H')); // add 1 hour
echo $dt->format('H:i'); // echo modified time
or procedural if you don't like OOP
$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');
The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details
.
Select a plug-in you want to uninstall, then click Uninstall...
button at the bottom.
If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.
Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.
Sometimes using image = array(img).reshape(a,b,c,d)
will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is
np.expand_dims(img, axis=0)
It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.
I know, it is long ago, but since the easiest answer was not yet posted I will do so for other user that might step by.
Just move the var inside the "name" block:
- name: Download apache
vars:
url: czxcxz
shell: wget {{url}}
Though a bit late, there is :/
which is the dedicated notation to specify a commit (or revision) based on the commit message, just prefix the search string with :/
, e.g.:
git show :/keyword(s)
Here <keywords>
can be a single word, or a complex regex pattern consisting of whitespaces, so please make sure to quote/escape when necessary, e.g.:
git log -1 -p ":/a few words"
Alternatively, a start point can be specified, to find the closest commit reachable from a specific point, e.g.:
git show 'HEAD^{/fix nasty bug}'
See: git revisions manual.
I just stumbled on a situation where I needed to run a bunch of lines of bash code (not separated with semicolons) from within python. In this scenario the proposed solutions do not help. One approach would be to save a file and then run it with Popen
, but it wasn't possible in my situation.
What I ended up doing is something like:
commands = '''
echo "a"
echo "b"
echo "c"
echo "d"
'''
process = subprocess.Popen('/bin/bash', stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = process.communicate(commands)
print out
So I first create the child bash process and after I tell it what to execute. This approach removes the limitations of passing the command directly to the Popen
constructor.
Here are the instructions from github:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git push -u origin master
Here's what actually worked:
touch README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/tqisjim/google-oauth.git
git clone origin master
After cloning, then the push command succeeds by prompting for a username and password
In Sql Server Management Studio:
just go to security->schema->dbo
.
Double click dbo, then click on permission tab->(blue font)view database permission
and feel free to scroll for required fields like "execute".
Help yourself to choose usinggrant
or deny
controls. Hope this will help:)
You can do the following (assuming you are checked out on master and want to push to a remote branch master):
Set up the 'remote' if you don't have it already
git remote add origin ssh://...
Now configure master to know to track:
git config branch.master.remote origin
git config branch.master.merge refs/heads/master
And push:
git push origin master
running this command worked for me on my mac OS Catalina
:
compaudit | xargs chmod g-w,o-w
var newdata= //You call Ajax peticion//
$("#idGrid").clearGridData();
$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");
in event update data table
The top answers here mention using T to open a file in a new tab silently, or Ctrl+WW to hop back to nerd-tree window after file is opened normally.
IF WORKING WITH BUFFERS: use go to open a file in a new buffer, silently, meaning your focus will remain on nerd-tree.
Use this to open multiple files fast :)
For hibernate it is important to know that your object WILL have an id, when you want to persist/save it. Thus, make sure that
private String U_id;
will have a value, by the time you are going to persist your object. You can do that with the @GeneratedValue
annotation or by assigning a value manually.
In the case you need or want to assign your id's manually (and that's what the above error is actually about), I would prefer passing the values for the fields to your constructor, at least for U_id
, e.g.
public Role (String U_id) { ... }
This ensures that your object has an id, by the time you have instantiated it. I don't know what your use case is and how your application behaves in concurrency, however, in some cases this is not recommended. You need to ensure that your id is unique.
Further note: Hibernate will still require a default constructor, as stated in the hibernate documentation. In order to prevent you (and maybe other programmers if you're designing an api) of instantiations of Role
using the default constructor, just declare it as private
.
Declare them before the while loop.
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
You are getting the notice because the variables are declared and assigned inside the loop.
In foreach
loop instead of carBootSaleList
use carBootSaleList.data
.
You probably do not need answer anymore, but it could help someone.
Microsoft Visual Studio Express
It's a full IDE, with powerful debugging tools, syntax highlighting, etc.
That very well may be a false positive. Like the warning message says, it is common for a capture to start in the middle of a tcp session. In those cases it does not have that information. If you are really missing acks then it is time to start looking upstream from your host for where they are disappearing. It is possible that tshark can not keep up with the data and so it is dropping some metrics. At the end of your capture it will tell you if the "kernel dropped packet" and how many. By default tshark disables dns lookup, tcpdump does not. If you use tcpdump you need to pass in the "-n" switch. If you are having a disk IO issue then you can do something like write to memory /dev/shm. BUT be careful because if your captures get very large then you can cause your machine to start swapping.
My bet is that you have some very long running tcp sessions and when you start your capture you are simply missing some parts of the tcp session due to that. Having said that, here are some of the things that I have seen cause duplicate/missing acks.
the easy way is the "values" property df.iloc[:,1:].values
a=df.iloc[:,1:]
b=df.iloc[:,1:].values
print(type(df))
print(type(a))
print(type(b))
so, you can get type
<class 'pandas.core.frame.DataFrame'>
<class 'pandas.core.frame.DataFrame'>
<class 'numpy.ndarray'>
Use the DATEPART function to extract the month from the date.
So you would do something like this:
SELECT DATEPART(month, Closing_Date) AS Closing_Month, COUNT(Status) AS TotalCount
FROM t
GROUP BY DATEPART(month, Closing_Date)
The following works without flattening the folder structure:
gulp.src(['input/folder/**/*']).pipe(gulp.dest('output/folder'));
The '**/*'
is the important part. That expression is a glob which is a powerful file selection tool. For example, for copying only .js files use: 'input/folder/**/*.js'
I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).
The wiki lists some more wrappers:
a <div>
can be focused if it has a tabindex
attribute. (the value can be set to -1)
For example:
$("#focus_point").attr("tabindex",-1).focus();
In addition, consider setting outline: none !important;
so it displayed without a focus rectangle.
var element = $("#focus_point");
element.css('outline', 'none !important')
.attr("tabindex", -1)
.focus();
Use defaultValue and onChange like this
const [myValue, setMyValue] = useState('');
<select onChange={(e) => setMyValue(e.target.value)} defaultValue={props.myprop}>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
Instead of using <source>
tag, use <src>
attribute of <video>
as below and you will see the action.
<video width="320" height="240" src="mov1.mov"></video>
or
you can give multiple tags within the tag, each with a different video source. The browser will automatically go through the list and pick the first one it’s able to play. For example:
<video id="sampleMovie" width="640" height="360" preload controls>
<source src="HTML5Sample_H264.mov" />
<source src="HTML5Sample_Ogg.ogv" />
<source src="HTML5Sample_WebM.webm" />
</video>
If you test that code in Chrome, you’ll get the H.264 video. Run it in Firefox, though, and you’ll see the Ogg video in the same place.
If you want to use numpy, you must define darr
to be a numpy array, not a list
:
import numpy as np
darr = np.array([1, 3.14159, 1e100, -2.71828])
print(darr.min())
darr.argmin()
will give you the index corresponding to the minimum.
The reason you were getting an error is because argmin
is a method understood by numpy arrays, but not by Python lists
.
if we have single column to do the label encoding and its inverse transform its easy how to do it when there are multiple columns in python
def stringtocategory(dataset):
'''
@author puja.sharma
@see The function label encodes the object type columns and gives label encoded and inverse tranform of the label encoded data
@param dataset dataframe on whoes column the label encoding has to be done
@return label encoded and inverse tranform of the label encoded data.
'''
data_original = dataset[:]
data_tranformed = dataset[:]
for y in dataset.columns:
#check the dtype of the column object type contains strings or chars
if (dataset[y].dtype == object):
print("The string type features are : " + y)
le = preprocessing.LabelEncoder()
le.fit(dataset[y].unique())
#label encoded data
data_tranformed[y] = le.transform(dataset[y])
#inverse label transform data
data_original[y] = le.inverse_transform(data_tranformed[y])
return data_tranformed,data_original
try this
<servlet-mapping>
<servlet-name>default</servlet-name>
<url-pattern>*.js</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.ico</url-pattern>
<url-pattern>*.png</url-pattern>
<url-pattern>*.jpg</url-pattern>
<url-pattern>*.htc</url-pattern>
<url-pattern>*.gif</url-pattern>
</servlet-mapping>
Edit: This is only valid for the servlet 2.5 spec and up.
I recommend GitHub: Array sortBy - a best implementation of sortBy
method which uses the Schwartzian transform
But for now we are going to try this approach Gist: sortBy-old.js.
Let's create a method to sort arrays being able to arrange objects by some property.
var sortBy = (function () {
var toString = Object.prototype.toString,
// default parser function
parse = function (x) { return x; },
// gets the item to be sorted
getItem = function (x) {
var isObject = x != null && typeof x === "object";
var isProp = isObject && this.prop in x;
return this.parser(isProp ? x[this.prop] : x);
};
/**
* Sorts an array of elements.
*
* @param {Array} array: the collection to sort
* @param {Object} cfg: the configuration options
* @property {String} cfg.prop: property name (if it is an Array of objects)
* @property {Boolean} cfg.desc: determines whether the sort is descending
* @property {Function} cfg.parser: function to parse the items to expected type
* @return {Array}
*/
return function sortby (array, cfg) {
if (!(array instanceof Array && array.length)) return [];
if (toString.call(cfg) !== "[object Object]") cfg = {};
if (typeof cfg.parser !== "function") cfg.parser = parse;
cfg.desc = !!cfg.desc ? -1 : 1;
return array.sort(function (a, b) {
a = getItem.call(cfg, a);
b = getItem.call(cfg, b);
return cfg.desc * (a < b ? -1 : +(a > b));
});
};
}());
var data = [
{date: "2011-11-14T17:25:45Z", quantity: 2, total: 200, tip: 0, type: "cash"},
{date: "2011-11-14T16:28:54Z", quantity: 1, total: 300, tip: 200, type: "visa"},
{date: "2011-11-14T16:30:43Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T17:22:59Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:53:41Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:48:46Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-31T17:29:52Z", quantity: 1, total: 200, tip: 100, type: "visa"},
{date: "2011-11-01T16:17:54Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T16:58:03Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:20:19Z", quantity: 2, total: 190, tip: 100, type: "tab"},
{date: "2011-11-14T17:07:21Z", quantity: 2, total: 90, tip: 0, type: "tab"},
{date: "2011-11-14T16:54:06Z", quantity: 1, total: 100, tip: 0, type: "cash"}
];
Finally, we arrange the array, by "date"
property as string
//sort the object by a property (ascending)
//sorting takes into account uppercase and lowercase
sortBy(data, { prop: "date" });
If you want to ignore letter case, set the "parser"
callback:
//sort the object by a property (descending)
//sorting ignores uppercase and lowercase
sortBy(data, {
prop: "date",
desc: true,
parser: function (item) {
//ignore case sensitive
return item.toUpperCase();
}
});
If you want to treat the "date" field as Date
type:
//sort the object by a property (ascending)
//sorting parses each item to Date type
sortBy(data, {
prop: "date",
parser: function (item) {
return new Date(item);
}
});
Here you can play with the above example:
jsbin.com/lesebi
_MSC_VER
and possibly _MSC_FULL_VER
is what you need. You can also examine visualc.hpp in any recent boost install for some usage examples.
Some values for the more recent versions of the compiler are:
MSVC++ 14.24 _MSC_VER == 1924 (Visual Studio 2019 version 16.4)
MSVC++ 14.23 _MSC_VER == 1923 (Visual Studio 2019 version 16.3)
MSVC++ 14.22 _MSC_VER == 1922 (Visual Studio 2019 version 16.2)
MSVC++ 14.21 _MSC_VER == 1921 (Visual Studio 2019 version 16.1)
MSVC++ 14.2 _MSC_VER == 1920 (Visual Studio 2019 version 16.0)
MSVC++ 14.16 _MSC_VER == 1916 (Visual Studio 2017 version 15.9)
MSVC++ 14.15 _MSC_VER == 1915 (Visual Studio 2017 version 15.8)
MSVC++ 14.14 _MSC_VER == 1914 (Visual Studio 2017 version 15.7)
MSVC++ 14.13 _MSC_VER == 1913 (Visual Studio 2017 version 15.6)
MSVC++ 14.12 _MSC_VER == 1912 (Visual Studio 2017 version 15.5)
MSVC++ 14.11 _MSC_VER == 1911 (Visual Studio 2017 version 15.3)
MSVC++ 14.1 _MSC_VER == 1910 (Visual Studio 2017 version 15.0)
MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015 version 14.0)
MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013 version 12.0)
MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012 version 11.0)
MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010 version 10.0)
MSVC++ 9.0 _MSC_FULL_VER == 150030729 (Visual Studio 2008, SP1)
MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008 version 9.0)
MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005 version 8.0)
MSVC++ 7.1 _MSC_VER == 1310 (Visual Studio .NET 2003 version 7.1)
MSVC++ 7.0 _MSC_VER == 1300 (Visual Studio .NET 2002 version 7.0)
MSVC++ 6.0 _MSC_VER == 1200 (Visual Studio 6.0 version 6.0)
MSVC++ 5.0 _MSC_VER == 1100 (Visual Studio 97 version 5.0)
The version number above of course refers to the major version of your Visual studio you see in the about box, not to the year in the name. A thorough list can be found here. Starting recently, Visual Studio will start updating its ranges monotonically, meaning you should check ranges, rather than exact compiler values.
cl.exe /?
will give a hint of the used version, e.g.:
c:\program files (x86)\microsoft visual studio 11.0\vc\bin>cl /?
Microsoft (R) C/C++ Optimizing Compiler Version 17.00.50727.1 for x86
.....
How about this for IE?:
onmousedown: Hide all elements which could overlay the event. Because display:none visibility:hidden not realy works, push the overlaying div out of the screen for a fixed number of pixels. After a delay push back the overlaying div with the same number of pixels.
onmouseup: Meanwhile this is the event you like to fire.
//script
var allclickthrough=[];
function hidedivover(){
if(allclickthrough.length==0){
allclickthrough=getElementsByClassName(document.body,"clickthrough");// if so .parentNode
}
for(var i=0;i<allclickthrough.length;i++){
allclickthrough[i].style.left=parseInt(allclickthrough[i].style.left)+2000+"px";
}
setTimeout(function(){showdivover()},1000);
}
function showdivover(){
for(var i=0;i<allclickthrough.length;i++){
allclickthrough[i].style.left=parseInt(allclickthrough[i].style.left)-2000+"px";
}
}
//html
<span onmouseup="Dreck_he_got_me()">Click me if you can.</span>
<div onmousedown="hidedivover()" style="position:absolute" class="clickthrough">You'll don't get through!</div>
self.navigationItem.leftBarButtonItem = self.navigationItem.backBarButtonItem;
Works for me. I used this when I had more tabs then could fit on the tab bar, and a view controller pushed from the "More" overrode the leftBarButtonItem in its viewDidLoad.
Are there any performance benefits to using one over the other?
Keep in mind that there is no JavaScript engine yet that natively supports ES6 modules. You said yourself that you are using Babel. Babel converts import
and export
declaration to CommonJS (require
/module.exports
) by default anyway. So even if you use ES6 module syntax, you will be using CommonJS under the hood if you run the code in Node.
There are technical differences between CommonJS and ES6 modules, e.g. CommonJS allows you to load modules dynamically. ES6 doesn't allow this, but there is an API in development for that.
Since ES6 modules are part of the standard, I would use them.
Update 2020
Since Node v12, support for ES modules is enabled by default, but it's still experimental at the time of writing this. Files including node modules must either end in .mjs
or the nearest package.json
file must contain "type": "module"
. The Node documentation has a ton more information, also about interop between CommonJS and ES modules.
Performance-wise there is always the chance that newer features are not as well optimized as existing features. However, since module files are only evaluated once, the performance aspect can probably be ignored. In the end you have to run benchmarks to get a definite answer anyway.
ES modules can be loaded dynamically via the import()
function. Unlike require
, this returns a promise.
try this
String g1="Male";
String g2="Female";
if(gender.equals(g1))
salutation ="Mr.";
if(gender.equals(g2))
salutation ="Ms.";
you were ending your if statement if(gender.equals(g1));
<<--- here by adding ";"
Correct syntax looks like this. See MSDN.
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS
Dockerfile comments start with '#', just like Python. Here is a good example (kstaken/dockerfile-examples):
# Install a more-up-to date version of MongoDB than what is included in the default Ubuntu repositories.
FROM ubuntu
MAINTAINER Kimbro Staken
RUN apt-key adv --keyserver keyserver.ubuntu.com --recv 7F0CEB10
RUN echo "deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen" | tee -a /etc/apt/sources.list.d/10gen.list
RUN apt-get update
RUN apt-get -y install apt-utils
RUN apt-get -y install mongodb-10gen
#RUN echo "" >> /etc/mongodb.conf
CMD ["/usr/bin/mongod", "--config", "/etc/mongodb.conf"]
using display flex, first you need to wrap the container of the item that you want to align.
<div class="outdiv">
<div class="indiv">
<span>test1</span>
<span>test2</span>
</div>
</div>
then apply the following css to wrapper div or outdiv in my example
.outdiv {
display: flex;
justify-content:center;
align-items:center;
}
obj1 != null
is the right way.
String defines IsNullOrEmpty
as a nicer way to say
obj1 == null || obj == String.Empty
so it does more than just check for nullity.
There may be other classes that define a method to check for a sematically "blank or null" object, but that would depend on the semantics of the class, and is by no means universal.
It's also possible to create extension method to do this kind of thing if it helps the readability of your code. For example, a similar approach to collections:
public static bool IsNullOrEmpty (this ICollection collection)
{
return collection == null || collection.Count == 0;
}
In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).
Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396
Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396
I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...
By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.
Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.
Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.
It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.
Use the getCause()
method on the InvocationTargetException
to retrieve the original exception.
The Upgrade element inside the Product element, combined with proper scheduling of the action will perform the uninstall you're after. Be sure to list the upgrade codes of all the products you want to remove.
<Property Id="PREVIOUSVERSIONSINSTALLED" Secure="yes" />
<Upgrade Id="00000000-0000-0000-0000-000000000000">
<UpgradeVersion Minimum="1.0.0.0" Maximum="1.0.5.0" Property="PREVIOUSVERSIONSINSTALLED" IncludeMinimum="yes" IncludeMaximum="no" />
</Upgrade>
Note that, if you're careful with your builds, you can prevent people from accidentally installing an older version of your product over a newer one. That's what the Maximum field is for. When we build installers, we set UpgradeVersion Maximum to the version being built, but IncludeMaximum="no" to prevent this scenario.
You have choices regarding the scheduling of RemoveExistingProducts. I prefer scheduling it after InstallFinalize (rather than after InstallInitialize as others have recommended):
<InstallExecuteSequence>
<RemoveExistingProducts After="InstallFinalize"></RemoveExistingProducts>
</InstallExecuteSequence>
This leaves the previous version of the product installed until after the new files and registry keys are copied. This lets me migrate data from the old version to the new (for example, you've switched storage of user preferences from the registry to an XML file, but you want to be polite and migrate their settings). This migration is done in a deferred custom action just before InstallFinalize.
Another benefit is efficiency: if there are unchanged files, Windows Installer doesn't bother copying them again when you schedule after InstallFinalize. If you schedule after InstallInitialize, the previous version is completely removed first, and then the new version is installed. This results in unnecessary deletion and recopying of files.
For other scheduling options, see the RemoveExistingProducts help topic in MSDN. This week, the link is: http://msdn.microsoft.com/en-us/library/aa371197.aspx
Use the .val() method.
Also I think you meant to use $("#txtEmail")
as $("txtEmail")
returns elements of type <txtEmail>
which you probably don't have.
See here at the jQuery documentation.
Also jQuery val() method.
Firefox 3.0 and higher have disabled setting location
by default. resizable
and status
are also disabled by default. You can verify this by typing `about:config' in your address bar and filtering by "dom". The items of interest are:
You can get further information at the Mozilla Developer site. What this basically means, though, is that you won't be able to do what you want to do.
One thing you might want to do (though it won't solve your problem), is put quotes around your window feature parameters, like so:
window.open('/pageaddress.html','winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');