For drawing just the arrow, there is an easier method:-
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")
#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)
plt.show()
quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]
quiver(X, Y, Z, U, V, W, **kwargs)
Arguments:
X, Y, Z: The x, y and z coordinates of the arrow locations
U, V, W: The x, y and z components of the arrow vectors
The arguments could be array-like or scalars.
Keyword arguments:
length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes
arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3
pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’
normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.
For me work when i change my php.ini in my host:
; Default timeout for socket based streams (seconds)
default_socket_timeout = 300
You can store it in a hidden field, OR store it in a javascript object (my preference) as the likely access will be via javascript.
NOTE: since you have an array, this would then be accessed as myvariable[0]
for the first element (as you have it).
EDIT show example:
clip...
success: function(msg)
{
LoadProviders(msg);
},
...
var myvariable ="";
function LoadProviders(jdata)
{
myvariable = jdata;
};
alert(myvariable[0].id);// shows "15aea3fa" in the alert
EDIT: Created this page:http://jsfiddle.net/GNyQn/ to demonstrate the above. This example makes the assumption that you have already properly returned your named string values in the array and simply need to store it per OP question. In the example, I also put the values of the first array returned (per OP example) into a div as text.
I am not sure why this has been viewed as "complex" as I see no simpler way to handle these strings in this array.
If you are using Spring Boot, then add thymeleaf dependency into your pom.xml:
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
run "eclipse -clean -refresh" from command line. This fixed the issue for me when all other solutions failed.
Probably your problem is that for Docker that has been installed from default Ubuntu repository, the package name is docker.io
Or package name may be something like docker-ce
.
Try running
dpkg -l | grep -i docker
to identify what installed package you have
So you need to change package name in commands from https://stackoverflow.com/a/31313851/2340159 to match package name. For example, for docker.io
it would be:
sudo apt-get purge -y docker.io
sudo apt-get autoremove -y --purge docker.io
sudo apt-get autoclean
It adds:
The above commands will not remove images, containers, volumes, or user created configuration files on your host. If you wish to delete all images, containers, and volumes run the following command:
sudo rm -rf /var/lib/docker
Remove docker from apparmor.d:
sudo rm /etc/apparmor.d/docker
Remove docker group:
sudo groupdel docker
Just use
File.Copy(filepath, "\\\\192.168.1.28\\Files");
A windows fileshare exposed via a UNC path is treated as part of the file system, and has nothing to do with the web.
The credentials used will be that of the ASP.NET worker process, or any impersonation you've enabled. If you can tweak those to get it right, this can be done.
You may run into problems because you are using the IP address instead of the server name (windows trust settings prevent leaving the domain - by using IP you are hiding any domain details). If at all possible, use the server name!
If this is not on the same windows domain, and you are trying to use a different domain account, you will need to specify the username as "[domain_or_machine]\[username]"
If you need to specify explicit credentials, you'll need to look into coding an impersonation solution.
I was trying to restore a production database to a staging database on the same server.
The only thing that worked in my case was restore to a new blank database. This worked great, did not try to overwrite production files (which it would if you just restore production backup file to existing staging database). Then delete old database and rename - the files will keep the new temp name but in my case that is fine.
(Or otherwise delete the staging database first and then you can restore to new database with same name as staging database)
I have got the same issue when tried to get users information without auth.
Check if you have loggen in before any request.
$uid = $facebook->getUser();
if ($uid){
$me = $facebook->api('/me');
}
The code above should solve your issue.
I did it with transparent *.cur 1px to 1px, but it looks like small dot. :( I think it's the best cross-browser thing that I can do. CSS2.1 has no value 'none' for 'cursor' property - it was added in CSS3. Thats why it's workable not everywhere.
<video class="embed-responsive-item" controls>_x000D_
<source src="http://example.com/video.mp4" autostart="false">_x000D_
Your browser does not support the video tag._x000D_
</video>
_x000D_
mongo-db
is likely not a great choice for new developers.
On the other hand mongoose
as an ORM (Object Relational Mapping) can be a better choice for the new-bies.
As I understand you question, it is not about parsing JSON because you can copy-paste your JSON into your code directly - so if this is the case then just copy your JSON direct to dataObj
variable without wrapping it with single quotes (tip: eval==evil
)
var dataObj = {"count" : 1, "stack" : "sometext\n\n"};_x000D_
_x000D_
console.log(dataObj);
_x000D_
Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country
barplot(summary(df$Country))
The reason is performance. If instance != null
(which will always be the case except the very first time), there is no need to do a costly lock
: Two threads accessing the initialized singleton simultaneously would be synchronized unneccessarily.
I solved my problem. it's just the version of python which the interpreter reads off the first line. removing to version numbers did it for me, i.e.
#!/usr/bin/python2.7 --> #!/usr/bin/python
Here's my attempt to solve it in Java. Apologies for the non-standard formatting, but the code has a lot of duplication, and this is the best I can do to make it readable.
import java.util.Arrays;
public class Products {
static int[] products(int... nums) {
final int N = nums.length;
int[] prods = new int[N];
Arrays.fill(prods, 1);
for (int
i = 0, pi = 1 , j = N-1, pj = 1 ;
(i < N) && (j >= 0) ;
pi *= nums[i++] , pj *= nums[j--] )
{
prods[i] *= pi ; prods[j] *= pj ;
}
return prods;
}
public static void main(String[] args) {
System.out.println(
Arrays.toString(products(1, 2, 3, 4, 5))
); // prints "[120, 60, 40, 30, 24]"
}
}
The loop invariants are pi = nums[0] * nums[1] *.. nums[i-1]
and pj = nums[N-1] * nums[N-2] *.. nums[j+1]
. The i
part on the left is the "prefix" logic, and the j
part on the right is the "suffix" logic.
Jasmeet gave a (beautiful!) recursive solution; I've turned it into this (hideous!) Java one-liner. It does in-place modification, with O(N)
temporary space in the stack.
static int multiply(int[] nums, int p, int n) {
return (n == nums.length) ? 1
: nums[n] * (p = multiply(nums, nums[n] * (nums[n] = p), n + 1))
+ 0*(nums[n] *= p);
}
int[] arr = {1,2,3,4,5};
multiply(arr, 1, 0);
System.out.println(Arrays.toString(arr));
// prints "[120, 60, 40, 30, 24]"
I was having same issue.
String[] arr= new String[] { "A", "B", "C" };
Object obj = arr;
And then passed the obj as varargs argument. It worked.
Don't define variables in headers. Put declarations in header and definitions in one of the .c files.
In config.h
extern const char *names[];
In some .c file:
const char *names[] =
{
"brian", "stefan", "steve"
};
If you put a definition of a global variable in a header file, then this definition will go to every .c file that includes this header, and you will get multiple definition error because a varible may be declared multiple times but can be defined only once.
For me, I accidentally included my local database name inside the SQL query, hence the access denied issue came up when I deployed.
I removed the database name from the SQL query and it got fixed.
In addition if one uses static keyword on a variable like this example:
namespace {
static int flag;
}
It would not be seen in the mapping file
Honestly, I am going to argue that using NewRelic for profiling is the best.
It's a PHP extension which doesn't seem to slow down runtime at all and they do the monitoring for you, allowing decent drill down. In the expensive version they allow heavy drill down (but we can't afford their pricing model).
Still, even with the free/standard plan, it's obvious and simple where most of the low hanging fruit is. I also like that it can give you an idea on DB interactions too.
I like this approach, it is visual for me.
using (var webClient = new WebClient())
{
var response = webClient.DownloadString(url);
JObject result = JObject.Parse(response);
var users = result.SelectToken("data");
List<User> userList = JsonConvert.DeserializeObject<List<User>>(users.ToString());
}
convert_dtypes
The (self) accepted answer doesn't take into consideration the possibility of NaNs in object columns.
df = pd.DataFrame({
'a': [1, 2, np.nan],
'b': [True, False, np.nan]}, dtype=object)
df
a b
0 1 True
1 2 False
2 NaN NaN
df['a'].astype(str).astype(int) # raises ValueError
This chokes because the NaN is converted to a string "nan", and further attempts to coerce to integer will fail. To avoid this issue, we can soft-convert columns to their corresponding nullable type using convert_dtypes
:
df.convert_dtypes()
a b
0 1 True
1 2 False
2 <NA> <NA>
df.convert_dtypes().dtypes
a Int64
b boolean
dtype: object
If your data has junk text mixed in with your ints, you can use pd.to_numeric
as an initial step:
s = pd.Series(['1', '2', '...'])
s.convert_dtypes() # converts to string, which is not what we want
0 1
1 2
2 ...
dtype: string
# coerces non-numeric junk to NaNs
pd.to_numeric(s, errors='coerce')
0 1.0
1 2.0
2 NaN
dtype: float64
# one final `convert_dtypes` call to convert to nullable int
pd.to_numeric(s, errors='coerce').convert_dtypes()
0 1
1 2
2 <NA>
dtype: Int64
The problem exists in old versions on the iOS. in the latest, the right-to-left works well. What I did, is as follows:
first I check the iOS version:
if (![self compareCurVersionTo:4 minor:3 point:0])
Than:
// set RTL on the start on each line (except the first)
myUITextView.text = [myUITextView.text stringByReplacingOccurrencesOfString:@"\n"
withString:@"\u202B\n"];
This approach will not consume any resources for keeping process alive.
while :; do sleep 1; done & kill -STOP $! && wait $!
while :; do sleep 1; done &
Creates a dummy process in backgroundkill -STOP $!
Stops the background process wait $!
Wait for the background process, this will be blocking forever, cause background process was stopped beforeAs Johannes has already suggested, a background-image is probally the best way to achieve this in CSS alone.
A JavaScript solution would also have to affect "dragstart" to be effective across all popular browsers.
JavaScript:
<div onselectstart="return false;" ondragstart="return false;">your text</div>
jQuery:
var _preventDefault = function(evt) { evt.preventDefault(); };
$("div").bind("dragstart", _preventDefault).bind("selectstart", _preventDefault);
Rich
That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if
condition is always true.
The simplest way to make it work, it seems to me, is to account for this case:
var value = $(this).val();
if ( value.length > 0 && value != "Default text" ) ...
You can see how layout engines determine list-image sizes here: http://www.w3.org/wiki/CSS/Properties/list-style-image
There are three ways to do get around this while maintaining the benefits of CSS:
viewBox
that will then resize to 1em when used as a list-style-image
(Kudos to Jeremy).Another way to collect uniq columns with sql:
Model.group(:rating).pluck(:rating)
If I understand you correctly, You have two folders, one houses your php script that you want to include
into a file that is in another folder?
If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:
root
includes
php_scripts
script.php
blog
content
index.php
If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:
include("../../../includes/php_scripts/script.php");
The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.
First, eq is for comparing strings; == is for comparing numbers.
Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.
I think your problem is that your variables don't contain what you think they do. I think your $str1
or $str2
contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";
.
The trailing newline can be removed with the chomp($str1);
function.
Since Docker 1.5 you can now expose a range of ports to other linked containers using:
The Dockerfile EXPOSE command:
EXPOSE 7000-8000
or The Docker run command:
docker run --expose=7000-8000
Or instead you can publish a range of ports to the host machine via Docker run command:
docker run -p 7000-8000:7000-8000
The bracket stuff (e.g., [[ $a -gt $b ]]
or (( $a > $b ))
) isn't enough if you want to use float numbers as well; it would report a syntax error. If you want to compare float numbers or float number to integer, you can use (( $(bc <<< "...") ))
.
For example,
a=2.00
b=1
if (( $(bc <<<"$a > $b") )); then
echo "a is greater than b"
else
echo "a is not greater than b"
fi
You can include more than one comparison in the if statement. For example,
a=2.
b=1
c=1.0000
if (( $(bc <<<"$b == $c && $b < $a") )); then
echo "b is equal to c but less than a"
else
echo "b is either not equal to c and/or not less than a"
fi
That's helpful if you want to check if a numeric variable (integer or not) is within a numeric range.
Twood, Visibility expression is the expressions you write on how you want the "visibility" to behave. So, if you would want to hide or show the textbox, you want to write this:
=IIf((CountRows("ScannerStatisticsData")=0),True,False)
This means, if the dataset is 0, you want to hide the textbox.
following will show one table of dataset
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = ds; // dataset
DataGridView1.DataMember = "TableName"; // table name you need to show
if you want to show multiple tables, you need to create one datatable or custom object collection out of all tables.
if two tables with same table schema
dtAll = dtOne.Copy(); // dtOne = ds.Tables[0]
dtAll.Merge(dtTwo); // dtTwo = dtOne = ds.Tables[1]
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ; // datatable
sample code to mode all tables
DataTable dtAll = ds.Tables[0].Copy();
for (var i = 1; i < ds.Tables.Count; i++)
{
dtAll.Merge(ds.Tables[i]);
}
DataGridView1.AutoGenerateColumns = true;
DataGridView1.DataSource = dtAll ;
See TRY...CATCH (Transact-SQL)
CREATE PROCEDURE [dbo].[PL_GEN_PROVN_NO1]
@GAD_COMP_CODE VARCHAR(2) =NULL,
@@voucher_no numeric =null output
AS
BEGIN
begin try
-- your proc code
end try
begin catch
-- what you want to do in catch
end catch
END -- proc end
Basically, 1
is not a valid index of y
. If the visitor is comming from his own code he should check if his y
contains the index which he tries to access (in this case the index is 1
).
I wanted to display the first 300 words of a news story as a preview which unfortunately meant that if a story had an image within the first 300 words then it was displayed in the list of previews which really messed with my layout. I used the above code to hide all of the images from the string taken from my database and it works wonderfully!
$news = $row_latest_news ['content'];
$news = preg_replace("/<img[^>]+\>/i", "", $news);
if (strlen($news) > 300){
echo substr($news, 0, strpos($news,' ',300)).'...';
}
else {
echo $news;
}
In most of the programming language indexes is start from 0.So you must have to write i<names.length or i<=names.length-1 instead of i<=names.length.
The .Cells range isn't limited to ones that are being used, so your code is clearing the content of 1,048,576 rows and 16,384 columns - 17,179,869,184 total cells. That's going to take a while. Just clear the UsedRange instead:
Sheets("Zeros").UsedRange.ClearContents
Alternately, you can delete the sheet and re-add it:
Application.DisplayAlerts = False
Sheets("Zeros").Delete
Application.DisplayAlerts = True
Dim sheet As Worksheet
Set sheet = Sheets.Add
sheet.Name = "Zeros"
The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.
Your debut
and fin
values are floating point values, not integers, because taille
is a float.
Make those values integers instead:
item = plateau[int(debut):int(fin)]
Alternatively, make taille
an integer:
taille = int(sqrt(len(plateau)))
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
You can execute it just as you select a table using SELECT
clause. In addition you can provide parameters within parentheses.
Try with below syntax:
SELECT * FROM yourFunctionName(parameter1, parameter2)
Not with plain HTML I'm afraid.
You could use some jQuery to do this though:
$(function(){
var $select = $(".1-100");
for (i=1;i<=100;i++){
$select.append($('<option></option>').val(i).html(i))
}
});?
You can download jQuery here
ieshims.dll
is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess
) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll
is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.
I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.
#alertlist li:hover:after,#alertlist li.selected:after
{
position:absolute;
top: 0;
right:-10px;
bottom:0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid #303030;
content: "";
}?
One way:
SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
SELECT * FROM StoreClients sc2
WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)
One way would be store the current colour for each row within the model. Here's a simple model that is fixed at 3 columns and 3 rows:
static class MyTableModel extends DefaultTableModel {
List<Color> rowColours = Arrays.asList(
Color.RED,
Color.GREEN,
Color.CYAN
);
public void setRowColour(int row, Color c) {
rowColours.set(row, c);
fireTableRowsUpdated(row, row);
}
public Color getRowColour(int row) {
return rowColours.get(row);
}
@Override
public int getRowCount() {
return 3;
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public Object getValueAt(int row, int column) {
return String.format("%d %d", row, column);
}
}
Note that setRowColour
calls fireTableRowsUpdated
; this will cause just that row of the table to be updated.
The renderer can get the model from the table:
static class MyTableCellRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
MyTableModel model = (MyTableModel) table.getModel();
Component c = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
c.setBackground(model.getRowColour(row));
return c;
}
}
Changing a row's colour would be as simple as:
model.setRowColour(1, Color.YELLOW);
Another option is
Private Sub Worksheet_Change(ByVal Target As Range)
IF Target.Address = "$D$2" Then
MsgBox("Cell D2 Has Changed.")
End If
End Sub
I believe this uses fewer resources than Intersect
, which will be helpful if your worksheet changes a lot.
Why use jQuery for this?
str = "123-4";
alert(str.substring(0,str.length - 1));
Of course if you must:
Substr w/ jQuery:
//example test element
$(document.createElement('div'))
.addClass('test')
.text('123-4')
.appendTo('body');
//using substring with the jQuery function html
alert($('.test').html().substring(0,$('.test').html().length - 1));
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
The following program calculates nCr
in an efficient manner (compared to calculating factorials etc.)
import operator as op
from functools import reduce
def ncr(n, r):
r = min(r, n-r)
numer = reduce(op.mul, range(n, n-r, -1), 1)
denom = reduce(op.mul, range(1, r+1), 1)
return numer // denom # or / in Python 2
As of Python 3.8, binomial coefficients are available in the standard library as math.comb
:
>>> from math import comb
>>> comb(10,3)
120
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')
If you are using parametrized Stored procedure:
INNER JOIN ON t.PersonName = newTable.PersonName
using a table variable which contains passed in namesI'm not quite sure what a "good way" of copying a file is, but assuming "good" means "fast", I could broaden the subject a little.
Current operating systems have long been optimized to deal with run of the mill file copy. No clever bit of code will beat that. It is possible that some variant of your copy techniques will prove faster in some test scenario, but they most likely would fare worse in other cases.
Typically, the sendfile
function probably returns before the write has been committed, thus giving the impression of being faster than the rest. I haven't read the code, but it is most certainly because it allocates its own dedicated buffer, trading memory for time. And the reason why it won't work for files bigger than 2Gb.
As long as you're dealing with a small number of files, everything occurs inside various buffers (the C++ runtime's first if you use iostream
, the OS internal ones, apparently a file-sized extra buffer in the case of sendfile
). Actual storage media is only accessed once enough data has been moved around to be worth the trouble of spinning a hard disk.
I suppose you could slightly improve performances in specific cases. Off the top of my head:
copy_file
sequentially (though you'll hardly notice the difference as long as the file fits in the OS cache)But all that is outside the scope of a general purpose file copy function.
So in my arguably seasoned programmer's opinion, a C++ file copy should just use the C++17 file_copy
dedicated function, unless more is known about the context where the file copy occurs and some clever strategies can be devised to outsmart the OS.
this code worked for me in partial view:
<a href="/Content/[email protected]">@item.Title</a>
I'm just posting this since Chrome changes alot, and none of the answers were quite up to date.
def quit(self):
self.root.destroy()
Add parentheses after destroy
to call the method.
When you use command=self.root.destroy
you pass the method to Tkinter.Button
without the parentheses because you want Tkinter.Button
to store the method for future calling, not to call it immediately when the button is created.
But when you define the quit
method, you need to call self.root.destroy()
in the body of the method because by then the method has been called.
You can increment the stack depth allowed - with this, deeper recursive calls will be possible, like this:
import sys
sys.setrecursionlimit(10000) # 10000 is an example, try with different values
... But I'd advise you to first try to optimize your code, for instance, using iteration instead of recursion.
FORCE_INDEX
is going to be deprecated after MySQL 8:
Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in
a future release of MySQL, and at some time thereafter to be removed altogether.
https://dev.mysql.com/doc/refman/8.0/en/index-hints.html
You should be using JOIN_INDEX
, GROUP_INDEX
, ORDER_INDEX
, and INDEX
instead, for v8.
I show below an iterative solution. A recursive solution would be more compact, but since we don't know the length of the lists, recursion runs the risk of stack overflow.
The basic idea is similar to the merge step in merge sort; we keep a pointer corresponding to each input list; at each iteration, we advance the pointer corresponding to the smaller element. However, there's one crucial difference where most people get tripped. In merge sort, since we use a result array, the next position to insert is always the index of the result array. For a linked list, we need to keep a pointer to the last element of the sorted list. The pointer may jump around from one input list to another depending on which one has the smaller element for the current iteration.
With that, the following code should be self-explanatory.
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) {
return l2;
}
if (l2 == null) {
return l1;
}
ListNode first = l1;
ListNode second = l2;
ListNode head = null;
ListNode last = null;
while (first != null && second != null) {
if (first.val < second.val) {
if (last != null) {
last.next = first;
}
last = first;
first = first.next;
} else {
if (last != null) {
last.next = second;
}
last = second;
second = second.next;
}
if (head == null) {
head = last;
}
}
if (first == null) {
last.next = second;
}
if (second == null) {
last.next = first;
}
return head;
}
Below is the configuration in Maven software by default in MAVEN_HOME\conf\settings.xml.
<settings>
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
Add the below line under this configuration, will fulfill the requirement.
<localRepository>custom_path</localRepository>
Ex: <localRepository>D:/MYNAME/settings/.m2/repository</localRepository>
You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t
below) and alias the columns as well.
The DISTINCT
can also be safely removed as the internal GROUP BY
makes it redundant:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
Since the COUNT
is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*)
and further simplify the query:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;
As you have mentioned it doesn't change anything.
First, you should redirect both standard input and standard error from the crontab execution like below:
*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1
Then you can view the file /tmp/listener.log
to see if the script executed as you expected.
Second, I guess what you mean by change anything is by watching the files created by your program:
f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')
The crontab job above won't create these file in directory /home/souza/Documets/Listener
, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener
, the following cron job will do the trick:
*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1
Change to the working directory and execute the script from there, and then you can view the files created in place.
simple and clean example of how group by works in LINQ
http://www.a2zmenu.com/LINQ/LINQ-to-SQL-Group-By-Operator.aspx
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
So you want to create a list of lists... We need to start with an empty list
list_of_lists = []
next, we read the file content, line by line
with open('data') as f:
for line in f:
inner_list = [elt.strip() for elt in line.split(',')]
# in alternative, if you need to use the file content as numbers
# inner_list = [int(elt.strip()) for elt in line.split(',')]
list_of_lists.append(inner_list)
A common use case is that of columnar data, but our units of storage are the rows of the file, that we have read one by one, so you may want to transpose your list of lists. This can be done with the following idiom
by_cols = zip(*list_of_lists)
Another common use is to give a name to each column
col_names = ('apples sold', 'pears sold', 'apples revenue', 'pears revenue')
by_names = {}
for i, col_name in enumerate(col_names):
by_names[col_name] = by_cols[i]
so that you can operate on homogeneous data items
mean_apple_prices = [money/fruits for money, fruits in
zip(by_names['apples revenue'], by_names['apples_sold'])]
Most of what I've written can be speeded up using the csv
module, from the standard library. Another third party module is pandas
, that lets you automate most aspects of a typical data analysis (but has a number of dependencies).
Update While in Python 2 zip(*list_of_lists)
returns a different (transposed) list of lists, in Python 3 the situation has changed and zip(*list_of_lists)
returns a zip object that is not subscriptable.
If you need indexed access you can use
by_cols = list(zip(*list_of_lists))
that gives you a list of lists in both versions of Python.
On the other hand, if you don't need indexed access and what you want is just to build a dictionary indexed by column names, a zip object is just fine...
file = open('some_data.csv')
names = get_names(next(file))
columns = zip(*((x.strip() for x in line.split(',')) for line in file)))
d = {}
for name, column in zip(names, columns): d[name] = column
If your application mainly tethers web apis, or other io channels, give or take a user interface, node.js may be a fair pick for you, especially if you want to squeeze out the most scalability, or, if your main language in life is javascript (or javascript transpilers of sorts). If you build microservices, node.js is also okay. Node.js is also suitable for any project that is small or simple.
Its main selling point is it allows front-enders take responsibility for back-end stuff rather than the typical divide. Another justifiable selling point is if your workforce is javascript oriented to begin with.
Beyond a certain point however, you cannot scale your code without terrible hacks for forcing modularity, readability and flow control. Some people like those hacks though, especially coming from an event-driven javascript background, they seem familiar or forgivable.
In particular, when your application needs to perform synchronous flows, you start bleeding over half-baked solutions that slow you down considerably in terms of your development process. If you have computation intensive parts in your application, tread with caution picking (only) node.js. Maybe http://koajs.com/ or other novelties alleviate those originally thorny aspects, compared to when I originally used node.js or wrote this.
As mentioned elsewhere, undoubtedly, Linq to Xml makes creation and alteration of xml documents a breeze in comparison to XmlDocument
, and the XNamespace ns + "elementName"
syntax makes for pleasurable reading when dealing with namespaces.
One thing worth mentioning for xsl
and xpath
die hards to note is that it IS possible to still execute arbitrary xpath 1.0
expressions on Linq 2 Xml XNodes
by including:
using System.Xml.XPath;
and then we can navigate and project data using xpath
via these extension methods:
For instance, given the Xml document:
<xml>
<foo>
<baz id="1">10</baz>
<bar id="2" special="1">baa baa</bar>
<baz id="3">20</baz>
<bar id="4" />
<bar id="5" />
</foo>
<foo id="123">Text 1<moo />Text 2
</foo>
</xml>
We can evaluate:
var node = xele.XPathSelectElement("/xml/foo[@id='123']");
var nodes = xele.XPathSelectElements(
"//moo/ancestor::xml/descendant::baz[@id='1']/following-sibling::bar[not(@special='1')]");
var sum = xele.XPathEvaluate("sum(//foo[not(moo)]/baz)");
This plugin can help you,
Its easy to setup and has great set of features.
$.confirm({
title: 'Confirm!',
content: 'Simple confirm!',
buttons: {
confirm: function () {
$.alert('Confirmed!');
},
cancel: function () {
$.alert('Canceled!');
},
somethingElse: {
text: 'Something else',
btnClass: 'btn-blue',
keys: ['enter', 'shift'], // trigger when enter or shift is pressed
action: function(){
$.alert('Something else?');
}
}
}
});
Other than this you can also load your content from a remote url.
$.confirm({
content: 'url:hugedata.html' // location of your hugedata.html.
});
In short:
someValues.forEach((element) => {
console.log(element);
});
If you care about index, then second parameter can be passed to receive the index of current element:
someValues.forEach((element, index) => {
console.log(`Current index: ${index}`);
console.log(element);
});
Refer here to know more about Array of ES6: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
Okay, my problem wasn't the port, but the binding address. My server has an internal address (10.0.0.4) and an external address (52.175.223.XX). When I tried connecting with:
$sock = @stream_socket_server('tcp://52.175.223.XX:123', $errNo, $errStr, STREAM_SERVER_BIND|STREAM_SERVER_LISTEN);
It failed because the local socket was 10.0.0.4 and not the external 52.175.223.XX. You can checkout the local available interfaces with sudo ifconfig
.
Try this
q = Session.query(
User, Document, DocumentPermissions,
).filter(
User.email == Document.author,
).filter(
Document.name == DocumentPermissions.document,
).filter(
User.email == 'someemail',
).all()
You can iterate over the object to get the keys or values:
function numKeys(obj)
{
var count = 0;
for(var prop in obj)
{
count++;
}
return count;
}
It looks like a "spelling mistake" but just want to point out that your example is invalid syntax, should be
var object = {"key1":"value1","key2":"value2","key3":"value3"};
It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].
You should declare your function f() like this:
def f(n, x=None):
if x is None:
x = []
...
Contrary to some answers posted in this thread, adding 'DIRS': ['templates']
has no effect(it's redundant) since templates
is the default path where Django looks for templates.
If you are attempting to reference an app's template, ensure that your app is in the list of INSTALLED_APPS
in the main project settings.py
.
INSTALLED_APPS': [
# ...
'my_app',
]
Quoting Django's Templates documentation:
class DjangoTemplates¶
Set BACKEND to 'django.template.backends.django.DjangoTemplates' to configure a Django template engine.
When APP_DIRS is True, DjangoTemplates engines look for templates in the templates subdirectory of installed applications. This generic name was kept for backwards-compatibility.
When you create an application to your project, there's no templates
directory inside the application directory. Since that you can have an application without using templates, Django doesn't create such directory. That is, you have to create it and storing your templates in there.
Here's another paragraph from Django Tutorial documentation, which is even clearer:
Your project’s TEMPLATES setting describes how Django will load and render templates. The default settings file configures a DjangoTemplates backend whose APP_DIRS option is set to True. By convention DjangoTemplates looks for a “templates” subdirectory in each of the INSTALLED_APPS.
Check your build types of each project under project properties - I bet one or the other will be set to build against .NET XX - Client Profile
.
With inconsistent versions, specifically with one being Client Profile
and the other not, then it works at design time but fails at compile time. A real gotcha.
There is something funny going on in Visual Studio 2010 for me, which keeps setting projects seemingly randomly to Client Profile
, sometimes when I create a project, and sometimes a few days later. Probably some keyboard shortcut I'm accidentally hitting...
I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".
USE [DATABASENAME] GO ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9] GO ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName] GO
<a href="#"><button>Link Text</button></a>
You asked for a link that looks like a button, so use a link and a button :-) This will preserve default browser button styling. The button by itself does nothing, but clicking it activates its parent link.
Demo:
<a href="http://stackoverflow.com"><button>Link Text</button></a>
_x000D_
As described in the IPv6 Wikipedia article,
IPv6 addresses are normally written as eight groups of four hexadecimal digits, where each group is separated by a colon (:)
A typical IPv6 address:
2001:0db8:85a3:0000:0000:8a2e:0370:7334
This is 39 characters long. IPv6 addresses are 128 bits long, so you could conceivably use a binary(16) column, but I think I'd stick with an alphanumeric representation.
function setValToAssessment(id)
{
$.getJSON("<?= URL.$param->module."/".$param->controller?>/setvalue",{id: id}, function(response)
{
var form = $('<form></form>').attr("id",'hiddenForm' ).attr("name", 'hiddenForm');
$.each(response,function(key,value){
$("<input type='text' value='"+value+"' >")
.attr("id", key)
.attr("name", key)
.appendTo("form");
});
$('#hiddenForm').appendTo('body').submit();
// window.location.href = "<?=URL.$param->module?>/assessment";
});
}
Several reasons
Every single compilation unit requires hundreds or even thousands of headers to be (1) loaded and (2) compiled. Every one of them typically has to be recompiled for every compilation unit, because the preprocessor ensures that the result of compiling a header might vary between every compilation unit. (A macro may be defined in one compilation unit which changes the content of the header).
This is probably the main reason, as it requires huge amounts of code to be compiled for every compilation unit, and additionally, every header has to be compiled multiple times (once for every compilation unit that includes it).
Once compiled, all the object files have to be linked together. This is basically a monolithic process that can't very well be parallelized, and has to process your entire project.
The syntax is extremely complicated to parse, depends heavily on context, and is very hard to disambiguate. This takes a lot of time.
In C#, List<T>
is the only type that is compiled, no matter how many instantiations of List you have in your program.
In C++, vector<int>
is a completely separate type from vector<float>
, and each one will have to be compiled separately.
Add to this that templates make up a full Turing-complete "sub-language" that the compiler has to interpret, and this can become ridiculously complicated. Even relatively simple template metaprogramming code can define recursive templates that create dozens and dozens of template instantiations. Templates may also result in extremely complex types, with ridiculously long names, adding a lot of extra work to the linker. (It has to compare a lot of symbol names, and if these names can grow into many thousand characters, that can become fairly expensive).
And of course, they exacerbate the problems with header files, because templates generally have to be defined in headers, which means far more code has to be parsed and compiled for every compilation unit. In plain C code, a header typically only contains forward declarations, but very little actual code. In C++, it is not uncommon for almost all the code to reside in header files.
C++ allows for some very dramatic optimizations. C# or Java don't allow classes to be completely eliminated (they have to be there for reflection purposes), but even a simple C++ template metaprogram can easily generate dozens or hundreds of classes, all of which are inlined and eliminated again in the optimization phase.
Moreover, a C++ program must be fully optimized by the compiler. A C# program can rely on the JIT compiler to perform additional optimizations at load-time, C++ doesn't get any such "second chances". What the compiler generates is as optimized as it's going to get.
C++ is compiled to machine code which may be somewhat more complicated than the bytecode Java or .NET use (especially in the case of x86). (This is mentioned out of completeness only because it was mentioned in comments and such. In practice, this step is unlikely to take more than a tiny fraction of the total compilation time).
Most of these factors are shared by C code, which actually compiles fairly efficiently. The parsing step is a lot more complicated in C++, and can take up significantly more time, but the main offender is probably templates. They're useful, and make C++ a far more powerful language, but they also take their toll in terms of compilation speed.
You can access IE8 script console by launching the "Developer Tools" (F12). Click the "Script" tab, then click "Console" on the right.
From within your JavaScript code, you can do any of the following:
<script type="text/javascript">
console.log('some msg');
console.info('information');
console.warn('some warning');
console.error('some error');
console.assert(false, 'YOU FAIL');
</script>
Also, you can clear the Console by calling console.clear()
.
NOTE: It appears you must launch the Developer Tools first then refresh your page for this to work.
A stable sorting algorithm is the one that sorts the identical elements in their same order as they appear in the input, whilst unstable sorting may not satisfy the case. - I thank my algorithm lecturer Didem Gozupek to have provided insight into algorithms.
Stable Sorting Algorithms:
Unstable Sorting Algorithms:
If you want an recent copy of npgsql, then go here
This can be installed via package manager console as
PM> Install-Package Npgsql
You can use the following command :
$ grep "phpmyadmin" $path_to_access.log | grep -Po "^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" | sort | uniq | xargs -I% sudo iptables -A INPUT -s % -j DROP
Explanation:
Make sure your IP isn't listed before piping through iptables drop!!
This will first find all lines in $path_to_access.log that have phpmyadmin in them,
then grep out the ip address from the start of the line,
then sort and unique them,
then add a rule to drop them in iptables
Again, just edit in echo %
at the end instead of the iptables command to make sure your IP isn't in there. Don't inadvertently ban your access to the server!
Limitations
You may need to change the grep part of the command if you're on mac or any system that doesn't have grep -P. I'm not sure if all systems start with xargs, so that might need to be installed too. It's super useful anyway if you do a lot of bash.
If you are using Kotlin then this will solve your problem. (MS Json format)
val dataString = "/Date(1586583441106)/"
val date = Date(Long.parseLong(dataString.substring(6, dataString.length - 2)))
Use the default constructor for Socket and then use the connect() method.
The problem is frequently with 'secure' setup of mountpoints, such as /tmp
If they are mounted noexec
(check with cat /etc/mtab
and or sudo mount
) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.
E.g. to remount temporarily:
sudo mount -o remount,exec /tmp
Or to change permanently, remove noexec
in /etc/fstab
You can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
Set a width on the form element (which should exist in your example! ) and float (and clear) the input elements. Also, drop the br elements.
I was able to center a view using
android:layout_centerHorizontal="true"
and
android:layout_centerVertical="true"
params.
NuGet references
Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.
Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.
Swift 4
In viewDidLoad() just call below code:
CODE SAMPLE
//txtVComplaint is a textView
txtVComplaint.tintColor = UIColor.white
txtVComplaint.tintColorDidChange()
Try to do all the steps specified in the link below and before that upgrade VirtualBox to 4.2 by following the instructions in VirtualBox 4.2.0 Released With Support For Drag'n'drop From Host To Linux Guests, More. Then upgrade Genymotion to the latest version.
Go to the desktop and run Genymotion. Select a virtual device with Android version 4.2 and then drag and drop the two files Genymotion-ARM-Translation_v1.1.zip first. Then Genymotion will show progress and after this it will promt a dialog. Then click OK and it will ask to reboot the device. Restart ADB. Do the same steps for the second file, gapps-jb-20130812-signed.zip and restart ADB.
I hope this will resolve the issue. Check this link - it explains it clearer.
Using REQUIRES_NEW
is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED
- it will create a new transaction.
That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional
, it will create a new transaction.
So, with that in mind, if using REQUIRES_NEW
makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.
On rollback - using REQUIRES_NEW
will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations.
Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.
Below code shows the values that you can get from System API, these all things you can get through this API.
public class App {
public static void main( String[] args ) {
//Operating system name
System.out.println(System.getProperty("os.name"));
//Operating system version
System.out.println(System.getProperty("os.version"));
//Path separator character used in java.class.path
System.out.println(System.getProperty("path.separator"));
//User working directory
System.out.println(System.getProperty("user.dir"));
//User home directory
System.out.println(System.getProperty("user.home"));
//User account name
System.out.println(System.getProperty("user.name"));
//Operating system architecture
System.out.println(System.getProperty("os.arch"));
//Sequence used by operating system to separate lines in text files
System.out.println(System.getProperty("line.separator"));
System.out.println(System.getProperty("java.version")); //JRE version number
System.out.println(System.getProperty("java.vendor.url")); //JRE vendor URL
System.out.println(System.getProperty("java.vendor")); //JRE vendor name
System.out.println(System.getProperty("java.home")); //Installation directory for Java Runtime Environment (JRE)
System.out.println(System.getProperty("java.class.path"));
System.out.println(System.getProperty("file.separator"));
}
}
Answers:-
Windows 7
6.1
;
C:\Users\user\Documents\workspace-eclipse\JavaExample
C:\Users\user
user
amd64
1.7.0_71
http://java.oracle.com/
Oracle Corporation
C:\Program Files\Java\jre7
C:\Users\user\Documents\workspace-Eclipse\JavaExample\target\classes
\
Use numpy.dot
or a.dot(b)
. See the documentation here.
>>> a = np.array([[ 5, 1 ,3],
[ 1, 1 ,1],
[ 1, 2 ,1]])
>>> b = np.array([1, 2, 3])
>>> print a.dot(b)
array([16, 6, 8])
This occurs because numpy arrays are not matrices, and the standard operations *, +, -, /
work element-wise on arrays. Instead, you could try using numpy.matrix
, and *
will be treated like matrix multiplication.
Also know there are other options:
As noted below, if using python3.5+ the @
operator works as you'd expect:
>>> print(a @ b)
array([16, 6, 8])
If you want overkill, you can use numpy.einsum
. The documentation will give you a flavor for how it works, but honestly, I didn't fully understand how to use it until reading this answer and just playing around with it on my own.
>>> np.einsum('ji,i->j', a, b)
array([16, 6, 8])
As of mid 2016 (numpy 1.10.1), you can try the experimental numpy.matmul
, which works like numpy.dot
with two major exceptions: no scalar multiplication but it works with stacks of matrices.
>>> np.matmul(a, b)
array([16, 6, 8])
numpy.inner
functions the same way as numpy.dot
for matrix-vector multiplication but behaves differently for matrix-matrix and tensor multiplication (see Wikipedia regarding the differences between the inner product and dot product in general or see this SO answer regarding numpy's implementations).
>>> np.inner(a, b)
array([16, 6, 8])
# Beware using for matrix-matrix multiplication though!
>>> b = a.T
>>> np.dot(a, b)
array([[35, 9, 10],
[ 9, 3, 4],
[10, 4, 6]])
>>> np.inner(a, b)
array([[29, 12, 19],
[ 7, 4, 5],
[ 8, 5, 6]])
If you have tensors (arrays of dimension greater than or equal to one), you can use numpy.tensordot
with the optional argument axes=1
:
>>> np.tensordot(a, b, axes=1)
array([16, 6, 8])
Don't use numpy.vdot
if you have a matrix of complex numbers, as the matrix will be flattened to a 1D array, then it will try to find the complex conjugate dot product between your flattened matrix and vector (which will fail due to a size mismatch n*m
vs n
).
Check this:
a = [*(1..10), :top, *10.downto( 1 )]
I tried this to fix access issues to an IIS website, which manifested as something like the following in the Event Logs ? Windows ? Application:
Log Name: Application Source: ASP.NET 4.0.30319.0 Date: 1/5/2012 4:12:33 PM Event ID: 1314 Task Category: Web Event Level: Information Keywords: Classic User: N/A Computer: SALTIIS01 Description: Event code: 4008 Event message: File authorization failed for the request. Event time: 1/5/2012 4:12:33 PM Event time (UTC): 1/6/2012 12:12:33 AM Event ID: 349fcb2ec3c24b16a862f6eb9b23dd6c Event sequence: 7 Event occurrence: 3 Event detail code: 0 Application information: Application domain: /LM/W3SVC/2/ROOT/Application/SNCDW-19-129702818025409890 Trust level: Full Application Virtual Path: /Application/SNCDW Application Path: D:\Sites\WCF\Application\SNCDW\ Machine name: SALTIIS01 Process information: Process ID: 1896 Process name: w3wp.exe Account name: iisservice Request information: Request URL: http://webservicestest/Application/SNCDW/PC.svc Request path: /Application/SNCDW/PC.svc User host address: 10.60.16.79 User: js3228 Is authenticated: True Authentication Type: Negotiate Thread account name: iisservice
In the end I had to give the Windows Everyone
group read access to that folder to get it to work properly.
For those coming here from a later day and age and one a working solution:
(Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
this will give the total sum of bytes.
$bytes = (Get-WmiObject -class "cim_physicalmemory" | Measure-Object -Property Capacity -Sum).Sum
$kb = $bytes / 1024
$mb = $bytes / 1024 / 1024
$gb = $bytes / 1024 / 1024 / 1024
I tested this up to windows server 2008 (winver 6.0) even there this command seems to work
If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute
and setAttribute
methods as shown below:
JavaScript
<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>
Through jQuery
// Fetching data
var fruitCount = $(this).data('fruit');
// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');
// Assigning data
$(this).data('fruit','7');
// But when you get the value again, it will return old value.
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7');
Read this documentation for vanilla js or this documentation for jquery
Simple add
textAlign: "center"
in your styleSheet, that's it. Hope this would help.
edit: "center"
I got similar error after deleting a subproject, removed
"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"
in build.gradle
(dependencies) under Gradle Scripts
Another option is to hide based on bootstraps "sr-only" class. If you wrap the text in a span with the class "sr-only" then the text will not be displayed, but screen readers will still have access to it. So you would have:
<li><a href="somehwere"><span class="sr-only">Link text</span></a></li>
If you are not using bootstrap, still keep the above, but also add the below css to define the "sr-only" class:
.sr-only {position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); border: 0; }
Just to help anyone with this problem (locking requests when executing another one from the same session)...
Today I started to solve this issue and, after some hours of research, I solved it by removing the Session_Start
method (even if empty) from the Global.asax file.
This works in all projects I've tested.
If the result of, 'searchResult.Properties [ "user" ] [ 0 ]', is a string:
if ( ( searchResult.Properties [ "user" ].Count > 0 ) ) {
profile.User = System.Text.Encoding.UTF8.GetString ( searchResult.Properties [ "user" ] [ 0 ].ToCharArray ().Select ( character => ( byte ) character ).ToArray () );
}
The key point being that converting a string to a byte [] can be done using LINQ:
.ToCharArray ().Select ( character => ( byte ) character ).ToArray () )
And the inverse:
.Select ( character => ( char ) character ).ToArray () )
Ripple event for android Cardview
control:
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:foreground="?android:attr/selectableItemBackground"
android:clickable="true"
android:layout_marginBottom="4dp"
android:layout_marginTop="4dp" />
This code worked for me
.navbar .navbar-nav {
display: inline-block;
float: none;
}
.navbar .navbar-collapse {
text-align: center;
}
You can use request.getQueryString()
,if the query string is like
username=james&password=pwd
To get name you can do this
request.getParameter("username");
I modified the solution by @Kalyani and so far it's been working beautifully!
$('selector').click(function(event) {
if(!event.detail || event.detail == 1){ return true; }
else { return false; }
});
As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:
WHILE EXISTS (SELECT 1
FROM YourTable
WHERE <yourCondition>)
DELETE TOP(10000) FROM YourTable
WHERE <yourCondition>
Just escape your quotes:
echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";
If I understand well, you want to Join ScheduleRequest
with User
and apply the in
clause to the userName
property of the entity User
.
I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join
part (because it handles the Join
logic outside the Criteria Query).
List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);
In order to write more type-safe code you could also use Metamodel by replacing this line:
Expression<String> exp = scheduleRequest.get("createdBy");
with this:
Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);
If it works, then you may try to add the Join
logic into the Criteria Query
. But right now I can't test it, so I prefer to see if somebody else wants to try.
Not a perfect answer though may be code snippets might help.
public <T> List<T> findListWhereInCondition(Class<T> clazz,
String conditionColumnName, Serializable... conditionColumnValues) {
QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
addWhereInClause(queryBuilder, conditionColumnName,
conditionColumnValues);
queryBuilder.select();
return queryBuilder.getResultList();
}
private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
String conditionColumnName, Serializable... conditionColumnValues) {
Path<Object> path = queryBuilder.root.get(conditionColumnName);
In<Object> in = queryBuilder.criteriaBuilder.in(path);
for (Serializable conditionColumnValue : conditionColumnValues) {
in.value(conditionColumnValue);
}
queryBuilder.criteriaQuery.where(in);
}
I've resorted to
df[ (df[column_name].notnull()) & (df[column_name]!=u'') ].index
lately. That gets both null and empty-string cells in one go.
jQuery.fn.extend({
getStyles: function() {
var rulesUsed = [];
var sheets = document.styleSheets;
for (var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for (var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText.toLowerCase().replace(":hover","");
if (this.is(selectorText) || this.find(selectorText).length > 0) {
rulesUsed.push(rules[r]);
}
}
}
var style = rulesUsed.map(function(cssRule) {
return cssRule.selectorText.toLowerCase() + ' { ' + cssRule.style.cssText.toLowerCase() + ' }';
}).join("\n");
return style;
}
});
usage:
$("#login_wrapper").getStyles()
fieldset {
min-width: 0;
max-width: 100%;
width: 100%;
}
Either override the OnFormClosing or register for the event FormClosing.
This is an example of overriding the OnFormClosing function in the derived form:
protected override void OnFormClosing(FormClosingEventArgs e)
{
e.Cancel = true;
}
This is an example of the handler of the event to stop the form from closing which can be in any class:
private void FormClosing(object sender,FormClosingEventArgs e)
{
e.Cancel = true;
}
To get more advanced, check the CloseReason property on the FormClosingEventArgs to ensure the appropriate action is performed. You might want to only do the alternative action if the user tries to close the form.
int val = '1' & 15;
The binary of the ASCII charecters 0-9 is:
0 - 00110000
1 - 00110001
2 - 00110010
3 - 00110011
4 - 00110100
5 - 00110101
6 - 00110110
7 - 00110111
8 - 00111000
9 - 00111001
and if you take in each one of them the first 4 LSB(using bitwise AND with 8'b00001111 that equels to 15) you get the actual number (0000 = 0,0001=1,0010=2,... )
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
The following sets up the situation I had, using table variables.
DECLARE @Object_Table TABLE
(
Id INT NOT NULL PRIMARY KEY
)
DECLARE @Link_Table TABLE
(
ObjectId INT NOT NULL,
DataId INT NOT NULL
)
DECLARE @Data_Table TABLE
(
Id INT NOT NULL Identity(1,1),
Data VARCHAR(50) NOT NULL
)
-- create two objects '1' and '2'
INSERT INTO @Object_Table (Id) VALUES (1)
INSERT INTO @Object_Table (Id) VALUES (2)
-- create some data
INSERT INTO @Data_Table (Data) VALUES ('Data One')
INSERT INTO @Data_Table (Data) VALUES ('Data Two')
-- link all data to first object
INSERT INTO @Link_Table (ObjectId, DataId)
SELECT Objects.Id, Data.Id
FROM @Object_Table AS Objects, @Data_Table AS Data
WHERE Objects.Id = 1
Thanks to another answer that pointed me towards the OUTPUT clause I can demonstrate a solution:
-- now I want to copy the data from from object 1 to object 2 without looping
INSERT INTO @Data_Table (Data)
OUTPUT 2, INSERTED.Id INTO @Link_Table (ObjectId, DataId)
SELECT Data.Data
FROM @Data_Table AS Data INNER JOIN @Link_Table AS Link ON Data.Id = Link.DataId
INNER JOIN @Object_Table AS Objects ON Link.ObjectId = Objects.Id
WHERE Objects.Id = 1
It turns out however that it is not that simple in real life because of the following error
the OUTPUT INTO clause cannot be on either side of a (primary key, foreign key) relationship
I can still OUTPUT INTO
a temp table and then finish with normal insert. So I can avoid my loop but I cannot avoid the temp table.
If you don't want to remove/change dataType: json
, you can override jQuery's strict parsing by defining a custom converter
:
$.ajax({
// We're expecting a JSON response...
dataType: 'json',
// ...but we need to override jQuery's strict JSON parsing
converters: {
'text json': function(result) {
try {
// First try to use native browser parsing
if (typeof JSON === 'object' && typeof JSON.parse === 'function') {
return JSON.parse(result);
} else {
// Fallback to jQuery's parser
return $.parseJSON(result);
}
} catch (e) {
// Whatever you want as your alternative behavior, goes here.
// In this example, we send a warning to the console and return
// an empty JS object.
console.log("Warning: Could not parse expected JSON response.");
return {};
}
}
},
...
Using this, you can customize the behavior when the response cannot be parsed as JSON (even if you get an empty response body!)
With this custom converter, .done()
/success
will be triggered as long as the request was otherwise successful (1xx or 2xx response code).
StackOverflow: How to execute a command and get output of command within C++?
StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...
Also if you know how to make user become the super-user that would be nice also. Thanks!
sudo. su. chmod 04500. (setuid() & seteuid(), but they require you to already be root. E..g. chmod'ed 04***.)
Take care. These can open "interesting" security holes...
Depending on what you are doing, you may not need root. (For instance: I'll often chmod/chown /dev devices (serial ports, etc) (under sudo root) so I can use them from my software without being root. On the other hand, that doesn't work so well when loading/unloading kernel modules...)
Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):
xhr.open(method, url, true);
You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.
... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.
Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.
I hope that is helpful.
DUAL is necessary in PL/SQL development for using functions that are only available in SQL
e.g.
DECLARE
x XMLTYPE;
BEGIN
SELECT xmlelement("hhh", 'stuff')
INTO x
FROM dual;
END;
Emacs has comment-dwim (Do What I Mean) - just select the block and do a:
M-;
It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).
You can use the next code:
JS
function showname () {
var name = document.getElementById('fileInput');
alert('Selected file: ' + name.files.item(0).name);
alert('Selected file: ' + name.files.item(0).size);
alert('Selected file: ' + name.files.item(0).type);
};
HTML
<body>
<p>
<input type="file" id="fileInput" multiple onchange="showname()"/>
</p>
</body>
Found another example where you would have to call destructor(s) manually. Suppose you have implemented a variant-like class that holds one of several types of data:
struct Variant {
union {
std::string str;
int num;
bool b;
};
enum Type { Str, Int, Bool } type;
};
If the Variant
instance was holding a std::string
, and now you're assigning a different type to the union, you must destruct the std::string
first. The compiler will not do that automatically.
Declare object of EditText on top of class:
EditText myEditText;
Find EditText in onCreate Function and setOnFocusChangeListener of EditText:
myEditText = findViewById(R.id.yourEditTextNameInxml);
myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean hasFocus) {
if (!hasFocus) {
Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
}
}
});
It works fine.
You'll need the SQL Server Configuration Manager. Go to Sql Native Client Configuration, Select Client Protocols, Right Click on TCP/IP and set your default port there.
It is probably not a correct way for clean, but I made that to delete unnecessary files, and take less size of a project. It continuously finds and deletes all build and Gradle folders made file clean.bat copy that into the folder where your project is
set mypath=%cd%
for /d /r %mypath% %%a in (build\) do if exist "%%a" rmdir /s /q "%%a"
for /d /r %mypath% %%a in (.gradle\) do if exist "%%a" rmdir /s /q "%%a"
If you need to see the output of the execute, use CALL
together with or instead of START
.
Example:
CALL "C:\Program Files\Certain Directory\file.exe" -param
PAUSE
This will run the file.exe and print back whatever it outputs, in the same command window. Remember the PAUSE
after the call or else the window may close instantly.
In MAC OS Catalina, this are the steps that worked for me, all the above solutions did help but didn't solve my problem.
Below works for first tr
of the table under thead
table thead tr:first-child {
background: #f2f2f2;
}
And this works for the first tr
of thead
and tbody
both:
table thead tbody tr:first-child {
background: #f2f2f2;
}
The reason you cannot cast List<String>
to List<Object>
is that it would allow you to violate the constraints of the List<String>
.
Think about the following scenario: If I have a List<String>
, it is supposed to only contain objects of type String
. (Which is a final
class)
If I can cast that to a List<Object>
, then that allows me to add Object
to that list, thus violating the original contract of List<String>
.
Thus, in general, if class C
inherits from class P
, you cannot say that GenericType<C>
also inherits from GenericType<P>
.
N.B. I already commented on this in a previous answer but wanted to expand on it.
In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325
Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.
Make sure that you have checked it to work properly with the IE version you specify.
I've found myself using range.Rows for its effects in the Copy method. It copies the height of the rows from the origin to the destination, which is the behaviour I want.
rngLastRecord.Rows.Copy Destination:=Sheets("Availability").Range("a" & insertRow)
If I had used rngLastRecord.Copy instead of rngLastRecord.Rows.Copy, the row heights would be whatever was there before the copy.
Try this as it worked for me...
courtesy of Last paragraph mentioned in here
You can realize this layout using CSS table-cells.
Modify your HTML slightly as follows:
<div id="header">
<div class="container">
<div class="logoBar">
<img src="http://placehold.it/50x40" />
</div>
<div id="searchBar">
<input type="text" />
</div>
<div class="button orange" id="myAccount">My Account</div>
<div class="button red" id="basket">Basket (2)</div>
</div>
</div>
Just remove the wrapper element around the two .button
elements.
Apply the following CSS:
#header {
background-color: #323C3E;
width:100%;
}
.container {
display: table;
width: 100%;
}
.logoBar, #searchBar, .button {
display: table-cell;
vertical-align: middle;
width: auto;
}
.logoBar img {
display: block;
}
#searchBar {
background-color: #FFF2BC;
width: 90%;
padding: 0 50px 0 10px;
}
#searchBar input {
width: 100%;
}
.button {
white-space: nowrap;
padding:22px;
}
Apply display: table
to .container
and give it 100% width.
For .logoBar
, #searchBar
, .button
, apply display: table-cell
.
For the #searchBar
, set the width to 90%, which force all the other elements to compute a shrink-to-fit width and the search bar will expand to fill in the rest of the space.
Use text-align and vertical-align in the table cells as needed.
See demo at: http://jsfiddle.net/audetwebdesign/zWXQt/
The recommended approach is to add an OnBackPressedCallback
to the activity's OnBackPressedDispatcher
.
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
// handle back event
}
Below code gives a basic idea. This is not best solution though.
public static String splitJoin(String sourceStr, String delim,boolean trim,boolean ignoreEmpty){
return join(Arrays.asList(sourceStr.split(delim)), delim, ignoreEmpty);
}
public static String join(List<?> list, String delim, boolean ignoreEmpty) {
int len = list.size();
if (len == 0)
return "";
StringBuilder sb = new StringBuilder(list.get(0).toString());
for (int i = 1; i < len; i++) {
if (ignoreEmpty && !StringUtils.isBlank(list.get(i).toString())) {
sb.append(delim);
sb.append(list.get(i).toString().trim());
}
}
return sb.toString();
}
Currently you are clearing the name array, you need to call the array then the index you want to unset within the array:
$ar[0]==2
$ar[1]==7
$ar[2]==9
unset ($ar[2])
Two ways of unsetting values within an array:
<?php
# remove by key:
function array_remove_key ()
{
$args = func_get_args();
return array_diff_key($args[0],array_flip(array_slice($args,1)));
}
# remove by value:
function array_remove_value ()
{
$args = func_get_args();
return array_diff($args[0],array_slice($args,1));
}
$fruit_inventory = array(
'apples' => 52,
'bananas' => 78,
'peaches' => 'out of season',
'pears' => 'out of season',
'oranges' => 'no longer sold',
'carrots' => 15,
'beets' => 15,
);
echo "<pre>Original Array:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# For example, beets and carrots are not fruits...
$fruit_inventory = array_remove_key($fruit_inventory,
"beets",
"carrots");
echo "<pre>Array after key removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
# Let's also remove 'out of season' and 'no longer sold' fruit...
$fruit_inventory = array_remove_value($fruit_inventory,
"out of season",
"no longer sold");
echo "<pre>Array after value removal:\n",
print_r($fruit_inventory,TRUE),
'</pre>';
?>
So, unset has no effect to internal array counter!!!
You need to use the command pscp and forcing it to pass through sftp protocol. pscp is automatically installed when you install PuttY, a software to connect to a linux server through ssh.
When you have your pscp command here is the command line:
pscp -sftp -pw <yourPassword> "<pathToYourFile(s)>" <username>@<serverIP>:<PathInTheServerFromTheHomeDirectory>
These parameters (-sftp and -pw) are only available with pscp and not scp. You can also add -r if you want to upload everything in a folder in a recursive way.
A @ViewScoped
bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null
or void
(and thus navigates back to the same view). Once you refresh the page, or return a non-null
string (even an empty string!) navigation outcome, then the view scope will end.
A @RequestScoped
bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.
A @ViewScoped
bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped
one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped
bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped
bean. Every view has its own unique @ViewScoped
bean.
Inside container(in docker, not in VM), by default these are not installed. Even apt-get, wget will not work. My VM is running on Ubuntu 17.10. For me yum package manaager worked.
Yum is not part of debian or ubuntu. It is part of red-hat. But, it works in Ubuntu and it is installed by default like apt-get
Tu install vim, use this command
yum install -y vim-enhanced
To uninstall vim :
yum uninstall -y vim-enhanced
Similarly,
yum install -y wget
yum install -y sudo
-y is for assuming yes if prompted for any qustion asked after doing yum install packagename
Finally, it worked. Thank you guys.
I was not getting it to work because i was trying to resize the label in heightForRowAtIndexPath
method:
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
and (yeah silly me), i was resizing the label to default in cellForRowAtIndexPath
method - i was overlooking the code i had written earlier:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
EDIT: Note, this is if you have multiple tsconfig.json files in your typescript source. For my project we have each tsconfig.json file compile to a differently-named .js file. This makes watching every typescript file really easy.
I wrote a sweet bash script that finds all of your tsconfig.json files and runs them in the background, and then if you CTRL+C the terminal it will close all the running typescript watch commands.
This is tested on MacOS, but should work anywhere that BASH 3.2.57 is supported. Future versions may have changed some things, so be careful!
#!/bin/bash
# run "chmod +x typescript-search-and-compile.sh" in the directory of this file to ENABLE execution of this script
# then in terminal run "path/to/this/file/typescript-search-and-compile.sh" to execute this script
# (or "./typescript-search-and-compile.sh" if your terminal is in the folder the script is in)
# !!! CHANGE ME !!!
# location of your scripts root folder
# make sure that you do not add a trailing "/" at the end!!
# also, no spaces! If you have a space in the filepath, then
# you have to follow this link: https://stackoverflow.com/a/16703720/9800782
sr=~/path/to/scripts/root/folder
# !!! CHANGE ME !!!
# find all typescript config files
scripts=$(find $sr -name "tsconfig.json")
for s in $scripts
do
# strip off the word "tsconfig.json"
cd ${s%/*} # */ # this function gets incorrectly parsed by style linters on web
# run the typescript watch in the background
tsc -w &
# get the pid of the last executed background function
pids+=$!
# save it to an array
pids+=" "
done
# end all processes we spawned when you close this process
wait $pids
Helpful resources:
This may be helpful :
SecureRandom.base64(15).tr('+/=', '0aZ')
If you want to remove any special character than put in first argument '+/=' and any character put in second argument '0aZ' and 15 is the length here .
And if you want to remove the extra spaces and new line character than add the things like :
SecureRandom.base64(15).tr('+/=', '0aZ').strip.delete("\n")
Hope this will help to anybody.
In my case (want to reset and get a fresh database),
First I has got the error message :
There is already an object named 'TABLENAME' in the database.
and I saw, a little bit before:
"Applying migration '20111111111111_InitialCreate'.
Failed executing DbCommand (16ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE MYFIRSTTABLENAME"
My database was created, but no record in migrations history.
I drop all tables except dbo.__MigrationsHistory
MigrationsHistory was empty.
Run
dotnet ef database update -c StudyContext --verbose
(--verbose just for fun)
and got Done.
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
Slightly modified version of Sebastian's answer using find
instead of du
(to exclude file-size-related overhead that du
has to perform and that is never used):
find ./ -mindepth 2 -type f | cut -d/ -f2 | sort | uniq -c | sort -nr
-mindepth 2
parameter is used to exclude files in current directory. If you remove it, you'll see a bunch of lines like the following:
234 dir1
123 dir2
1 file1
1 file2
1 file3
...
1 fileN
(much like the du
-based variant does)
If you do need to count the files in current directory as well, use this enhanced version:
{ find ./ -mindepth 2 -type f | cut -d/ -f2 | sort && find ./ -maxdepth 1 -type f | cut -d/ -f1; } | uniq -c | sort -nr
The output will be like the following:
234 dir1
123 dir2
42 .
If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.
Ex.
Filename: csvsample.php
class csvsample {
}
Something else you can do, if you want to preserve your scroll position is this:
<asp:LinkButton runat="server" id="someId" href="javascript: void;" Text="Click Me" />
There is no default value to control deleting old log files created by DailyRollingFileAppender. But you can write your own custom Appender that deletes old log files in much the same way as setting maxBackupIndex does for RollingFileAppender.
Simple instructions found here
From 1:
If you are trying to use the Apache Log4J DailyRollingFileAppender for a daily log file, you may need to want to specify the maximum number of files which should be kept. Just like rolling RollingFileAppender supports maxBackupIndex. But the current version of Log4j (Apache log4j 1.2.16) does not provide any mechanism to delete old log files if you are using DailyRollingFileAppender. I tried to make small modifications in the original version of DailyRollingFileAppender to add maxBackupIndex property. So, it would be possible to clean up old log files which may not be required for future usage.
Here, this api allows you to get fb, google and twitter profile pics easily
It's an API that returns the profile image when given a username for a variety of social networks including Twitter, Facebook, Instagram, and gravatar. It has libraries for iOS, Android, Ruby, Node, PHP, Python, and JavaScript.
The best I've seen so far is HtmlCleaner:
HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.
With HtmlCleaner you can locate any element using XPath.
For other html parsers see this SO question.
I would have thought that something like this would be much better, since you're adding a variable, so why not restrict access and make it cleaner? Your getter/setters should do what they say on the tin.
public abstract class ExternalScript extends Script {
private String source;
public void setSource(String file) {
source = file;
}
public String getSource() {
return source;
}
}
Bringing this back to the question, do you ever bother looking at where the getter/setter code is when reading it? If they all do getting and setting then you don't need to worry about what the function 'does' when reading the code. There are a few other reasons to think about too:
Always think whether your class is really a different thing or not, and that should help decide whether you need anything more.
<span>You have {{products|length}} products</span>
You can also use this syntax in expressions like
{% if products|length > 1 %}
jinja2's builtin filters are documented here; and specifically, as you've already found, length
(and its synonym count
) is documented to:
Return the number of items of a sequence or mapping.
So, again as you've found, {{products|count}}
(or equivalently {{products|length}}
) in your template will give the "number of products" ("length of list")
IsAssignableFrom
is now moved to TypeInfo
:
typeof(ISMSRequest).GetTypeInfo().IsAssignableFrom(typeof(T).GetTypeInfo());
As of ruby 2.3.0
class Check
def self.first_method
second_method
end
private
def self.second_method
puts "well I executed"
end
end
Check.first_method
#=> well I executed
-(void) addBlurEffectOverImageView:(UIImageView *) _imageView
{
UIVisualEffect *blurEffect;
blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
UIVisualEffectView *visualEffectView;
visualEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
visualEffectView.frame = _imageView.bounds;
[_imageView addSubview:visualEffectView];
}
Run either of these a few second apart. You'll detect the high CPU connection. Or: stored CPU in a local variable, WAITFOR DELAY, compare stored and current CPU values
select * from master..sysprocesses
where status = 'runnable' --comment this out
order by CPU
desc
select * from master..sysprocesses
order by CPU
desc
May not be the most elegant but it'd effective and quick.
It appears to me that del will give you the memory back, while assigning a new list will make the old one be deleted only when the gc runs.matter.
This may be useful for large lists, but for small list it should be negligible.
Edit: As Algorias, it doesn't matter.
Note that
del old_list[ 0:len(old_list) ]
is equivalent to
del old_list[:]
This is a feature, not a bug.
See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.
Modulus operator gives you the result in 'reduced residue system'. For example for mod 5 there are 5 integers counted: 0,1,2,3,4. In fact 19=12=5=-2=-9 (mod 7). The main difference that the answer is given by programming languages by 'reduced residue system'.
The downfall of ArrayList and LinkedList is that when iterating through them, depending on the search algorithm, the time it takes to find an item grows with the size of the list.
The beauty of hashing is that although you sacrifice some extra time searching for the element, the time taken does not grow with the size of the map. This is because the HashMap finds information by converting the element you are searching for, directly into the index, so it can make the jump.
Long story short... LinkedList: Consumes a little more memory than ArrayList, low cost for insertions(add & remove) ArrayList: Consumes low memory, but similar to LinkedList, and takes extra time to search when large. HashMap: Can perform a jump to the value, making the search time constant for large maps. Consumes more memory and takes longer to find the value than small lists.
Make sure your computer is connected to the internet, then click on the link that comes with the error message i.e "install missing platform(s) and sync project". Give it a few seconds especially if your computer has low specs, it will bring up a window called SDK Quickfix Installation and everything is straightforward from there.
You can try this code
import random
N = 5
count_list = range(1,N+1)
random.shuffle(count_list)
while count_list:
value = count_list.pop()
# do whatever you want with 'value'
I find the simple solution
pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))
OnClientClick seems to be very picky when used with OnClick.
I tried unsuccessfully with the following use cases:
OnClientClick="return ValidateSearch();"
OnClientClick="if(ValidateSearch()) return true;"
OnClientClick="ValidateSearch();"
But they did not work. The following worked:
<asp:Button ID="keywordSearch" runat="server" Text="Search" TabIndex="1"
OnClick="keywordSearch_Click"
OnClientClick="if (!ValidateSearch()) { return false;};" />
I've had the same problem, This was due to the firewall. I use windows server,
Can you allow the connection permission for program, intead of port 21,22 permission.
Windows Firewall with Advanced Security->
Inbound Rules->
Add Rule->
Program->
"Select Filezilla path with Browse button"->
Allow the Connection
Using furl, pip install furl
it will be:
furl.furl('/media/path/').add(path='js/foo.js')
It's the first result on Google: http://docs.python.org/library/stdtypes.html#string-formatting
See also the new format() function: http://docs.python.org/library/stdtypes.html#str.format
height: 100%
gives the element 100% height of its parent container.
height: auto
means the element height will depend upon the height of its children.
Consider these examples:
height: 100%
<div style="height: 50px">
<div id="innerDiv" style="height: 100%">
</div>
</div>
#innerDiv
is going to have height: 50px
height: auto
<div style="height: 50px">
<div id="innerDiv" style="height: auto">
<div id="evenInner" style="height: 10px">
</div>
</div>
</div>
#innerDiv
is going to have height: 10px
To remove title bar in AppCompat:
@Override
protected void onCreate(Bundle savedInstanceState) {
supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
}
.text is correct, the following code works for me:
$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);
Try following query to format datetime in sql server
FORMAT (frr.valid_from , 'dd/MM/yyyy hh:mm:ss')
import groovyx.net.http.HTTPBuilder;
public class HttpclassgetrRoles {
static void main(String[] args){
def baseUrl = new URL('http://test.city.com/api/Cirtxyz/GetUser')
HttpURLConnection connection = (HttpURLConnection) baseUrl.openConnection();
connection.addRequestProperty("Accept", "application/json")
connection.with {
doOutput = true
requestMethod = 'GET'
println content.text
}
}
}
Simple popup window by using html5 and javascript.
html:-
<dialog id="window">
<h3>Sample Dialog!</h3>
<p>Lorem ipsum dolor sit amet</p>
<button id="exit">Close Dialog</button>
</dialog>
<button id="show">Show Dialog</button>
JavaScript:-
(function() {
var dialog = document.getElementById('window');
document.getElementById('show').onclick = function() {
dialog.show();
};
document.getElementById('exit').onclick = function() {
dialog.close();
};
})();
Until I get a better option, this is the most "bootstrappy" answer I can work out:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/6cbrjrt5/
I have switched to using LESS and including the Bootstrap Source NuGet package to ensure compatibility (by giving me access to the bootstrap variables.less
file:
in _layout.cshtml master page
body-content
containernavbar-fixed-bottom
on the footer<hr/>
before the footer (as now redundant)Relevant page HTML:
<div class="container-fluid body-content">
@RenderBody()
</div>
<footer class="navbar-fixed-bottom">
<p>© @DateTime.Now.Year - My ASP.NET Application</p>
</footer>
In Site.less
HTML
and BODY
heights to 100%BODY
overflow
to hidden
body-content
div position
to absolute
body-content
div top
to @navbar-height
instead of hard-wiring valuebody-content
div bottom
to 30px
.body-content
div left
and right
to 0body-content
div overflow-y
to auto
Site.less
html {
height: 100%;
body {
height: 100%;
overflow: hidden;
.container-fluid.body-content {
position: absolute;
top: @navbar-height;
bottom: 30px;
right: 0;
left: 0;
overflow-y: auto;
}
}
}
The remaining problem is there seems to be no defining variable for the footer height
in bootstrap. If someone call tell me if there is a magic 30px variable defined in Bootstrap I would appreciate it.
You can "style echo" with adding new HTML code.
echo '<span class="city">' . $ip['cityName'] . '</span>';
Bit late response to this question, however I do have something to add that might be useful for others.
If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH
One of the simplest way I found is to use pynput module.can be found here with nice examples as well
from pynput import keyboard
def on_press(key):
try:
print('alphanumeric key {0} pressed'.format(
key.char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def on_release(key):
print('{0} released'.format(
key))
if key == keyboard.Key.esc:
# Stop listener
return False
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
above is the example worked out for me and to install, go
for python 2:
pip install pynput
for python 3:
pip3 install pynput
You could listen to the 'keydown'
event and then check for an enter key.
Your handler would be like:
function (e) {
if (13 == e.keyCode) {
... do whatever ...
}
}
I use this pattern fairly frequently - I've found that it gives me a pretty huge amount of flexibility when I need it. In use it's rather similar to Java-style classes.
var Foo = function()
{
var privateStaticMethod = function() {};
var privateStaticVariable = "foo";
var constructor = function Foo(foo, bar)
{
var privateMethod = function() {};
this.publicMethod = function() {};
};
constructor.publicStaticMethod = function() {};
return constructor;
}();
This uses an anonymous function that is called upon creation, returning a new constructor function. Because the anonymous function is called only once, you can create private static variables in it (they're inside the closure, visible to the other members of the class). The constructor function is basically a standard Javascript object - you define private attributes inside of it, and public attributes are attached to the this
variable.
Basically, this approach combines the Crockfordian approach with standard Javascript objects to create a more powerful class.
You can use it just like you would any other Javascript object:
Foo.publicStaticMethod(); //calling a static method
var test = new Foo(); //instantiation
test.publicMethod(); //calling a method
Same situation: Having done multiple Angular projects and moving to React, not having a simple way to provide services through DI seems like a missing piece (the particulars of the service aside).
Using context and ES7 decorators we can come close:
https://jaysoo.ca/2015/06/09/react-contexts-and-dependency-injection/
Seems these guys have taken it a step further / in a different direction:
http://blog.wolksoftware.com/dependency-injection-in-react-powered-inversifyjs
Still feels like working against the grain. Will revisit this answer in 6 months time after undertaking a major React project.
EDIT: Back 6 months later with some more React experience. Consider the nature of the logic:
Some also reach for HOCs for reuse but for me the above covers almost all use cases. Also, consider scaling state management using ducks to keep concerns separate and state UI-centric.
Just Simple Answer. FETCH DELETE
function deleteData(item, url) {
return fetch(url + '/' + item, {
method: 'delete'
})
.then(response => response.json());
}
for CakePHP 3:
$this->Url->build(null, true) // full URL with hostname
$this->Url->build(null) // /controller/action/params
You are debugging two or more times. so the application may run more at a time. Then only this issue will occur. You should close all debugging applications using task-manager, Then debug again.
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
This approach only works on Android AND if you have the number on your contact list. If you don't have it, Android opens your SMS app, so you can invite the contact to use Whatsapp.
<a href="https://api.whatsapp.com/send?phone=2567xxxxxxxxx" method="get" target="_blank"><i class="fa fa-whatsapp"></i></a>
Google Chrome am targeting a blank window
What worked for me is a combination of answers, namely:
# Reinstall OpenSSL
brew update
brew remove openssl
brew install openssl
# Download CURL CA bundle
cd /usr/local/etc/openssl/certs
wget http://curl.haxx.se/ca/cacert.pem
/usr/local/opt/openssl/bin/c_rehash
# Reinstall Ruby from source
rvm reinstall 2.2.3 --disable-binary
Java support microseconds through TimeUnit
enum.
Here is the java doc: Enum TimeUnit
You can get microseconds in java by this way:
long microsenconds = TimeUnit.MILLISECONDS.toMicros(System.currentTimeMillis());
You also can convert microseconds back to another time units, for example:
long seconds = TimeUnit.MICROSECONDS.toSeconds(microsenconds);
Try looking into the following CSS:
word-wrap:break-word;
Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.
You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.
Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.
I think you want to set it in your httpd.conf
file instead of the .htaccess
file.
I am not sure what OS you use, but this link for Ubuntu might give you some pointers on what to do.
https://help.ubuntu.com/community/EnablingUseOfApacheHtaccessFiles
Check $ git log
, copy the SHA-1 ID of the two different commits, and run the git diff
command with those IDs. for example:
$ git diff (sha-id-one) (sha-id-two)
I think is more robust to use regular expressions:
import re
for i, line in enumerate(content):
print line if not (re.match('\r?\n', line)) else pass
This would match in Windows/unix. In addition if you are not sure about lines containing only space char you could use '\s*\r?\n'
as expression
You shouldn't need to configure the consumes or produces attribute at all. Spring will automatically serve JSON based on the following factors.
You should also follow Wim's suggestion and define your controller with the @RestController annotation. This will save you from annotating each request method with @ResponseBody
Another benefit of this approach would be if a client wants XML instead of JSON, they would get it. They would just need to specify xml in the accepts header.