I fear that restarting the entire application using Process is approaching your problem in the wrong way.
An easier way is to modify the Program.cs file to restart:
static bool restart = true; // A variable that is accessible from program
static int restartCount = 0; // Count the number of restarts
static int maxRestarts = 3; // Maximum restarts before quitting the program
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
while (restart && restartCount < maxRestarts)
{
restart = false; // if you like.. the program can set it to true again
restartCount++; // mark another restart,
// if you want to limit the number of restarts
// this is useful if your program is crashing on
// startup and cannot close normally as it will avoid
// a potential infinite loop
try {
Application.Run(new YourMainForm());
}
catch { // Application has crashed
restart = true;
}
}
}
The pseudo-elements generated by ::before and ::after are contained by the element's formatting box, and thus don't apply to replaced elements such as img, or to br elements.
The definition of method_two
is invalid. When you call method_two
, you'll get TypeError: method_two() takes 0 positional arguments but 1 was given
from the interpreter.
An instance method is a bounded function when you call it like a_test.method_two()
. It automatically accepts self
, which points to an instance of Test
, as its first parameter. Through the self
parameter, an instance method can freely access attributes and modify them on the same object.
You can try this:
if (isset($_POST["mail"]) !== false) {
echo "Yes, mail is set";
}else{
echo "N0, mail is not set";
}
From the PostgreSQL wiki.
NOTE: Databases to which the user cannot connect are sorted as if they were infinite size.
SELECT d.datname AS Name, pg_catalog.pg_get_userbyid(d.datdba) AS Owner,
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))
ELSE 'No Access'
END AS Size
FROM pg_catalog.pg_database d
ORDER BY
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_database_size(d.datname)
ELSE NULL
END DESC -- nulls first
LIMIT 20
The page also has snippets for finding the size of your biggest relations and largest tables.
You can specify an array in your HTML this way:
<input type="hidden" name="id[]" value="1"/>
<input type="hidden" name="id[]" value="2"/>
<input type="hidden" name="id[]" value="3"/>
This will result in this $_GET array in PHP:
array(
'id' => array(
0 => 1,
1 => 2,
2 => 3
)
)
Of course, you can use any sort of HTML input, here. The important thing is that all inputs whose values you want in the 'id' array have the name id[]
.
If your input file has a fixed amount of columns separated by commas and you know in which columns are the strings it might be best to use the function
textscan()
Note that you can specify a format where you read up to a maximum number of characters in the string or until a delimiter (comma) is found.
You also can do it with functional programming:
from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)
I believe that the correct answer has already been posted and accepted, yet there is an issue that I have experienced myself and that some others have mentioned here.
On certain platforms, various properties such as window dimensions (window.innerWidth
, window.innerHeight
) and the window.orientation
property will not be updated by the time that the event "orientationchange"
has fired. Many times, the property window.orientation
is undefined
for a few milliseconds after the firing of "orientationchange"
(at least it is in Chrome on iOS).
The best way that I found to handle this issue was:
var handleOrientationChange = (function() {
var struct = function(){
struct.parse();
};
struct.showPortraitView = function(){
alert("Portrait Orientation: " + window.orientation);
};
struct.showLandscapeView = function(){
alert("Landscape Orientation: " + window.orientation);
};
struct.parse = function(){
switch(window.orientation){
case 0:
//Portrait Orientation
this.showPortraitView();
break;
default:
//Landscape Orientation
if(!parseInt(window.orientation)
|| window.orientation === this.lastOrientation)
setTimeout(this, 10);
else
{
this.lastOrientation = window.orientation;
this.showLandscapeView();
}
break;
}
};
struct.lastOrientation = window.orientation;
return struct;
})();
window.addEventListener("orientationchange", handleOrientationChange, false);
I am checking to see if the orientation is either undefined or if the orientation is equal to the last orientation detected. If either is true, I wait ten milliseconds and then parse the orientation again. If the orientation is a proper value, I call the showXOrientation
functions. If the orientation is invalid, I continue to loop my checking function, waiting ten milliseconds each time, until it is valid.
Now, I would make a JSFiddle for this, as I usually did, but JSFiddle has not been working for me and my support bug for it was closed as no one else is reporting the same problem. If anyone else wants to turn this into a JSFiddle, please go ahead.
Thanks! I hope this helps!
I used all the above answers and it was giving me errors so I tried
adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1
and it worked. One advantage is you dont have to specify your launcher activity if you use this command.
You can control select all customised classes and methods, and right-click, choose "Source", then select "Generate Element Comment". You should get what you want.
If you want to modify the Code Template then you can go to Preferences -- Java -- Code Style -- Code Templates, then do whatever you want.
This is what I use (typically for html table email reports)
declare @time int, @hms varchar(20)
set @time = 12345
set @hms = cast(cast((@Time)/3600 as int) as varchar(3))
+':'+ right('0'+ cast(cast(((@Time)%3600)/60 as int) as varchar(2)),2)
+':'+ right('0'+ cast(((@Time)%3600)%60 as varchar(2)),2) +' (hh:mm:ss)'
select @hms
Solution: Remove height: 100%
in .item-inner and add display: flex
in .item
The limitation of execl is that when executing a shell command or any other script that is not in the current working directory, then we have to pass the full path of the command or the script. Example:
execl("/bin/ls", "ls", "-la", NULL);
The workaround to passing the full path of the executable is to use the function execlp, that searches for the file (1st argument of execlp) in those directories pointed by PATH:
execlp("ls", "ls", "-la", NULL);
Can you try this,
var ajaxSubmit = function(formE1) {
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
async: "false",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
if(arr == "Successful")
{
**$("form[name='form']").submit();**
return true;
}
else
{ return false;
}
}
});
**return false;**
}
Probably you got the solution already @lukik, but if you wanna remove a scheduling, you should use:
job = scheduler.add_job(myfunc, 'interval', minutes=2)
job.remove()
or
scheduler.add_job(myfunc, 'interval', minutes=2, id='my_job_id')
scheduler.remove_job('my_job_id')
if you need to use a explicit job ID
For more information, you should check: https://apscheduler.readthedocs.io/en/stable/userguide.html#removing-jobs
I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].
The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.
Good to go! here is my working code for this:
$.ajax({_x000D_
crossOrigin: true,_x000D_
url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
type : "GET",_x000D_
success:function(data){_x000D_
console.log(data);_x000D_
}_x000D_
})
_x000D_
from datetime import datetime
a = datetime.strptime(f, "%Y-%m-%d")
A supplementarily handy (but trivial) tip for installing older version of packages from source.
First, if you call "install.packages", it always installs the latest package from repo. If you want to install the older version of packages, say for compatibility, you can call install.packages("url_to_source", repo=NULL, type="source"). For example:
install.packages("http://cran.r-project.org/src/contrib/Archive/RNetLogo/RNetLogo_0.9-6.tar.gz", repo=NULL, type="source")
Without manually downloading packages to the local disk and switching to the command line or installing from local disk, I found it is very convenient and simplify the call (one-step).
Plus: you can use this trick with devtools library's dev_mode, in order to manage different versions of packages:
Reference: doc devtools
c = np.array([[1,2,3],[4,5,6]])
list(c.flatten())
You can use the runOnUiThread()
method as follows. If you're not using a ListActivity
, just adapt the code to get a reference to your ArrayAdapter
.
final ArrayAdapter adapter = ((ArrayAdapter)getListAdapter());
runOnUiThread(new Runnable() {
public void run() {
adapter.notifyDataSetChanged();
}
});
Fortunately a solution exists. You must add a wrapper for parent and change z-index of this wrapper for example 10, and set z-index for child to -1:
.parent {_x000D_
position: relative;_x000D_
width: 750px;_x000D_
height: 7150px;_x000D_
background: red;_x000D_
border: solid 1px #000;_x000D_
z-index: initial;_x000D_
}_x000D_
_x000D_
.child {_x000D_
position: relative;_x000D_
background-color: blue;_x000D_
z-index: -1;_x000D_
color: white;_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
position: relative;_x000D_
background: green;_x000D_
z-index: 10;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="parent">parent parent_x000D_
<div class="child">child child child</div>_x000D_
</div>_x000D_
</div>
_x000D_
var Text = File.ReadAllLines("Path"); foreach (var i in Text) { var SplitText = i.Split().Where(x=> x.Lenght>1).ToList(); //@Array1 add SplitText[0] //@Array2 add SpliteText[1] }
Given that Windows has no sys/socket.h, you might consider just doing something like this:
#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a
#ifdef __WIN32__
WORD versionWanted = MAKEWORD(1, 1);
WSADATA wsaData;
WSAStartup(versionWanted, &wsaData);
#endif
at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.
This only determines if the top level of the tree is balanced. That is, you could have a tree with two long branches off the far left and far right, with nothing in the middle, and this would return true. You need to recursively check the root.left
and root.right
to see if they are internally balanced as well before returning true.
You might find your code is more maintainable if you keep all your styles, etc. in CSS and just set / unset class names in JavaScript.
Your CSS would obviously be something like:
.highlight {
background:#ff00aa;
}
Then in JavaScript:
element.className = element.className === 'highlight' ? '' : 'highlight';
For me, running Fedora 22 with Gnome 16.2, this solution helped me. In short, you should install the java-1.8.0-openjdk-devel, the development files of the JDK.
Open the Terminal and search for the latest version of the JDK development package:
$ dnf search jdk-devel
Last metadata expiration check performed 12:44:51 ago on Mon Aug 3 22:20:24 2015.
============================ N/S Matched: jdk-devel ============================
java-1.8.0-openjdk-devel.x86_64 : OpenJDK Development Environment
java-1.8.0-openjdk-devel-debug.x86_64 : OpenJDK Development Environment with
: full debug on
$ sudo dnf install java-1.8.0-openjdk-devel
Yay recursion!
def trunc(s,l):
if l > 0:
return s[:l] + trunc(s, l - len(s))
return ''
Won't scale forever, but it's fine for smaller strings. And it's pretty.
I admit I just read the Little Schemer and I like recursion right now.
You need to run your code AFTER jQuery finished loading
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
script.onload = function(){
// your jQuery code here
}
or if you're running it in an async function you could use await
in the above code
var script = document.createElement('script');
document.head.appendChild(script);
script.type = 'text/javascript';
script.src = "//ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js";
await script.onload
// your jQuery code here
If you want to check first if jQuery already exists in the page, try this
Don't forget that you can treat pointers as iterators:
w_.assign(w, w + len);
when we using this line open(filename, "a")
, that a
indicates the appending the file, that means allow to insert extra data to the existing file.
You can just use this following lines to append the text in your file
def FileSave(filename,content):
with open(filename, "a") as myfile:
myfile.write(content)
FileSave("test.txt","test1 \n")
FileSave("test.txt","test2 \n")
With Java 8:
map.keySet().forEach(key -> System.out.println(key + "->" + map.get(key)));
You need to add
#container
{
display:inline-block;
position:relative;
background:rgb(255,100,0);
margin:0px;
width:40%;
height:100px;
margin-right:-4px;
}
because whenever you write display:inline-block
it takes an additional margin-right:4px
. So, you need to remove it.
I was looking for the solution to show the label dynamically from database like this:
checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database
So none of the above solution worked for me so I used like this:
@Html.CheckBoxFor(m => m.Option1, new { @class = "options" })
<label for="Option1">@Model.Option1Text</label>
@Html.CheckBoxFor(m => m.Option2, new { @class = "options" })
<label for="Option2">@Mode2.Option1Text</label>
In this way when user will click on label, checkbox will be selected.
Might be it can help someone.
TV Sony Bravia KLV-32T550A Below mention config works greatly You should add the following into the /boot/config.txt to force the output to HDMI and set the
resolution 82 1920x1080 60Hz 1080p
hdmi_ignore_edid=0xa5000080
hdmi_force_hotplug=1
hdmi_boost=7
hdmi_group=2
hdmi_mode=82
hdmi_drive=1
Even they seem to identical(same implemented inteface List - non thread-safe),they give different results in terms of performance in add/delete and searching time and consuming memory (LinkedList consumes more).
LinkedLists can be used if you use highly insertion/deletion with performance O(1). ArrayLists can be used if you use direct access operations with performance O(1)
This code may make clear of these comments and you can try to understand performance results. (Sorry for boiler plate code)
public class Test {
private static Random rnd;
static {
rnd = new Random();
}
static List<String> testArrayList;
static List<String> testLinkedList;
public static final int COUNT_OBJ = 2000000;
public static void main(String[] args) {
testArrayList = new ArrayList<>();
testLinkedList = new LinkedList<>();
insertSomeDummyData(testLinkedList);
insertSomeDummyData(testArrayList);
checkInsertionPerformance(testLinkedList); //O(1)
checkInsertionPerformance(testArrayList); //O(1) -> O(n)
checkPerformanceForFinding(testArrayList); // O(1)
checkPerformanceForFinding(testLinkedList); // O(n)
}
public static void insertSomeDummyData(List<String> list) {
for (int i = COUNT_OBJ; i-- > 0; ) {
list.add(new String("" + i));
}
}
public static void checkInsertionPerformance(List<String> list) {
long startTime, finishedTime;
startTime = System.currentTimeMillis();
int rndIndex;
for (int i = 200; i-- > 0; ) {
rndIndex = rnd.nextInt(100000);
list.add(rndIndex, "test");
}
finishedTime = System.currentTimeMillis();
System.out.println(String.format("%s time passed at insertion:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
}
public static void checkPerformanceForFinding(List<String> list) {
long startTime, finishedTime;
startTime = System.currentTimeMillis();
int rndIndex;
for (int i = 200; i-- > 0; ) {
rndIndex = rnd.nextInt(100000);
list.get(rndIndex);
}
finishedTime = System.currentTimeMillis();
System.out.println(String.format("%s time passed at searching:%d", list.getClass().getSimpleName(), (finishedTime - startTime)));
}
}
Look into twitter cards.
The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook
sharing.
Example:
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">
Depends on what your definition of "offscreen" is. Is that within the viewport, or within the defined boundaries of your page?
Using Element.getBoundingClientRect() you can easily detect whether or not your element is within the boundries of your viewport (i.e. onscreen or offscreen):
jQuery.expr.filters.offscreen = function(el) {
var rect = el.getBoundingClientRect();
return (
(rect.x + rect.width) < 0
|| (rect.y + rect.height) < 0
|| (rect.x > window.innerWidth || rect.y > window.innerHeight)
);
};
You could then use that in several ways:
// returns all elements that are offscreen
$(':offscreen');
// boolean returned if element is offscreen
$('div').is(':offscreen');
In JUnit 4:
@Before
method, to catch failures.final
, exactly as stated in the question,@Before
, to catch failures.@BeforeClass
, but be careful of dependencies between tests.Initializing in a @Before
method or test method allows you to get better error reporting on failures. This is especially useful for instantiating the Class Under Test (which you might break), but is also useful for calling external systems, like filesystem access ("file not found") or connecting to a database ("connection refused").
It is acceptable to have a simple standard and always use @Before
(clear errors but verbose) or always initialize in declaration (concise but gives confusing errors), since complex coding rules are hard to follow, and this isn't a big deal.
Initializing in setUp
is a relic of JUnit 3, where all test instances were initialized eagerly, which causes problems (speed, memory, resource exhaustion) if you do expensive initialization. Thus best practice was to do expensive initialization in setUp
, which was only run when the test was executed. This no longer applies, so it is much less necessary to use setUp
.
This summarizes several other replies that bury the lede, notably by Craig P. Motlin (question itself and self-answer), Moss Collum (class under test), and dsaff.
Something like this will do the trick. Don't know about performance, so do make some tests.
select
id, name, city
from
[stuff] s
where
1 < (select count(*) from [stuff] i where i.city = s.city and i.name = s.name)
With zero jQuery
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<style>
.inv {
display: none;
}
</style>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
<script>
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
</script>
</body>
</html>
Codepen
document
.getElementById('target')
.addEventListener('change', function () {
'use strict';
var vis = document.querySelector('.vis'),
target = document.getElementById(this.value);
if (vis !== null) {
vis.className = 'inv';
}
if (target !== null ) {
target.className = 'vis';
}
});
_x000D_
.inv {
display: none;
}
_x000D_
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title></title>
</head>
<body>
<select id="target">
<option value="">Select...</option>
<option value="content_1">Option 1</option>
<option value="content_2">Option 2</option>
<option value="content_3">Option 3</option>
<select>
<div id="content_1" class="inv">Content 1</div>
<div id="content_2" class="inv">Content 2</div>
<div id="content_3" class="inv">Content 3</div>
</body>
</html>
_x000D_
You can break lines in between parenthesises and braces. Additionally, you can append the backslash character \
to a line to explicitly break it:
x = (tuples_first_value,
second_value)
y = 1 + \
2
R Studio (and Eclipse + StatET): Highlight the text and use CTRL+SHIFT+C to comment multiple lines in Windows. Or, command+SHIFT+C in OS-X.
Other answers show how to globally configure client certificates. However if you want to programmatically define the client key for one particular connection, rather than globally define it across every application running on your JVM, then you can configure your own SSLContext like so:
String keyPassphrase = "";
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(new FileInputStream("cert-key-pair.pfx"), keyPassphrase.toCharArray());
SSLContext sslContext = SSLContexts.custom()
.loadKeyMaterial(keyStore, null)
.build();
HttpClient httpClient = HttpClients.custom().setSSLContext(sslContext).build();
HttpResponse response = httpClient.execute(new HttpGet("https://example.com"));
The function you need is CInt
.
ie CInt(PrinterLabel)
See Type Conversion Functions (Visual Basic) on MSDN
Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!
I have resolved the same problem using the below code:
String query = "SELECT violationDate, COUNT(*) as date " +
"FROM challan " +
"WHERE challanType = '" + type + "' GROUP BY violationDate";
Here violationDate and date are two columns of the result table. date column will return occurrence.
cr.getInt(1)
With JUnit 4.12 the following didn't work for me:
java -cp .:/usr/share/java/junit.jar org.junit.runner.JUnitCore [test class name]
Apparently, from JUnit 4.11 onwards you should also include hamcrest-core.jar
in your classpath:
java -cp .:/usr/share/java/junit.jar:/usr/share/java/hamcrest-core.jar org.junit.runner.JUnitCore [test class name]
A simple 4on4 pasting function that works-
def paste(background,foreground,pos=(0,0)):
#get position and crop pasting area if needed
x = pos[0]
y = pos[1]
bgWidth = background.shape[0]
bgHeight = background.shape[1]
frWidth = foreground.shape[0]
frHeight = foreground.shape[1]
width = bgWidth-x
height = bgHeight-y
if frWidth<width:
width = frWidth
if frHeight<height:
height = frHeight
# normalize alpha channels from 0-255 to 0-1
alpha_background = background[x:x+width,y:y+height,3] / 255.0
alpha_foreground = foreground[:width,:height,3] / 255.0
# set adjusted colors
for color in range(0, 3):
fr = alpha_foreground * foreground[:width,:height,color]
bg = alpha_background * background[x:x+width,y:y+height,color] * (1 - alpha_foreground)
background[x:x+width,y:y+height,color] = fr+bg
# set adjusted alpha and denormalize back to 0-255
background[x:x+width,y:y+height,3] = (1 - (1 - alpha_foreground) * (1 - alpha_background)) * 255
return background
Note that the ansible
command doesn't collect facts, but the ansible-playbook
command does. When running ansible -m setup
, the setup module happens to run the fact collection so you get the facts, but running ansible -m command
does not. Therefore the facts aren't available. This is why the other answers include playbook YAML files and indicate the lookup works.
Other possible solution : I tried to map the result of a restTemplate.getForObject with a private class instance (defined inside of my working class). It did not work, but if I define the object to public, inside its own file, it worked correctly.
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
i have used this code given below
CustomerType = ((EnumCustomerType)(cus.CustomerType)).ToString()
Consider the following servlet conf:
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet/*</url-pattern>
</servlet-mapping>
Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi
, it will invoke NewServlet
as it is mapped with the pattern described above.
Here:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
We have those ones:
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string
None of the above answers worked for me. The solution to my issue was to change the way the snapshot dependency was consumed inside the package.json. Use the following template to pull in the snapshot dependency that you need
"dependency": "git+http://github.com/[pathtoproject].git#[branchname]",
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>?
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })?
Or, similar to erikkallen's idea, make the background of the A tag black, and make the image semitransparent on mouseover. That way you won't have to create additional divs.
Source for the CSS-based solution:
a.darken {
display: inline-block;
background: black;
padding: 0;
}
a.darken img {
display: block;
-webkit-transition: all 0.5s linear;
-moz-transition: all 0.5s linear;
-ms-transition: all 0.5s linear;
-o-transition: all 0.5s linear;
transition: all 0.5s linear;
}
a.darken:hover img {
opacity: 0.7;
}
And the image:
<a href="http://google.com" class="darken">
<img src="http://www.prelovac.com/vladimir/wp-content/uploads/2008/03/example.jpg" width="200">
</a>
If you don't want to do this in a batch script, you can do this from the command line like this:
for %I in (test.jpg) do @echo %~zI
Ugly, but it works. You can also pass in a file mask to get a listing for more than one file:
for %I in (*.doc) do @echo %~znI
Will display the size, file name of each .DOC file.
You can use Tikz/pgfplots for creating animations in beamer. http://www.texample.net/tikz/examples/tag/animations/
You can try just finishAffinity() , its close all current activities to works on above v4.1
Make an jInternalFrame into main frame and make it invisible. Then you can use it for further events.
jInternalFrame.setSize(300,150);
jInternalFrame.setVisible(true);
The best approach is to create a symbolic link like @SlateEntropy very well pointed out in the answer below. To help with this, since version 5.3, Laravel includes a command which makes this incredibly easy to do:
php artisan storage:link
That creates a symlink from public/storage
to storage/app/public
for you and that's all there is to it. Now any file in /storage/app/public
can be accessed via a link like:
http://somedomain.com/storage/image.jpg
If, for any reason, your can't create symbolic links (maybe you're on shared hosting, etc.) or you want to protect some files behind some access control logic, there is the alternative of having a special route that reads and serves the image. For example a simple closure route like this:
Route::get('storage/{filename}', function ($filename)
{
$path = storage_path('public/' . $filename);
if (!File::exists($path)) {
abort(404);
}
$file = File::get($path);
$type = File::mimeType($path);
$response = Response::make($file, 200);
$response->header("Content-Type", $type);
return $response;
});
You can now access your files just as you would if you had a symlink:
http://somedomain.com/storage/image.jpg
If you're using the Intervention Image Library you can use its built in response
method to make things more succinct:
Route::get('storage/{filename}', function ($filename)
{
return Image::make(storage_path('public/' . $filename))->response();
});
WARNING
Keep in mind that by manually serving the files you're incurring a performance penalty, because you're going through the entire Laravel request lifecycle in order to read and send the file contents, which is considerably slower than having the HTTP server handle it.
jezrael's answer is good, but did not answer a question I had: Will getting the "sort" flag wrong mess up my data in any way? The answer is apparently "no", you are fine either way.
from pandas import DataFrame, concat
a = DataFrame([{'a':1, 'c':2,'d':3 }])
b = DataFrame([{'a':4,'b':5, 'd':6,'e':7}])
>>> concat([a,b],sort=False)
a c d b e
0 1 2.0 3 NaN NaN
0 4 NaN 6 5.0 7.0
>>> concat([a,b],sort=True)
a b c d e
0 1 NaN 2.0 3 NaN
0 4 5.0 NaN 6 7.0
Don't forget to use
charset utf8
If your sql file is in utf-8 :)
So you need to do:
cmd.exe
mysql -u root
mysql> charset utf8
mysql> use mydbname
mysql> source C:\myfolder\myfile.sql
Good luck ))
You can do it by javascript on client side or using some regex validator on the textbox.
script type="text/javascript" language="javascript">
function validateNumbersOnly(e) {
var unicode = e.charCode ? e.charCode : e.keyCode;
if ((unicode == 8) || (unicode == 9) || (unicode > 47 && unicode < 58)) {
return true;
}
else {
window.alert("This field accepts only Numbers");
return false;
}
}
</script>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator6" runat="server" Display="None" ErrorMessage="Accepts only numbers." ControlToValidate="TextBox1" ValidationExpression="^[0-9]*$" Text="*"></asp:RegularExpressionValidator>
One option would be to use a System.ComponenetModel.BindingList rather than a list.
This allows you to use it directly within a DataGridView. And unlike a normal System.Collections.Generic.List updates the DataGridView on changes.
From the javadoc
@param the sole object to be stored in the returned list.
@return an immutable list containing only the specified object.
example
import java.util.*;
public class HelloWorld {
public static void main(String args[]) {
// create an array of string objs
String initList[] = { "One", "Two", "Four", "One",};
// create one list
List list = new ArrayList(Arrays.asList(initList));
System.out.println("List value before: "+list);
// create singleton list
list = Collections.singletonList("OnlyOneElement");
list.add("five"); //throws UnsupportedOperationException
System.out.println("List value after: "+list);
}
}
Use it when code expects a read-only list, but you only want to pass one element in it. singletonList
is (thread-)safe and fast.
I can think of a quick code like this.
Since all USB ports can be accessed via /dev/bus/usb/< bus >/< device >
For the ID generated, even if you unplug the device and reattach it [ could be some other port ]. It will be the same.
import re
import subprocess
device_re = re.compile("Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split('\n'):
if i:
info = device_re.match(i)
if info:
dinfo = info.groupdict()
dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
devices.append(dinfo)
print devices
Sample output here will be:
[
{'device': '/dev/bus/usb/001/009', 'tag': 'Apple, Inc. Optical USB Mouse [Mitsumi]', 'id': '05ac:0304'},
{'device': '/dev/bus/usb/001/001', 'tag': 'Linux Foundation 2.0 root hub', 'id': '1d6b:0002'},
{'device': '/dev/bus/usb/001/002', 'tag': 'Intel Corp. Integrated Rate Matching Hub', 'id': '8087:0020'},
{'device': '/dev/bus/usb/001/004', 'tag': 'Microdia ', 'id': '0c45:641d'}
]
import re
import subprocess
device_re = re.compile(b"Bus\s+(?P<bus>\d+)\s+Device\s+(?P<device>\d+).+ID\s(?P<id>\w+:\w+)\s(?P<tag>.+)$", re.I)
df = subprocess.check_output("lsusb")
devices = []
for i in df.split(b'\n'):
if i:
info = device_re.match(i)
if info:
dinfo = info.groupdict()
dinfo['device'] = '/dev/bus/usb/%s/%s' % (dinfo.pop('bus'), dinfo.pop('device'))
devices.append(dinfo)
print(devices)
The third inet_pton
parameter is a pointer to an in_addr
structure. After a successful inet_pton
call, the in_addr
structure will be populated with the address information. The structure's S_addr
field contains the IP address in network byte order (reverse order).
Example :
#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
int result;
uint32_t IPv4Identifier = 0;
struct in_addr addr;
// store this IP address in sa:
result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
}
else if (result == 0) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
}
else {
IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
}
return IPv4Identifier;
}
Another workaround is to use grep -o
with a little regex magic to get three chars followed by the end of line:
$ foo=1234567890
$ echo $foo | grep -o ...$
890
To make it optionally get the 1 to 3 last chars, in case of strings with less than 3 chars, you can use egrep
with this regex:
$ echo a | egrep -o '.{1,3}$'
a
$ echo ab | egrep -o '.{1,3}$'
ab
$ echo abc | egrep -o '.{1,3}$'
abc
$ echo abcd | egrep -o '.{1,3}$'
bcd
You can also use different ranges, such as 5,10
to get the last five to ten chars.
.clickable {
cursor:pointer;
}
By specifying the positions we can achieve this,
.div1 {
width:300px;
height: auto;
background-color: grey;
border:1px solid;
position:relative;
overflow:auto;
}
.div2 {
width:150px;
height:auto;
background-color: #F4A460;
float:left;
}
.div3 {
width:150px;
height:100%;
position:absolute;
right:0px;
background-color: #FFFFE0;
float:right;
}
but it is not possible to achieve this using float.
This worked for me.
In php.ini
file, change the following property.
Before:
mbstring.encoding_transration = On
After:
mbstring.encoding_transration = Off
The CSS pointer-events
property alone doesn't disable child elements from scrolling, and it's not supported by IE10 and under for DIV elements (only for SVG).
http://caniuse.com/#feat=pointer-events
To disable the contents of a DIV on all browsers.
Javascript:
$("#myDiv")
.addClass("disable")
.click(function () {
return false;
});
Css:
.disable {
opacity: 0.4;
}
// Disable scrolling on child elements
.disable div,
.disable textarea {
overflow: hidden;
}
To disable the contents of a DIV on all browsers, except IE10 and under.
Javascript:
$("#myDiv").addClass("disable");
Css:
.disable {
// Note: pointer-events not supported by IE10 and under
pointer-events: none;
opacity: 0.4;
}
// Disable scrolling on child elements
.disable div,
.disable textarea {
overflow: hidden;
}
a {
target-name: new;
target-new: tab;
}
The target-new property specifies whether new destination links should open in a new window or in a new tab of an existing window.
Note: The target-new property only works if the target-name property creates a new tab or a new window.
put the following in ~/.gdbinit
define print_vector
if $argc == 2
set $elem = $arg0.size()
if $arg1 >= $arg0.size()
printf "Error, %s.size() = %d, printing last element:\n", "$arg0", $arg0.size()
set $elem = $arg1 -1
end
print *($arg0._M_impl._M_start + $elem)@1
else
print *($arg0._M_impl._M_start)@$arg0.size()
end
end
document print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
end
After restarting gdb (or sourcing ~/.gdbinit), show the associated help like this
gdb) help print_vector
Display vector contents
Usage: print_vector VECTOR_NAME INDEX
VECTOR_NAME is the name of the vector
INDEX is an optional argument specifying the element to display
Example usage:
(gdb) print_vector videoconfig_.entries 0
$32 = {{subChannelId = 177 '\261', sourceId = 0 '\000', hasH264PayloadInfo = false, bitrate = 0, payloadType = 68 'D', maxFs = 0, maxMbps = 0, maxFps = 134, encoder = 0 '\000', temporalLayers = 0 '\000'}}
I have experienced this exact problem and found, on the users machine, one of the libraries I depended on was marked as "MISSING" in the references dialog. In that case it was some office font library that was available in my version of Office 2007, but not on the client desktop.
The error you get is a complete red herring (as pointed out by divo).
Fortunately I wasn't using anything from the library, so I was able to remove it from the XLA references entirely. I guess, an extension of divo' suggested best practice would be for testing to check the XLA on all the target Office versions (not a bad idea in any case).
In your case you can use __FILE__
variable !
It should help.
It is one of predefined.
Read more about predefined constants in PHP http://php.net/manual/en/language.constants.predefined.php
You can use Java 8 Lambda approach to achieve this. Like this:
persons.sort(Comparator.comparing(Person::getName).thenComparing(Person::getAge));
Using CTE. The idea is to join on one or more columns that form a duplicate record and then remove whichever you like:
;with cte as (
select
min(PrimaryKey) as PrimaryKey
UniqueColumn1,
UniqueColumn2
from dbo.DuplicatesTable
group by
UniqueColumn1, UniqueColumn1
having count(*) > 1
)
delete d
from dbo.DuplicatesTable d
inner join cte on
d.PrimaryKey > cte.PrimaryKey and
d.UniqueColumn1 = cte.UniqueColumn1 and
d.UniqueColumn2 = cte.UniqueColumn2;
Here is a literal pure Python translation of the Welford's algorithm implementation from http://www.johndcook.com/standard_deviation.html:
https://github.com/liyanage/python-modules/blob/master/running_stats.py
import math
class RunningStats:
def __init__(self):
self.n = 0
self.old_m = 0
self.new_m = 0
self.old_s = 0
self.new_s = 0
def clear(self):
self.n = 0
def push(self, x):
self.n += 1
if self.n == 1:
self.old_m = self.new_m = x
self.old_s = 0
else:
self.new_m = self.old_m + (x - self.old_m) / self.n
self.new_s = self.old_s + (x - self.old_m) * (x - self.new_m)
self.old_m = self.new_m
self.old_s = self.new_s
def mean(self):
return self.new_m if self.n else 0.0
def variance(self):
return self.new_s / (self.n - 1) if self.n > 1 else 0.0
def standard_deviation(self):
return math.sqrt(self.variance())
Usage:
rs = RunningStats()
rs.push(17.0)
rs.push(19.0)
rs.push(24.0)
mean = rs.mean()
variance = rs.variance()
stdev = rs.standard_deviation()
print(f'Mean: {mean}, Variance: {variance}, Std. Dev.: {stdev}')
git checkout master
git pull
should do the job.
You will get the "Your branch is behind" message every time when you work on a branch different than master, someone does changes to master and you git pull.
(branch) $ //hack hack hack, while someone push the changes to origin/master
(branch) $ git pull
now the origin/master reference is pulled, but your master is not merged with it
(branch) $ git checkout master
(master) $
now master is behind origin/master and can be fast forwarded
this will pull and merge (so merge also newer commits to origin/master)
(master) $ git pull
this will just merge what you have already pulled
(master) $ git merge origin/master
now your master and origin/master are in sync
Does this help?
http://www.quirksmode.org/js/iframe.html
I only tested this in firefox, but if you have something like this:
<iframe name='myframe' id='myframe' src='http://www.google.com'></iframe>
You can get its address by using:
document.getElementById('myframe').src
Not sure if I understood your question correctly but anyways :)
The names *args
and **kwargs
or **kw
are purely by convention. It makes it easier for us to read each other's code
One place it is handy is when using the struct module
struct.unpack()
returns a tuple whereas struct.pack()
uses a variable number of arguments. When manipulating data it is convenient to be able to pass a tuple to struck.pack()
eg.
tuple_of_data = struct.unpack(format_str, data)
... manipulate the data
new_data = struct.pack(format_str, *tuple_of_data)
without this ability you would be forced to write
new_data = struct.pack(format_str, tuple_of_data[0], tuple_of_data[1], tuple_of_data[2],...)
which also means the if the format_str changes and the size of the tuple changes, I'll have to go back and edit that really long line
You can use document.evaluate
:
Evaluates an XPath expression string and returns a result of the specified type if possible.
It is w3-standardized and whole documented: https://developer.mozilla.org/en-US/docs/Web/API/Document.evaluate
function getElementByXpath(path) {_x000D_
return document.evaluate(path, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;_x000D_
}_x000D_
_x000D_
console.log( getElementByXpath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo</div>
_x000D_
https://gist.github.com/yckart/6351935
There's also a great introduction on mozilla developer network: https://developer.mozilla.org/en-US/docs/Introduction_to_using_XPath_in_JavaScript#document.evaluate
Alternative version, using XPathEvaluator
:
function getElementByXPath(xpath) {_x000D_
return new XPathEvaluator()_x000D_
.createExpression(xpath)_x000D_
.evaluate(document, XPathResult.FIRST_ORDERED_NODE_TYPE)_x000D_
.singleNodeValue_x000D_
}_x000D_
_x000D_
console.log( getElementByXPath("//html[1]/body[1]/div[1]") );
_x000D_
<div>foo/bar</div>
_x000D_
Incase it helps someone - I have used this before and seems to do what I need it to...
public static bool HasValueAndIsNotDefault<T>(this T? v)
where T : struct
{
return v.HasValue && !v.Value.Equals(default(T));
}
Change your nginx.conf
user
property to www-static
files owener.
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user your_user_name;
# same other config
Per Caching SHA-2 Pluggable Authentication
In MySQL 8.0,
caching_sha2_password
is the default authentication plugin rather thanmysql_native_password
.
You're using mysql_native_password
, which is no longer the default. Assuming you're using the correct connector for your version you need to specify the auth_plugin
argument when instantiating your connection object
cnx = mysql.connector.connect(user='lcherukuri', password='password',
host='127.0.0.1', database='test',
auth_plugin='mysql_native_password')
From those same docs:
The
connect()
method supports anauth_plugin
argument that can be used to force use of a particular plugin. For example, if the server is configured to usesha256_password
by default and you want to connect to an account that authenticates usingmysql_native_password
, either connect using SSL or specifyauth_plugin='mysql_native_password'
.
The docs are pretty clear on this: HashSet.add
doesn't replace:
Adds the specified element to this set if it is not already present. More formally, adds the specified element e to this set if this set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false.
But HashMap.put
will replace:
If the map previously contained a mapping for the key, the old value is replaced.
not about efficiency, but easy to follow, here is an example of unions and intersections of sets, it handles arrays of sets and sets of sets.
http://jsfiddle.net/zhulien/NF68T/
// process array [element, element...], if allow abort ignore the result
function processArray(arr_a, cb_a, blnAllowAbort_a)
{
var arrResult = [];
var blnAborted = false;
var intI = 0;
while ((intI < arr_a.length) && (blnAborted === false))
{
if (blnAllowAbort_a)
{
blnAborted = cb_a(arr_a[intI]);
}
else
{
arrResult[intI] = cb_a(arr_a[intI]);
}
intI++;
}
return arrResult;
}
// process array of operations [operation,arguments...]
function processOperations(arrOperations_a)
{
var arrResult = [];
var fnOperationE;
for(var intI = 0, intR = 0; intI < arrOperations_a.length; intI+=2, intR++)
{
var fnOperation = arrOperations_a[intI+0];
var fnArgs = arrOperations_a[intI+1];
if (fnArgs === undefined)
{
arrResult[intR] = fnOperation();
}
else
{
arrResult[intR] = fnOperation(fnArgs);
}
}
return arrResult;
}
// return whether an element exists in an array
function find(arr_a, varElement_a)
{
var blnResult = false;
processArray(arr_a, function(varToMatch_a)
{
var blnAbort = false;
if (varToMatch_a === varElement_a)
{
blnResult = true;
blnAbort = true;
}
return blnAbort;
}, true);
return blnResult;
}
// return the union of all sets
function union(arr_a)
{
var arrResult = [];
var intI = 0;
processArray(arr_a, function(arrSet_a)
{
processArray(arrSet_a, function(varElement_a)
{
// if the element doesn't exist in our result
if (find(arrResult, varElement_a) === false)
{
// add it
arrResult[intI] = varElement_a;
intI++;
}
});
});
return arrResult;
}
// return the intersection of all sets
function intersection(arr_a)
{
var arrResult = [];
var intI = 0;
// for each set
processArray(arr_a, function(arrSet_a)
{
// every number is a candidate
processArray(arrSet_a, function(varCandidate_a)
{
var blnCandidate = true;
// for each set
processArray(arr_a, function(arrSet_a)
{
// check that the candidate exists
var blnFoundPart = find(arrSet_a, varCandidate_a);
// if the candidate does not exist
if (blnFoundPart === false)
{
// no longer a candidate
blnCandidate = false;
}
});
if (blnCandidate)
{
// if the candidate doesn't exist in our result
if (find(arrResult, varCandidate_a) === false)
{
// add it
arrResult[intI] = varCandidate_a;
intI++;
}
}
});
});
return arrResult;
}
var strOutput = ''
var arrSet1 = [1,2,3];
var arrSet2 = [2,5,6];
var arrSet3 = [7,8,9,2];
// return the union of the sets
strOutput = union([arrSet1, arrSet2, arrSet3]);
alert(strOutput);
// return the intersection of 3 sets
strOutput = intersection([arrSet1, arrSet2, arrSet3]);
alert(strOutput);
// of 3 sets of sets, which set is the intersecting set
strOutput = processOperations([intersection,[[arrSet1, arrSet2], [arrSet2], [arrSet2, arrSet3]]]);
alert(strOutput);
In addition to @canvastag, use a while
loop with shift
I think is more concise:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var poly = [5, 5, 100, 50, 50, 100, 10, 90];
// copy array
var shape = poly.slice(0);
ctx.fillStyle = '#f00'
ctx.beginPath();
ctx.moveTo(shape.shift(), shape.shift());
while(shape.length) {
ctx.lineTo(shape.shift(), shape.shift());
}
ctx.closePath();
ctx.fill();
This XML file does not appear to have any style information associated with it. The document tree is shown below.
You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml
instead of text/html
and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.
In case of JSF/Facelets files which have the default extension of .xhtml
, that can in turn happen if the HTTP request hasn't invoked the FacesServlet
and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml
file extension which is in your Firefox configuration apparently by default interpreted as text/xml
.
You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern>
of the FacesServlet
as registered in webapp's web.xml
, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf
, then you need to open the page by /some.jsf
instead of /some.xhtml
. Alternatively, you can also just change the <url-pattern>
to *.xhtml
. This way you never need to fiddle with virtual URLs.
Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.
corrcoef
returns the normalised covariance matrix.
The covariance matrix is the matrix
Cov( X, X ) Cov( X, Y )
Cov( Y, X ) Cov( Y, Y )
Normalised, this will yield the matrix:
Corr( X, X ) Corr( X, Y )
Corr( Y, X ) Corr( Y, Y )
correlation1[0, 0 ]
is the correlation between Strategy1Returns
and itself, which must be 1. You just want correlation1[ 0, 1 ]
.
You can move this code to index.html for preload images from any url
<link rel="preload" href="https://via.placeholder.com/160" as="image">
I just went throughout this and I hovering here for an answer.. In my case the solution was to clear the browser history.
Maybe
SELECT count(*) FROM (
SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total
although that would not be the sum of all the movies, just how many have 4 genre's.
So maybe you want
SELECT sum(
SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total
Is there any good example to give the difference between a 'struct' and a 'union'?
An imaginary communications protocol
struct packetheader {
int sourceaddress;
int destaddress;
int messagetype;
union request {
char fourcc[4];
int requestnumber;
};
};
In this imaginary protocol, it has been sepecified that, based on the "message type", the following location in the header will either be a request number, or a four character code, but not both. In short, unions allow for the same storage location to represent more than one data type, where it is guaranteed that you will only want to store one of the types of data at any one time.
Unions are largely a low-level detail based in C's heritage as a system programming language, where "overlapping" storage locations are sometimes used in this way. You can sometimes use unions to save memory where you have a data structure where only one of several types will be saved at one time.
In general, the OS doesn't care or know about structs and unions -- they are both simply blocks of memory to it. A struct is a block of memory that stores several data objects, where those objects don't overlap. A union is a block of memory that stores several data objects, but has only storage for the largest of these, and thus can only store one of the data objects at any one time.
If you have a gradle module with the same name as your projects root folder, the gradle import will replace your toplevel module configuration and change your view completely.
Make sure you have no gradle module with the same name as your root directory.
mongod
wasn't working to start the daemon for me but after I ran the following, it started working:
'mongod --fork --logpath /var/log/mongodb.log'
(from here: https://docs.mongodb.com/manual/tutorial/manage-mongodb-processes/)
One liner is best
kill -9 $(lsof -i:PORT -t) 2> /dev/null
Example : On mac, wanted to clear port 9604. Following command worked like a charm
kill -9 $(lsof -i:9604 -t) 2> /dev/null
<a href="<?php echo $_SERVER['DOCUMENT_ROOT'].'/hello.html'; ?>">go with php</a>
<br />
<a href="/hello.html">go to with html</a>
Try this yourself and find that they are not exactly the same.
$_SERVER['DOCUMENT_ROOT']
renders an actual file path (on my computer running as it's own server, C:/wamp/www/
HTML's /
renders the root of the server url, in my case, localhost/
But C:/wamp/www/hello.html
and localhost/hello.html
are in fact the same file
Instead of this :
for(int a = 0, b = 1; a<cards.length-1; b=a+1; a++;){
It should be
for(int a = 0, b = 1; a<cards.length()-1; b=a+1, a++){
^ ^ ^
| | |
| | |
-------------------------------------------Note the changes
|
v |
if(rank==cards.substring(a,b){ |
-------------------------------------------------------------
|
v
System.out.println(c); //capital S in system
Use find
with a wildcard:
find . -name 'mystring*'
As stated in an article by Slicehost:
User setup
So let's start by adding the main user to the Apache user group:
sudo usermod -a -G www-data demo
That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.
You will need to log out and log back in again to enable the group change.
Check the groups now:
groups ... # demo www-data
So now I am a member of two groups: My own (demo) and the Apache group (www-data).
Folder setup
Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).
Let's set that up:
sudo chgrp -R www-data /home/demo/public_html
As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.
If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.
Setgid
Good so far, but remember the command we just gave only affects existing folders. What about anything new?
We can set the ownership so anything new is also in the 'www-data' group.
The first command will change the permissions for the public_html directory to include the "setgid" bit:
sudo chmod 2750 /home/demo/public_html
That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.
If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:
sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads
The permissions only need to be set once as new files will automatically be assigned the correct ownership.
Maybe you'd find Redux suiting your needs. It's no overkill and comes packed solely with bare features most of us would require. The dev and contributors were very strict on what code was contributed.
This is the official page
You just need to add @JoinColumn(name="column_name")
to Host Entity relation . column_name is the database column name in person table.
@Entity
public class Person {
@Id
public int id;
@OneToOne
@JoinColumn(name="other_info")
public OtherInfo otherInfo;
rest of attributes ...
}
Person has a one-to-one relationship with OtherInfo: mappedBy="var_name" var_name is variable name for otherInfo in Person class.
@Entity
public class OtherInfo {
@Id
@OneToOne(mappedBy="otherInfo")
public Person person;
rest of attributes ...
}
this work for me
ncharacters.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent openncharacter = new Intent(getApplicationContext(),ncharacters.class);
startActivity(openncharacter);
}
});
File protocol URIs are like this
file://[HOST]/[PATH]
that's why you often see file URLs like this (3 slashes) file:///c:\path...
So if the host is server01, you want
file://server01/folder/path....
This is according to the wikipedia page on file:// protocols and checks out with .NET's Uri.IsWellFormedUriString method.
You need to use
$rootScope.$broadcast()
in the controller that must send datas. And in the one that receive those datas, you use
$scope.$on
Here is a fiddle that i forked a few time ago (I don't know who did it first anymore
Sometimes Google Chrome throws this error, even if it should not. I experienced it when Chrome had a new version, and it needed to be restarted. After restarting the same page worked without any errors. The error in the console was:
net::ERR_INSECURE_RESPONSE
the very same as above, here is my solution
template<typename TString>
inline bool starts_with(const TString& str, const TString& start) {
if (start.size() > str.size()) return false;
return str.compare(0, start.size(), start) == 0;
}
template<typename TString>
inline bool ends_with(const TString& str, const TString& end) {
if (end.size() > str.size()) return false;
return std::equal(end.rbegin(), end.rend(), str.rbegin());
}
To clarify why the other answers can not work:
System.gc()
(along with Runtime.getRuntime().gc()
, which does the exact same thing) hints that you want stuff destroyed. Vaguely. The JVM is free to ignore requests to run a GC cycle, if it doesn't see the need for one. Plus, unless you've nulled out all reachable references to the object, GC won't touch it anyway. So A and B are both disqualified.
Runtime.getRuntime.gc()
is bad grammar. getRuntime
is a function, not a variable; you need parentheses after it to call it. So B is double-disqualified.
Object
has no delete
method. So C is disqualified.
While Object
does have a finalize
method, it doesn't destroy anything. Only the garbage collector can actually delete an object. (And in many cases, they technically don't even bother to do that; they just don't copy it when they do the others, so it gets left behind.) All finalize
does is give an object a chance to clean up before the JVM discards it. What's more, you should never ever be calling finalize
directly. (As finalize
is protected, the JVM won't let you call it on an arbitrary object anyway.) So D is disqualified.
Besides all that, object.doAnythingAtAllEvenCommitSuicide()
requires that running code have a reference to object
. That alone makes it "alive" and thus ineligible for garbage collection. So C and D are double-disqualified.
No, you can't undo, rollback or reverse a commit.
(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE
or similar, not an rm -rf /data/directory
scenario).
If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate
so that no checkpoint is run on shutdown.
You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.
If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.
Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base
, pg_clog
, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog
etc. No part is unimportant.
Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.
If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT
or UPDATE
. Thus, the old versions of the UPDATE
d rows might still be lying around, present but inaccessible.
Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter
and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl
in immediate
mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.
Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.
You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.
I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOAST
ed data so it's of limited utility. Give it a try, if you're lucky it might work.
See: pg_dirtyread on GitHub.
I've removed what I'd written in this section as it's obsoleted by that tool.
See also PostgreSQL row storage fundamentals
See my blog entry Preventing PostgreSQL database corruption.
On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED
for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.
You have misunderstood the Python list
object. It is similar to a C pointer-array
. It does not actually "copy" the object which you append to it. Instead, it just store a "pointer" to that object.
Try the following code:
>>> d={}
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d)
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print(dlist)
[{'data': 2}, {'data': 2}, {'data': 2}]
So why is print(dlist)
not the same as print(d)
?
The following code shows you the reason:
>>> for i in dlist:
print "the list item point to object:", id(i)
the list item point to object: 47472232
the list item point to object: 47472232
the list item point to object: 47472232
So you can see all the items in the dlist
is actually pointing to the same dict
object.
The real answer to this question will be to append the "copy" of the target item, by using d.copy()
.
>>> dlist=[]
>>> for i in xrange(0,3):
d['data']=i
dlist.append(d.copy())
print(d)
{'data': 0}
{'data': 1}
{'data': 2}
>>> print dlist
[{'data': 0}, {'data': 1}, {'data': 2}]
Try the id()
trick, you can see the list items actually point to completely different objects.
>>> for i in dlist:
print "the list item points to object:", id(i)
the list item points to object: 33861576
the list item points to object: 47472520
the list item points to object: 47458120
You need to enable SQL Server Authentication:
add this single line to your relative activity where key board cover edit text.inside onCreat()method of activity.
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
moment.utc(date).format(...);
is the way to go, since
moment().utc(date).format(...);
does behave weird...
If you still didn't understand after reading the marvellous answers given above.
Here are two simple examples of how you can achieve it.
.wrapper {_x000D_
display: table-cell;_x000D_
vertical-align: middle;_x000D_
text-align: center;_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
border: 1px solid #555;_x000D_
}_x000D_
_x000D_
.container {_x000D_
display: inline-block;_x000D_
text-align: left;_x000D_
padding: 20px;_x000D_
border: 1px solid #cd0000;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="container">_x000D_
Center align a div using "<strong>display: table-cell</strong>"_x000D_
</div>_x000D_
</div>
_x000D_
.wrapper {_x000D_
display: flex;_x000D_
justify-content: center;_x000D_
width: 400px;_x000D_
height: 300px;_x000D_
border: 1px solid #555;_x000D_
}_x000D_
_x000D_
.container {_x000D_
align-self: center;_x000D_
padding: 20px;_x000D_
border: 1px solid #cd0000;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div class="container">_x000D_
Centering a div using "<strong>display: flex</strong>"_x000D_
</div>_x000D_
</div>
_x000D_
Note: Check the browser compatibility of display: table-cell and flex before using the above mentioned implementations.
You can use the description
method inherited by NSDictionary
from NSObject
, or write a custom method that formats NSDictionary
to your liking.
try once:-
USE master
DECLARE @portNumber NVARCHAR(10)
EXEC xp_instance_regread
@rootkey = 'HKEY_LOCAL_MACHINE',
@key =
'Software\Microsoft\Microsoft SQL Server\MSSQLServer\SuperSocketNetLib\Tcp\IpAll',
@value_name = 'TcpDynamicPorts',
@value = @portNumber OUTPUT
SELECT [Port Number] = @portNumber
GO
If you can have dependency to apache utils you can use org.apache.commons.lang3.SystemUtils.
System.out.println("Is Java version at least 1.8: " + SystemUtils.isJavaVersionAtLeast(JavaVersion.JAVA_1_8));
Element.style
MDNvar toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.style.display = (content.dataset.toggled ^= 1) ? "block" : "none";
});
_x000D_
#content{
display:none;
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
About the ^
bitwise XOR as I/O toggler
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/dataset
.classList.toggle()
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function() {
content.classList.toggle("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggle()
Docs; .fadeToggle()
Docs; .slideToggle()
Docs$("#toggle").on("click", function(){
$("#content").toggle(); // .fadeToggle() // .slideToggle()
});
_x000D_
#content{
display:none;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
.toggleClass()
Docs.toggle()
toggles an element's display
"block"/"none"
values
$("#toggle").on("click", function(){
$("#content").toggleClass("show");
});
_x000D_
#content{
display:none;
}
#content.show{
display:block; /* P.S: Use `!important` if missing `#content` (selector specificity). */
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="toggle">TOGGLE</button>
<div id="content">Some content...</div>
_x000D_
<summary>
and <details>
(unsupported on IE and Opera Mini)
<details>
<summary>TOGGLE</summary>
<p>Some content...</p>
</details>
_x000D_
checkbox
[id^=toggle],
[id^=toggle] + *{
display:none;
}
[id^=toggle]:checked + *{
display:block;
}
_x000D_
<label for="toggle-1">TOGGLE</label>
<input id="toggle-1" type="checkbox">
<div>Some content...</div>
_x000D_
radio
[id^=switch],
[id^=switch] + *{
display:none;
}
[id^=switch]:checked + *{
display:block;
}
_x000D_
<label for="switch-1">SHOW 1</label>
<label for="switch-2">SHOW 2</label>
<input id="switch-1" type="radio" name="tog">
<div>1 Merol Muspi...</div>
<input id="switch-2" type="radio" name="tog">
<div>2 Lorem Ipsum...</div>
_x000D_
:target
(just to make sure you have it in your arsenal)
[id^=switch] + *{
display:none;
}
[id^=switch]:target + *{
display:block;
}
_x000D_
<a href="#switch1">SHOW 1</a>
<a href="#switch2">SHOW 2</a>
<i id="switch1"></i>
<div>1 Merol Muspi ...</div>
<i id="switch2"></i>
<div>2 Lorem Ipsum...</div>
_x000D_
If you pick one of JS / jQuery way to actually toggle a className
, you can always add animated transitions to your element, here's a basic example:
var toggle = document.getElementById("toggle");
var content = document.getElementById("content");
toggle.addEventListener("click", function(){
content.classList.toggle("appear");
}, false);
_x000D_
#content{
/* DON'T USE DISPLAY NONE/BLOCK! Instead: */
background: #cf5;
padding: 10px;
position: absolute;
visibility: hidden;
opacity: 0;
transition: 0.6s;
-webkit-transition: 0.6s;
transform: translateX(-100%);
-webkit-transform: translateX(-100%);
}
#content.appear{
visibility: visible;
opacity: 1;
transform: translateX(0);
-webkit-transform: translateX(0);
}
_x000D_
<button id="toggle">TOGGLE</button>
<div id="content">Some Togglable content...</div>
_x000D_
Conditional compilation directives are your friend:
#if DEBUG
var jsBundle = new Bundle("~/Scripts/js");
#else
var jsBundle = new ScriptBundle("~/Scripts/js");
#endif
This issue has been fixed in the regular release of MVC4. Now you can do:
public string GetFindBooks(string author="", string title="", string isbn="", string somethingelse="", DateTime? date= null)
{
// ...
}
and everything will work out of the box.
Copied from the formal specification: ECMAScript 5.1 section 11.9.5
11.9.4 The Strict Equals Operator ( === )
The production EqualityExpression : EqualityExpression === RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref).
- Return the result of performing the strict equality comparison rval === lval. (See 11.9.6)
11.9.5 The Strict Does-not-equal Operator ( !== )
The production EqualityExpression : EqualityExpression !== RelationalExpression is evaluated as follows:
- Let lref be the result of evaluating EqualityExpression.
- Let lval be GetValue(lref).
- Let rref be the result of evaluating RelationalExpression.
- Let rval be GetValue(rref). Let r be the result of performing strict equality comparison rval === lval. (See 11.9.6)
- If r is true, return false. Otherwise, return true.
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or false. Such a comparison is performed as follows:
- If Type(x) is different from Type(y), return false.
- Type(x) is Undefined, return true.
- Type(x) is Null, return true.
- Type(x) is Number, then
- If x is NaN, return false.
- If y is NaN, return false.
- If x is the same Number value as y, return true.
- If x is +0 and y is -0, return true.
- If x is -0 and y is +0, return true.
- Return false.
- If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions); otherwise, return false.
- If Type(x) is Boolean, return true if x and y are both true or both false; otherwise, return false.
- Return true if x and y refer to the same object. Otherwise, return false.
Just use dictionary comprehension to copy the relevant items into a new dict
>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = { k : v for k,v in d.iteritems() if v}
>>> d
{'a': [1], 'b': [1, 2]}
For this in Python 3
>>> d
{'a': [1], 'c': [], 'b': [1, 2], 'd': []}
>>> d = { k : v for k,v in d.items() if v}
>>> d
{'a': [1], 'b': [1, 2]}
In simple way, you can use the following code to clear all the text field, textarea, dropdown, radio button, checkbox in a form.
function reset(){
$('input[type=text]').val('');
$('#textarea').val('');
$('input[type=select]').val('');
$('input[type=radio]').val('');
$('input[type=checkbox]').val('');
}
You could try something like:
char ch;
fstream fin("file", fstream::in);
while (fin >> noskipws >> ch) {
cout << ch; // Or whatever
}
You are right that greediness is an issue:
--A--Z--A--Z--
^^^^^^^^^^
A.*Z
If you want to match both A--Z
, you'd have to use A.*?Z
(the ?
makes the *
"reluctant", or lazy).
There are sometimes better ways to do this, though, e.g.
A[^Z]*+Z
This uses negated character class and possessive quantifier, to reduce backtracking, and is likely to be more efficient.
In your case, the regex would be:
/(\[[^\]]++\])/
Unfortunately Javascript regex doesn't support possessive quantifier, so you'd just have to do with:
/(\[[^\]]+\])/
* Zero or more, greedy
*? Zero or more, reluctant
*+ Zero or more, possessive
+ One or more, greedy
+? One or more, reluctant
++ One or more, possessive
? Zero or one, greedy
?? Zero or one, reluctant
?+ Zero or one, possessive
Note that the reluctant and possessive quantifiers are also applicable to the finite repetition {n,m}
constructs.
Examples in Java:
System.out.println("aAoZbAoZc".replaceAll("A.*Z", "!")); // prints "a!c"
System.out.println("aAoZbAoZc".replaceAll("A.*?Z", "!")); // prints "a!b!c"
System.out.println("xxxxxx".replaceAll("x{3,5}", "Y")); // prints "Yx"
System.out.println("xxxxxx".replaceAll("x{3,5}?", "Y")); // prints "YY"
In your C# code, you are using transaction for the command. Just commit the transaction and after that access your parameter value, you will get the value. Worked for me. :)
You are using g++ 4.6 version you must invoke the flag -std=c++0x to compile
g++ -std=c++0x *.cpp -o output
You can use Cell.Interior.Color
, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).
localStorage.clear();
or
window.localStorage.clear();
to clear particular item
window.localStorage.removeItem("item_name");
To remove particular value by id :
var item_detail = JSON.parse(localStorage.getItem("key_name")) || [];
$.each(item_detail, function(index, obj){
if (key_id == data('key')) {
item_detail.splice(index,1);
localStorage["key_name"] = JSON.stringify(item_detail);
return false;
}
});
Delete the finalizers block from resource (pod,deployment,ds etc...) yaml:
"finalizers": [
"foregroundDeletion"
]
For a path use os.path.abspath
import os
print os.path.abspath(my_file_path)
Simply create a .bat file with the following lines in it:
@ECHO OFF
set CLASSPATH=.
set CLASSPATH=%CLASSPATH%;path/to/needed/jars/my.jar
%JAVA_HOME%\bin\java -Xms128m -Xmx384m -Xnoclassgc ro.my.class.MyClass
I am also having the same problem. I have a json which is to be converted to ArrayList.
Account looks like this.
Account{
Person p ;
Related r ;
}
Person{
String Name ;
Address a ;
}
All of the above classes have been annotated properly. I have tried TypeReference>() {} but is not working.
It gives me Arraylist but ArrayList has a linkedHashMap which contains some more linked hashmaps containing final values.
My code is as Follows:
public T unmarshal(String responseXML,String c)
{
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);
mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
try
{
this.targetclass = (T) mapper.readValue(responseXML, new TypeReference<ArrayList<T>>() {});
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return this.targetclass;
}
I finally solved the problem. I am able to convert the List in Json String directly to ArrayList as follows:
JsonMarshallerUnmarshaller<T>{
T targetClass ;
public ArrayList<T> unmarshal(String jsonString)
{
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig().withAnnotationIntrospector(introspector);
mapper.getSerializationConfig().withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(ArrayList.class, targetclass.getClass()) ;
try
{
Class c1 = this.targetclass.getClass() ;
Class c2 = this.targetclass1.getClass() ;
ArrayList<T> temp = (ArrayList<T>) mapper.readValue(jsonString, type);
return temp ;
}
catch (JsonParseException e)
{
e.printStackTrace();
}
catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
Suppose if we are calling a form from a menu click on MDI form, then we need to create the instance declaration of that form at top level like this:
Form1 fm = null;
Then we need to define the menu click event to call the Form1 as follows:
private void form1ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (fm == null|| fm.Text=="")
{
fm = new Form1();
fm.MdiParent = this;
fm.Dock = DockStyle.Fill;
fm.Show();
}
else if (CheckOpened(fm.Text))
{
fm.WindowState = FormWindowState.Normal;
fm.Dock = DockStyle.Fill;
fm.Show();
fm.Focus();
}
}
The CheckOpened defined to check the Form1 is already opened or not:
private bool CheckOpened(string name)
{
FormCollection fc = Application.OpenForms;
foreach (Form frm in fc)
{
if (frm.Text == name)
{
return true;
}
}
return false;
}
Hope this will solve the issues on creating multiple instance of a form also getting focus to the Form1 on menu click if it is already opened or minimized.
with ggplot2:
library(ggplot2)
Animals <- read.table(
header=TRUE, text='Category Reason Species
1 Decline Genuine 24
2 Improved Genuine 16
3 Improved Misclassified 85
4 Decline Misclassified 41
5 Decline Taxonomic 2
6 Improved Taxonomic 7
7 Decline Unclear 41
8 Improved Unclear 117')
ggplot(Animals, aes(factor(Reason), Species, fill = Category)) +
geom_bar(stat="identity", position = "dodge") +
scale_fill_brewer(palette = "Set1")
Or you can trigger a custom event when one function completes, then bind it to the document:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
Here is my approach:
labels = [0, 0, 1, 1]
from collections import Counter
from scipy import stats
stats.entropy(list(Counter(labels).values()), base=2)
It's much easier if you use Response.raw
and shutil.copyfileobj()
:
import requests
import shutil
def download_file(url):
local_filename = url.split('/')[-1]
with requests.get(url, stream=True) as r:
with open(local_filename, 'wb') as f:
shutil.copyfileobj(r.raw, f)
return local_filename
This streams the file to disk without using excessive memory, and the code is simple.
sed -E interprets regular expressions as extended (modern) regular expressions
Update: -E on MacOS X, -r in GNU sed.
Try
<img src="assets/img/logo.png" align="left" />
Text Goes here
Simple HTML Attribute:
align="left"
Other values for attribute:
If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:
ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
will give you a ScheduledExecutorService
with similar functionality to Timer
(i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer
class). Using a ScheduledExecutorService
also gives you advantages such as:
newScheduledThreadPoolExecutor()
or the ScheduledThreadPoolExecutor
class)About the only reasons for sticking to Timer
I can think of are:
Try to run xcrun simctl delete unavailable
in your terminal.
Original answer: Xcode - free to clear devices folder?
Provided that any element has the id attribute on a webpage. One could simply link/jump to the element that is referenced by the tag.
Within the same page:
<div id="markOne"> ..... </div>
......
<a href="#markOne">Jump to markOne</a>
Other page:
<div id="http://randomwebsite.com/mypage.html#markOne">
Jumps to the markOne element in the mypage of the linked website
</div>
The targets don't necessarily have an anchor element.
You can go check this fiddle out.
org.apache.maven.plugins:maven-source-plugin
does not exist in the repository http://repo.maven.apache.org/maven2.
You have to download it from Maven central where it exists => maven-source-plugin
Verify your pom definition or your settings.xml file.
Same as matt said. The "SQL Server(SQLEXPRESS)" was stopped. Enabled it by opening Control Panel > Administrative Tools > Services, right-clicking on the "SQL Server(SQLEXPRESS)" service and selecting "Start" from the available options. Could connect fine after that.
One very small nit to pick:
The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:
"john@work"@myemployer.com
This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:
SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1
More information:
Check std::mismatch
method of C++.
comparing vectors has been discussed on DaniWeb forum and also answered.
Check the below SO post. will helpful for you. they have achieved the same with different-2 method.
This looks a little ugly. Is it possible to cast an entire stream to a different type? Like cast
Stream<Object>
to aStream<Client>
?
No that wouldn't be possible. This is not new in Java 8. This is specific to generics. A List<Object>
is not a super type of List<String>
, so you can't just cast a List<Object>
to a List<String>
.
Similar is the issue here. You can't cast Stream<Object>
to Stream<Client>
. Of course you can cast it indirectly like this:
Stream<Client> intStream = (Stream<Client>) (Stream<?>)stream;
but that is not safe, and might fail at runtime. The underlying reason for this is, generics in Java are implemented using erasure. So, there is no type information available about which type of Stream
it is at runtime. Everything is just Stream
.
BTW, what's wrong with your approach? Looks fine to me.
IQueryable query = from x in appEntities
where x.id = 32
select x;
var queryString = query.ToString();
Will return the sql query. Working using datacontext of EntityFramework 6
you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.
Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html
If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.
There are (more than) three popular ways to use MySQL from PHP. This outlines some features/differences PHP: Choosing an API:
I would recommend using PDO with prepared statements. It is a well-designed API and will let you more easily move to another database (including any that supports ODBC) if necessary.
In my case $1 was not working, but $0 works fine for my purpose.
In this case I was trying to replace strings with the correct format to translate them in Laravel, I hope this could be useful to someone else because it took me a while to sort it out!
Search: (?<=<div>).*?(?=</div>)
Replace: {{ __('$0') }}
Java 8 with apache httpClient 4
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("www.site.com");
String json = "details={\"name\":\"myname\",\"age\":\"20\"} ";
try {
StringEntity entity = new StringEntity(json);
httpPost.setEntity(entity);
// set your POST request headers to accept json contents
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
try {
// your closeablehttp response
CloseableHttpResponse response = client.execute(httpPost);
// print your status code from the response
System.out.println(response.getStatusLine().getStatusCode());
// take the response body as a json formatted string
String responseJSON = EntityUtils.toString(response.getEntity());
// convert/parse the json formatted string to a json object
JSONObject jobj = new JSONObject(responseJSON);
//print your response body that formatted into json
System.out.println(jobj);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
If all vectors have equal size, create a matrix and plot it.
Each column is plotted with a different color automatically
Then you can use legend
to indicate columns:
data = randn(100, 5);
figure;
plot(data);
legend(cellstr(num2str((1:size(data,2))')))
Or, if you have a cell with kernels names, use
legend(names)
Here's my go with comments in the code.
I'm just brushing up by biatch skills so forgive any blatant errors.
I tried to write an all in one solution as best I can with a little modification where the user requires it.
Some important notes: Just change the variable recursive
to FALSE
if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.
C&C most welcome...
@echo off
title %~nx0
chcp 65001 >NUL
set "dir=c:\users\%username%\desktop"
::
:: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1
::
setlocal EnableDelayedExpansion
rem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]
rem By removing the /s switch from the first loop if you want to loop through
rem the base folder only.
set recursive=TRUE
if %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )
endlocal & set recursive=%recursive%
cd /d %dir%
echo Directory %cd%
for %%F in ("*") do (echo ? %%F) %= Loop through the current directory. =%
for /f "delims==" %%D in ('dir "%dir%" /ad /b %recursive%') do ( %= Loop through the sub-directories only if the recursive variable is TRUE. =%
echo Directory %%D
echo %recursive% | find "/s" >NUL 2>NUL && (
pushd %%D
cd /d %%D
for /f "delims==" %%F in ('dir "*" /b') do ( %= Then loop through each pushd' folder and work on the files and folders =%
echo %%~aF | find /v "d" >NUL 2>NUL && ( %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%
rem You can do stuff to your files here.
rem Below are some examples of the info you can get by expanding the %%F variable.
rem Uncomment one at a time to see the results.
echo ? %%~F &rem expands %%F removing any surrounding quotes (")
rem echo ? %%~dF &rem expands %%F to a drive letter only
rem echo ? %%~fF &rem expands %%F to a fully qualified path name
rem echo ? %%~pF &rem expands %%A to a path only
rem echo ? %%~nF &rem expands %%F to a file name only
rem echo ? %%~xF &rem expands %%F to a file extension only
rem echo ? %%~sF &rem expanded path contains short names only
rem echo ? %%~aF &rem expands %%F to file attributes of file
rem echo ? %%~tF &rem expands %%F to date/time of file
rem echo ? %%~zF &rem expands %%F to size of file
rem echo ? %%~dpF &rem expands %%F to a drive letter and path only
rem echo ? %%~nxF &rem expands %%F to a file name and extension only
rem echo ? %%~fsF &rem expands %%F to a full path name with short names only
rem echo ? %%~dp$dir:F &rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
rem echo ? %%~ftzaF &rem expands %%F to a DIR like output line
)
)
popd
)
)
echo/ & pause & cls
I would say to set up the font size change in your CSS stylesheet file.
I'm pretty sure that you want all text at the same size for all your form fields. Adding inline styles in your HTML will add to many lines at the end... plus you would need to add it to the other types of form fields such as <select>
.
HTML:
<div id="cForm">
<form method="post">
<input type="text" name="name" placeholder="Name" data-required="true">
<option value="" selected="selected" >Choose Category...</option>
</form>
</div>
CSS:
input, select {
font-size: 18px;
}
Just define them yourself.
#ifdef _MSC_VER
typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
typedef __int64 int64_t;
typedef unsigned __int64 uint64_t;
#else
#include <stdint.h>
#endif
Python has the pickle module just for this kind of thing.
These functions are all that you need for saving and loading almost any object:
def save_obj(obj, name ):
with open('obj/'+ name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(name ):
with open('obj/' + name + '.pkl', 'rb') as f:
return pickle.load(f)
These functions assume that you have an obj
folder in your current working directory, which will be used to store the objects.
Note that pickle.HIGHEST_PROTOCOL
is a binary format, which could not be always convenient, but is good for performance. Protocol 0
is a text format.
In order to save collections of Python there is the shelve module.
Other alternatives to an installer and gacutil are GUI tools like Gac Manager or GACAdmin. Or if you like PowerShell you could use PowerShell GAC from which I am the author.
I know this thread is really old but the solution from @Ivan Bondarenko helped me in my situation.
I had the following in my pom.xml
.
<build>
...
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<execution>
<id>generate-citrus-war</id>
<goals>
<goal>test-war</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
What I wanted, was to disable the execution of generate-citrus-war
for a specific profile and this was the solution:
<profile>
<id>it</id>
<build>
<plugins>
<plugin>
<groupId>com.consol.citrus</groupId>
<artifactId>citrus-remote-maven-plugin</artifactId>
<version>${citrus.version}</version>
<executions>
<!-- disable generating the war for this profile -->
<execution>
<id>generate-citrus-war</id>
<phase/>
</execution>
<!-- do something else -->
<execution>
...
</execution>
</executions>
</plugin>
</plugins>
</build>
</profile>
how to retrieve keystore password
You cannot retrieve the password. If you forgot it, you are doomed.
how to retrieve key alias
$ keytool -list -v -keystore <store>
But you need keystore password for this first.
EDIT
What I don't remember is the 'Key Password'
No password can be restored. If you forgot key password for good then you are doomed too and there's no other way than trying harder to recall it. There's no password reset thing nor anything like that.
Be aware that if you forgot your password for good then you will issue no further updates to your app (docs):
Warning: Keep your keystore and private key in a safe and secure place, and ensure that you have secure backups of them. If you publish an app to Google Play and then lose the key with which you signed your app, you will not be able to publish any updates to your app, since you must always sign all versions of your app with the same key.
Swift 4 version of accepted answer:
@IBDesignable
class CircledDotView: UIView {
@IBInspectable var mainColor: UIColor = .white {
didSet { print("mainColor was set here") }
}
@IBInspectable var ringColor: UIColor = .black {
didSet { print("bColor was set here") }
}
@IBInspectable var ringThickness: CGFloat = 4 {
didSet { print("ringThickness was set here") }
}
@IBInspectable var isSelected: Bool = true
override func draw(_ rect: CGRect) {
let dotPath = UIBezierPath(ovalIn: rect)
let shapeLayer = CAShapeLayer()
shapeLayer.path = dotPath.cgPath
shapeLayer.fillColor = mainColor.cgColor
layer.addSublayer(shapeLayer)
if (isSelected) {
drawRingFittingInsideView(rect: rect)
}
}
internal func drawRingFittingInsideView(rect: CGRect) {
let hw: CGFloat = ringThickness / 2
let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw, dy: hw))
let shapeLayer = CAShapeLayer()
shapeLayer.path = circlePath.cgPath
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = ringColor.cgColor
shapeLayer.lineWidth = ringThickness
layer.addSublayer(shapeLayer)
}
}
You need to use Range<String.Index>
instead of the classic NSRange
. The way I do it (maybe there is a better way) is by taking the string's String.Index
a moving it with advance
.
I don't know what range you are trying to replace, but let's pretend you want to replace the first 2 characters.
var start = textField.text.startIndex // Start at the string's start index
var end = advance(textField.text.startIndex, 2) // Take start index and advance 2 characters forward
var range: Range<String.Index> = Range<String.Index>(start: start,end: end)
textField.text.stringByReplacingCharactersInRange(range, withString: string)
You were close. The key is to have the hidden layout inflate to match_parent
in both height and weight. Simply start it off as View.GONE
. This way, using the percentage in the animators works properly.
Layout (activity_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_screen"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:text="@string/hello_world" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="@string/hello_world" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:onClick="slideUpDown"
android:text="Slide up / down" />
<RelativeLayout
android:id="@+id/hidden_panel"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
android:visibility="gone" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/app_name"
android:layout_centerInParent="true"
android:onClick="slideUpDown" />
</RelativeLayout>
</RelativeLayout>
Activity (MainActivity.java):
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
public class OffscreenActivity extends Activity {
private View hiddenPanel;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
hiddenPanel = findViewById(R.id.hidden_panel);
}
public void slideUpDown(final View view) {
if (!isPanelShown()) {
// Show the panel
Animation bottomUp = AnimationUtils.loadAnimation(this,
R.anim.bottom_up);
hiddenPanel.startAnimation(bottomUp);
hiddenPanel.setVisibility(View.VISIBLE);
}
else {
// Hide the Panel
Animation bottomDown = AnimationUtils.loadAnimation(this,
R.anim.bottom_down);
hiddenPanel.startAnimation(bottomDown);
hiddenPanel.setVisibility(View.GONE);
}
}
private boolean isPanelShown() {
return hiddenPanel.getVisibility() == View.VISIBLE;
}
}
Only other thing I changed was in bottom_up.xml
. Instead of
android:fromYDelta="75%p"
I used:
android:fromYDelta="100%p"
But that's a matter of preference, I suppose.
To solve a similar problem, I'm using groupby
:
print(f"Distinct entries: {len(df.groupby(['col1', 'col2']))}")
Whether that's appropriate will depend on what you want to do with the result, though (in my case, I just wanted the equivalent of COUNT DISTINCT
as shown).
Not mentioned above. You could also crate a DateTime object by providing a timestamp as string in the constructor with a leading @ sign.
$dt = new DateTime('@123456789');
$dt->setTimezone(new DateTimeZone('America/New_York'));
echo $dt->format('F j, Y - G:i');
See the documentation about compound formats: https://www.php.net/manual/en/datetime.formats.compound.php
I've created a module called cors-bypass
, that allows you to do this without the need for a server. It uses postMessage
to send cross-domain events, which is used to provide mock HTTP APIs (fetch
, WebSocket
, XMLHTTPRequest
etc.).
It fundamentally does the same as the answer by Endless, but requires no code changes to use it.
Example usage:
import { Client, WebSocket } from 'cors-bypass'
const client = new Client()
await client.openServerInNewTab({
serverUrl: 'http://random-domain.com/server.html',
adapterUrl: 'https://your-site.com/adapter.html'
})
const ws = new WebSocket('ws://echo.websocket.org')
ws.onopen = () => ws.send('hello')
ws.onmessage = ({ data }) => console.log('received', data)
Isn't the height of the text in pixels equal to the font size (in pts) if you define the font using context.font ?
If the keystore is for tomcat then, after creating the keystore with the above answers, you must add a final step to create the "tomcat" alias for the key:
keytool -changealias -alias "1" -destalias "tomcat" -keystore keystore-file.jks
You can check the result with:
keytool -list -keystore keystore-file.jks -v
I think of two ways to test for the type of a value:
Method 1:
You can use the isNaN
javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN
. That's why if you console.log
out the result, you will be surprised that the code:
if (isNaN(i)) {
console.log('This is not number');
}
will not return anything. For this reason a better alternative would be the method 2.
Method 2:
You may use javascript typeof method to test the type of a variable or value
if (typeof i != "number") {
console.log('This is not number');
}
Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.
A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.
You can call dispose()
on the current window and setVisible(true)
on the one you want to display.
Laravel Framework 5.6.26
return more than one array then we use compact('array1', 'array2', 'array3', ...)
to return view.
viewblade
is the frontend (view) blade.
return view('viewblade', compact('view1','view2','view3','view4'));
From Pavel and jnm2:
private int DumpApproximateObjectSize(object toWeight)
{
return Marshal.ReadInt32(toWeight.GetType().TypeHandle.Value, 4);
}
On a side note be careful because it only work with contiguous memory objects
You can achieve what you want without the instanceof
keyword as you can write custom type guards now:
interface A{
member:string;
}
function instanceOfA(object: any): object is A {
return 'member' in object;
}
var a:any={member:"foobar"};
if (instanceOfA(a)) {
alert(a.member);
}
If you need to check a lot of members to determine whether an object matches your type, you could instead add a discriminator. The below is the most basic example, and requires you to manage your own discriminators... you'd need to get deeper into the patterns to ensure you avoid duplicate discriminators.
interface A{
discriminator: 'I-AM-A';
member:string;
}
function instanceOfA(object: any): object is A {
return object.discriminator === 'I-AM-A';
}
var a:any = {discriminator: 'I-AM-A', member:"foobar"};
if (instanceOfA(a)) {
alert(a.member);
}
For me this code worked best:
private func getCoordinate(_ view: UIView) -> CGPoint {
var x = view.frame.origin.x
var y = view.frame.origin.y
var oldView = view
while let superView = oldView.superview {
x += superView.frame.origin.x
y += superView.frame.origin.y
if superView.next is UIViewController {
break //superView is the rootView of a UIViewController
}
oldView = superView
}
return CGPoint(x: x, y: y)
}
The operating system takes default shell to run your shell script. so mentioning shell path at the beginning of script, you are asking the OS to use that particular shell. It is also useful for portability.
set width or height(what ever u need to match parent ) to 0dp and set margins of left , right, top, bottom to act as match parent
Some controls, like Button in System.Windows.Forms, have a "PerformClick" method to do just that.
There is no standard macro that is set according to C standard. Some C compilers will set one on some platforms (e.g. Apple's patched GCC sets a macro to indicate that it is compiling on an Apple system and for the Darwin platform). Your platform and/or your C compiler might set something as well, but there is no general way.
Like hayalci said, it's best to have these macros set in your build process somehow. It is easy to define a macro with most compilers without modifying the code. You can simply pass -D MACRO
to GCC, i.e.
gcc -D Windows
gcc -D UNIX
And in your code:
#if defined(Windows)
// do some cool Windows stuff
#elif defined(UNIX)
// do some cool Unix stuff
#else
# error Unsupported operating system
#endif
Most of the cases issue is due to problem with hostname . Please check the hostname ,some times database team will maintain many hostname for connecting same database . Please check with database team regarding this connection issue.
It's best if you judge on your own,
1) Sublime works on Mac & Linux that may be its plus point, with VI mode that makes things easily searchable for the VI lover(UNIX & Linux).
http://text-editors.findthebest.com/compare/9-45/Notepad-vs-Sublime-Text
This Link is no more working so please watch this video for similar details Video
Initial observation revealed that everything else should work fine and almost similar;(with help of available plugins in notepad++)
Some Variation: Some user find plugins useful for PHP coders on that
http://codelikeapoem.com/2013/01/goodbye-notepad-hellooooo-sublime-text.html
although, there are many plugins for Notepad Plus Plus ..
I am not sure of your requirements, nor I am promoter of either of these editors :)
So, judge on basis of your requirements, this should satisfy you query...
Yes we can add that both are evolving and changing fast..
You can pass the element into the function <input type="button" value="mybutton1" onclick="dosomething(this)">test
by passing this. Then in the function you can access the value like this:
function dosomething(element) {
console.log(element.value);
}
sudo setfacl -m u:$USER:rwx /dev/kvm
Worked for me.
This assumes that the first row of the csv is the headers
import csv
# open the file in universal line ending mode
with open('test.csv', 'rU') as infile:
# read the file as a dictionary for each row ({header : value})
reader = csv.DictReader(infile)
data = {}
for row in reader:
for header, value in row.items():
try:
data[header].append(value)
except KeyError:
data[header] = [value]
# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']
Following is an up to date ES6 example using a ref.
Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount()
because we can only determine the height of an element after it is rendered in the DOM.
import React, {Component} from 'react'
import {render} from 'react-dom'
class DivSize extends Component {
constructor(props) {
super(props)
this.state = {
height: 0
}
}
componentDidMount() {
const height = this.divElement.clientHeight;
this.setState({ height });
}
render() {
return (
<div
className="test"
ref={ (divElement) => { this.divElement = divElement } }
>
Size: <b>{this.state.height}px</b> but it should be 18px after the render
</div>
)
}
}
render(<DivSize />, document.querySelector('#container'))
You can find the running example here: https://codepen.io/bassgang/pen/povzjKw
In my case it was simply that I had a variable named the same as a function.
Example:
def cleanCache = functionReturningABoolean()
if( cleanCache ){
echo "Clean cache option is true, do not uninstall previous features / urls"
uninstallCmd = ""
// and we call the cleanCache method
cleanCache(userId, serverName)
}
...
and later in my code I have the function:
def cleanCache(user, server){
//some operations to the server
}
Apparently the Groovy language does not support this (but other languages like Java does).
I just renamed my function to executeCleanCache
and it works perfectly (or you can also rename your variable whatever option you prefer).
In case .empty() doesn't work for you, which is for me
function SetDropDownToEmpty()
{
$('#dropdown').find('option').remove().end().append('<option value="0"></option>');
$("#dropdown").trigger("liszt:updated");
}
$(document).ready(
SetDropDownToEmpty() ;
)
An output reg foo
is just shorthand for output foo_wire; reg foo; assign foo_wire = foo
. It's handy when you plan to register that output anyway. I don't think input reg
is meaningful for module
(perhaps task
). input wire
and output wire
are the same as input
and output
: it's just more explicit.
By default ls -t
sorts output from newest to oldest, so the combination of commands to use depends in which direction you want your output to be ordered.
For the newest 5 files ordered from newest to oldest, use head
to take the first 5 lines of output:
ls -t | head -n 5
For the newest 5 files ordered from oldest to newest, use the -r
switch to reverse ls
's sort order, and use tail
to take the last 5 lines of output:
ls -tr | tail -n 5
You should do:
try:
value_index = my_list.index(value)
except:
value_index = -1;
That also resolved my issue.
@ViewChild('map', {static: false}) googleMap;